multithreading
tags question: http://stackoverflow.com/q/50306527
tags question: http://stackoverflow.com/q/50314924
type: Tag
tags question: http://stackoverflow.com/q/50271043
tags question: http://stackoverflow.com/q/50368906
tags question: http://stackoverflow.com/q/50350890
tags question: http://stackoverflow.com/q/50290308
tags question: http://stackoverflow.com/q/50275646
tags question: http://stackoverflow.com/q/50368307
tags question: http://stackoverflow.com/q/50239219
tags question: http://stackoverflow.com/q/50282478
tags question: http://stackoverflow.com/q/50365318
tags question: http://stackoverflow.com/q/50237335
tags question: http://stackoverflow.com/q/50369868
tags question: http://stackoverflow.com/q/50294263
tags question: http://stackoverflow.com/q/50290226
tags question: http://stackoverflow.com/q/50359291
tags question: http://stackoverflow.com/q/50249949
tags question: http://stackoverflow.com/q/50322436
tags question: http://stackoverflow.com/q/50316978
tags question: http://stackoverflow.com/q/50379009
tags question: http://stackoverflow.com/q/50235121
tag name: multithreading
tags question: http://stackoverflow.com/q/50379706
tags question: http://stackoverflow.com/q/50337089
tags question: http://stackoverflow.com/q/50377833
tags question: http://stackoverflow.com/q/50290875
tags question: http://stackoverflow.com/q/50233828
tags question: http://stackoverflow.com/q/50359667
tags question: http://stackoverflow.com/q/50248559
tags question: http://stackoverflow.com/q/50379652
tags question: http://stackoverflow.com/q/50270692
tags question: http://stackoverflow.com/q/50370225
tags question: http://stackoverflow.com/q/50272021

http://stackoverflow.com/comment/87638574
comment on: http://stackoverflow.com/a/50310078
has text: Actually having looked at my large amount of data more closely I can see that all the different inner lists are being created but they're all being created many many times like [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],...[6,7,8,9],[6,7,8,9],[6,7,8,9],...]. Hmmm.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88626077
has text: Hi @Hoefling, is there a way to parametrize tests in above test environment, in case if different test data list is available for a single test?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50336242

http://stackoverflow.com/comment/87620906
comment on: http://stackoverflow.com/q/50302207
type: Comment
type: QuestionComment
score: 0
has text: Please explain what is the "result from the current script" instead of just "weird".

http://stackoverflow.com/q/50281288
tagged with: python
has comment: http://stackoverflow.com/comment/87579381
has comment: http://stackoverflow.com/comment/87580474
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87579920
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50281548
has body: For a project, I am trying to determine the time it would take for a photon to leave the Sun. However, I am having trouble with my code (found below). More specifically, I set up a for loop with an if statement, and if some randomly generated probability is less than the probability of collision, that means the photon collides and it changes direction. What I am having trouble with is setting up a condition where the for loop stops if the photon escapes (when distance > Sun radius). The one I have set up already doesn't appear to work. I use a very scaled down measurement of the Sun's radius because if I didn't it would take a long time for the photon to escape in my simulation. from numpy.random import random as rng # we want them random numbers import numpy as np # for the math functions import matplotlib.pyplot as plt # to make pretty pretty class mass_proton = 1.67e-27 mass_electron = 9.11e-31 Thompson_cross = 6.65e-29 Sun_density = 150000 Sun_radius = .005 Mean_Free = (mass_proton + mass_electron)/(Thompson_cross*Sun_density*np.sqrt(2)) time_step= 10**-13 # Used this specifically in order for the path length to be &lt; Mean free Path path_length = (3e8)*time_step Probability = 1-np.exp(-path_length/Mean_Free) # Probability of the photon colliding def Random_walk(): x = 0 # Start at origin (0,0) y = 0 N = 1000 m=0 # This is a counter I have set up for the number of collisions for i in range(1,N+1): prand = rng(N+1) # Randomly generated probability if prand[i] &lt; Probability: # If my prand is less than the probability # of collision, the photon collides and changes # direction x += Mean_Free*np.cos(2*np.pi*prand) y += Mean_Free*np.sin(2*np.pi*prand) m += 1 # Everytime a collision occurs 1 is added to my collision counter distance = np.sqrt(x**2 + y**2) # Final distance the photon covers if np.all(distance) &gt; Sun_radius: # if the distance the photon travels break # is greater than the Radius of the Sun, # the for loop stops, meaning the #photon escaped print(…
has comment: http://stackoverflow.com/comment/87581061
has comment: http://stackoverflow.com/comment/87580265
has comment: http://stackoverflow.com/comment/87581136
favorite count: 0
has title: Random Walk of a Photon Through the Sun
has comment: http://stackoverflow.com/comment/87580994
has comment: http://stackoverflow.com/comment/87581230
has comment: http://stackoverflow.com/comment/87580761
type: Question
tagged with: physics
has answer: http://stackoverflow.com/a/50283471
type: UnansweredQuestion

http://stackoverflow.com/comment/87611349
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50296997
has text: The data is coming from a WITS simulator made by Erdos Miller, it's representative of a typical WITS protocol that is only used in the oil industry, so it's difficult to find a lot of information on.

http://stackoverflow.com/a/50296705
type: Answer
answers question: http://stackoverflow.com/q/50292851
score: 0
has comment: http://stackoverflow.com/comment/87627151
has body: class SomeModelSerializer(serializers.ModelSerializer): value1 = serializer.CharField(source='related_table1.name', read_only=True) value2 = serializer.CharField(source='related_table1.related_table2.name') ............ # and so on class Meta: model = ModelName fields = ( 'value1', 'value2', .... ) I think, it is not so much to write it Information about it: http://www.django-rest-framework.org/api-guide/fields/#source

http://stackoverflow.com/q/50319614
has answer: http://stackoverflow.com/a/50319805
has title: count plot with stacked bars per hue
tagged with: seaborn
tagged with: bar-chart
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/22787209
score: 19
favorite count: 0
type: Question
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/22787209
tagged with: pandas
has body: I am looking for an efficient way of drawing a count plot with stacked bars according to "hue". Standard hue behavior is to split a count into parallel bars according to the value of a second column, what I am looking for is an efficient way to have the hue bars stacked in order to quickly compare totals. Let me explain with an example from the titanic dataset: import pandas as pd import numpy as np import seaborn as sns %matplotlib inline df = sns.load_dataset('titanic') sns.countplot(x='survived',hue='class',data=df) gives standard Seaborn behavior with countplot and hue what I am looking for is something like stacked bars per hue to get the last image I used the following code def aggregate(rows,columns,df): column_keys = df[columns].unique() row_keys = df[rows].unique() agg = { key : [ len(df[(df[rows]==value) &amp; (df[columns]==key)]) for value in row_keys] for key in column_keys } aggdf = pd.DataFrame(agg,index = row_keys) aggdf.index.rename(rows,inplace=True) return aggdf aggregate('survived','class',df).plot(kind='bar',stacked=True) I am sure there is some more efficient way. I know seaborn is not very stacked bars friendly... so I tried to rearrange the dataset with my function and used matplotlib, but I guess there is a more clever way to do that as well. Thank you very much!
tagged with: stacked-chart
tagged with: python
accepted answer: http://stackoverflow.com/a/50319805
upvote count: 19

http://stackoverflow.com/q/50344738
linked to: http://stackoverflow.com/q/423379
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/423379
tagged with: file-io
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 0
has title: PYTHON - File I/O with JSON objects
has body: The problem that I am running into is that 'data' variable is not being set whenever I try to read in the json object. I only get an empty set. Below I have the code and the outputs. import json data = [] def add(name, amt): data.append({"ticker": name, "amount": amt}) def write(): with open('portfolio.json', 'w') as file: json.dump(data, file) def load(): with open('portfolio.json', 'r') as file: data = json.load(file) def main(): choice = input("Do you want to add vals? (y/n): ") if choice == 'y': add('btc', 43.2) add('xrp', 256.5) add('xmr', 655.3) print(data) write() if choice == 'n': load() print(data) main() Output 1: Do you want to add vals? (y/n): y [{'ticker': 'btc', 'amount': 43.2}, {'ticker': 'xrp', 'amount': 256.5}, {'ticker': 'xmr', 'amount': 655.3}] Press any key to continue . . . So now the file 'portfolio.json' contains the json object with all of the data, correct? So, now when I try to read that in, this is what I get: Output 2: Do you want to add vals? (y/n): n [] Press any key to continue . . . As you can see, the data variable is just an empty set, and it is not taking in the data. However, if I were to go inside the load function and print out the data variable, I would get my value.
answer count: 1
has answer: http://stackoverflow.com/a/50344866

http://stackoverflow.com/a/50359571
has comment: http://stackoverflow.com/comment/87812335
downvote count: 0
type: Answer
score: 1
has body: This is my solution as I mention in the comment df1=df.copy() df['PID']-=1000;df['PC']/=9;df['TID']-=1;df['ID']-=9 s=df.eq(0).idxmax(axis=0) s Out[492]: ID 0 PID 2 PC 0 TID 2 dtype: int64 for x ,i in s.iteritems(): df.loc[i:,x]=df1.loc[i:,x]
answers question: http://stackoverflow.com/q/50358598
upvote count: 1

http://stackoverflow.com/a/50367621
has comment: http://stackoverflow.com/comment/87756993
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50367594
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87755263
has comment: http://stackoverflow.com/comment/87754557
has comment: http://stackoverflow.com/comment/87754987
type: Answer
accepted answer of: http://stackoverflow.com/q/50367594
upvote count: 6
has body: Use the glob module to list files in a directory matching a pattern: import glob import os.path csv_files = glob.glob(os.path.join(directory_name, '*.csv')) If csv_files is a non-empty list, there are matching files. Under the hood, the glob module transforms the glob pattern to a regular expression for you (via fnmatch.translate(), runs os.listdir() on the given directory, and returns only those names that match the pattern, as full paths: &gt;&gt;&gt; import os.path, glob, tempfile &gt;&gt;&gt; with tempfile.TemporaryDirectory() as directory_name: ... pattern = os.path.join(directory_name, '*.csv') ... # nothing in the directory, empty glob ... print('CSV file count:', len(glob.glob(pattern))) ... # create some files ... for n in ('foo.csv', 'bar.txt', 'ham.csv', 'spam.png'): ... __ = open(os.path.join(directory_name, n), 'w') # touches file, creating it ... csv_files = glob.glob(pattern) ... print('CSV file count after creation:', len(csv_files)) ... for filename in csv_files: ... print(filename) ... CSV file count: 0 CSV file count after creation: 2 /var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmp2vttt0qf/foo.csv /var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmp2vttt0qf/ham.csv

http://stackoverflow.com/comment/87872982
type: Comment
has text: so you want to append new to list3, but the problem is that new is not a proper dict??
type: AnswerComment
comment on: http://stackoverflow.com/a/50306595
score: 0

http://stackoverflow.com/q/50278016
accepted answer: http://stackoverflow.com/a/50278658
tagged with: python
has comment: http://stackoverflow.com/comment/87573155
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has body: I'm running a long script which has a dataframe df. as the script runs, building up and modifying df column by column I get this error over and over again in the command line: 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 But then it will print out the line that is causing the warning and it wont look like a problem. Lines such as the following will trigger it (each line triggered it separately): df['ZIP_DENS'] = df['ZIP_DENS'].astype(str) df['AVG_WAGE'] = df['AVG_WAGE'].astype(str).apply(lambda x:x if x != 'nan' else 'unknown') df['TERM_BIN'] = df['TERMS'].map(terms_dict) df['LOSS_ONE'] = 'T_'+ df['TERM'].astype(str) +'_C_'+ df['COMP'].astype(str) + df['SIZE'] # this one's inside a loop: df[i + '_BIN'] = df[i + '_BIN'].apply(lambda x:x if x != 'nan' else 'unknown') There are some examples of the mutations I'm making on the dataframe. Now, this warning just started showing up but I can't recreate this problem in the interpreter. When I open a terminal I try things like this and it gives me no warnings: import pandas as pd df = pd.DataFrame([list('ab'),list('ef')],columns=['first','second']) df['third'] = df'first','second'.astype('str') Is there something I'm missing, something I don't understand about the nature of DataFrames that this warning is trying to tell me? Do you think perhaps I did something to this dataframe at the beginning of the script and then all subsequent mutations on the object are mutations on a view or a copy of it or something weird like that is going on?
has comment: http://stackoverflow.com/comment/87573118
type: Question
has title: Python view vs copy error wants me to use .loc in script only
has answer: http://stackoverflow.com/a/50278658

http://stackoverflow.com/comment/87613990
has text: `&` is called the bitwise and operator. It will happen to do the right thing if both values are booleans, but should not be used where `and` is desired. I wouldn't say "& is also same as and".
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50298327
type: AnswerComment

http://stackoverflow.com/comment/87711989
has text: That is true. I already forgot about that conversion But I'd still try to avoid using `.apply()`... I'll upvote your answer.
type: Comment
comment on: http://stackoverflow.com/a/50347276
type: AnswerComment
score: 1

http://stackoverflow.com/q/50239137
type: Question
tagged with: image-segmentation
has comment: http://stackoverflow.com/comment/87503764
has comment: http://stackoverflow.com/comment/87496829
has comment: http://stackoverflow.com/comment/87497188
tagged with: python
has body: I have created a net for image segmentation, in particular brain tumors. The jupyter notebook with the code is here. When I train the CNN with minibatch size of 1, I get a fairly good result: But when I change the size to something larger ( 2 or more) the results are terrible: Tensorboard shows the diference in the loss. Clearly the the net with batchsize 2 is not minimizing the loss (blue) Any ideas on why this could be the case?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50262972
score: 0
has comment: http://stackoverflow.com/comment/87497269
has answer: http://stackoverflow.com/a/50262972
has comment: http://stackoverflow.com/comment/87504364
answer count: 1
has title: Tensorflow for image segmentation: Changing minibatch size stops learning
has comment: http://stackoverflow.com/comment/87502647
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87496642

http://stackoverflow.com/q/50276640
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87570104
has comment: http://stackoverflow.com/comment/87569891
score: 1
has title: Why is pylint telling me that my dict attribute is an undefined variable?
tagged with: pylint
tagged with: python
has comment: http://stackoverflow.com/comment/87569953
has answer: http://stackoverflow.com/a/50276690
tagged with: python-3.x
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: I'm working with this code using pylint configured for python 3+: import utils valid_commands = ['category', 'help', 'exit'] def createCategory(): utils.clear() category = { name: 'test' &lt;- allegedly undefined } utils.insertCategory(category) def listActions(): utils.clear() for command in valid_commands: print(command) def exit(): utils.clear() actions = { 'category': createCategory, 'help': listActions, 'exit': exit } command = '' while command != 'exit': command = input('task_tracker&gt; ') if command in valid_commands: actions[command]() I'm getting this error: My code is running fine but the fact that this error won't go away is driving me nuts. Why is it telling me that this is undefined?

http://stackoverflow.com/comment/126655477
has text: This is gone [since April 2020](https://github.com/pypa/wheel/commit/a51977075740fda01b2c0e983a79bfe753567219) and it is clearly stated in wheel's README that there is no stable API.
comment on: http://stackoverflow.com/a/65049935
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87633039
type: Comment
has text: Thank you. Do you try my answer? How looks your code with real data? Is there some problem?
type: AnswerComment
comment on: http://stackoverflow.com/a/50307477
score: 0

http://stackoverflow.com/comment/87694791
comment on: http://stackoverflow.com/a/50338693
has text: Thanks abarnert! I'll look it tomorrow.
type: Comment
score: 0
type: AnswerComment

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

http://stackoverflow.com/q/50373530
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/87764012
linked to: http://stackoverflow.com/q/50366484
has body: I came across this question and this one both pointing to the same exercise. I want to do the same thing but using recursion. I would like to return the list of possible substrings within the full string that satisfy this condition: All letters are in alphabetical order. eg if the full string was 'abca' the function should return ['a', 'b', 'c' , 'ab', 'bc', 'abc'] in any order. My function below tries to get the number of substrings of length num from the full string s. It isn't working. the result is an empty list always. It never enters the first if statement. Please point out where I'm wrong. The statement I use to call the function is: print(recursion('abca',3)) def recursion(s, num): wrds = [] if num &gt; 1: if num &lt;= len(s) - 1: num -= 1 wrds.extend(recursion(s, num)) return wrds else: for starting_position in range(len(s) - num): for counter in range(num): if s[starting_position + counter] &lt; s[starting_position+counter - 1]: wrds.append(s[:(starting_position + counter + 1)]) return wrds else: return wrds
upvote count: 2
has answer: http://stackoverflow.com/a/50374217
has comment: http://stackoverflow.com/comment/87821957
downvote count: 0
has comment: http://stackoverflow.com/comment/87827386
has comment: http://stackoverflow.com/comment/87763239
has comment: http://stackoverflow.com/comment/87826998
has title: List of possible substrings where letters alphabetical. Recursively
favorite count: 0
type: Question
tagged with: recursion
accepted answer: http://stackoverflow.com/a/50402887
has answer: http://stackoverflow.com/a/50402887
has comment: http://stackoverflow.com/comment/87763185
possible better answer: http://stackoverflow.com/a/50374179
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50374722
has comment: http://stackoverflow.com/comment/87763421
has answer: http://stackoverflow.com/a/50374179
has answer: http://stackoverflow.com/a/50374206
has comment: http://stackoverflow.com/comment/87763345

http://stackoverflow.com/a/50300922
downvote count: 0
has comment: http://stackoverflow.com/comment/87618611
score: 3
upvote count: 3
type: Answer
has body: Put the return False after the for loop def is_square(n): if n&lt;0: return False if n == 0 or n == 1: return True if n &gt; 1: for i in range(0,n): if i*i==n: return True return False
has comment: http://stackoverflow.com/comment/87618691
answers question: http://stackoverflow.com/q/50300877

http://stackoverflow.com/q/50311861
answer count: 1
upvote count: 1
has body: I'm trying to find a way to convert a matplotlib figure to a numpy array without any white spaces or borders. I found out that if I use the code below, I'll get something pretty close, but the numpy array "data" would still have some white borders. The white border (white changes as I scale the window) is saved as part of the numpy array but I only want the content. Is there any way to get rid of this white area? fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.set_ylim(height, 0) ax.set_xlim(0, width) ax.axis('off') fig.add_axes(ax) ax.imshow(myimage) # Plus lots of other things plt.show() # fig.canvas.draw() also works the same data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) plt.close() A similar question has been asked here previously but the author's own work-around with PIL doesn't fit what I need.
tagged with: python
has answer: http://stackoverflow.com/a/50313833
favorite count: 0
linked to: http://stackoverflow.com/q/8632290
has title: matplotlib figure to numpy array without white borders
type: AnsweredQuestion
score: 1
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50313833
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87640700
downvote count: 0

http://stackoverflow.com/comment/87581953
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50281351
score: 0
has text: I edited the entry and exit rules as I understand them. If that's still not right, maybe an example list of what position you're expecting on which days would help clarify.

http://stackoverflow.com/a/50296291
type: Answer
has comment: http://stackoverflow.com/comment/87610403
has body: It sounds like you want to clone the base Conda environment. You just need to use the --clone argument with the create command. See the link to documentation below: https://conda.io/docs/user-guide/tasks/manage-environments.html#cloning-an-environment
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/95467723
has comment: http://stackoverflow.com/comment/92029155
accepted answer of: http://stackoverflow.com/q/50295907
score: 3
answers question: http://stackoverflow.com/q/50295907

python-3.x
tags question: http://stackoverflow.com/q/50282478
tags question: http://stackoverflow.com/q/50324942
tags question: http://stackoverflow.com/q/50248548
tags question: http://stackoverflow.com/q/50277675
tags question: http://stackoverflow.com/q/50363987
tags question: http://stackoverflow.com/q/50277478
tags question: http://stackoverflow.com/q/50273547
tags question: http://stackoverflow.com/q/50270049
tags question: http://stackoverflow.com/q/50356802
tags question: http://stackoverflow.com/q/50382347
tags question: http://stackoverflow.com/q/50329848
tags question: http://stackoverflow.com/q/50357948
tags question: http://stackoverflow.com/q/50278592
tags question: http://stackoverflow.com/q/50309622
tags question: http://stackoverflow.com/q/50273517
tags question: http://stackoverflow.com/q/50293639
tags question: http://stackoverflow.com/q/50232794
tags question: http://stackoverflow.com/q/50375933
tags question: http://stackoverflow.com/q/50307256
tags question: http://stackoverflow.com/q/50249012
tags question: http://stackoverflow.com/q/50341867
tags question: http://stackoverflow.com/q/50230918
tags question: http://stackoverflow.com/q/50384549
tags question: http://stackoverflow.com/q/50309671
tags question: http://stackoverflow.com/q/50359627
tags question: http://stackoverflow.com/q/50247110
tags question: http://stackoverflow.com/q/50368416
tags question: http://stackoverflow.com/q/50240030
tags question: http://stackoverflow.com/q/50339997
tags question: http://stackoverflow.com/q/50300224
tags question: http://stackoverflow.com/q/50249571
tags question: http://stackoverflow.com/q/50370901
tags question: http://stackoverflow.com/q/50329807
tags question: http://stackoverflow.com/q/50306315
tags question: http://stackoverflow.com/q/50281190
tags question: http://stackoverflow.com/q/50377335
tags question: http://stackoverflow.com/q/50274456
tags question: http://stackoverflow.com/q/50274270
tags question: http://stackoverflow.com/q/50355944
tags question: http://stackoverflow.com/q/50365414
tags question: http://stackoverflow.com/q/50317244
tags question: http://stackoverflow.com/q/50247012
tags question: http://stackoverflow.com/q/50356355
tags question: http://stackoverflow.com/q/50326423
tags question: http://stackoverflow.com/q/50269598
tags question: http://stackoverflow.com/q/50267732
tags question: http://stackoverflow.com/q/50380990
tags question: http://stackoverflow.com/q/50310493
tags question: http://stackoverflow.com/q/50316656
tags question: http://stackoverflow.com/q/50337586
tags question: http://stackoverflow.com/q/50375225
tags question: http://stackoverflow.com/q/50377176
tags question: http://stackoverflow.com/q/50301837
tags question: http://stackoverflow.com/q/50276799
tags question: http://stackoverflow.com/q/50367789
tags question: http://stackoverflow.com/q/50256081
tags question: http://stackoverflow.com/q/50367837
tags question: http://stackoverflow.com/q/50262866
tags question: http://stackoverflow.com/q/50339065
tags question: http://stackoverflow.com/q/50272670
tags question: http://stackoverflow.com/q/50375320
tags question: http://stackoverflow.com/q/50382371
tags question: http://stackoverflow.com/q/50294375
tags question: http://stackoverflow.com/q/50300976
tags question: http://stackoverflow.com/q/50235569
tags question: http://stackoverflow.com/q/50361640
tags question: http://stackoverflow.com/q/50261869
tags question: http://stackoverflow.com/q/50382629
tags question: http://stackoverflow.com/q/50370433
tags question: http://stackoverflow.com/q/50262296
tags question: http://stackoverflow.com/q/50379654
tags question: http://stackoverflow.com/q/50339895
tags question: http://stackoverflow.com/q/50312405
tags question: http://stackoverflow.com/q/50263545
tags question: http://stackoverflow.com/q/50365006
tags question: http://stackoverflow.com/q/50273640
tags question: http://stackoverflow.com/q/50342517
tags question: http://stackoverflow.com/q/50344738
tags question: http://stackoverflow.com/q/50259043
tags question: http://stackoverflow.com/q/50324400

http://stackoverflow.com/comment/87633718
has text: You never alter `self.n`.
score: 4
comment on: http://stackoverflow.com/q/50308886
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87780100
has text: I updated the code
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50381937
type: AnswerComment

pysftp
tags question: http://stackoverflow.com/q/50237335
tag name: pysftp
type: Tag

http://stackoverflow.com/comment/87651924
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50318031
score: 0
has text: You can also try this `df.loc[:, ['col1', 'col2']] = df'col1', 'col2'.clip(lower=10)`

http://stackoverflow.com/q/50359965
type: Question
has body: Base DataFrame df = pd.DataFrame(np.random.randint(0,10,size=(100,6)),columns = ['red','blue','yellow','green','purple','total']) How do I code this with a loop? df_x = df[df.columnsy,5] I'd like to apply this logic to a dataframe with many more columns, but for simplicity sake, boiled down the question into this. Below is desired output, 5 new dataframes created (Assuming I don't have to type all the 5 lines) df_red = df[df.columns[[0,5]]] df_blue = df[df.columns[[1,5]]] df_yellow = df[df.columns[[2,5]]] df_green = df[df.columns[[3,5]]] df_purple = df[df.columns[[4,5]]]
has comment: http://stackoverflow.com/comment/87736589
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50360082
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87736657
has answer: http://stackoverflow.com/a/50360082
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: How to create multiple subsets of DataFrame with loop
answer count: 1
has comment: http://stackoverflow.com/comment/87738744
has comment: http://stackoverflow.com/comment/87736824

http://stackoverflow.com/q/50242636
score: 0
has comment: http://stackoverflow.com/comment/87523051
has answer: http://stackoverflow.com/a/50243237
has body: Hello to the community, I learned some MATLAB coding skills a while ago and now I'm using python as a substitute. I would like to create a function similar to inputdlg from MATLAB. I did a little bit of coding on python in order to create a function to import data from a tkinter window e.g.,the user gives two inputs (temperature 1 and 2) and the data gets saved to a variable. However, I'm getting problems when I call the function in another script or when I paste the function code into another script. The window appears but it will not close nor will the python return from running. I assume that by mistake I made an infinite loop that is not getting solved. Can anyone help? Best regards! def input_dlg(): import tkinter as tk from tkinter import ttk class GetEntry(): def __init__(self, master): self.master=master self.master.title('Input Dialog Box') self.entry_contents=None ## Set point entries # First point self.point1 = ttk.Entry(master) self.point1.grid(row=0, column=1) self.point1.focus_set() # Second point self.point2 = ttk.Entry(master) self.point2.grid(row=1, column=1) self.point2.focus_set() # labels ttk.Label(text='First Point').grid(row=0, column=0) ttk.Label(text='Second Point').grid(row=1, column=0) ttk.Button(master, text="Done", width=10,command=self.callback).grid(row=5, column=2) def callback(self): """ get the contents of the Entries and exit the prompt""" self.entry_contents=[self.point1.get(),self.point2.get()] self.master.quit() master = tk.Tk() GetPoints=GetEntry(master) master.mainloop() Points=GetPoints.entry_contents return list(Points)
type: Question
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Extracting data from tkinter window. Geting a function similar to Matlab's inputdlg

http://stackoverflow.com/comment/87616378
comment on: http://stackoverflow.com/q/50299811
has text: Is the array guaranteed to be sorted?
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/q/50298244
tagged with: excel
type: Question
has body: I'm starting baby steps on python and I have to merge 2 excel spread sheet books into just one. The books contain the same structure and they are in .txt format. Which quote do you recommend me to merge then, I have been working on this: import numpy as np import pandas as pd bd1 = pd.read_excel (r' \\C:..xls, sheet_name= "Sheet1") bd2 = pd.read_excel (r' \\C:..xls, sheet_name= "Sheet1", header = "none",skiprows=1) bd3_new= pd.merge('bd1','bd2') bd3_new.to_excel(r'\\C....) Thanks for your help
type: UnansweredQuestion
tagged with: python
has title: Simple Excel Merge
has comment: http://stackoverflow.com/comment/87614801
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87613392
has comment: http://stackoverflow.com/comment/87613501

http://stackoverflow.com/comment/87552413
type: Comment
comment on: http://stackoverflow.com/a/50260345
score: 0
type: AnswerComment
has text: @wasay You should not only use the code, but also the correct YAML file. Your YAML input doesn't have 361 lines, so you are testing with the incorrect `test.yaml` (alternatively you should post a **new** question that has the relevant part of that other `test.yaml`, line 361 and context, included).

http://stackoverflow.com/comment/87548972
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50265314
has text: @Jimbo - Is possible use `conv` function from [this](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#representing-out-of-bounds-spans) ?
score: 0

python
tags question: http://stackoverflow.com/q/50299868
tags question: http://stackoverflow.com/q/50302238
tags question: http://stackoverflow.com/q/50290298
tags question: http://stackoverflow.com/q/50261285
tags question: http://stackoverflow.com/q/50287990
tags question: http://stackoverflow.com/q/50239473
tags question: http://stackoverflow.com/q/50345763
tags question: http://stackoverflow.com/q/50368207
tags question: http://stackoverflow.com/q/50273308
tags question: http://stackoverflow.com/q/50305223
tags question: http://stackoverflow.com/q/50233916
tags question: http://stackoverflow.com/q/50244224
tags question: http://stackoverflow.com/q/50305572
tags question: http://stackoverflow.com/q/50293947
tags question: http://stackoverflow.com/q/50309815
tags question: http://stackoverflow.com/q/50275860
tags question: http://stackoverflow.com/q/50299811
tags question: http://stackoverflow.com/q/50277199
tags question: http://stackoverflow.com/q/50302082
tags question: http://stackoverflow.com/q/50303654
tags question: http://stackoverflow.com/q/50361325
tags question: http://stackoverflow.com/q/50365436
tags question: http://stackoverflow.com/q/50265501
tags question: http://stackoverflow.com/q/50378970
tags question: http://stackoverflow.com/q/50244202
tags question: http://stackoverflow.com/q/50383582
tags question: http://stackoverflow.com/q/50274211
tags question: http://stackoverflow.com/q/50279905
tags question: http://stackoverflow.com/q/50313107
tags question: http://stackoverflow.com/q/50241195
tags question: http://stackoverflow.com/q/50271267
tags question: http://stackoverflow.com/q/50357490
tags question: http://stackoverflow.com/q/50357142
tags question: http://stackoverflow.com/q/50310526
tags question: http://stackoverflow.com/q/50356723
tags question: http://stackoverflow.com/q/50321037
tags question: http://stackoverflow.com/q/50335544
tags question: http://stackoverflow.com/q/50377479
tags question: http://stackoverflow.com/q/50378877
tags question: http://stackoverflow.com/q/50379530
tags question: http://stackoverflow.com/q/50233156
tags question: http://stackoverflow.com/q/50337843
tags question: http://stackoverflow.com/q/50326052
tags question: http://stackoverflow.com/q/50378906
tags question: http://stackoverflow.com/q/50255930
tags question: http://stackoverflow.com/q/50350632
tags question: http://stackoverflow.com/q/50251435
tags question: http://stackoverflow.com/q/50239793
tags question: http://stackoverflow.com/q/50252114
tags question: http://stackoverflow.com/q/50341071
tags question: http://stackoverflow.com/q/50250432
tags question: http://stackoverflow.com/q/50251821
tags question: http://stackoverflow.com/q/50254594
tags question: http://stackoverflow.com/q/50303449
tags question: http://stackoverflow.com/q/50282453
tags question: http://stackoverflow.com/q/50318330
tags question: http://stackoverflow.com/q/50304607
tags question: http://stackoverflow.com/q/50380479
tags question: http://stackoverflow.com/q/50263472
tags question: http://stackoverflow.com/q/50263858
tags question: http://stackoverflow.com/q/50346498
tags question: http://stackoverflow.com/q/50304993
tags question: http://stackoverflow.com/q/50263712
tags question: http://stackoverflow.com/q/50320939
tags question: http://stackoverflow.com/q/50295488
tags question: http://stackoverflow.com/q/50303307
tags question: http://stackoverflow.com/q/50293090
tags question: http://stackoverflow.com/q/50283933
tags question: http://stackoverflow.com/q/50296546
tags question: http://stackoverflow.com/q/50278332
tags question: http://stackoverflow.com/q/50314574
tags question: http://stackoverflow.com/q/50300679
tags question: http://stackoverflow.com/q/50317553
tags question: http://stackoverflow.com/q/50383210
tags question: http://stackoverflow.com/q/50281762
tags question: http://stackoverflow.com/q/50302209
tags question: http://stackoverflow.com/q/50376081
tags question: http://stackoverflow.com/q/50251073
tags question: http://stackoverflow.com/q/50303670
tags question: http://stackoverflow.com/q/50333432

http://stackoverflow.com/q/50253392
type: Question
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49353097
has comment: http://stackoverflow.com/comment/87709969
has body: I want to perform Global Sensitivity Analysis using Python after importing my model from Dymola. I have a detailed One Family house model in Dymola and want to perform sensitivity Analysis to check the effect of different Parameters,in the total energy consumption, throughout the whole year. Is there any suggestions or examples regarding this issue?
has title: Performing Global Sennsitivity Analysis using Python after importing model from Dymola
has answer: http://stackoverflow.com/a/50347332
score: 0
tagged with: analysis
answer count: 1
tagged with: dymola

http://stackoverflow.com/comment/102996128
type: AnswerComment
has text: thanks for the insight. it's really helpful to see future possibilities.
type: Comment
comment on: http://stackoverflow.com/a/58306989
score: 0

http://stackoverflow.com/a/50282957
has comment: http://stackoverflow.com/comment/87625558
has comment: http://stackoverflow.com/comment/87854533
accepted answer of: http://stackoverflow.com/q/50279667
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50279667
has body: You'll probably find this easier to do with animation constraints rather than doing it with math. You would point-constrain the light to both locators at equal weight -- that will place it halfway between them. Then aim-constrain it to point at one of them with the world up as the 'side vector' and a rotation offset to keep the light from flipping (it's an area light, yes?) def area_light_between(target1, target2): lightShape = cmds.createNode('areaLight') lightXform = cmds.listRelatives(lightShape, p=True) #You can get the distance manually without creating a distance dimension: start = cmds.xform(target1, q=True, t=True) end = cmds.xform(target2, q=True, t=True) difference = [end[k] - start[k] for k in range(3)] distance = math.sqrt(difference[0]**2 + difference[1]**2 + difference[2]**2) cmds.xform(lightXform, s = (distance / 2.0, 0.1, 1)) # constrain the light between the targets # use the mo=False flag so you don't keep the offset cmds.pointConstraint(target1, target2,lightXform, mo = False) # add the aim constraint (your world-up vector may vary) cmds.aimConstraint(target2, lightXform, worldUpVector = (0,0,1), aimVector=(1,0,0), upVector = (0,0,1), mo = False) return lightXform area_light_between('pSphere1', 'pSphere2') My scene is Z-Up so I have to specify a world up vector of (0,0,1) -- if you're using vanilla Maya Y-up your worldUpVector will be (0,1,0). As with any aim constraint situation you'll get flipping if the aim vector gets too close to the up vector -- you'll have to handle that if you do it this way or with pure math. One nice advantage of this is that you can edit the constraints after the fact to offset the position or aim while retaining the overall relationship.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87638820
has comment: http://stackoverflow.com/comment/87851964
has comment: http://stackoverflow.com/comment/87632766
has comment: http://stackoverflow.com/comment/87625369
type: Answer

http://stackoverflow.com/a/50288573
has comment: http://stackoverflow.com/comment/87599082
answers question: http://stackoverflow.com/q/50287024
has comment: http://stackoverflow.com/comment/87602988
type: Answer
has comment: http://stackoverflow.com/comment/117189676
has comment: http://stackoverflow.com/comment/87598301
has body: You could try updating the Macro settings in the registry to allow all macros to run. You would need to either run your Python script as an administrator, or ensure that the registry key has suitable permissions: import winreg import os import win32com.client def registry_set_key(hive, regpath, key, type, value): try: hkey = winreg.OpenKey(hive, regpath, 0, winreg.KEY_ALL_ACCESS) except FileNotFountError as e: hkey = winreg.CreateKey(hive, regpath, 0, winreg.KEY_ALL_ACCESS) try: old = winreg.QueryValueEx(hkey, key) except: old = None winreg.SetValueEx(hkey, key, 0, type, value) winreg.CloseKey(hkey) return old if os.path.exists(r"C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm"): # Set macro settings to 1 to allow all macros old = registry_set_key(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Office\14.0\Excel\Security', 'VBAWarnings', winreg.REG_DWORD, 1) xl = win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm") xl.Visible = True xl.Run('Mem_Leak') # If there was an existing value, put it back if old: registry_set_key(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Office\14.0\Excel\Security', 'VBAWarnings', winreg.REG_DWORD, old[0]) Note, you might need to adjust the registry path depending on the version of Office installed, use REGEDIT to check. i.e. make sure that Office\14.0 is present. Also take a look at Microsoft Project – how to control Macro Settings using registry keys for more information.
score: 0

http://stackoverflow.com/a/50244541
upvote count: 2
has comment: http://stackoverflow.com/comment/87517457
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50244523
has comment: http://stackoverflow.com/comment/87507477
has comment: http://stackoverflow.com/comment/87507425
type: Answer
has comment: http://stackoverflow.com/comment/87507402
has body: You can use iexact in your filter, A case-insensitive exact match. retailer_deals = Deal.objects.filter( field_name__iexact=retailer).order_by('expired','-date_added') As many of other people suggest, the best way is to do such query with slug, so you would have: from django.template.defaultfilters import slugify import uuid class YourModel(mdoels): slug = models.SlugField() name = models.CharField(max_mength=100) # override the save method to have slug automatically generated def save(self, *args, **kwargs): if self.pk is None: slug = slugify(self.name) while self.__class__.objects.filter(slug=slug).exists(): slug = "%s-%s" % (slug,str(uuid.uuid4())[:5]) self.slug = slug super(YourModel, self).save(*args, **kwargs) your url would become: path('retailer-deals/&lt;slug:slug&gt;', deals_by_retailer, name='retailer'), and your views: def deals_by_retailer(request,slug): retailer_deals = Deal.objects.filter(retailer__slug=slug) ''' codes '''

http://stackoverflow.com/a/63016968
score: 2
has body: You can use boto3 client to query Athena tables. You can read more about it here: Simple way to query Amazon Athena in python with boto3
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50291963

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

http://stackoverflow.com/comment/87488014
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50234968
has text: In that case, you can just do `from example2 import *` - not the best way to do it, but will work. I will update the answer to include another usecase.

http://stackoverflow.com/comment/87539962
type: Comment
comment on: http://stackoverflow.com/q/50260825
score: 0
has text: Maybe your mime types are misconfigured? Try [these tips](https://stackoverflow.com/help/how-to-ask) to get more, better, and faster answers.
type: QuestionComment

http://stackoverflow.com/q/50339345
has comment: http://stackoverflow.com/comment/87694982
has comment: http://stackoverflow.com/comment/87695002
duplicate of: http://stackoverflow.com/q/11792629
has comment: http://stackoverflow.com/comment/87695013
answer count: 0
linked to: http://stackoverflow.com/q/18864859
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87695133
linked to: http://stackoverflow.com/q/11792629
has comment: http://stackoverflow.com/comment/87694970
tagged with: python
has comment: http://stackoverflow.com/comment/87695174
duplicate of: http://stackoverflow.com/q/18864859
has comment: http://stackoverflow.com/comment/87695074
has comment: http://stackoverflow.com/comment/87694978
has body: I have been working on a small project of mine. It's pretty much a robot that goes forward using a gyroscope. I am aiming for very high accuracy in this case. I have two commands, which stop the motors. The problem is that there's a small delay between the two and I constantly get 3-5mm errors on the same motor (the one that gets stopped one line later). Due to the nature of my program, I cannot tell that specific motor to 'do 3-5 mm less'. Is there a way I could speed this up in any way? def stop_motors(): p1 = Process(target=stop_left()); p2 = Process(target=stop_right()); p1.start(); p2.start(); def stop_left(): MotorLeft.stop(stop_action='hold'); MotorLeft.reset(); def stop_right(): MotorRight.stop(stop_action='hold'); MotorRight.reset(); I tried this, same results.
score: 0
has comment: http://stackoverflow.com/comment/87695048
has comment: http://stackoverflow.com/comment/87695177
has comment: http://stackoverflow.com/comment/87695241
has comment: http://stackoverflow.com/comment/87695187
has comment: http://stackoverflow.com/comment/87695027
has comment: http://stackoverflow.com/comment/87695073
has comment: http://stackoverflow.com/comment/87695255
has comment: http://stackoverflow.com/comment/87694975
type: Question
has comment: http://stackoverflow.com/comment/87695278
has comment: http://stackoverflow.com/comment/87695001
has title: Is there a way in Python to fire two lines at once?

http://stackoverflow.com/q/50296427
has comment: http://stackoverflow.com/comment/87609923
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87609897
duplicate of: http://stackoverflow.com/q/24140114
tagged with: algorithm
has body: Algo (Source: Elements of Programming Interviews, 5.16) You are given n numbers as well as probabilities p0, p1,.., pn-1 which sum up to 1. Given a rand num generator that produces values in [0,1] uniformly, how would you generate one of the n numbers according to their specific probabilities. Example If numbers are 3, 5, 7, 11, and the probabilities are 9/18, 6/18, 2/18, 1/18, then in 1000000 cals to the program, 3 should appear 500000 times, 7 should appear 111111 times, etc. The book says to create intervals p0, p0 + p1, p0 + p1 + p2, etc so in the example above the intervals are [0.0, 5.0), [0.5, 0.0.8333), etc and combining these intervals into a sorted array of endpoints could look something like [1/18, 3/18, 9/18, 18/18]. Then run the random function generator, and find the smallest element that is larger than the generated element - the array index that it corresponds to maps to an index in the given n numbers. This would require O(N) pre-processing time and then O(log N) to binary search for the value. I have an alternate solution that requires O(N) pre-processing time and O(1) execution time, and am wondering what may be wrong with it. Why can't we iterate through each number in n, multiplying [n] * 100 * probability that matches with n. E.g [3] * (9/18) * 100. Concatenate all these arrays to get, at the end, a list of 100 elements, with the number of elements for each mapping to how likely it is to occur. Then, run the random num function and index into the array, and return the value. Wouldn't this be more efficient than the provided solution?
score: 1
has comment: http://stackoverflow.com/comment/87609862
tagged with: python
has title: Generate non-uniform random numbers
answer count: 2
possible better answer: http://stackoverflow.com/a/50296535
accepted answer: http://stackoverflow.com/a/50296509
upvote count: 2
has answer: http://stackoverflow.com/a/50296535
has answer: http://stackoverflow.com/a/50296509
tagged with: arrays
linked to: http://stackoverflow.com/q/24140114
downvote count: 1
favorite count: 0
type: Question

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/50242278
tags question: http://stackoverflow.com/q/50296981
tags question: http://stackoverflow.com/q/50250264
tags question: http://stackoverflow.com/q/50305831
tags question: http://stackoverflow.com/q/50265160
tags question: http://stackoverflow.com/q/50359589
tags question: http://stackoverflow.com/q/50328620
tags question: http://stackoverflow.com/q/50368286
tags question: http://stackoverflow.com/q/50281488
tags question: http://stackoverflow.com/q/50346065
tags question: http://stackoverflow.com/q/50248626
tags question: http://stackoverflow.com/q/50278592
tags question: http://stackoverflow.com/q/50260242
tags question: http://stackoverflow.com/q/50289703
tags question: http://stackoverflow.com/q/50245685
tags question: http://stackoverflow.com/q/50358481
tags question: http://stackoverflow.com/q/50233842
tags question: http://stackoverflow.com/q/50319394
tags question: http://stackoverflow.com/q/50284013
tags question: http://stackoverflow.com/q/50266369
tags question: http://stackoverflow.com/q/50343999
tags question: http://stackoverflow.com/q/50323471
tags question: http://stackoverflow.com/q/50343119
tags question: http://stackoverflow.com/q/50251447
tags question: http://stackoverflow.com/q/50374375
tags question: http://stackoverflow.com/q/50241887
tags question: http://stackoverflow.com/q/50304858
tags question: http://stackoverflow.com/q/50355697
tags question: http://stackoverflow.com/q/50287816
tags question: http://stackoverflow.com/q/50277322
tags question: http://stackoverflow.com/q/50307049
tags question: http://stackoverflow.com/q/50292851
tags question: http://stackoverflow.com/q/50312181
tags question: http://stackoverflow.com/q/50272980
tags question: http://stackoverflow.com/q/50242919
tags question: http://stackoverflow.com/q/50288476
tags question: http://stackoverflow.com/q/50308614
tags question: http://stackoverflow.com/q/50255240
tags question: http://stackoverflow.com/q/50338341
type: Tag
tags question: http://stackoverflow.com/q/50377905
tags question: http://stackoverflow.com/q/50310878

http://stackoverflow.com/a/50369405
upvote count: 1
has comment: http://stackoverflow.com/comment/87755033
has comment: http://stackoverflow.com/comment/87766587
has body: With classes, you have no need to use globals. At the moment you have a strange mix between global tkinter widgets and those owned by the ConcreteElement class. I've created a new version of your code that might show you how to better achieve your end result. Based on your description, the below should work from tkinter import * from tkinter import ttk myApp = Tk() myApp.title("Kalkulator za materijal") myApp.geometry("450x850") class ConcreteElement(object): def __init__(self,myApp): self.Label1=Label(myApp, text="Answer") self.Label1.grid(row=0,column=1) self.ColumnNumber = 1 #Create a blank list to store our entries self.EntryBoxList = [] #Create the answer entry box self.Answer=Entry(myApp) self.Answer.grid(row=1,column=self.ColumnNumber) newbutton=Button(myApp, text="add", command=self.NewElement) newbutton.grid(row=4,column=1) buttonsum=Button(myApp, text="sum", command=self.summing) buttonsum.grid(row=2,column=1) def NewElement(self): self.ColumnNumber +=1 self.LabelNew=Label(myApp, text="New Entry") self.LabelNew.grid(row=0,column=self.ColumnNumber) #Create a new entry box and add it to the list EntryNew=Entry(myApp) EntryNew.grid(row=1,column=self.ColumnNumber) self.EntryBoxList.append(EntryNew) def summing(self): x=0 for box in self.EntryBoxList: x += float(box.get()) self.Answer.delete(0,"end") self.Answer.insert(0,x) ConcreteElement=ConcreteElement(myApp) myApp.mainloop() You will also note I've added a list to the class. With you orignal code you had no way of remembering what boxes you had created. By adding a list, I can now iterate though all the boxes and sum the contents.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50368939
has comment: http://stackoverflow.com/comment/87790665
downvote count: 0

http://stackoverflow.com/q/50376282
tagged with: replace
answer count: 1
type: Question
has body: I'm using the following code to read 1 million rows of SQL data and replace any control characters which might appear in the data, the only problem is that is slow and it is definitely the 'replace' which is slowing it down. Anyone have any suggestion about taking a different approach or tweaking to might make the code any faster? d = {} x = map(chr, list(range(0,9)) + list(range(11,13)) + list(range(14,32)) + list(range(127,160))) for item in list(x): d.update({item:' '}) with open("out_cleaned.csv", "w", encoding='utf-8') as fh: chunks = pd.read_sql_query(SQLCommand, connection, chunksize=10000) c = next(chunks) c.replace(d, regex=True, inplace=True) c.to_csv(fh, index=False, header=False, sep='\t', chunksize=10000) for chunk in chunks: chunk.replace(d, regex=True, inplace=True) chunk.to_csv(fh, index=False, header=False, sep='\t', chunksize=10000) Takes 16 minutes to read, clean and write out 1 million rows (of 31 fields.)
accepted answer: http://stackoverflow.com/a/50380426
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50380426
tagged with: pandas
has title: Python 3.6: Speed up regex replace in Pandas dataframe
tagged with: python

http://stackoverflow.com/a/50367128
score: 12
upvote count: 12
downvote count: 0
has body: That's what TypeVar is for: from typing import TypeVar, List T = TypeVar('T') def make_list(el: T) -&gt; List[T]: return [el, el]
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50367007
type: Answer
accepted answer of: http://stackoverflow.com/q/50367007

http://stackoverflow.com/a/50325764
score: 0
has body: you are passing a relative path when you should probably enter an absolute.
answers question: http://stackoverflow.com/q/50325431
type: Answer

http://stackoverflow.com/a/50241911
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50241698
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50241698
has body: This is just syntactic sugar but does the job. @np.vectorize def apply_vec(f, x): return f(x) result = apply_vec(functionMatrix, valueMatrix)

http://stackoverflow.com/q/50237676
tagged with: python
has body: I'm using asyncio to make TCP connections: reader, writer = await asyncio.open_connection(addr) I need to keep connections alive. For this, I'm storing a pair of (reader, writer) for future communications. However, I don't know when reader has data to read. What can I do with it? Is there a way to make a handler, when the reader is ready?
type: AnsweredQuestion
tagged with: python-asyncio
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50241573
favorite count: 0
type: Question
has title: How to know when StreamReader is ready?
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/50241573
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50282218
has answer: http://stackoverflow.com/a/50307297
tagged with: python
has title: Graph creation problems in Tensorboard from Google Developers videos
has body: So I was watching the Google Developers video on youtube Hands-on TensorBoard (TensorFlow Dev Summit 2017) and I have a lot of problem recreating his graph at time 6:01. The following is my code: import tensorflow as tf #1. add some name for w and b #2. apply name scope def conv_layer(input, channels_in, channels_out, name = "conv"): with tf.name_scope(name): w = tf.Variable(tf.zeros([5, 5, channels_in, channels_out]), name = "W") b = tf.Variable(tf.zeros([channels_out]), name = "B") conv = tf.nn.conv2d(input, w, strides=[1, 1, 1, 1], padding="SAME") act = tf.nn.relu(conv + b) return act #1. add some name for w and b #2. apply name scope def fc_layer(input, channels_in, channels_out, name = "fc"): with tf.name_scope(name): w = tf.Variable(tf.zeros([channels_in, channels_out]), name = "W") b = tf.Variable(tf.zeros([channels_out]), name = "B") act = tf.nn.relu(tf.matmul(input,w) + b) return act #1. add some name for placeholders, cov layer, fc, logits #2. apply name scope # Setup placeholders, and reshape the data x = tf.placeholder(tf.float32, shape=[None, 784], name = "x") y = tf.placeholder(tf.float32, shape=[None, 10], name = "labels") x_image = tf.reshape(x, [-1, 28, 28, 1]) conv1 = conv_layer(x_image, 1, 32, "conv1") pool1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides = [1,2,2,1], padding = "SAME") conv2 = conv_layer(pool1, 32, 64, "conv2") pool2 = tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides = [1,2,2,1], padding = "SAME") flattened = tf.reshape(pool2, [-1, 7*7*64]) fcl = fc_layer(flattened, 7*7*64, 1024, "fcl") logits = fc_layer(fcl, 1024, 10, "fc2") added name scope and changed the name for cross_entropyu with tf.name_scope("xent"): xent = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels = y)) #cross_entropy = tf.reduce_mean( # tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = y)) with tf.name_scope("train"): train_step = tf.train.AdamOptimizer(1e-4).minimize(xent) with tf.name_scope("accuracy"): correct_predic…
downvote count: 0
upvote count: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: tensorboard

http://stackoverflow.com/comment/87609062
has text: If we cancel out all the `m`s from all sides of all equations and substitute the second and third equation in the first one, we still get an equation that contains both `u` and `v` in it. So I think you system of equations has no unique solution.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50290678

http://stackoverflow.com/q/50307049
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
score: 0
tagged with: django-views
has title: adding badges to user for doing tasks in django
has body: Hi Djangonauts, How is everyone today, I am new to Django so please forgive any silly mistakes in logic or code. I have a user, a User_Profile and a posts model. I want to give the user badges for the number of posts the user posts. Example if the user posts 3 posts he/she gets a beginner badge and so on... Below is my user Profile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(default='', blank=True, null=True) badge_image = models.ImageField(default='', blank=True, null=True)#maybe default can be "static/images/beginner_image.jpg" but it does not work posts models.py User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() Now I want to achieve something like this: user = User.objects.get(username=request.user.username) if user.posts.count &gt;= 3 : badge_image = '&lt;img src="some image"&gt;'# I don't know how to make a image variable in views and models. I know how to use it in Django templates with {{image.url}} elif user.posts.count &gt;= 20 : badge_image = '&lt;img src="some image"&gt;' else: badge_image ='&lt;img src="beginner_image"&gt;' Where do I write this code in the models, in the views? I am sorry if my questions are too basic. None of the projects I learned had a similar scenario
answer count: 1
has answer: http://stackoverflow.com/a/50307215
accepted answer: http://stackoverflow.com/a/50307215
type: Question

http://stackoverflow.com/comment/87656369
comment on: http://stackoverflow.com/a/50319770
type: AnswerComment
has text: yes just saw that. it should be OK. The last command I can do df=py$get_similar_CRs(arg1, arg2) and then do further processing.
score: 0
type: Comment

http://stackoverflow.com/a/74390823
has comment: http://stackoverflow.com/comment/131395597
answers question: http://stackoverflow.com/q/50302180
type: Answer
score: 0
has body: df['label']----single column df'label'----multiple columns for eg: if 'labels' are independent variables , and 'able' is a target variable, then when plotting it is as df'labels' and df['able'].

http://stackoverflow.com/comment/87607839
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50295399
score: 0
has text: ktzr - done! jdehasa - didn't work.

http://stackoverflow.com/a/50308132
downvote count: 1
has comment: http://stackoverflow.com/comment/87648036
accepted answer of: http://stackoverflow.com/q/50307707
score: 100
type: Answer
answers question: http://stackoverflow.com/q/50307707
has body: I'm referring to the question in the title as you haven't really specified anything else in the text, so just converting the DataFrame into a PyTorch tensor. Without information about your data, I'm just taking float values as example targets here. Convert Pandas dataframe to PyTorch tensor? import pandas as pd import torch import random # creating dummy targets (float values) targets_data = [random.random() for i in range(10)] # creating DataFrame from targets_data targets_df = pd.DataFrame(data=targets_data) targets_df.columns = ['targets'] # creating tensor from targets_df torch_tensor = torch.tensor(targets_df['targets'].values) # printing out result print(torch_tensor) Output: tensor([ 0.5827, 0.5881, 0.1543, 0.6815, 0.9400, 0.8683, 0.4289, 0.5940, 0.6438, 0.7514], dtype=torch.float64) Tested with Pytorch 0.4.0. I hope this helps, if you have any further questions - just ask. :)
upvote count: 101
has comment: http://stackoverflow.com/comment/140180418
has comment: http://stackoverflow.com/comment/106124733
has comment: http://stackoverflow.com/comment/87647909
has comment: http://stackoverflow.com/comment/112192950
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87648148
has comment: http://stackoverflow.com/comment/87676092

http://stackoverflow.com/q/50337544
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/50341645
tagged with: python
has body: :) I develop a Android Cook-App with a Meal price calculation. I nearly finished my Api but now I get a TypeError: 'RelationshipProperty' object is not iterable. I struggle with my sum(mealprice) I have my json but I like to query my mealprice with @classmethod def find_by_mealprice(cls, mealprice): return cls.query.filter_by(mealprice=mealprice).first() But I can only build my sum in the json method. class MealModel(db.Model): __tablename__ = 'meal' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) description = db.Column(db.String) usp = db.Column(db.String) workTime = db.Column(db.TIME) mainIngredients =db.Column(db.String) img = db.Column(db.String) difficulty_id = db.Column(db.Integer, db.ForeignKey('difficulty.id')) difficulty = db.relationship('DifficultyModel') diet_id = db.Column(db.Integer, db.ForeignKey('diet.id')) diet = db.relationship('DietModel') category_id = db.Column(db.Integer, db.ForeignKey('category.id')) category = db.relationship('CategoryModel') recipes = db.relationship('RecipeModel', lazy="dynamic") mealprice = (sum([(recipe.ingredients.price/recipe.ingredients.minamount * recipe.quantity) for recipe in recipes])) &lt;-- TypeError? def __repr__(self): return (self.name) def json(self): mealprice = (sum([(recipe.ingredients.price/recipe.ingredients.minamount * recipe.quantity) for recipe in self.recipes])) return { 'id': self.id, 'name': self.name, 'mIng': self.mainIngredients, 'usp': self.usp, 'difficulty': self.difficulty.name, 'workTime': self.workTime.isoformat(), 'diet': self.diet.name, 'description': self.description, 'mealImage': self.img, 'category': self.category.name, 'recipes': [recipe.json() for recipe in self.recipes], 'meal_price': mealprice } I hope this Question is not to stupid, I am newish in Flask Api and Python, I startet programming a few months ago with Android Studio. I hope you can help! :) How can I query with mealprice??
has title: 'RelationshipProperty' object is not iterable - Flask Api - sqlalchemy
downvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/50373689
accepted answer of: http://stackoverflow.com/q/50372641
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50372641
has body: Giving columns a weight does not force the columns to have an equal size, but forces them to grow at the same rate. From effbot: weight= A relative weight used to distribute additional space between columns. A column with the weight 2 will grow twice as fast as a column with weight 1. The default is 0, which means that the column will not grow at all. Then from the documentation of the Text widget (off of which the ScrolledText is based) you can see that the default width of the widget is 80 (characters, not pixels!), while the Listbox has a default width of 20 (again, characters). So while both columns grow at the same rate, they do not start off at the same size. Now if you give both widgets the same width value, you might see that they are still not the same width. This can happen because the fonts for the Text and Listbox widgets are not the same. If you give them both the same width and the same font, they should have the same width to start off with, so they will stay the same width when they grow: from tkinter import * from tkinter.scrolledtext import * page = Tk() page.rowconfigure(1, weight=1) page.columnconfigure(0, weight=1) page.columnconfigure(6, weight=1) lb_reports = Listbox(page, selectmode=SINGLE, font=('Arial', 12), width=20) lb_reports.grid(row=1, column=0, columnspan=5, sticky=W + N + S + E, pady=5, padx=5) st_test = ScrolledText(page, font=('Arial', 12), width=20) st_test.grid(row=1, column=6, columnspan=5, sticky=W + N + S + E, pady=5, padx=5) page.mainloop()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87778672
has text: I thought perhaps I needed the '\n' to get rid of the white space. I print out the rows after each iteration and have no white spaces in the cmd line output. However, when I open up the file I have all the white space. Scratching my head.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50379814
type: AnswerComment

http://stackoverflow.com/comment/87557030
score: 0
type: AnswerComment
has text: In that case, what `del` does is remove the 'foo' entry in the `vars()` dict. Since it's the only reference, the object cannot be referenced, *even if you knew its id*.
type: Comment
comment on: http://stackoverflow.com/a/50264311

http://stackoverflow.com/a/50261082
has comment: http://stackoverflow.com/comment/87540325
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50260946
upvote count: 2
answers question: http://stackoverflow.com/q/50260946
has body: You've called your own script pdfminer.py which is now shadowing the module you're trying to import. Rename your script. You can see this in the traceback: File "C:\Users\me\Documents\myprog\pdfminer.py", line 4, in &lt;module&gt; That isn't the path that you installed the package on, but we can see that there is a file called pdfminer.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87484827
has text: How does selecting subcat1 result in subcat2 results?
comment on: http://stackoverflow.com/q/50233302
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87714595
has text: Look at `ast.literal_eval`. (Must be a dupe).
type: Comment
comment on: http://stackoverflow.com/q/50349433
type: QuestionComment
score: 1

http://stackoverflow.com/q/50230160
has answer: http://stackoverflow.com/a/50231115
tagged with: python
possible better answer: http://stackoverflow.com/a/50230421
answer count: 4
has title: Extract departure and arrival from a list
score: 2
type: AnsweredQuestion
has body: I'm trying to extract some parameters from a list whose the structure and the length are variable. Basically, these parameters are the departure and the arrival addresses for a route. This list is built from a sentence in natural language so it does not follow any particular template: 1st example : ['go', 'Buzenval', 'from', 'Chatelet'] 2nd example : ['How', 'go', 'street', 'Saint', 'Augustin', 'from', 'Buzenval'] 3rd example : ['go', 'from', '33', 'street', 'Republique', 'to', '12','street','Napoleon'] I already managed to create another list that is pretty much similar, for each case, except the departure and arrival are replaced by the actual words 'departure' and 'arrival'. With the examples above I obtain: 1st example : ['go', 'arrival', 'from', 'departure'] 2nd example : ['How', 'go', 'arrival', 'from', 'departure'] 3rd example : ['go', 'from', 'departure', 'to', 'arrival'] Now that I have these two kind of lists, I would like to identify departure and arrival : 1rst example : departure = ['Chatelet'], arrival = ['Buzenval'] 2nd example : departure = ['Buzenval'], arrival = ['street','Saint','Augustin'] 3rd example : departure = ['33','street','Republique'], arrival = ['12','street','Napoleon'] Basically, the parameters are everything that are different in the two lists, but I need to identify which one is the departure and which one is the arrival. I think Regex could help me on this one but I don't know how. Thanks for your help!
tagged with: list
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50230709
accepted answer: http://stackoverflow.com/a/50230709
has answer: http://stackoverflow.com/a/50230421
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50231149
tagged with: identification

http://stackoverflow.com/comment/87518152
comment on: http://stackoverflow.com/q/50249305
score: 0
type: Comment
type: QuestionComment
has text: Thanks a lot! Are you sure Instagram lets me do so through their API? @DanielRoseman

http://stackoverflow.com/comment/87734871
comment on: http://stackoverflow.com/q/50338607
type: QuestionComment
score: 0
has text: There is not a specific reason that I cannot create the figure first. The reason I asked is that occasionally it is useful to plot data, and then mess with the aesthetics without having to replot everything.
type: Comment

http://stackoverflow.com/comment/87761058
score: 0
comment on: http://stackoverflow.com/q/50372272
has text: related: https://stackoverflow.com/questions/30926670/pandas-add-multiple-empty-columns-to-dataframe
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87806220
type: AnswerComment
score: 0
type: Comment
has text: So if there's no way to "write" to tarfile how do I "catch" or receive the tarfle being sent in .tar.gz format? This is the crux of what I'm looking for.
comment on: http://stackoverflow.com/a/50380313

http://stackoverflow.com/comment/87764113
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50373524
has text: Hmm, well it was yours I actually used :\ Maybe they could be combined? I am going to upvote both now anyway.
score: 0

http://stackoverflow.com/q/50382729
accepted answer: http://stackoverflow.com/a/50382865
downvote count: 0
has answer: http://stackoverflow.com/a/50382865
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50382948
upvote count: 2
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/50382774
tagged with: python
has answer: http://stackoverflow.com/a/50382774
has comment: http://stackoverflow.com/comment/87781477
score: 2
has body: I have a nested list: [['spam', 'eggs'], ['spam', 'eggs', '111'], ['spam', 'eggs', 'foo'], ['spam', 'eggs', '111', 'bar'], ['spam', 'eggs', 'foo', 'bar']] What I need is an algorithm to get indexes of shorter sublists, all elements of which are contained in longer ones. In this example algorithm should return: [0, 1, 2] Any help would be appreciated!
type: AnsweredQuestion
has title: Filtering out shorter sublists
tagged with: list
answer count: 3

http://stackoverflow.com/comment/87732810
comment on: http://stackoverflow.com/q/50356884
type: Comment
type: QuestionComment
has text: Did you try doing `data.Storage.hist()`?
score: 0

http://stackoverflow.com/a/50305902
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50305858
answers question: http://stackoverflow.com/q/50305858
type: Answer
has body: You can build a template string like that: &gt;&gt;&gt; template_string = "You have purchased %s bananas for price of %s" And then, you can fill in the variable placeholders with values later: &gt;&gt;&gt; line_one = template_string % (2, 200) &gt;&gt;&gt; line_one "You have purchased 2 bananas for price of 200" &gt;&gt;&gt; line_two = template_string % (5, 500) &gt;&gt;&gt; line_two "You have purchased 5 bananas for price of 500" Let's say you have 5 use cases, you should build the line 5 times for each case: banana_price = 100 banana_transactions = [2, 3, 6, 7, 11] template_string = "You have purchased %s bananas for price of %s" with open('transactions.txt', 'w') as myfile: for transaction in banana_transactions: myfile.write(template_string % (transaction, banana_price*transaction))
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50284721
has body: Try the following code: def remove_chars(text): return str(re.sub(r'[\t\r]','',text)) i = df['Column'].map(remove_chars)
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50283422
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50283422

http://stackoverflow.com/q/50309910
has answer: http://stackoverflow.com/a/50310095
linked to: http://stackoverflow.com/q/26942061
has comment: http://stackoverflow.com/comment/87635684
tagged with: python
linked to: http://stackoverflow.com/q/252703
score: 4
accepted answer: http://stackoverflow.com/a/50310095
upvote count: 4
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/252703
downvote count: 0
answer count: 1
has body: I don't understand how the list function works. Here is the research I have done: Documentation I am looking at: documentation In particular, I am looking at this paragraph: class list([iterable]) Return a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, []. list is a mutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built in dict, set, and tuple classes, and the collections module. Here is another post: Another post about the list function On that post, the someone posts the following: &gt;&gt;&gt; myList = ['hello'] &gt;&gt;&gt; myList=list(myList[0]) &gt;&gt;&gt; myList ['h', 'e', 'l', 'l', 'o'] But when I do this: for root, dirs, files in os.walk(os.getcwd()): path_files.append(files) path_files 'combinedPdfs.py', 'meetingminutes.pdf', 'meetingminutes_encrypted.pdf', 'pdf_intro.py', 'pdf_paranoia.py', 'readDocx.py' &gt;&gt;&gt; path_files_2 = list(path_files[0]) &gt;&gt;&gt; path_files_2 ['combinedPdfs.py', 'meetingminutes.pdf', 'meetingminutes_encrypted.pdf', 'pdf_intro.py', 'pdf_paranoia.py', 'readDocx.py'] &gt;&gt;&gt; path_files_2[0] 'combinedPdfs.py' &gt;&gt;&gt; path_files_2[1] 'meetingminutes.pdf' Why did what I do work differently than the user from the other post? Edit #1: If I run something like this: &gt;&gt;&gt; myList2 = ['hello', 'goodbye'] &gt;&gt;&gt; myList2[0] 'hello' &gt;&gt;&gt; myList2 = list(myList2) &gt;&gt;&gt; myList2 ['hello', 'goodbye'] &gt;&gt;&gt; myList2 = list(myList2[0]) &gt;&gt;&gt; myList2 ['h', 'e', 'l', 'l', 'o'] If I run something like this: &gt;&gt;&gt; myList4 = 'Hello', 'goodbye' &gt;&gt;…
favorite count: 0
type: Question
tagged with: python-3.x
has title: list() function confusion

pyqt
type: Tag
tags question: http://stackoverflow.com/q/50232639
tags question: http://stackoverflow.com/q/50250025
tags question: http://stackoverflow.com/q/50353476
tags question: http://stackoverflow.com/q/50249949
tags question: http://stackoverflow.com/q/50237093
tags question: http://stackoverflow.com/q/50298745
tags question: http://stackoverflow.com/q/50252587
tags question: http://stackoverflow.com/q/50368307
tags question: http://stackoverflow.com/q/50270311
tags question: http://stackoverflow.com/q/50313410
tags question: http://stackoverflow.com/q/50380475
tags question: http://stackoverflow.com/q/50263858
tags question: http://stackoverflow.com/q/50314924
tags question: http://stackoverflow.com/q/50344551
tags question: http://stackoverflow.com/q/50311879
tags question: http://stackoverflow.com/q/50256606
tags question: http://stackoverflow.com/q/50278123
tags question: http://stackoverflow.com/q/50381025
tags question: http://stackoverflow.com/q/50337382
tags question: http://stackoverflow.com/q/50309257
tags question: http://stackoverflow.com/q/50282156
tags question: http://stackoverflow.com/q/50272397
tags question: http://stackoverflow.com/q/50353239
tags question: http://stackoverflow.com/q/50370722
tags question: http://stackoverflow.com/q/50315784
tags question: http://stackoverflow.com/q/50230500
tags question: http://stackoverflow.com/q/50355919
tag name: pyqt
tags question: http://stackoverflow.com/q/50237665
tags question: http://stackoverflow.com/q/50233156
tags question: http://stackoverflow.com/q/50357948
tags question: http://stackoverflow.com/q/50367837
tags question: http://stackoverflow.com/q/50263545
tags question: http://stackoverflow.com/q/50344872
tags question: http://stackoverflow.com/q/50283851
tags question: http://stackoverflow.com/q/50230230
tags question: http://stackoverflow.com/q/50282786
tags question: http://stackoverflow.com/q/50378653

http://stackoverflow.com/q/50370124
tagged with: django-commands
has answer: http://stackoverflow.com/a/50370556
has title: Django: generate python code from command line
score: 2
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50370291
favorite count: 0
type: Question
tagged with: python
has body: Is here a way to write a Django command to generate code automatically? In my case: every time I create a new model I must create the following stuff too: Create Administration classes in admin.py Create service functions related to this model. Create a factory using FactoryBoy. Create test classes. It would be nice if there was a command that generates this stuff automatically. Not everything, of course, but just the basic, the definition. Is there something like this today in Django? Or is there a way I can write Django commands to generate code?

http://stackoverflow.com/q/50351663
tagged with: pandas
has title: group rows on basis of columns value match
has body: I have df like this . I want to group row of id &amp; times values matches. I tried groupby but was unable . &gt;&gt;&gt; df number title id time 0 10 aa 100 02.05.2018 04 1 11 bb 100 02.05.2018 04 desired output &gt;&gt;&gt; df number title id time 0 10 11 aa bb 100 02.05.2018 04 Please help in solving this. Thanks
upvote count: 0
accepted answer: http://stackoverflow.com/a/50351919
downvote count: 1
has comment: http://stackoverflow.com/comment/87720055
has answer: http://stackoverflow.com/a/50351919
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50351731
has answer: http://stackoverflow.com/a/50351731
tagged with: python
score: -1
type: AnsweredQuestion
answer count: 2

networkx
tags question: http://stackoverflow.com/q/50239182
tags question: http://stackoverflow.com/q/50273402
tags question: http://stackoverflow.com/q/50293977
tags question: http://stackoverflow.com/q/50376066
tags question: http://stackoverflow.com/q/50330783
tag name: networkx
tags question: http://stackoverflow.com/q/50330413
tags question: http://stackoverflow.com/q/50243215
tags question: http://stackoverflow.com/q/50322188
tags question: http://stackoverflow.com/q/50280193
tags question: http://stackoverflow.com/q/50292880
tags question: http://stackoverflow.com/q/50284529
type: Tag

http://stackoverflow.com/a/50319059
score: 0
type: Answer
has body: Modify your code to fill password as follows # fil the password password = browser.find_element_by_xpath('//*[@id="PASSWORD"]') password.click() password = browser.find_element_by_xpath('//*[@id="PASSWORD"]') password.send_keys(passwordStr) StaleElement exception is thrown when you are trying to perform operation on a webElement which is no more available on the page probably because the page has been refreshed and hence your code is holding on to an object which is no more valid. You need to do a lookup again after performing click for the password field and then try to send_keys on it. It might be possible that xpath would have changed after clicking, update your xpath after click if that's the scenario.
answers question: http://stackoverflow.com/q/50317447

http://stackoverflow.com/comment/87509838
score: 0
type: Comment
has text: What version of ansible are you using?
type: QuestionComment
comment on: http://stackoverflow.com/q/50246050

http://stackoverflow.com/a/50266206
has comment: http://stackoverflow.com/comment/87551067
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87551234
answers question: http://stackoverflow.com/q/50265160
has body: I am looking to: add the user Profile,Reason_reported from Report table and datetime that they were banned into the Banned_User table once banned. send these details to the users email Cutting down your question into the actual problem, the steps are first to create the ban report, then add the user and finally send the email. The error message is telling you there is no report attribute for the request object, which makes sense since the report it tied to the user, not the request. def banning_users(self, request, queryset): for obj in queryset: if hasattr(obj, 'user'): # This object is a Profile, so lookup the user profile = obj user = obj.user user.is_active = False # Get the report(s) for this user user_reports = Report.objects.filter(user_reported=profile) # Go through each report, in case there are multiples, # add a record in the ban table banned_reasons = [] for report in user_reports: ban_record = Banned_User.create(profile=profile, report_reason=report, date_banned=datetime.datetime.today()) banned_reasons.append(report.get_report_reason_display()) # Send the email subject = 'Ban' message = 'You have been banned for the following reasons: {}' message.format(','.join(banned_reasons)) email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] send_mail( subject, message,email_from, recipient_list) self.message_user(request, "User is banned and Email has been sent")
has comment: http://stackoverflow.com/comment/87550617

http://stackoverflow.com/q/50303398
favorite count: 0
type: Question
score: 0
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/87629052
has comment: http://stackoverflow.com/comment/87633536
has title: Comparing R squared for least squares line fit and plane fit (Python)
tagged with: python
has comment: http://stackoverflow.com/comment/87639291
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87660438
tagged with: least-squares
has body: I have a set of datapoints in 3D space, and I'd like to determine quantifiably if I can ignore the y component of the data. I've computed ordinary least-squares for z = ax + b and ordinary least squares for z = ax + b*y + c. I get an R^2 value for my 2D plot and a residual (sum of squared errors) for my 3D plot. How do I go from a residual to R^2 value for the 3D plot and is this acceptable to compare to my R^2 value for my 2D plot? xs = array of x data ys = array of y data zs = array of z data For 2D: slope, intercept, r_value, p_value, std_err = stats.linregress(xs, zs) For 3D: tmp_A = [] tmp_b = [] for i in range(len(xs)): tmp_A.append([xs[i], ys[i], 1]) tmp_b.append(zs[i]) b = np.matrix(tmp_b).T A = np.matrix(tmp_A) fit = (A.T * A).I * A.T * b errors = b - A * fit residual = np.linalg.norm(errors) Thanks! Jason Edit Here's the answer: E = np.squeeze(np.asarray(errors)) Z = np.array(zs) r2 = 1 - (E.var() / Z.var())
has comment: http://stackoverflow.com/comment/87639214
upvote count: 1
has comment: http://stackoverflow.com/comment/87660498
has comment: http://stackoverflow.com/comment/87639486
downvote count: 1

http://stackoverflow.com/comment/87495856
comment on: http://stackoverflow.com/a/50239252
type: Comment
score: 0
type: AnswerComment
has text: I tried replacing yes with 1 and no with 0 but it still yield the same result

http://stackoverflow.com/a/50260203
has body: Your aiohttp package might be out of date. Try pip install --upgrade aiohttp
has comment: http://stackoverflow.com/comment/87539465
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50259795
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50259795
score: 3
type: Answer

http://stackoverflow.com/q/50321667
has body: I'm trying to decrypt an SMIME encrypted message (encrypted in JavaScript using PKI.js library), which looks like this: Content-Type: application/pkcs7-mime; name=smime.p7m; smime-type=enveloped-data Content-Description: Enveloped Data Content-Disposition: attachment; filename=smime.p7m Content-Transfer-Encoding: base64 From: sender@example.com To: recipient@example.com Subject: Example S/MIME encrypted message Date: Sun, 13 May 2018 23:53:48 +0000 Message-Id: &lt;1526255628125-055f663b-fd554ae9-1ed33cf1@example.com&gt; MIME-Version: 1.0 [binary] And I do it the following way: from M2Crypto import BIO, SMIME, X509 def decrypt(s): mime = SMIME.SMIME() with open("tmp.p7", 'wb') as f: f.write(s.encode('utf-8')) p7, data = SMIME.smime_load_pkcs7("tmp.p7") return mime.decrypt(p7) What I get is the following message: File "/Users/Adam/Library/Python/3.5/lib/python/site-packages/M2Crypto/SMIME.py", line 113, in smime_load_pkcs7 p7_ptr, bio_ptr = m2.smime_read_pkcs7(bio) M2Crypto.SMIME.SMIME_Error: no content type If I do with open("tmp.p7", 'w') as f: f.write(s) instead, the result is the same... that no content type error message. Can anybody, please, help me?
answer count: 1
tagged with: python
tagged with: smime
has comment: http://stackoverflow.com/comment/87710780
tagged with: m2crypto
has comment: http://stackoverflow.com/comment/87680245
score: 0
has comment: http://stackoverflow.com/comment/87660208
has title: M2Crypto: Trying to decrypt SMIME string. Getting no content type Error
has answer: http://stackoverflow.com/a/50322809
type: Question
has comment: http://stackoverflow.com/comment/87714256
type: UnansweredQuestion
tagged with: encryption

http://stackoverflow.com/a/50359577
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50359226
has comment: http://stackoverflow.com/comment/87737370
type: Answer
has body: Your issue is with the path - os.listdir() only lists the files/directories but not their paths so, unless you happen to be executing your script from the specified path, Python won't be able to find the file. You can always define your home path as: source_dir = r"C:\Users\Kurt\Music\Music\Brad Paisley\python test" for name in os.listdir(source_dir): # iterate over all files/directories in source_dir if name[-4:].lower() != ".mp3": # ignore non-mp3 files continue path = os.path.join(source_dir, name) # build the whole file path # you can also check with os.path.isfile(path) to make sure it's a file you're processing # etc. (your mutagen update logic) You may also want to look into glob.glob() for direct directory list with an applied extension filter pattern so you don't have to do the manual check yourself.
accepted answer of: http://stackoverflow.com/q/50359226

http://stackoverflow.com/comment/87792140
type: AnswerComment
comment on: http://stackoverflow.com/a/50377151
has text: `scrapy crawl Company -o out.json`
type: Comment
score: 0

http://stackoverflow.com/q/50265039
has comment: http://stackoverflow.com/comment/87548249
answer count: 2
has answer: http://stackoverflow.com/a/50265096
has answer: http://stackoverflow.com/a/50265158
score: 0
has comment: http://stackoverflow.com/comment/87548473
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87548310
has comment: http://stackoverflow.com/comment/87548394
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87548234
has comment: http://stackoverflow.com/comment/87548392
has comment: http://stackoverflow.com/comment/87548344
has title: Python Django- Not Returning a Valid Result
possible better answer: http://stackoverflow.com/a/50265096
has body: I am generating all possible combinations for the given scrambled letters and storing it in a list. Then, I'm checking if words from that list are in my database. Although, the word is in the database, it is not returning so. example for result list: result = ['aargh', 'raagh', 'hraag'] Although there is a word called aargh in my database, its not returning it. for r in result: # print(r) try: actual = Dictionary.objects.get(word=r) print(actual.word) except: actual = 'Not found' print("Actual Word " + str(actual)) I have words stored in 'Dictionary' Table. What is wrong here?
accepted answer: http://stackoverflow.com/a/50265158
type: AnsweredQuestion

http://stackoverflow.com/comment/87723969
has text: Something is quite wrong about the code you posted here. The error message clearly shows that Leaky Rely 6 is the final output of your model.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50353078
type: Comment

http://stackoverflow.com/a/50358610
type: Answer
accepted answer of: http://stackoverflow.com/q/50357629
score: 0
answers question: http://stackoverflow.com/q/50357629
type: AcceptedAnswer
has body: Unfortunately I can't simply comment on your question because my reputation isn't high enough, but it seems to me that you have not done any research with regards to this problem because it's simply 2 lines of code. Instead of just telling you the answer I would like to encourage you to research loops in python, but at the risk of losing rep by not actually answering your question in this box there are 2 ways you can accomplish your task: These methods are based on the assumption that A, B and X in your equation are the indexed values of each of the arrays and that they are all of the same length method 1 - simple for loop for i in range(len(A)): c = (a + (X[i] - A[i]) * (b - a)) / (B[i] - A[i]) method 2 - for loop with zipped arrays/lists for i, j, k in zip(A, B, X): c = (a + (k - i) * (b - a)) / (j - i)

http://stackoverflow.com/q/50280590
answer count: 2
duplicate of: http://stackoverflow.com/q/11041405
upvote count: 3
has comment: http://stackoverflow.com/comment/87577972
has answer: http://stackoverflow.com/a/50280763
possible better answer: http://stackoverflow.com/a/50280763
linked to: http://stackoverflow.com/q/37143664
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87577830
has comment: http://stackoverflow.com/comment/87577876
has title: Dictionary key does not exist - but it does
has comment: http://stackoverflow.com/comment/87577929
duplicate of: http://stackoverflow.com/q/37143664
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/87578054
tagged with: dictionary
linked to: http://stackoverflow.com/q/11041405
has answer: http://stackoverflow.com/a/50280732
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50280732
has comment: http://stackoverflow.com/comment/87577959
tagged with: python-3.x
has body: I'm using exifread to get some Exif info from photos. Currently, I'm trying to get the GPS Latitude and Longitude, which I can do: def main(): images = image_paths(IMAGE_FOLDER) # folder is say "Sample Photos\\" info = {} for img in images: _lat, _lon = "", "" tags = exifread.process_file(open(img,'rb')) for i in tags.keys(): if i == "GPS GPSLatitude": print(i, ":::", tags[i]) This prints what I expect, they key name and the values: GPS GPSLatitude ::: [32, 52, 66443/1250] GPS GPSLatitude ::: [32, 52, 531699/10000] GPS GPSLatitude ::: [32, 52, 531699/10000] GPS GPSLatitude ::: [32, 52, 132789/2500] GPS GPSLatitude ::: [32, 52, 265817/5000] But, to skip doing that loop and just get the key/value pairs quickly, I'm trying instead (this replaces the for i ... loop) _lon = tags["GPS GPSLatitude"] But I get an error: KeyError: 'GPS GPSLatitude' How do I access "GPS GPSLatitude" (and "GPS GPSLongitude") without looping through the keys of tags? Edit: tags is &lt;class 'dict'&gt;

http://stackoverflow.com/q/50377905
type: AnsweredQuestion
tagged with: anaconda
has body: I am new python also Django. I know the same issue is posted in this forum. but still, can't figure it out. created a model and need to import in my views.py file so I can render my data. this is my views.py from first_app.models import Topic, webpage, AccessRecord from django.shortcuts import render from django.http import HttpResponse # from django.apps import AppConfig # Create your views here. def index(request): webpage_list = AccessRecord.objects.order_by('date') date_dict = {'acess_records': webpage_list} return render(request, 'first_app/index.html') and it showed me this error PS E:\python\firstp\first_project&gt; python manage.py runserver Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0000024518AB58C8&gt; Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, …
tagged with: django-models
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50378147
has title: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when I import model
has answer: http://stackoverflow.com/a/50378147
upvote count: 0
has comment: http://stackoverflow.com/comment/87772289
answer count: 1
tagged with: django
tagged with: python
score: -1
downvote count: 1

http://stackoverflow.com/comment/87640106
comment on: http://stackoverflow.com/q/50261070
score: 1
type: Comment
type: QuestionComment
has text: (you may want to put that as an answer, so that this question doesn't appear unanswered)

http://stackoverflow.com/q/50266770
linked to: http://stackoverflow.com/q/72899
possible better answer: http://stackoverflow.com/a/50266826
duplicate of: http://stackoverflow.com/q/72899
tagged with: python
tagged with: dictionary
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: list
answer count: 2
accepted answer: http://stackoverflow.com/a/50266821
has answer: http://stackoverflow.com/a/50266821
downvote count: 0
has answer: http://stackoverflow.com/a/50266826
has title: Sort nested dictionary inside a list in Python?
favorite count: 0
type: Question
has body: [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ] How can I sort according to Price..?

http://stackoverflow.com/q/50383109
possible better answer: http://stackoverflow.com/a/50383251
has title: How to find the numbers in a list that come in numerical order in Python3?
has answer: http://stackoverflow.com/a/50383181
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
has body: I have a list, like this: list_1 = [1,2,2,3,1,2] I want to create another nested lists like this: [[1,2,2,1,2],[2,2,3,2]] The first nested list is only composed of 1 and 2 because, according to the numerical order, 2 comes after 1 and 1 is must be included. 3 is not in the first nested list because after 1 comes 2 and not 3. In the second nested list, there is 2 and 3 because 3 comes after 2 and 2 needs to be included. 1 is not there because one doesn't come after 2. How can I achieve this in Python 3?
has comment: http://stackoverflow.com/comment/87781854
tagged with: python
has comment: http://stackoverflow.com/comment/87781836
has answer: http://stackoverflow.com/a/50383251
upvote count: 4
tagged with: python-3.x
tagged with: list
answer count: 2
accepted answer: http://stackoverflow.com/a/50383181

http://stackoverflow.com/a/50296229
downvote count: 0
has body: You can use something like this (XPath string() function): for quote in response.xpath('//div[@class="entry-content"]'): yield { 'title': quote.xpath('./h3[@class="widget-title"]/text()').extract_first(), 'text': quote.xpath('string(./div/p)').extract_first(), }
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50268266
answers question: http://stackoverflow.com/q/50268266
score: 1
has comment: http://stackoverflow.com/comment/87672152

http://stackoverflow.com/comment/87582325
score: 0
comment on: http://stackoverflow.com/q/50282765
has text: @eclark It's basically a group of bar graphs when i print it out
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87627901
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50305803
has text: The plan was to make firstNumber become the previous total, so continue has firstNumber = total
type: Comment

http://stackoverflow.com/q/50343736
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/50343827
has body: I am trying to implement a script which tests a tracking URL is reachable to the app on the app store or not. For this, I need to get the IP address of country in question and using that IP I need to request the tracking URL. So it will be like request went through that country and we will come to know if URL is reachable to the app store for that country or not. Question: How do I request the URL as if its requested from IP I provide? Example: def check_url_is_valid(url, ip_address): # Trying to request url using ip_address # return True or False PS: Not expecting to complete this code but any direction or guidance is appreciated.
accepted answer: http://stackoverflow.com/a/50343850
downvote count: 1
has title: Request a url using IP address of specific country in python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50343789
possible better answer: http://stackoverflow.com/a/50343789
has answer: http://stackoverflow.com/a/50343850
tagged with: python
score: -1
type: AnsweredQuestion

http://stackoverflow.com/comment/87724884
comment on: http://stackoverflow.com/a/50353752
score: 0
type: AnswerComment
type: Comment
has text: @unutbu Correct. Local solvers are very dependent on the starting point when the model contains non-convexities, Non-convex models are not that easy,

http://stackoverflow.com/a/50401674
has comment: http://stackoverflow.com/comment/87858335
has comment: http://stackoverflow.com/comment/87936483
has comment: http://stackoverflow.com/comment/87950320
type: Answer
has comment: http://stackoverflow.com/comment/87921628
answers question: http://stackoverflow.com/q/50384264
has comment: http://stackoverflow.com/comment/87970488
has body: The thing that you want - print(sess.run(y_pred)) - is exactly what you should do after restore. You imported the graph and restored the variables. The TensorFlow world is pretty much in the same state as what you had in your training script. You can run the graph the same way you run it in the training script. To advance your understanding a bit. Calling tf.layers.dense creates the variables and operations (represented as nodes in the graph). You called it in your training script for this reason. When you imported the graph and restored variable values, you created the variables and operations. Calling tf.layers.dense again makes little sense. When you tried calling sess.run() with a string, it did not work because you need to pass in a tensor object. There are several ways to get the tensors you want: Using get_tensor_by_name as you did. This is a little brittle because tensor names can change as you work on your model. You can add your tensors to a collection before saving the graph and retrieve them from this collection when restoring. The collection name should be more stable than the tensor name. If you have the code that builds the graph (i.e. your training script). You can use that code to recreate the same graph. Then, you would have the same python object y_pred you had during training. You would need to make a change to your restoring script in this case. Since you created the graph using your code, you don't need to import_meta_graph_def. You just need to restore variable values.
score: 0
has comment: http://stackoverflow.com/comment/87849881
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50384264
has comment: http://stackoverflow.com/comment/87823129

http://stackoverflow.com/comment/138530267
comment on: http://stackoverflow.com/a/50260378
type: AnswerComment
score: 0
has text: I had a different problem where it was used like this - ```data['Age'] = data['Age'].fillna(data['Age'].median)``` here median was missing () and fills up the NaN values with method
type: Comment

http://stackoverflow.com/a/50310090
type: AcceptedAnswer
downvote count: 0
has body: You are adding dashes between class names, where no such dashes exist. The &lt;tr&gt; element you are selecting has two classes, perhour and rowmargin, but you are selecting on a non-existing class perhour-rowmargin. The same applies to the td elements; they have separate classes fulltime and innerTableCell Just pick one or the other for both; the following returns the cells you want: four_days.select(".perhour .fulltime") You probably also want to remove the extra newlines around each cell data; add strip=True to the get_text() calls: [p.get_text(strip=True) for p in four_days.select(".perhour .fulltime")]
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50310021
has comment: http://stackoverflow.com/comment/87636164
type: Answer
has comment: http://stackoverflow.com/comment/87636027
answers question: http://stackoverflow.com/q/50310021
score: 1

http://stackoverflow.com/comment/90296111
type: QuestionComment
score: 0
has text: Related post - [Symbol Table in Python](https://stackoverflow.com/q/9085450/465053)
comment on: http://stackoverflow.com/q/50264069
type: Comment

http://stackoverflow.com/comment/87578194
comment on: http://stackoverflow.com/q/50280509
has text: JSON stands for JavaScript Object Notation - the syntax originates from JS and valid JSON should automatically be valid JS.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/50322558
answers question: http://stackoverflow.com/q/50322529
downvote count: 0
score: 1
upvote count: 1
has body: The problem with your source code is the way you construct the if statement. You should edit it to look like this: if bolivia == "La Paz" or bolivia == "Sucre": Notice that you should use the bolivia variable again.
type: Answer

http://stackoverflow.com/comment/87583957
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50283745
score: 0
has text: @hpaulj I want to save it in csv format for further processing, and also i have one variable (id) and one array (feature), which i want to combine.

http://stackoverflow.com/q/50255930
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87540430
has answer: http://stackoverflow.com/a/50256321
has comment: http://stackoverflow.com/comment/87530644
has comment: http://stackoverflow.com/comment/87530509
tagged with: python
has comment: http://stackoverflow.com/comment/87543092
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 2
accepted answer: http://stackoverflow.com/a/50256321
has title: Generate a 2D list based on probability
has body: I want to generate an n-row list where each row is k columns. Then order is based on probability. Given: L = [1, 2, 3] and the probability list P = [0.3, 0.2, 0.5], Expected output based on the probability: [[3, 3],[3, 1],[1, 3],[3, 2],[2, 3],[1, 1]] where [3,3] is the first since it yields the highest probability of 1.0. second is [3,1] with 0.8 and so on. Here's my code: L = [3, 1, 2] # Input List P = [0.3, 0.2, 0.5] # Probability List k = 2 # 2 columns per row n = 6 # 6 rows in 2D array nL = np.array(L) generated_list = np.zeros(shape=(1, k), dtype=int) while generated_list.shape[0] != n: choice = np.random.choice(L, size=k, p=P) if not np.any(generated_list == [choice]): generated_list = np.append(generated_list, [choice], axis=0) I can't seem to have an ordered list based on probability. It also contains duplicate elements. Sample generated_list output: [[0, 0],[3, 1],[2, 3],[1, 2],[2, 3],[2, 3]] What's the best way to do this: 1. Compare if a 1-D element is already in 2-D array 2. Have the random choice return first the highest probability combination
downvote count: 1
has answer: http://stackoverflow.com/a/50256201
has comment: http://stackoverflow.com/comment/87543065
possible better answer: http://stackoverflow.com/a/50256201
has comment: http://stackoverflow.com/comment/87532907

http://stackoverflow.com/comment/87583511
comment on: http://stackoverflow.com/q/50260481
type: Comment
score: 0
has text: I edited the original post to include my actual code... The problem is occurring when I set the "b" variable.
type: QuestionComment

http://stackoverflow.com/a/50373474
answers question: http://stackoverflow.com/q/50372558
has body: This is sort of a wild guess, but I think the problem is here: querywords = txt.split() You just split the text, which means that some stop words might still be glued to punctuation and thus are not filtered in the next step. &gt;&gt;&gt; text = "Text containing stop words like a, the, and similar" &gt;&gt;&gt; stopwords = ["a", "the", "and"] &gt;&gt;&gt; querywords = text.split() &gt;&gt;&gt; cleantxt = ' '.join(w for w in querywords if w not in stopwords) &gt;&gt;&gt; cleantxt 'Text containing stop words like a, the, similar' Instead, you could use re.findall like you did later in your code: &gt;&gt;&gt; querywords = re.findall(r"\w+", text) &gt;&gt;&gt; cleantxt = ' '.join(w for w in querywords if w not in stopwords) &gt;&gt;&gt; cleantxt 'Text containing stop words like similar' Note, however, that this will split compound words like "re-arranged" into "re" and "arranged". If that's not what you want, you could also use this to just split by whitespace and then trim (some) pnuctuation characters (there might be more in the text, though): querywords = [w.strip(" ,.-!?") for w in txt.split()] Changing just that one line seems to fix the problem for the input files you provided. The rest looks okay, though there are a few minor points: you should convert stopwords to a set so the lookup is O(1) instead of O(n) make sure to lower the stop words if they are not already no need to ' '.join the cleaned text if you intent to split it again right afterwards top25 = word_counts[:25] is redundant, the list is already at most 25 elements long
has comment: http://stackoverflow.com/comment/87767456
downvote count: 0
has comment: http://stackoverflow.com/comment/87766525
upvote count: 1
has comment: http://stackoverflow.com/comment/87766560
has comment: http://stackoverflow.com/comment/87765579
score: 1
has comment: http://stackoverflow.com/comment/87766612
type: Answer
has comment: http://stackoverflow.com/comment/87767357
has comment: http://stackoverflow.com/comment/87765338

http://stackoverflow.com/comment/87789567
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50373062
has text: @trollster No, the main idea is to extract dates from contracts. So, the function has as an input the contract and must output the dates.

http://stackoverflow.com/q/50278268
downvote count: 0
favorite count: 0
type: Question
tagged with: dummy-variable
has answer: http://stackoverflow.com/a/50278328
has body: I have a pandas dataframe with two whose combination I consider the unique identifier and then one single column 'C' that can have different values. So the same unique identifier can repeat as many times as the number of different 'C' values it has. import pandas as pd data = {'A' : ['000001','000001','000001','000001','000002','000002','000003'], 'B' : ['1A','1A','1C','1D','1A','1A','1D'], 'C' : ['003','012','016','003','020','012','053']} df = pd.DataFrame(data) +-------------------+ | A | B | C | +-------------------+ | 000001 | 1A | 003 | | 000001 | 1A | 012 | | 000001 | 1C | 016 | | 000001 | 1D | 003 | | 000002 | 1A | 020 | | 000002 | 1A | 012 | | 000003 | 1D | 053 | +-------------------+ I want to group rows based on A, B and then pivot out the C column and turn them into dummies. This is what I need the final output to look like: +----------------------------------------------------+ | A | B | C_003 | C_012 | C_016 | C_020 |C_053 | +----------------------------------------------------+ | 000001 | 1A | 1 | 1 | 0 | 0 | 0 | | 000001 | 1C | 0 | 0 | 1 | 0 | 0 | | 000001 | 1D | 1 | 0 | 0 | 0 | 0 | | 000002 | 1A | 0 | 1 | 0 | 1 | 0 | | 000003 | 1D | 0 | 0 | 0 | 0 | 1 | +----------------------------------------------------+ I'm really bad at pivot tables, but also just not sure if a pivot table can get my to my desired output. I'm looking for a super efficient process, as the actual data has several more columns as part of the identifier (like A, B), thousands of possible C values, and millions of rows. Any ideas?
possible better answer: http://stackoverflow.com/a/50278324
has answer: http://stackoverflow.com/a/50278310
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50278324
has title: Pandas pivot out unique column
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/50278310
answer count: 3
upvote count: 2
tagged with: pandas
tagged with: pivot

http://stackoverflow.com/q/50277574
tagged with: python
has body: Why does this work? a=pd.DataFrame() a.loc[1,2]=0 &gt; 2 1 0.0 And, this does not work? a=pd.DataFrame() a.loc[(1,2),2]=0 &gt; KeyError: '[1 2] not in index' The latter is what I would like to do. I will be filling the values by assignment via loc selection with tuple specified index, from a dataframe with no values, 0 rows, 0 columns.
favorite count: 0
tagged with: assign
type: Question
has answer: http://stackoverflow.com/a/50278032
possible better answer: http://stackoverflow.com/a/50278032
answer count: 2
downvote count: 0
upvote count: 1
type: AnsweredQuestion
has title: Filling an empty dataframe by assignment via loc selection with tuple indices
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50277751
accepted answer: http://stackoverflow.com/a/50277751
tagged with: dataframe

http://stackoverflow.com/comment/87852992
comment on: http://stackoverflow.com/q/50341162
type: Comment
type: QuestionComment
score: 0
has text: If `darkestValue==0` and `whitestValue==255` then your loop doesn't change anything. If these values are different, your loop will only stretch the intensity axis, which you would see as a change of the x-axis of the histogram, but not a change of its shape. As I said, histogram equalization is something different. It is a non-linear mapping. You use the cumulative histogram as a lookup table. Look at the links I gave you, you will learn how equalization works.

http://stackoverflow.com/a/50261827
has comment: http://stackoverflow.com/comment/87547086
downvote count: 0
has body: formsets use #id_form-TOTAL_FORMS (and a few other things) to see how many forms there are and were initialy. If you want to display more than one formset on a single page you'll run into the problem that you end up with two of these objects with the same id. To solve this you can define a prefix for one (or both) of the formsets.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50260414
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50260414
type: Answer

http://stackoverflow.com/q/50263191
type: Question
has title: Open file has data but reports back length 0 in python
has comment: http://stackoverflow.com/comment/87544484
accepted answer: http://stackoverflow.com/a/50278362
tagged with: http://stackoverflow.com/tag/csv
has body: I must be missing something very simple here, but I've been hitting my head against the wall for a while and don't understand where the error is. I am trying to open a csv file and read the data. I am detecting the delimiter, then reading in the data with this code: with open(filepath, 'r') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read()) delimiter = repr(dialect.delimiter)[1:-1] csvdata = [line.split(delimiter) for line in csvfile.readlines()] However, my csvfile is being read as having no length. If I run: print(sum(1 for line in csvfile)) The result is zero. If I run: print(sum(1 for line in open(filepath, 'r'))) Then I get five lines, as expected. I've checked for name clashes by changing csvfile to other random names, but this does not change the result. Am I missing a step somewhere?
tagged with: python
has comment: http://stackoverflow.com/comment/87544459
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/50278362

http://stackoverflow.com/q/50377737
has title: how i can use if statment without else in tensorflow?
has comment: http://stackoverflow.com/comment/87790767
has body: i think that i have to put my question in different way.i wanna do this exactly as follows: i used relu(x) function in keras layers, now i wanna change it and create my own activation function as follow: 1.create array as a look up table whose value between [-5,5] with 's' step (s=0.1) so my look up table should contain 102 numbers,e.g. [-5,-4.9...+4.9,5] 2.create Y array in shape of above lookup table.initial value of Y is zero, {Yi} are learnable parameters in training 3=calculated f(x)=1/s(yi(xi+1−x)+yi+1(x−xi)), if xi ≤ x ≤ xi+1 For any input value between xi and xi+1, the output is linearly interpolated from yi and yi+1,xi and xi+1 should be find in look up table and corresponding yi and yi+1 in Y 4=relu(f(x)) the problem is how can i write this activation function in keras?
type: Question
has comment: http://stackoverflow.com/comment/87840077
has answer: http://stackoverflow.com/a/50377827
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87771973
has comment: http://stackoverflow.com/comment/87818029
has comment: http://stackoverflow.com/comment/87771848
score: 0
has comment: http://stackoverflow.com/comment/87814360
tagged with: tensorflow

http://stackoverflow.com/a/50285127
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50284098
type: Answer
has body: &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(r"(\w)(?=\w)", r"\1^", "SUPER MAN") 'S^U^P^E^R M^A^N' For more on why that works: https://docs.python.org/3/library/re.html

http://stackoverflow.com/comment/87793223
comment on: http://stackoverflow.com/q/50358454
type: Comment
has text: you should try to update then. Latest version is [2.7.0](https://searchfox.org/mozilla-central/rev/d4b9e50875ad7e5d20f2fee6a53418315f6dfcc0/testing/marionette/client/marionette_driver/__init__.py#7) and B2G was removed since then.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87500728
has text: I have another problem also in this project, can I take help from you?
comment on: http://stackoverflow.com/a/50240823
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50296498
has comment: http://stackoverflow.com/comment/87611021
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87624409
has comment: http://stackoverflow.com/comment/87627047
tagged with: python
has title: Plot validation curve for class-weight in sklearn
has body: I would greatly appreciate if you could let me know how to plot validation curve for class weight. In fact, I tired the following code to do this task: from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split, StratifiedKFold, validation_curve, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline import numpy as np import matplotlib.pyplot as plt def plot_validation_curve(param_range, train_scores, test_scores, title, alpha=0.1): train_mean = np.mean(train_scores, axis=1) train_std = np.std(train_scores, axis=1) test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) plt.plot(param_range, train_mean, label='train score', color='blue', marker='o') plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, color='blue', alpha=alpha) plt.plot(param_range, test_mean, label='test score', color='red', marker='o') plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, color='red', alpha=alpha) plt.title(title) plt.grid(ls='--') plt.xlabel('Parameter value') plt.ylabel('F-measure') plt.legend(loc='best') plt.show() if __name__ == '__main__': X, y = make_classification(n_classes=2, class_sep=2, weights=[0.9, 0.1], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=1000, random_state=10) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) st = StandardScaler() rg = LogisticRegression(class_weight={0: 1, 1: 6.5}, random_state=42, solver='saga', max_iter=100, n_jobs=-1) param_grid = {'clf__C': [0.001, 0.01, 0.1], 'clf__class_weight': [{0: 1, 1: 6}, {0: 1, 1: 5.5}]} pipeline = Pipeline(steps=[('scaler', st), ('clf', rg)]) cv = StratifiedKFold(n_splits=5, random_state=42) rg_cv = GridSearchCV(pipeline, param_grid, cv=cv, scoring='f1') rg_cv.fit(X_train, y_train) plt.figure(figsize=(9, 6)) param_range2 = [{0: 1, 1: 6}…
accepted answer: http://stackoverflow.com/a/50298699
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: validation
has answer: http://stackoverflow.com/a/50298699
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/comment/87697536
type: Comment
type: QuestionComment
has text: @Tool Then it's no longer an anonymous function, just bad practice. When you're naming lambdas, just write a function. Anyway, besides the point...
score: 2
comment on: http://stackoverflow.com/q/50340499

http://stackoverflow.com/q/50322704
has answer: http://stackoverflow.com/a/50323344
has title: Box plot for continuous data in Python
tagged with: seaborn
tagged with: boxplot
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/87661510
upvote count: 4
tagged with: continuous
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87662092
downvote count: 0
linked to: http://stackoverflow.com/q/50434784
has body: I have a csv file with 2 columns: col1- Timestamp data(yyyy-mm-dd hh:mm:ss.ms (8 months data)) col2 : Heat data (continuous variable) . Since there are almost 50k record, I would like to partition the col1(timestamp col) into months or weeks and then apply box plot on the heat data w.r.t timestamp. I tried in R,it takes a long time. Need help to do in Python. I think I need to use seaborn.boxplot. Please guide.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50323344

http://stackoverflow.com/q/50243271
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87504598
has comment: http://stackoverflow.com/comment/87504392
has body: I'm new to python and programming and had a question about the different ways to write a palindrome detector. From the little that I know, I was able to make one using a while loop... word = str(input("Enter a word: ")) length = len(word) x = 0 while length-x &gt;= x: if word[(length-1)-x] == word[x]: y = True x += 1 else: y = False break print (y) But from other palindrome questions I saw the shorter (more pythonic?) way... word = input("Enter a word: ") rword = word[-1::-1] print (word == rword) Besides the obvious difference in length, what are the pros and cons of using either code? Also, not sure if this is a dumb question but are either of these considered recursive?
score: 0
has title: Pros and Cons of two different ways to recognize palindrome Python
answer count: 1
has answer: http://stackoverflow.com/a/50243331
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87504333

http://stackoverflow.com/comment/87553396
type: Comment
type: QuestionComment
has text: I have labeled data for segmentation network which is indexed as class arg number. After I trained the neural network, it predicts the index number for each pixel. So now I wanna visualize the predicted pixel. That is why I wanted to convert the indexed color to RGB color-space.
comment on: http://stackoverflow.com/q/50267606
score: 1

http://stackoverflow.com/q/50380899
favorite count: 0
has answer: http://stackoverflow.com/a/50381000
score: 9
type: Question
upvote count: 9
has title: Get the requirements of a package in PyPI without installing it?
answer count: 2
downvote count: 0
type: UnansweredQuestion
tagged with: package
linked to: http://stackoverflow.com/q/11147667
has answer: http://stackoverflow.com/a/50380944
tagged with: pip
tagged with: package-management
has body: I need something like the following: pip showrequirements tensorflow This would return something that allows me to parse the names of the required packages and the required versions: astor&gt;0.6, tensorboard&gt;1.0.11, etc. pip is getting this information in some form during the install and download command. I can see where it's happening in the code... but before I hack my way to using pip's internal code, is there any easy API or existing library that can do this? edit: I cannot install the package to see this, so pip show won't work. One (hacky) solution is parsing the output of pip download. Thanks!
tagged with: python
tagged with: pypi
duplicate of: http://stackoverflow.com/q/11147667

http://stackoverflow.com/q/50306480
has comment: http://stackoverflow.com/comment/87628990
tagged with: python
has title: How to represent a square wave in python and how to convolve it?
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50312021
downvote count: 0
accepted answer: http://stackoverflow.com/a/50312021
answer count: 1
favorite count: 0
tagged with: signal-processing
type: Question
tagged with: numpy
tagged with: convolution
has body: I am trying to convolve a square wave with itself more than once and see the resulting graph. I know how to do convolution by my hands but I am not experienced in signal processing with Python. So my questions are: How can I represent a signal in Python? For example: x(t) = 1 , 0 ≤ t ≤ 1 x(t) = 0, otherwise How can I convolve this square wave with itself? What I have come so far is that I must use numpy's built-in convolve method; but the problem is I am stuck representing this square wave.

selenium
tags question: http://stackoverflow.com/q/50294167
tags question: http://stackoverflow.com/q/50378877
tags question: http://stackoverflow.com/q/50294151
tags question: http://stackoverflow.com/q/50266500
tags question: http://stackoverflow.com/q/50269191
tags question: http://stackoverflow.com/q/50252138
tags question: http://stackoverflow.com/q/50298120
tags question: http://stackoverflow.com/q/50378508
tags question: http://stackoverflow.com/q/50264877
tags question: http://stackoverflow.com/q/50271772
tags question: http://stackoverflow.com/q/50331882
tags question: http://stackoverflow.com/q/50270576
tags question: http://stackoverflow.com/q/50251423
tags question: http://stackoverflow.com/q/50254279
tags question: http://stackoverflow.com/q/50284208
tags question: http://stackoverflow.com/q/50248876
tags question: http://stackoverflow.com/q/50359334
tags question: http://stackoverflow.com/q/50287106
tags question: http://stackoverflow.com/q/50328617
tags question: http://stackoverflow.com/q/50279442
tags question: http://stackoverflow.com/q/50301696
tags question: http://stackoverflow.com/q/50253744
tags question: http://stackoverflow.com/q/50315587
tags question: http://stackoverflow.com/q/50310148
tags question: http://stackoverflow.com/q/50272194
tags question: http://stackoverflow.com/q/50270199
tags question: http://stackoverflow.com/q/50310674
tags question: http://stackoverflow.com/q/50243867
tags question: http://stackoverflow.com/q/50295136
tags question: http://stackoverflow.com/q/50355120
tags question: http://stackoverflow.com/q/50351258
tags question: http://stackoverflow.com/q/50287049
tags question: http://stackoverflow.com/q/50301920
tags question: http://stackoverflow.com/q/50250478
tags question: http://stackoverflow.com/q/50327432
tags question: http://stackoverflow.com/q/50322820
tags question: http://stackoverflow.com/q/50299868
tags question: http://stackoverflow.com/q/50279960
tags question: http://stackoverflow.com/q/50306612
tags question: http://stackoverflow.com/q/50320915
tags question: http://stackoverflow.com/q/50303797
tags question: http://stackoverflow.com/q/50294963
tags question: http://stackoverflow.com/q/50270930
tags question: http://stackoverflow.com/q/50356360
tags question: http://stackoverflow.com/q/50302110
tags question: http://stackoverflow.com/q/50240886
tags question: http://stackoverflow.com/q/50361640
tags question: http://stackoverflow.com/q/50339055
tags question: http://stackoverflow.com/q/50298553
tags question: http://stackoverflow.com/q/50317447
tags question: http://stackoverflow.com/q/50309926
type: Tag
tags question: http://stackoverflow.com/q/50354157
tags question: http://stackoverflow.com/q/50358324
tags question: http://stackoverflow.com/q/50231166
tags question: http://stackoverflow.com/q/50337244
tags question: http://stackoverflow.com/q/50353960
tags question: http://stackoverflow.com/q/50242587
tags question: http://stackoverflow.com/q/50353906
tags question: http://stackoverflow.com/q/50330126
tags question: http://stackoverflow.com/q/50244970
tag name: selenium
tags question: http://stackoverflow.com/q/50244957
tags question: http://stackoverflow.com/q/50304063
tags question: http://stackoverflow.com/q/50324563
tags question: http://stackoverflow.com/q/50347024
tags question: http://stackoverflow.com/q/50373848
tags question: http://stackoverflow.com/q/50253997
tags question: http://stackoverflow.com/q/50253037
tags question: http://stackoverflow.com/q/50372017
tags question: http://stackoverflow.com/q/50340985
tags question: http://stackoverflow.com/q/50285863
tags question: http://stackoverflow.com/q/50270826
tags question: http://stackoverflow.com/q/50322340
tags question: http://stackoverflow.com/q/50321278
tags question: http://stackoverflow.com/q/50301263
tags question: http://stackoverflow.com/q/50274194
tags question: http://stackoverflow.com/q/50268279

http://stackoverflow.com/a/50262381
answers question: http://stackoverflow.com/q/50261759
score: 0
has body: itertools.product gives you the combinations that you want. The problem is that you need to rebuild dictionaries from its result. In this example, I expanded temp into (key, value) tuples which can be used to update the data dictionary. I copy data so that I don't have to worry about stale data on each loop. I made this a runnable python 2 script with extra prints to show the intermediate steps. import numpy as np import itertools def f(data, t): x = data['focus']*data['integration']*data['upper'] return t*x def Trial(t, temp, data): calcdata = {} # make list of (key:value) pairs for each value list temp_vector = [[(key, value) for value in valuelist] for key,valuelist in temp.iteritems()] print "temp_vector" for item in temp_vector: print item print "-------------------------------" # run for all combinations for counter, subs in enumerate(itertools.product(*temp_vector)): mydata = data.copy() mydata.update(subs) print "dict for calcuation:", mydata x_axis, y_axis = np.vstack((t,np.vectorize(f)(mydata,t))) mydata['xaxis'] = x_axis mydata['yaxis'] = y_axis calcdata[counter] = mydata print "--------------------------------" return calcdata #data['focus'] = 100 data = {'focus':100} t = np.linspace(1,10,10) temp = {'integration': [1,2], 'upper': [3,4], 'other': [5,6]} calcdata = Trial(t, temp, data) for item in sorted(calcdata.items()): print(item)
type: Answer

numpy-ndarray
tags question: http://stackoverflow.com/q/50280640
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/50307820
tags question: http://stackoverflow.com/q/50286093
tags question: http://stackoverflow.com/q/50233649
tags question: http://stackoverflow.com/q/50374672
type: Tag

http://stackoverflow.com/comment/87481510
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50232127
has text: what's the error you're getting?
score: 0

http://stackoverflow.com/comment/87648706
comment on: http://stackoverflow.com/q/50316415
has text: I tried to run it and the code works fine. It prints ```[['student1', ' 2', ' 3 '], [' student2', ' 1', ' 4'], ['Student3', '3', '5']]```. Check this link : http://tpcg.io/0Z3bGa
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87780261
score: 0
has text: Very, very helpful. Thanks. Actually I already have an inner function that I can optimize the way you suggest first, and an outer loop which can get called many times too. For that I can look into arrays.
comment on: http://stackoverflow.com/a/50368006
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50244149
accepted answer: http://stackoverflow.com/a/50244234
has comment: http://stackoverflow.com/comment/87506062
linked to: http://stackoverflow.com/q/32468402
tagged with: python
possible better answer: http://stackoverflow.com/a/50244232
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Reshaping strings-as-lists into rows
answer count: 2
has answer: http://stackoverflow.com/a/50244232
tagged with: pandas
downvote count: 0
has body: I have a pandas data frame like this: df = pandas.DataFrame({ 'Grouping': ["A", "B", "C"], 'Elements': ['[\"A1\"]', '[\"B1\", \"B2\", \"B3\"]', '[\"C1\", \"C2\"]'] }).set_index('Grouping') so Elements Grouping =============================== A ["A1"] B ["B1", "B2", "B3"] C ["C1", "C2"] i.e. some lists are encoded as strings-as-lists. What is a clean way to reshape this into a tidy data set like this: Elements Grouping ==================== A A1 B B1 B B2 B B3 C C1 C C2 without resorting to a for-loop? The best I can come up with is: df1 = pandas.DataFrame() for index, row in df.iterrows(): df_temp = pandas.DataFrame({'Elements': row['Elements'].replace("[\"", "").replace("\"]", "").split('\", \"')}) df_temp['Grouping'] = index df1 = pandas.concat([df1, df_temp]) df1.set_index('Grouping', inplace=True) but that's pretty ugly.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50244234

http://stackoverflow.com/q/50294626
upvote count: 2
has title: Count unique values in JSON file
downvote count: 0
accepted answer: http://stackoverflow.com/a/50294676
tagged with: python
has body: I have a JSON file with the following setup: { "1": { "id":123456, "name":"John Doe", "address":"Address 1" }, "2": { "id":789011, "name":"Name Nameson", "address":"Address 2" } } The thing with this file, is that it contains A LOT of duplicates. So what I want is to be able to count how many unique people there are just by their ID. Or really any value they have would work, as no one has the same name or address. So say there are 300 people in the list, and only 50 of them are unique, the rest are duplicates, I want to be able to display that. I've looked it up on google, but I can't really find anything that works for me...
has answer: http://stackoverflow.com/a/50294676
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/87605763
has comment: http://stackoverflow.com/comment/87605714
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87605866
has comment: http://stackoverflow.com/comment/87605859

http://stackoverflow.com/q/50278360
tagged with: plot
has title: How can I programatically access bokeh plot styling options (description, default value)
upvote count: 3
score: 3
answer count: 1
has body: As the question states, I need a way to programatically access the description and default value of a plot option, e.g. plot/width. So, is there something that holds all the styling options like width, xrotation, with its description and default values?
tagged with: python
tagged with: bokeh
has answer: http://stackoverflow.com/a/50278434
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/50307581
type: Answer
has comment: http://stackoverflow.com/comment/87843617
has comment: http://stackoverflow.com/comment/87631266
score: 0
accepted answer of: http://stackoverflow.com/q/50307124
has comment: http://stackoverflow.com/comment/87631118
type: AcceptedAnswer
has body: You can pass the value to Checkbutton like this: def checkbox(self): print ("I M in checkBox") checkBox1 = Checkbutton(self.tab1, text=str(t.keys()[0]), variable=t.values()[0]) checkBox2 = Checkbutton(self.tab1, text=str(t.keys()[1]), variable=t.values()[1]) Checkbutton() checkBox1.grid() checkBox2.grid() and you must change readExcelValue, like below: def readExcelValue(self): result_data = {} for sheet in self.wb.sheets(): for curr_row in range(1, self.number_of_rows, 1): data = sheet.cell_value(curr_row, 0) value = sheet.cell_value(curr_row, 1) result_data[data] = value return result_data
answers question: http://stackoverflow.com/q/50307124

http://stackoverflow.com/comment/87687359
type: AnswerComment
has text: @Alfe: Now, it could be that the refactor to use `trunc()` breaks the test because `x + 0.5` returns an object that `trunc()` doesn't support, or whose implementation of the `__trunc__` method is broken. Using a MagicMock object *would not detect that problem at all*. Your test would break (the returned object is `mock_c.return_value.__trunc__.return_value`), you fix your test to use the `__trunc__` version, but the actual production system still breaks because no test puts the proper types through your function-under-test.
comment on: http://stackoverflow.com/a/50330620
type: Comment
score: 0

http://stackoverflow.com/q/50270685
has body: I have a file that looks like this: scaf12446 275 482 loc.04759 . + 9.99087136654 scaf9003 58436 58745 loc.36424 . + 9.98867551051e-07 scaf6164 41519 44781 loc.29229 . - 9.97790659076e-07 scaf20 64796 100635 loc.14273 . - 9.97726500173 scaf19280 12335 12568 loc.13668 . + 9.95702976886 scaf8877 30882 32362 loc.36113 . - 9.94423702955e-08 I want to subtract the 3rd column from the 2nd column and print out the values. So the resultant file should be like this: scaf12446 207 loc.04759 . + 9.99087136654 scaf9003 309 loc.36424 . + 9.98867551051e-07 scaf6164 3262 loc.29229 . - 9.97790659076e-07 scaf20 35839 loc.14273 . - 9.97726500173 scaf19280 233 loc.13668 . + 9.95702976886 scaf8877 1480 loc.36113 . - 9.94423702955e- This table is quite long - would there be an easy way to simply subtract column 3 from column 2? A linux shortcut would be ideal.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50271001
tagged with: linux
has comment: http://stackoverflow.com/comment/87558840
tagged with: python
has title: How to subtract two separate columns in a file
type: AnsweredQuestion
downvote count: 4
has comment: http://stackoverflow.com/comment/87559456
answer count: 1
score: -3
upvote count: 1
accepted answer: http://stackoverflow.com/a/50271001

http://stackoverflow.com/q/50269104
type: Question
tagged with: infoblox-client
has body: I am trying to update 'host record name', and for achieving the same I am using infoblox-client but I am hitting a roadblock coz of which m not able to modify/update the host record. I have tried the same via REST API and m able to modify the name as required but via infoblox-client m kind of stuck. Following are the steps that m trying to update the record: opts = {'host': '192.168.1.10', 'username': 'admin', 'password': 'admin'} conn = connector.Connector(opts) my_ip = objects.IP.create(ip='192.168.1.25') #to create new host record with parameters record = objects.HostRecord.create(conn, view='my_dns_view', name='my_host_record.my_zone.com', ip=my_ip) #to modify m trying following but no luck: #1_both of below snippet adds a new name to record instead of upodating the same -&gt; result = objects.HostRecord.create(conn, view='my_dns_view', name='new_name.my_zone.com', ip=my_ip, check_if_exists=True, update_if_exists=True) -&gt; result = objects.ARecordBase.create(conn, ip='192.168.102.14', name='some-new_name.ansible.com', view='default', update_if_exists=True) #2_I have gone through infoblox-client test case(test_update_fields_on_create) which I have following steps to modify record: a_record = [{'_ref': 'record:previously_created_record', 'ip': '192.168.1.52', 'name': 'other_name'}] #this gives me error for host,username missing. conn = connector.Connector(a_record) #this results to None which ultimately blocks me res = conn.get_object('record:host',a_record)
tagged with: infoblox
answer count: 1
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50354330
has answer: http://stackoverflow.com/a/50354330
tagged with: python
has title: Not able to modify the host record name in infoblox via infoblox-client

http://stackoverflow.com/a/50380064
upvote count: 2
answers question: http://stackoverflow.com/q/50379977
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50379977
score: 1
type: Answer
downvote count: 1
has body: You can apply list comprehension in order to filter list. Also, use filter method by applying a lambda expression as argument. lst = ['Hello World', 'Hello', 'This is test', 'is test'] lst = [string for string in lst if len(list(filter(lambda x: string in x, lst))) == 1] Output ['Hello World', 'This is test']

http://stackoverflow.com/comment/87559674
comment on: http://stackoverflow.com/q/50271245
type: QuestionComment
score: 0
has text: I do have my bot working already, I just want to add the daily feature, I forgot to mention, I believe I am using Rewrite with EXT.
type: Comment

http://stackoverflow.com/q/50307145
accepted answer: http://stackoverflow.com/a/50307531
has title: Pandas xlrd engine passed still value error
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 3
tagged with: xlrd
has body: I am trying to read an xls file from a url: using requests : page = requests.get(url) # xls url df = pd.read_excel(page.content,engine = 'xlrd') #engine is passed File "f:\python36\lib\site-packages\pandas\util\_decorators.py", line 118, in wrapper return func(*args, **kwargs) File "f:\python36\lib\site-packages\pandas\io\excel.py", line 230, in read_excel io = ExcelFile(io, engine=engine) File "f:\python36\lib\site-packages\pandas\io\excel.py", line 296, in __init__ raise ValueError('Must explicitly set engine if not passing in' ValueError: Must explicitly set engine if not passing in buffer or path for io. # if i put in random engine name it throws an unsupported engine error but with xlrd it throws must set engine I tried saving the file and then reading it: with open('file.xls','wb') as f: f.write(page.content) df = pd.read_excel('file.xls',engine='xlrd') #this works EDIT: I have tried passing page.text it raises: ValueError: embedded null character
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50307531
linked to: http://stackoverflow.com/q/48295284
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87686453
score: 0
comment on: http://stackoverflow.com/q/50335057
type: Comment
type: QuestionComment
has text: nothing is always the best :D

http://stackoverflow.com/comment/87693938
has text: Did you try `print`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50338795
score: 0
type: Comment

http://stackoverflow.com/comment/87570951
score: 0
type: Comment
has text: Off course, I uploaded the code in the question
type: QuestionComment
comment on: http://stackoverflow.com/q/50276424

http://stackoverflow.com/comment/87557304
type: AnswerComment
has text: if i delete the line rawinput then getting a name error
type: Comment
comment on: http://stackoverflow.com/a/50268962
score: 0

http://stackoverflow.com/comment/89712199
type: QuestionComment
comment on: http://stackoverflow.com/q/50240057
type: Comment
score: 0
has text: Did you find a solution?

http://stackoverflow.com/comment/87663201
has text: This answer would be better if you added some explanatory text.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50323095

http://stackoverflow.com/q/50324157
downvote count: 0
upvote count: 1
has body: enter image description hereI have a mongodb connection(posted in image),which is having a collection of say some 20 files. i would like to read/load each collection from python and do the necessary computing. Please find the sample below what i am trying to do. import pandas as pd import json from pandas.io.json import json_normalize from unittest.mock import inplace from pymongo import MongoClient connection = MongoClient('localhost', 27017) db=connection.Tmobile collection=db.collection_names(include_system_collections=False) for collect1 in collection: print(collect1) with open(collect1,'r') as fi: d=json.load(fi) print(d) when i try this it gives me below error. Mynew Traceback (most recent call last): File "C:\Users\esrilka\eclipse-workspace\My First PyDev Project\dbsample.py", line 12, in with open(collect1,'r') as fi: FileNotFoundError: [Errno 2] No such file or directory: 'Mynew'
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/87664312
score: 1
has title: how to parse data of all collections using pymongo
tagged with: python
has comment: http://stackoverflow.com/comment/87664441
answer count: 0
linked to: http://stackoverflow.com/q/16249736
type: UnansweredQuestion
tagged with: pymongo

http://stackoverflow.com/comment/87779842
comment on: http://stackoverflow.com/q/50381839
has text: Yes, printing sql is inside the error message 'select idip from ip where ip=0 and mask=DEFAULT' I am pretty noob at sql so I'm still trying to understand how to do this selection with 2 values, once doing so with only one value works pretty well
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50242357
type: Answer
score: 0
has body: If I understand correctly you want to convert all the Unicode control characters to space, except the tab, carriage return and new line. You can use str.translate for this: good = map(ord, '\t\r\n') TBL_CONTROL_TO_SPACE = { i: u' ' for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i))[0] == "C" and i not in good } def cleanup(s): return s.translate(TBL_CONTROL_TO_SPACE)
answers question: http://stackoverflow.com/q/50235071

http://stackoverflow.com/a/50337065
upvote count: 1
has body: If the xlsx truly only contains 2 columns, then why don't you just read the entire file as raw text, then do a split by newline, instead of using xlrd to load the workbook? The file already has the columns "combined" if you think about it that way... Could be as simple as: rows = open("filename").read().splitlines()
answers question: http://stackoverflow.com/q/50336690
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87809913
type: Comment
type: AnswerComment
has text: Thank you very much! So let me see if I'm an understanding this. So in the analyze function, are you recalling the Example window so that way you can display the information there? Also If you have to do that, then what the ex = Example() do at the bottom of the code?
comment on: http://stackoverflow.com/a/50381702
score: 0

http://stackoverflow.com/comment/87498739
has text: First, you need to fix your indentation. Second, if I understand your code correctly, you are dropping the first row of the results. Finally, you need to show what actually gets written to the file - I don't think that the elements of `query` are what you think they are (I think they are all dicts).
comment on: http://stackoverflow.com/q/50239856
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87488048
type: AnswerComment
comment on: http://stackoverflow.com/a/50230336
type: Comment
has text: that works! so import matplotlib.image as mpimg is not necessary?
score: 0

http://stackoverflow.com/comment/87638320
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50310074
score: 0
has text: Thank you. Could you also please add another possible way of making sessions? Another way to make sessions is this: For every user, if two consequent actions happen in a time delta less than 5 minutes are grouped in one session. Any action that is done in a time delta longer than 5 minutes will be the start of a new session.

http://stackoverflow.com/q/50259904
has comment: http://stackoverflow.com/comment/87829133
has comment: http://stackoverflow.com/comment/87544178
has comment: http://stackoverflow.com/comment/87544084
has comment: http://stackoverflow.com/comment/87819484
has comment: http://stackoverflow.com/comment/87538149
has comment: http://stackoverflow.com/comment/87608790
linked to: http://stackoverflow.com/q/56779305
answer count: 1
downvote count: 1
favorite count: 0
has body: I have a code which formats these lines from files below into a dictionary: CommonChar pins Category General CommonChar pins Contact Mark CommonChar pins Description This is a CommonChar nails Category specific CommonChar nails Contact John CommonChar pins Description This is a description Final dict looks like this: main_dict = { 'pins': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a'] }, 'nails': { 'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] }} I have this code today to create above dict: filePath= os.path.join(dirName,eachFile) fh=open(filePath, "r") contents=fh.read() items=re.findall("CommonChar.*$",contents,re.MULTILINE) for x in items: parts=x.split() if parts[1] in mainDict: if parts[2] in mainDict[parts[1]]: sys.exit("exit") else: mainDict[parts[1]].update({parts[2]:parts[3:]}) else: mainDict[parts[1]]={} mainDict[parts[1]].update({parts[2]:parts[3:]}) If my input to the code changes as below, then I need to append the values of similar keys: CommonChar pins Category General CommonChar pins Contact Mark CommonChar pins Description This is a CommonChar pins Description secondLine CommonChar nails Category specific CommonChar nails Contact John CommonChar pins Description This is a description I need an output like this below from above lines : &lt;/br&gt; being added to it as well . main_dict = { 'pins': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a','&lt;/br&gt;','secondLine'] }, 'nails': { 'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] }} For that I am replacing this line: sys.exit("exit") with this: mainDict[parts[1]][parts[2]].append(parts[3:]) But I get an output like this: main_dict = { 'pins': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a',['secondLine']] }, 'nails': { 'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', '…
has comment: http://stackoverflow.com/comment/87610187
type: Question
has comment: http://stackoverflow.com/comment/87541444
accepted answer: http://stackoverflow.com/a/50260268
upvote count: 0
has comment: http://stackoverflow.com/comment/87698161
has comment: http://stackoverflow.com/comment/87543767
has answer: http://stackoverflow.com/a/50260268
tagged with: python
has comment: http://stackoverflow.com/comment/87538058
score: -1
has title: How to append values to a key in a nested dict and avoid brackets
has comment: http://stackoverflow.com/comment/87538156
has comment: http://stackoverflow.com/comment/87745157
has comment: http://stackoverflow.com/comment/87726481
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87687566

http://stackoverflow.com/comment/88182482
score: 0
comment on: http://stackoverflow.com/a/50556283
type: Comment
type: AnswerComment
has text: `./foo --path a b --path c d bar e f`

http://stackoverflow.com/comment/87728098
score: 0
type: AnswerComment
type: Comment
has text: Thanks. I've the rough idea. Anyway the generating num i reserved for other purposed :)
comment on: http://stackoverflow.com/a/50355889

http://stackoverflow.com/comment/87675363
comment on: http://stackoverflow.com/a/50328646
type: AnswerComment
score: 0
type: Comment
has text: Figured it out, as @Joe mentioned in another answer.

http://stackoverflow.com/comment/87996254
type: QuestionComment
comment on: http://stackoverflow.com/q/50352614
has text: Question worthy of bounty imo.
score: 3
type: Comment

http://stackoverflow.com/comment/87779217
has text: I've already tried it.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50381513

http://stackoverflow.com/comment/135985641
comment on: http://stackoverflow.com/a/60925864
has text: Simple and clean!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50235375
has title: Using select.poll() on a nonblocking file descriptor
type: Question
has body: I have a named pipe opened in non-blocking mode: fd = os.open('mypipe', os.O_RDONLY|os.O_NONBLOCK) I want to be able to know if there's something to read with a timeout, so I tried to use select: poller = select.poll() poller.register(fd, select.POLLIN) But when I try to poll and specify a timeout: poller.poll(3000) ...it always returns immediately, even if there's nothing to read. My question is this: is it possible to use timeouts with poll() on a file descriptor opened with O_NONBLOCK flag? Is it possible that I'm doing it wrong, and there is another way to achieve this?
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
tagged with: named-pipes
tagged with: linux
score: 1
tagged with: select

http://stackoverflow.com/comment/87617211
comment on: http://stackoverflow.com/a/50299883
type: Comment
has text: @user2357112 I've done my best to address every issue you've listed... thanks a bunch.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50315645
tagged with: sudo
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50315865
answer count: 3
tagged with: pip
has answer: http://stackoverflow.com/a/73799013
score: 11
has comment: http://stackoverflow.com/comment/87647170
favorite count: 0
has comment: http://stackoverflow.com/comment/87647206
type: Question
has body: I have a simple script which is using signalr-client-py as an external module. from requests import Session from signalr import Connection import threading When I try to run my script using the sudo python myScriptName.py I get an error: Traceback (most recent call last): File "buttonEventDetectSample.py", line 3, in &lt;module&gt; from signalrManager import * File "/home/pi/Desktop/GitRepo/DiatAssign/Main/signalrManager.py", line 2, in &lt;module&gt; from signalr import Connection ImportError: No module named signalr If I run my script typing only python myScriptName.py it works perfectly fine but I need to have the sudo in front because later on in my other scripts (that use this one) I perform write operation on the File system. I am quite new to Python and that's why I need to know how I can handle this situation. If I type pydoc modules I get a list which contains: signalr signalrManager If I type pip freeze I can see there listed: signalr-client==0.0.7
accepted answer: http://stackoverflow.com/a/50315865
possible better answer: http://stackoverflow.com/a/50315816
tagged with: python
has title: Cannot run Python script using sudo
upvote count: 11
has answer: http://stackoverflow.com/a/50315816

http://stackoverflow.com/comment/87681699
score: 0
comment on: http://stackoverflow.com/q/50332573
type: Comment
type: QuestionComment
has text: @pyton17 thats ok. Well, the [0] means we're trying to access 0th element in an array. Inside the main json file, there is a single key, `Customer`, and this key's value is an array. We want to access the array first, which can be accessed using `hd['Customer']`. After that, we want to access to the 1st element (0th index) inside array, which is the whole JSON body, including `Information`, `Id`, `Res`, `Role` and `Limit`.

http://stackoverflow.com/comment/87695742
has text: Placeholders, it could be anything, numbers, string, etc.
type: Comment
comment on: http://stackoverflow.com/q/50339726
type: QuestionComment
score: 0

http://stackoverflow.com/q/50243645
linked to: http://stackoverflow.com/q/36681836
has answer: http://stackoverflow.com/a/56244422
tagged with: python
has title: I can't import pyaudio?
linked to: http://stackoverflow.com/q/14512741
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50244911
tagged with: shell
has body: I'm trying to import pyaudio i installed portaudio with the command brew install portaudio and i installed pyaudio with pip now Im trying to import pyaudio and python shows me the error Could not import the PyAudio C module '_portaudio' now when i try to follow the instructions of the answer of pyaudio could not import _portaudio the portaudio tar doesn't have the install file PORTAUDIO TAR CONTENENTS What can i do? Python: 3.4 Operating system: Mac OSX the captain
type: Question
has comment: http://stackoverflow.com/comment/87504975
type: UnansweredQuestion

http://stackoverflow.com/q/50306006
has comment: http://stackoverflow.com/comment/87639546
type: Question
answer count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87628722
tagged with: visual-studio
tagged with: c++
has comment: http://stackoverflow.com/comment/87628626
tagged with: scons
tagged with: windows
downvote count: 0
score: 1
has title: SCons Fails to Detect Visual Studio Build 2017 Tools on Windows 7
favorite count: 0
has body: I'm trying to Compile Godot Engine - Godot Engine which is a 3D Game Engine made with C++. According to the Latest Godot Docs - Compiling Godot on Windows, I was trying to Compile Godot on my 32 bit Windows 7 Ultimate PC. I installed Scons from Official Sources using Command - ./setup.py install So, I did installed successfully without any error. Then I Downloaded Visual C++ Build Tools and Installed it, the Prompt also works fine. I installed Python2.7 in the directory C:\python27\ Using - python --version Also, seems that it's working correctly. But, When I open The Bash Prompt of Visual Studio C++ with present Directory I run these Commands - cd. cd \godot-master\ C:/python2.7/scons.bat p=windows I'm greeted with some strange error, the C:\godot-gles2\godot-gles2&gt;C:/python27/scons.bat p=windows scons: Reading SConscript files ... scons: warning: No version of Visual Studio compiler found - C/C++ compilers mos t likely not set correctly File "C:\godot-gles2\godot-gles2\SConstruct", line 3, in &lt;module&gt; scons: warning: No version of Visual Studio compiler found - C/C++ compilers mos t likely not set correctly File "C:\godot-gles2\godot-gles2\SConstruct", line 71, in &lt;module&gt; Configuring for Windows: target=debug, bits=default Found MSVC compiler: x86 Compiled program architecture will be a 32 bit executable. (forcing bits=32). TypeError: unsupported operand type(s) for +: 'NoneType' and 'str': File "C:\godot-gles2\godot-gles2\SConstruct", line 327: detect.configure(env) File "./platform/windows\detect.py", line 343: configure_msvc(env, manual_msvc_config) File "./platform/windows\detect.py", line 196: env.Append(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"]) C:\godot-gles2\godot-gles2&gt; What's the problem here? Is there something I'm missing?

http://stackoverflow.com/comment/87696470
comment on: http://stackoverflow.com/q/50339997
type: QuestionComment
score: 0
has text: The point of a variable is to evaluate to something. So yes, `x = s` means to evaluate `s`, which is `"a"`, and then assign `x` to it. So now `x` and `s` are two names for the same object, `"a"`. When you then say `x = ` something else, you are now assigning the name to another object. It does nothing to any other names. `s` has no reason to be reassigned.
type: Comment

http://stackoverflow.com/comment/87673233
comment on: http://stackoverflow.com/a/50328646
score: 1
type: Comment
type: AnswerComment
has text: There's no such thing as infinite precision. Decimal have _fixed_ precision. That's reason for using them.

http://stackoverflow.com/comment/87783826
score: 0
has text: Possible duplicate of [Implementation of Luhn Formula](https://stackoverflow.com/questions/21079439/implementation-of-luhn-formula)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50384078

http://stackoverflow.com/q/50309540
score: 0
has comment: http://stackoverflow.com/comment/87635097
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87635075
has body: Code def fill_dictionary_with_valid_addr_row_data( df ): data_list = [] dictionary = {} int_endianness = 0 for i in df.index: addrstr = str(df['Address'][i]) if (addrstr != 'nan'): try: addr = int(addrstr, 16) except: print("Address in excel is not in hex format : %s", addrstr) sys.exit() width = int(df['Width'][i]) width = int(width / 8); endianess = df['Endianess'][i] if (endianess != 'B') and (endianess != 'L'): print("ERROR: Register endianess is not B or L"); print("Register : %x, Endianess : %s" % (addr, endianess)) sys.exit() if endianess == 'B': int_endianness = 1 data_list.append(addr) data_list.append(width) data_list.append(int_endianness) dictionary[i] = data_list print(dictionary) data_list.clear() print(dictionary) return dictionary Problem When i print dictionary inside for loop, Everything is fine. When i print dictionary outside for loop, all the value(lists) are empty. Below are the logs {0: [22216704, 4, 1]} {0: [22216716, 4, 1], 5: [22216716, 4, 1]} {0: [22216720, 4, 1], 5: [22216720, 4, 1], 7: [22216720, 4, 1]} {0: [], 5: [], 38: [], 7: []} I am a beginner python programmer. I tried to search a lot over internet but I have not found any solution. Any clues?
has title: Dictionary value for all keys gets deleted automatically
accepted answer: http://stackoverflow.com/a/50309651
has comment: http://stackoverflow.com/comment/87635073
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87635100
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50309651
has comment: http://stackoverflow.com/comment/87635147
has comment: http://stackoverflow.com/comment/87636073
answer count: 1
has comment: http://stackoverflow.com/comment/87635196
upvote count: 1
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/50270781
has comment: http://stackoverflow.com/comment/87559166
upvote count: 2
has body: You could simply add a filter like this: dialog = QFileDialog() dialog.setNameFilter("Text Spam Files (*spam*.txt)") dialog.exec() But it can be overriden if the user types *.* in the filename field. A better way to do this would be to implement your own QSortFilterProxyModel, here is my attempt: from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog) from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex import sys class FileFilterProxyModel(QSortFilterProxyModel): def __init__(self, parent=None): super(QSortFilterProxyModel, self).__init__(parent) def filterAcceptsRow(self, source_row: int, source_parent: QModelIndex) -&gt; bool: source_model = self.sourceModel() index0 = source_model.index(source_row, 0, source_parent) if source_model.isDir(index0): return True return 'spam' in source_model.fileName(index0).lower() class Window(QMainWindow): def __init__(self): QMainWindow.__init__(self) dialog = QFileDialog() dialog.setOption(QFileDialog.DontUseNativeDialog) dialog.setProxyModel(FileFilterProxyModel()) dialog.setNameFilter("Text Files (*.txt)") dialog.exec() app = QApplication(sys.argv) window = Window() window.show() app.exec_()
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50270311
has comment: http://stackoverflow.com/comment/87559214
type: Answer

http://stackoverflow.com/a/50362298
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50362074
answers question: http://stackoverflow.com/q/50362074
upvote count: 3
score: 3
type: AcceptedAnswer
has body: You can do this with a recursive function: def find_set(d, k, v): for key, value in d.items(): if isinstance(value, dict): find_set(d[key], k, v) return if key == k: d[key] = {} for i in v: d[key][i] = None return d d[k] = {} for i in v: d[k][i] = None return d Code: l = [{'A': ['B', 'C', 'D']}, {'B': ['E', 'F']}, {'C': ['E']}, {'F': ['G', 'H']}] d = {} for node in l: for key, value in node.items(): find_set(d, key, value) d will be : {'A': {'B': {'E': None, 'F': {'G': None, 'H': None}, 'C': {'E': None}}, 'C': None, 'D': None}}

http://stackoverflow.com/comment/87657837
type: QuestionComment
comment on: http://stackoverflow.com/q/50302110
type: Comment
has text: i just made a video so you can that the page_content from selenium is different from google chrome view source. https://youtu.be/a6iLB358Qxs
score: 0

http://stackoverflow.com/q/50368307
type: UnansweredQuestion
tagged with: multithreading
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/87753311
linked to: http://stackoverflow.com/q/6524459
has title: Suitable way to control one python script by another
has comment: http://stackoverflow.com/comment/87754288
has comment: http://stackoverflow.com/comment/87752768
has body: with PyQt I've made a GUI (gui.py) with a "start" and a "stop" button. Now I would like to start a another python script (streamData.py), which is in same directory as the GUI script, by pressing the start button. The streamData script is logging some sensor-Data to a file. If I press "stop" button the execution of the streamData script should be terminated. What is the best way to achieve this? Should I import the streamData.py in my gui script? Or should I use some kind of processing module to start streamData as own process? The streamData script has following functions inside: def ctrl_c_handler(signal, frame, node) raise Exception("") node = someNode() def main(): signal.signal(signalSIGINT, ctrl_c_handler) while 1: node.stream() if __name__ == "__main__": main() if printInformation: print("disconnected") node.disconnect() time.sleep(1) exit(0) So is there a way to get the script execution in node.stream let jump to node.disconnect() time.sleep(1) exit(0) ?
tagged with: python
type: Question
score: 0
answer count: 0
tagged with: pyqt

http://stackoverflow.com/comment/87661200
has text: I will do that later , for now I am concerned with "Newmail" button
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50317173

http://stackoverflow.com/comment/87685479
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50334183
has text: Thank you for your response Davide, I'll give this a try and get back to you!
score: 0

http://stackoverflow.com/q/50284542
answer count: 1
has title: I want to set background color of a cell to red or green based on pass or fail in python
has answer: http://stackoverflow.com/a/50284601
has comment: http://stackoverflow.com/comment/87585496
tagged with: python
type: Question
has body: Please help me in condition check for pass or fail to change background color of a cell in html using python. my code will check for a couple of values and return pass and fail. now i want to make the pass field in html to green and fail field to RED. Basically to generate a report. Code snippet def generateReport(reportpath, dict1, dict2): html = """ FileName MD5 MD5 MD5 Result Sha1 Sha1 Sha1 Result Sha256 Sha256 Sha256 Result """ for key in dict1: if(str(dict1[key][0]==dict2[key][0])): status1='PASS' else: status1='FAIL' if(str(dict1[key][1]==dict2[key][1])): status2='PASS' else: status2='FAIL' if(str(dict1[key][2]==dict2[key][2])): status3='PASS' else: status3='FAIL' html = html + " %s %s %s %s %s %s %s %s %s %s " % (key,dict1[key][0],dict2[key][0],status1,dict1[key][1],dict2[key][1],status2,dict1[key][2],dict2[key][2],status3) html = html + " " newhtml = open(reportpath, "w") newhtml.write(html) newhtml.close() In the above code , i am facing the problem to add background color based on condition to status1,status2,status3. please help me. thanks praveen.
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50370571
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
tagged with: odoo-10
has answer: http://stackoverflow.com/a/50378386
has title: Odoo possibility to track changes on compute field
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50378386
tagged with: odoo
tagged with: odoo-8
has body: I have model A with compute field b (it depends on field c and field d values). b = fields.Float(compute='_compute_field') My task is every month compare past and current month field b values and get differences. For example I want to compare 2018-04-01 field b value with 2018-05-01 field b value. Firstly I was thinking to store compute value in database. But the problem is that I can't do that (store=True) because if I store field b value in database I always got 0 value on field b. What can be other alternatives to track or store compute field values that I can compare the differences depend on time (date).
has comment: http://stackoverflow.com/comment/87772944
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/comment/87638383
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50310078
has text: @IwanPhillips iow, you chose examples where all values `x - y` are `0.001`
type: Comment

http://stackoverflow.com/q/50321300
accepted answer: http://stackoverflow.com/a/50335468
tagged with: python
has body: I have a Python script like this to work with Google Cloud DataStore def implicit(): query = client.query(kind='task') query.add_filter('status', '=', True) query_iter = query.fetch() print(query_iter.num_results) for entity in query_iter: print(entity['title']) I've inserted 5 'task' entities to DataStore already, and it still print out the titles however, I got the query_iter.num_results is 0, it supposed to be 5 instead. Is there anything wrong with my code. Thanks and Regards
type: AnsweredQuestion
score: 0
has title: How I find the total entities from a query, using Google Datastore
tagged with: google-cloud-datastore
answer count: 1
has answer: http://stackoverflow.com/a/50335468
type: Question

http://stackoverflow.com/comment/88602592
type: AnswerComment
has text: Okay now it works out really fine with that Code: folder = Folder(account=account, parent=account.inbox, name="RFS") folder.save() subfolder = Folder(account=account, parent=folder, name="RFS_1150-1199") subfolder.save() subsubfolder = Folder(account=account, parent=subfolder, name=item.subject) subsubfolder.save() item.move(subsubfolder) Again thanks for helping me out.
type: Comment
comment on: http://stackoverflow.com/a/50407053
score: 0

http://stackoverflow.com/q/50278300
tagged with: list
downvote count: 0
tagged with: pandas
score: 29
has answer: http://stackoverflow.com/a/50278364
tagged with: string
accepted answer: http://stackoverflow.com/a/50278364
favorite count: 0
type: Question
tagged with: tuples
has answer: http://stackoverflow.com/a/50278388
possible better answer: http://stackoverflow.com/a/50278388
answer count: 5
has answer: http://stackoverflow.com/a/65616937
has title: Convert a columns of string to list in pandas
has body: I have a problem with the type of one of my column in a pandas dataframe. Basically the column is saved in a csv file as a string, and I wanna use it as a tuple to be able to convert it in a list of numbers. Following there is a very simple csv: ID,LABELS 1,"(1.0,2.0,2.0,3.0,3.0,1.0,4.0)" 2,"(1.0,2.0,2.0,3.0,3.0,1.0,4.0)" If a load it with the function "read_csv" I get a list of strings. I have tried to convert to a list, but I get the list version of a string: df.LABELS.apply(lambda x: list(x)) returns: ['(','1','.','0',.,.,.,.,.,'4','.','0',')'] Any idea on how to be able to do it? Thank you.
has answer: http://stackoverflow.com/a/60423765
upvote count: 29
tagged with: python
has answer: http://stackoverflow.com/a/50278361
type: AnsweredQuestion

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

http://stackoverflow.com/q/50322035
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50322083
favorite count: 0
type: Question
has title: Python - writing data from a csv to new csv but row overwriten
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: twitter
type: AnsweredQuestion
score: 2
upvote count: 2
has body: I have a few thousand Twitter tweets in a csv with one tweet per row (there are blank rows between each tweet). Each column of each row contains different parts of the tweet (like time, text, language, location, etc.) but not each column has the same information (ie: sometimes language appears in column AG or AH or some other one). I'm trying to clean up the data by creating a new CSV containing only English tweets and also filtering out the punctuations from each of these (English) tweets. I'm currently stuck on how to filter out only the English tweets. This is what I have so far: import csv f = open('twitDB.csv') csv_f = csv.reader(f) # csv_f is a list of lists for row in csv_f: for col in row: if col == 'lang:"en"': with open('cleaned.csv', 'w') as fp: wr = csv.writer(fp, delimiter = ',') wr.writerow(row) wr.writerow('\n') The new cleaned.csv only contains the last English tweet (of thousands) in its Row 1. I have a feeling that my code is continuously overwriting the first row of cleaned.csv and not writing each tweet onto the next row but I'm unsure how to fix this.
accepted answer: http://stackoverflow.com/a/50322083

http://stackoverflow.com/q/50244520
type: Question
upvote count: 5
has title: How to show specific intervals of tick labels while maintaining the ticks
score: 5
tagged with: matplotlib
tagged with: python
possible better answer: http://stackoverflow.com/a/50244665
tagged with: x-axis
has body: I'm currently trying to plot a figure with a lot of ticks. It has ticks for each value from 0 to 50 resulting in packed tick labels that are merged making the plot quite messy. I made the ticks using fig, ax = plt.subplots() ax.set_xticks(np.arange(0,50)) ax.set_yticks(np.arange(0,50)) and hidden the tick labels using ax.set_xticklabels([]) ax.set_yticklabels([]) However, the problem is that this hides all the tick labels, whereas I want some of the labels to remain so that I can track easily using the labels. I've tried doing ax.set_xticklabels(np.arange(0,50,5)) but this only resulted in labeling the first 10 ticks with inappropriate labels (which were range(0,50) with the interval of 5) I'm hoping to figure out a way to show tick 'labels' with a interval of 5 (or any specific interval) while maintaining all the actual ticks (so that I can use them for grids).
has answer: http://stackoverflow.com/a/50244665
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50250083
answer count: 2
has comment: http://stackoverflow.com/comment/87509608
has comment: http://stackoverflow.com/comment/87506633
downvote count: 0
tagged with: xticks
has answer: http://stackoverflow.com/a/50250083
favorite count: 0

http://stackoverflow.com/q/50315700
type: Question
downvote count: 0
upvote count: 1
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50315712
tagged with: indexing
has title: Extract value of a particular column name in pandas as listed in another column
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50315712
tagged with: pandas
answer count: 1
score: 1
has body: The title wasn't too clear but here's an example. Suppose I have: person apple orange type Alice 11 23 apple Bob 14 20 orange and I want to get this column person new_col Alice 11 Bob 20 so we get the column 'apple' for row 'Alice' and 'orange' for row 'Bob'. I'm thinking iterrows, but that would be slow. Are there faster ways to do this?
favorite count: 0

http://stackoverflow.com/comment/87626039
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50304867
has text: So, this is not an excel problem then - why tag excel?

http://stackoverflow.com/comment/87507945
type: QuestionComment
comment on: http://stackoverflow.com/q/50245256
has text: `np.empty` is used to assign memory, it has nothing to do with the array being actually empty... which is dictated by its size being 0 or not.
score: 0
type: Comment

http://stackoverflow.com/a/50375466
type: Answer
upvote count: 3
score: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50374610
has body: You are opening the file as a text file, which means read tries to decode the data using UTF-8 in order to return a str object. Instead, open it as a binary file, so that read simply returns a bytes object without trying to decode the data at all. der = open('...', 'rb').read()
accepted answer of: http://stackoverflow.com/q/50374610
downvote count: 0

http://stackoverflow.com/comment/87718486
has text: @JeffC In each tab, Im clicking on a submit button. You could say that each submit triggers a function call and I would like these function calls to be as close to each other as possible. But yeah, its not possible for me to directly call these functions. It can only be triggered by clicking on the submit button. I wouldnt really say thats its parallel execution.
score: 0
comment on: http://stackoverflow.com/q/50348040
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87484410
score: 0
type: Comment
type: QuestionComment
has text: You mean `''.join(a.upper()+b.lower() for a,b in zip(NAME[0::2],NAME[1::2]))` But that only works on strings of `len(NAME) % 2 == 0`.
comment on: http://stackoverflow.com/q/50233337

http://stackoverflow.com/a/50307104
has comment: http://stackoverflow.com/comment/121586182
downvote count: 0
has comment: http://stackoverflow.com/comment/87643463
has comment: http://stackoverflow.com/comment/108869546
score: 14
has comment: http://stackoverflow.com/comment/108855042
upvote count: 14
has comment: http://stackoverflow.com/comment/121559870
type: Answer
has body: pd.DataFrame.std assumes 1 degree of freedom by default, also known as sample standard deviation. This results in NaN results for groups with one number. numpy.std, by contrast, assumes 0 degree of freedom by default, also known as population standard deviation. This gives 0 for groups with one number. To understand the difference between sample and population, see Bessel's correction. Therefore, you can specify numpy.std for your calculation. Note, however, that the output will be different as the calculation is different. Here's a minimal example. import pandas as pd, numpy as np df = pd.DataFrame(np.random.randint(0, 9, (5, 2))) def std(x): return np.std(x) res = df.groupby(0)[1].agg(['size', 'sum', 'mean', std]) print(res) size sum mean std 0 0 2 13 6.5 0.5 4 1 3 3.0 0.0 5 1 3 3.0 0.0 6 1 3 3.0 0.0 Alternatively, if you require 1 degree of freedom, you can use fillna to replace NaN values with 0: res = df.groupby(0)[1].agg(['size', 'sum', 'mean', 'std']).fillna(0)
has comment: http://stackoverflow.com/comment/108855551
has comment: http://stackoverflow.com/comment/108865149
answers question: http://stackoverflow.com/q/50306914

http://stackoverflow.com/comment/87654085
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50319136
has text: provide the `STATICFILES_DIRS`
score: 0

http://stackoverflow.com/a/50286440
has body: Take your set interval function in a variable and simply pass that variable into clearInterval() function your interval function execute once only var myVar = setInterval(function(){ myTimer() }, 2000); function myTimer() { $('.image-area').load("{{ url_for('image',im=image_date) }}"); update(); } setInterval(function(){ clearInterval(myVar); }, 2000);
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87589338
answers question: http://stackoverflow.com/q/50286355
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87589931

http://stackoverflow.com/comment/87549626
has text: Will it be okay to read myLoggingLevel from a database every time the loop is run? The value in database can be changed which will change the logging level when the script is running
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50265340

http://stackoverflow.com/comment/87730934
comment on: http://stackoverflow.com/q/50357222
type: Comment
score: 7
has text: What's wrong with `os.walk()`?
type: QuestionComment

http://stackoverflow.com/comment/87665023
comment on: http://stackoverflow.com/a/50277375
type: AnswerComment
score: 0
has text: @liliscent did you try avoiding the slow name lookup by caching `equal_outer = numpy.equal.outer`?
type: Comment

http://stackoverflow.com/q/50296181
has comment: http://stackoverflow.com/comment/87609319
has body: I am a just starting with opencv so I am looking for your advice. I need to process images and extract text from it. So far it all works well except images with frames. Here is an example. In this case frame is white. (border on the edge is just to show image dimension) Here is another example with a grey frame. Please give me some tips how I can cut image out of the frame with python. Thank you in advance!
upvote count: 1
tagged with: python
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/87609392
has comment: http://stackoverflow.com/comment/87634913
favorite count: 0
has comment: http://stackoverflow.com/comment/87626866
type: Question
has comment: http://stackoverflow.com/comment/87620559
answer count: 0
linked to: http://stackoverflow.com/q/10615901
type: UnansweredQuestion
score: 0
has title: OpenCV detect square frame on the image
linked to: http://stackoverflow.com/q/19271692

http://stackoverflow.com/a/71352432
type: Answer
downvote count: 0
upvote count: 1
has body: I have had a similar issue but reducing the batch size for me did not solve it (My code actually ran fine when the batch value was 16). I started working on a model under it that involved scanning pictures that's when I had issues about memory. In the model, there is a Dense value, from the Keras package that i had initially set to 4096. I divided this value by 2 and the whole code stop showing the memory error. Moreover, reducing the value of image resolution would fix the problem too but my pictures were already in low resolution (100X100)
answers question: http://stackoverflow.com/q/50304156
score: 1

http://stackoverflow.com/q/50321153
tagged with: blender
tagged with: texture-mapping
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/87869063
has title: Blender scripting - Incorrect texture add
has comment: http://stackoverflow.com/comment/87864593
answer count: 0
has comment: http://stackoverflow.com/comment/87658340
type: UnansweredQuestion
score: 0
tagged with: collada
has comment: http://stackoverflow.com/comment/87865129
has comment: http://stackoverflow.com/comment/87846430
has body: I wrote a python script that automatically add a texture to the DAE model. Usage: blender --background --python Script.py This script gives an incorrect display of the texture: import bpy from math import pi from mathutils import Quaternion myscale = 0.1; daepath = "input.dae" bpy.ops.wm.read_factory_settings(use_empty=True) # Import Dae bpy.ops.wm.collada_import(filepath=daepath) # Rotate bpy.ops.transform.rotate(value=-pi/2, constraint_axis=(False, True, True)) bpy.ops.transform.resize(value=(myscale, myscale, myscale)) # Change to orthographic view and switch to topview bpy.context.screen.areas[2].type = 'VIEW_3D' rv3d = bpy.context.screen.areas[2].spaces[0].region_3d rv3d.view_rotation = Quaternion((1.0, 0.0, 0.0, 0.0)) rv3d.view_perspective = "ORTHO" rv3d.view_distance += 1000.0 # Unwrap bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action = 'SELECT') for oWindow in bpy.context.window_manager.windows: oScreen = oWindow.screen for oArea in oScreen.areas: if oArea.type == 'VIEW_3D': for oRegion in oArea.regions: if oRegion.type == 'WINDOW': override = {'window': oWindow, 'screen': oScreen, 'area': oArea, 'region': oRegion, 'scene': bpy.context.scene, 'edit_object': bpy.context.edit_object, 'active_object': bpy.context.active_object, 'selected_objects': bpy.context.selected_objects} bpy.ops.uv.project_from_view(override , camera_bounds=False, correct_aspect=True, scale_to_bounds=True) bpy.ops.object.mode_set(mode = 'OBJECT') # Add Texture imgpath = "input.jpg" img = bpy.data.images.load(filepath=imgpath) mat = bpy.data.materials['m0DefaultMaterial'] mat.diffuse_intensity = 1.0 mat.specular_intensity = 0.0 tex = bpy.data.textures.new("SomeName", 'IMAGE') tex.image = img slot = mat.texture_slots.add() slot.texture = tex # Save Dae bpy.ops.wm.collada_export(filepath="output.dae") If I divide the script into 2 parts (1 part before section # Unwrap) and run their in Blender open app choose scripting mode open .py files in run I get right result. I was …
type: Question

http://stackoverflow.com/comment/87727448
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50350532
has text: Thanks! I tweaked this approach slightly (e.g. extended `collections.MutableMapping`) and it seems to work for Python 3. Unfortunately we're on Python 2 until Apache Beam upgrades. If I try to override sys.modules in Python 2, I get notified when `multiprocessing` is imported by `logging`, but I don't get other notifications I would expect. I'll investigate further and report back.
type: Comment

http://stackoverflow.com/comment/87783512
has text: thing is if i don't add the parameter chunksize it gives out an error as `ValueError: Expected object or value`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50383952
type: AnswerComment

http://stackoverflow.com/a/50309756
answers question: http://stackoverflow.com/q/50308623
score: 2
accepted answer of: http://stackoverflow.com/q/50308623
type: Answer
upvote count: 2
has body: This has nothing to do with your random numbers. Notice that you use the random number generator only once when you create the shuffled indices. When you load the indices from the file, the random number generator is not used, since only a file is read. Your issue occurs at a different place: You save the scrambled Lena as a .jpg. Thereby, poor Lena's scrambled image gets compressed and the colour values change a little bit. When you load the image again and reorder the indices, you do not get the original colours back but only the values after the compression. Solution: Save your images as a *.png and everything works out. If you run into problems with an alpha channel, just convert the image back to RGB: scrambled_img = Image.open(img_path).convert("RGB")
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50314440
score: 39
type: Question
tagged with: ord
accepted answer: http://stackoverflow.com/a/50314470
has answer: http://stackoverflow.com/a/57918743
upvote count: 41
has answer: http://stackoverflow.com/a/50314470
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/57918743
answer count: 2
has comment: http://stackoverflow.com/comment/87644819
tagged with: built-in
tagged with: ordinal
has body: The official Python documentation explains ord(c) ord(c): Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr(). It does not specify the meaning of ord, google searches are not helpful. What's the origin of it?
downvote count: 2
has title: What does the name of the ord() function stand for?
has comment: http://stackoverflow.com/comment/87644840
tagged with: unicode
favorite count: 0

http://stackoverflow.com/comment/87723957
type: QuestionComment
comment on: http://stackoverflow.com/q/50351457
type: Comment
has text: Do you have any annotated data to train on? Would it be feasible to obtain such data somehow?
score: 0

http://stackoverflow.com/q/50313386
tagged with: flask
favorite count: 0
type: Question
has body: So to preface this: the goal is to split a sqlite database into three shards through code. I have a majority of the background of storing and accessing the databases, but seem to have run into an issue trying to query more than one of those shards in a row to find a specific row. Code more than likely speaks for itself, so please look at it below. def get_db(): """Opens a new database connection if there is none yet for the current application context. """ top = _app_ctx_stack.top if not hasattr(top, 'sqlite_db'): top.sqlite_db = [ sqlite3.connect(DATABASE_1, detect_types=sqlite3.PARSE_DECLTYPES), sqlite3.connect(DATABASE_2, detect_types=sqlite3.PARSE_DECLTYPES), sqlite3.connect(DATABASE_3, detect_types=sqlite3.PARSE_DECLTYPES) ] top.sqlite_db[0].row_factory = sqlite3.Row top.sqlite_db[1].row_factory = sqlite3.Row top.sqlite_db[2].row_factory = sqlite3.Row return top.sqlite_db def query_db(query, shard, args=(), one=False): """Queries the database and returns a list of dictionaries.""" db = get_db() cur = db[shard].execute(query, args) rv = cur.fetchall() return (rv[0] if rv else None) if one else rv def get_user_id(username): """Convenience method to look up the id for a username.""" rb = query_db('select user_id from user where username = ?', 1, [username], one=True) rv = query_db('select user_id from user where username = ?', 2, [username], one=True) return rv[0] if rv else None @app.teardown_appcontext def close_database(exception): """Closes the database again at the end of the request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db[0].close() top.sqlite_db[1].close() top.sqlite_db[2].close() I tried to include everything that may be needed. get_user_id is where I'm encountering an issue; it seems that calling into query_db twice in arrow is causing the problem below (it seems that it doesn't matter what they're assigned to either, as it encounters the same problem either way). TypeError: 'NoneType' object has no attribute '__getitem__'…
has comment: http://stackoverflow.com/comment/87644067
type: UnansweredQuestion
has title: Python SQLite3: Strange NoneType issue when executing query twice in a row
tagged with: python
has comment: http://stackoverflow.com/comment/87643105
has comment: http://stackoverflow.com/comment/87644052
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87643493
tagged with: sqlite
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87643518

http://stackoverflow.com/q/50234253
has comment: http://stackoverflow.com/comment/87486427
downvote count: 0
has body: I have an excel sheet entry having multiple strings encompassing characters like "{,-,}," in every row. I am parsing through each of the string and checking for entries of "{" My string looks like below: string1="stack-{data}-XYZ-ABC-DEF- {data}-DAB24-GOOD45-XYA-BYCS-{data}-" I have the above string1 which has few data inside "{ }". I want to parse through the string and check if the data inside the "{ }" are same or not. I am new to python, can anyone help me with this.
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has title: Existence of similar data inside flower bracket- python
has answer: http://stackoverflow.com/a/50234555
tagged with: python
accepted answer: http://stackoverflow.com/a/50234555
type: AnsweredQuestion

http://stackoverflow.com/a/50247445
has body: You shouldn’t include .py when specifying the script to run. Change your command to: python manage.py runscript myscriptname
accepted answer of: http://stackoverflow.com/q/50242156
type: AcceptedAnswer
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50242156
score: 5
downvote count: 0

http://stackoverflow.com/comment/87564854
type: Comment
type: QuestionComment
has text: `ans` is never changed from its initial constant value - why? I don't think 0x7FFF_FFFF is of any significance except that it's the maximum possible number, and therefore is guaranteed to be overwritten with the numbers from the array. It's arguably better than 1001 because even someone who hadn't read the problem description properly would be able to see that it's the maximum possible number. That's all there is to it, I reckon.
comment on: http://stackoverflow.com/q/50273897
score: 1

http://stackoverflow.com/comment/87713587
type: Comment
score: 0
type: AnswerComment
has text: So I can't open the zip file straight from the web?
comment on: http://stackoverflow.com/a/50321997

http://stackoverflow.com/q/50372220
has answer: http://stackoverflow.com/a/50632962
accepted answer: http://stackoverflow.com/a/50632962
answer count: 1
has title: Tensorflow 1.8.0: Wide and Deep Model results are not stable. Random seed is not working
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87760368
favorite count: 0
type: Question
score: 5
upvote count: 5
linked to: http://stackoverflow.com/q/36096386
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
tagged with: deep-learning
downvote count: 0
has body: I've trained a Wide and Deep Model using Tensorflow 1.8.0. My test and training dataset are separate files which were split previously. I'm using tf.set_random_seed(1234) before tf.contrib.learn.DNNLinearCombinedClassifier as follows - tf.set_random_seed(1234) import tempfile model_dir = tempfile.mkdtemp() m = tf.contrib.learn.DNNLinearCombinedClassifier(model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=[100, 50]) It shows the following logs- INFO:tensorflow:Using default config. INFO:tensorflow:Using config: {'_task_type': None, '_task_id': 0, '_cluster_spec': &lt;tensorflow.python.training.server_lib.ClusterSpec object at 0x7f394b585c18&gt;, '_master': '', '_num_ps_replicas': 0, '_num_worker_replicas': 0, '_environment': 'local', '_is_chief': True, '_evaluation_master': '', '_train_distribute': None, '_tf_config': gpu_options { per_process_gpu_memory_fraction: 1.0 } , '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_secs': 600, '_log_step_count_steps': 100, '_session_config': None, '_save_checkpoints_steps': None, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_model_dir': '/tmp/tmpxka6vy6t'} From the log, I can see that the random seed was not applied. Whenever I run the script I get different accuracy results. How can I make the result stable? Why random seed is not getting applied?

http://stackoverflow.com/comment/87742786
comment on: http://stackoverflow.com/a/50356990
type: Comment
has text: @slaw Sure, If you really don't want the caller to know anything about asyncio, you can place `run_until_complete` in a function. I was just pointing out that it's a suboptimal use of asyncio. Normally asyncio allows one to compose different async code by starting multiple coroutines "in parallel" or integrating them with callback-based futures. You can even have coroutines that don't know of each other, all running in the same event loop. By hiding the use of asyncio inside a function, you have a design that disables that.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87629352
comment on: http://stackoverflow.com/q/50305634
type: QuestionComment
has text: If you look at the [conda-forge/opencv](https://anaconda.org/conda-forge/opencv/files) page, you'll see that it's supposed to be 3.4. This most likely means that your anaconda environment is a mess where some other package will break if you install opencv 3.4. I will post an answer in a bit, in the meantime please read on how to [manage anaconda environments](https://conda.io/docs/user-guide/tasks/manage-environments.html) very carefully.
score: 1
type: Comment

http://stackoverflow.com/comment/96670777
type: Comment
has text: I was having a similar problem--glad a dictionary can still work even if it displays 'u when printed.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50322730

http://stackoverflow.com/comment/87640360
has text: You're welcome. I found an alternative method as well, thought you may be interested.
comment on: http://stackoverflow.com/a/50312024
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50301380
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50301411
score: 0
has title: Null returns in a simple Python program
answer count: 1
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50301411
tagged with: object
has body: I'm currently working on my Programming Fundamentals w/ Python final project which is a collection of small games. I'm trying to make the game "High Card", where 2 random numbers between 1 &amp; 13(the face values of a 52 card deck) are generated, then compared for the higher number and a winner is displayed. We are required to have seperate files for the Class and Program code. This is what my Class looks like. import random class card: def __init__(self, value): self.card_value = value def deal(self): numb = random.randrange(1, 13) def set_value(self, value): self.card_value = value def get_value(self): return self.card_value def find_face_value(self, numb): #face = 'test' print(numb) if numb == 1: print("numb == 1") return 'Ace' elif numb == 2: return 'two' ## elif numb == 3: ## face = 'three' ## elif numb == 4: ## face = 'four' ## elif numb == 5: ## face = 'five' ## elif numb == 6: ## face = 'six' ## elif numb == 7: ## face = 'seven' ## elif numb == 8: ## face = 'eight' ## elif numb == 9: ## face = 'nine' ## elif numb == 10: ## face = 'ten' ## elif numb == 11: ## face = 'jack' ## elif numb == 12: ## face = 'queen' ## elif numb == 13: ## face = 'king' #return face def __str__(self): return 'Numeric Value: ' + str(self.card_value) I've commented out those (if numb == ...) statements b/c I am testing to see if I can get one correct return. And Here is my Program code for the game. def high_card(): #player1_card = cardClass.card(random.randrange(1, 13)) player1_card = cardClass.card(1) player2_card = cardClass.card(2) card1 = player1_card.find_face_value(player1_card) #player2_card = cardClass.card(random.randrange(1, 13)) card2 = player2_card.find_face_value(player2_card) print('Player 1 got', card1, player1_card, '\nPlayer 2 got', card2, player2_card) And this is the output I recieve when I run the high_card() function. &gt;&gt;&gt; high_card() Numeric Value: 1 Numeric Value: 2 Player 1 got None Numeric Value: 1 Player 2 got None Numeric Value: 2 My problem is in …
tagged with: python
tagged with: class

http://stackoverflow.com/comment/87742906
comment on: http://stackoverflow.com/q/50363277
type: Comment
type: QuestionComment
score: 0
has text: a1.txt file has data which shows the student id and assignment marks: 2345|8 9798|7 student.txt file has data which shows the student id, first name, last name: 2345|joy|smith 9798|peter|Jones so, from the two file, I made two list list1 and list2. now I need an output of those students who have submitted assignments.

http://stackoverflow.com/comment/87479802
type: QuestionComment
has text: delete `runtime.txt` and recreate it with `python-3.6.4`. Nothing should magically edit the content of that file
comment on: http://stackoverflow.com/q/50230255
type: Comment
score: 1

http://stackoverflow.com/comment/87577186
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50280153
has text: I would look into Events API.

http://stackoverflow.com/comment/87813264
comment on: http://stackoverflow.com/a/50382813
score: 0
type: Comment
has text: @eternity1 with the MultiIndex you may not even need the groupby's - take a look at the MultiIndex section of the docs and there are some pretty flexible indexing methods that might obviate the groupby's - http://pandas.pydata.org/pandas-docs/stable/advanced.html
type: AnswerComment

http://stackoverflow.com/comment/87504467
type: AnswerComment
comment on: http://stackoverflow.com/a/50240823
has text: dear sir one more thing is left here please, when user login successfully, the URL always remain (http://127.0.0.1:8000/login/) I want to change this url when user is in student_profile for login to (studenthome)
type: Comment
score: 0

http://stackoverflow.com/comment/87572693
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50277797
type: Comment
has text: @piRSquared great tips sir

http://stackoverflow.com/comment/87608665
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50294355
score: 0
has text: @AmiTavory, given the variable names, both look like questions about kriging.

http://stackoverflow.com/q/50262594
tagged with: tuples
type: AnsweredQuestion
tagged with: python
tagged with: dictionary
has body: so I have this string dictionary of tuples: data = '604452601061112210' NewDict = {'60': ('PUSH1', 1), '61': ('PUSH2', 2), '52' : ('MSTORE', 0 ), '12' : ('ADD', 0)} im trying to scan the string for the dictionary keys, to add to add the dict key to the list, along with the following bytes within the string, for example, it should print out in this order: [PUSH1 44, MSTORE, PUSH1 10, PUSH2 1122, ADD] however, my output is: ['PUSH1 44', 'MSTORE ', 'PUSH1 10', 'PUSH2 2210'] this is my code: i = 0 L = [] while i &lt; len(data): op = data[i:i+2] for item in NewDict: if op in item: i += NewDict[item][1] * 2 pep = NewDict[item][0] + ' ' + data[i:i+NewDict[item][1] * 2] L.append(pep) else: i += 2 print(L) any help would be appreciated, thanks
favorite count: 0
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87543313
has title: python adding tuple to list based on string representation
accepted answer: http://stackoverflow.com/a/50262730
upvote count: 0
has answer: http://stackoverflow.com/a/50262730
possible better answer: http://stackoverflow.com/a/50262720
downvote count: 1
has answer: http://stackoverflow.com/a/50262720

http://stackoverflow.com/comment/88431122
comment on: http://stackoverflow.com/q/50352614
has text: This is python behaviour and not directly related to the RStudio IDE. I'm assuming you are using `matplotlib.pyplot`, which uses *Qt* to draw and the result is what is appearing in the popup window. You can read [here](https://stackoverflow.com/questions/28269157/plotting-in-a-non-blocking-way-with-matplotlib#33050617) and [here](https://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue) about the blocking behaviour and ways you may workaround this.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50359777
favorite count: 0
has title: Index error when trying to access list element
type: Question
tagged with: indexing
possible better answer: http://stackoverflow.com/a/50359846
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/50359911
has answer: http://stackoverflow.com/a/50359871
tagged with: python
has answer: http://stackoverflow.com/a/50359846
has body: So I have a text document in csv style, like this: Line number,1 1,K1,O1,L1,L2,L3 2,K2,O2,L2,L3 3,K3,O3,L1,L3 4,K4,O4,L2 I want to check if the number in the first line, after "Line number", is equal to the first element in one of the following lines. In this case this number can be 1, 2, 3 or 4. My code is as follows: import csv lineNumber = 0 with open('B.txt', 'r') as f: reader = csv.reader(f, delimiter=",") for row in reader: if "Line Number" in row[0]: lineNumber = int(row[1]) &lt;- not sure about this syntax btw print("Is equal") break I end up with this error: if "Line Number" in row[0]: IndexError: list index out of range Everything with row[n] seems to give an error.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87736257
accepted answer: http://stackoverflow.com/a/50359871
answer count: 3
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/comment/87613012
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50298035
has text: I am actually using `print i` in that for loop, thats typo while posting the question..

http://stackoverflow.com/q/50338026
has body: I have a dataframe in below format Col-1Col-2 a d1 a d2 x d3 a d4 f d5 a d6 a d7 I want to merge the values in col-2 by looking at consecutive duplicates in col1.We can see a has two occurrences of consecutive duplicates so.It should merge d1+d2 and d6+d7 separately.The datatype of these columns are strings,d1+d2 means concatenating string d1 with d2 The final output should be as shown below Col-1Col-2 a d1+d2 x d3 a d4 f d5 a d6+d7
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87694423
has comment: http://stackoverflow.com/comment/87694860
linked to: http://stackoverflow.com/q/48216482
has answer: http://stackoverflow.com/a/50339306
tagged with: apache-spark
linked to: http://stackoverflow.com/q/26046410
upvote count: 3
score: 3
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87694099
tagged with: apache-spark-sql
type: Question
tagged with: pyspark
has title: How to merge consecutive duplicate rows in pyspark

http://stackoverflow.com/comment/87532877
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50255630
has text: It ran like that for me, but yes it should've been `links = [link.find_elements_by_tag_name("a") for link in lists]`
type: Comment

http://stackoverflow.com/a/50384817
type: Answer
has body: Find the length of the file(FILE_SIZE) using stat command Open the file in append mode Write to file number of bytes = 9153 - FILE_SIZE
score: 0
answers question: http://stackoverflow.com/q/50384713

http://stackoverflow.com/q/50250609
tagged with: dataframe
tagged with: python
has body: I have a small question about pandas dataframe. How can I pivot my dataframe from this AGE | GROUP-A | ... | GROUP-Q ----------|---------|-----|--------- 00-04 |77 | |133 05-17 |117 | |106 18-25 |64 | |110 to this GROUP | 00-04 | 05-17 | 18-25 ------|-------|-------|------- A |77 |117 |64 ... | | | Q |133 |106 |110
has comment: http://stackoverflow.com/comment/87522336
linked to: http://stackoverflow.com/q/39874956
accepted answer: http://stackoverflow.com/a/50252833
has answer: http://stackoverflow.com/a/50252833
tagged with: pandas
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50253838
has comment: http://stackoverflow.com/comment/87519157
has comment: http://stackoverflow.com/comment/87518667
downvote count: 0
has title: How can I pivot dataframe in a specific way in pandas
has comment: http://stackoverflow.com/comment/87518502
favorite count: 0
possible better answer: http://stackoverflow.com/a/50253838
has comment: http://stackoverflow.com/comment/87518598
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87519755

http://stackoverflow.com/a/50289099
answers question: http://stackoverflow.com/q/50262174
downvote count: 0
upvote count: 1
has body: You should be getting the same output in both the cases. I'll illustrate this with a toy example below: > 1. Setting up the inputs and the parameters of the network: # Set RNN params batch_size = 2 time_steps = 10 vector_size = 5 # Create a random input dataset= tf.random_normal((batch_size, time_steps, vector_size), dtype=tf.float32, seed=42) # input tensor to the RNN X = tf.Variable(dataset, dtype=tf.float32) > 2. Time series LSTM with input: [batch_size, time_steps, vector_size] # Initializers cannot be set to random value, so set it a fixed value. with tf.variable_scope('rnn_full', initializer=tf.initializers.ones()): basic_cell= tf.contrib.rnn.BasicRNNCell(num_units=10) output_f, state_f= tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32) > 3. LSTM called in a loop count of time_steps to create tim_series, where each LSTM is fed an input: [batch_size, vector_size] and the returned state is set as the initial state # Unstack the inputs across time_steps unstack_X = tf.unstack(X,axis=1) outputs = [] with tf.variable_scope('rnn_unstacked', initializer=tf.initializers.ones()): basic_cell= tf.contrib.rnn.BasicRNNCell(num_units=10) #init_state has to be set to zero init_state = basic_cell.zero_state(batch_size, dtype=tf.float32) # Create a loop of N LSTM cells, N = time_steps. for i in range(len(unstack_X)): output, state= tf.nn.dynamic_rnn(basic_cell, tf.expand_dims(unstack_X[i], 1), dtype=tf.float32, initial_state= init_state) # copy the init_state with the new state init_state = state outputs.append(output) # Transform the output to [batch_size, time_steps, vector_size] output_r = tf.transpose(tf.squeeze(tf.stack(outputs)), [1, 0, 2]) > 4. Checking the outputs with tf.Session() as sess: sess.run(tf.global_variables_initializer()) out_f, st_f =sess.run([output_f, state_f]) out_r, st_r =sess.run([output_r, state]) npt.assert_almost_equal(out_f, out_r) npt.assert_almost_equal(st_f, st_r) Both the states and the outputs matches.
type: Answer
score: 1

http://stackoverflow.com/comment/87766612
type: AnswerComment
comment on: http://stackoverflow.com/a/50373474
score: 0
has text: And the stopwordfile like this: x y your yours yourself yourselves you yond yonder yon ye yet z zillion j u umpteen usually us username uponed upons uponing upon ups upping upped up unto until unless unlike unliker unlikest under underneath use used usedest r rath rather rathest rathe re relate related relatively regarding really res respecting respectively q quite que qua n neither neaths neath nethe nethermost necessary necessariest necessarier never nevertheless nigh nighest nigher nine noone nobody
type: Comment

http://stackoverflow.com/a/50331400
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/87735879
has body: if encoding to utf-8 is failing try to encode to ascii try both : - print(soup.encode('utf-8').prettify()) and print(soup.encode('ascii').prettify())
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/50331257
has comment: http://stackoverflow.com/comment/87678892

http://stackoverflow.com/comment/87692809
score: 0
type: Comment
type: AnswerComment
has text: in my code its float: first={'a': '0.1000', 'b': '0.2000', 'c': '0.2400'} so I change it to float but now getting this error:TypeError: float() argument must be a string or a number, not 'NoneType' What this could be ?
comment on: http://stackoverflow.com/a/50317297

http://stackoverflow.com/q/50339726
answer count: 2
has body: Say someone gives me a string like: "[[A,B],[C,D]]" and I want to extract the list it describes: [[A,B],[C,D]] How do I do this? P.S. A, B, C, D are just placeholders, they could be numeric values or strings.
linked to: http://stackoverflow.com/q/15197673
downvote count: 0
has title: Convert string to the list it describes
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87695742
has comment: http://stackoverflow.com/comment/87695725
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87698030
linked to: http://stackoverflow.com/q/1894269
has comment: http://stackoverflow.com/comment/87695722
has answer: http://stackoverflow.com/a/50339774
tagged with: python
duplicate of: http://stackoverflow.com/q/1894269
has answer: http://stackoverflow.com/a/50339745

http://stackoverflow.com/a/50383930
upvote count: 3
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87784424
accepted answer of: http://stackoverflow.com/q/50383883
downvote count: 0
answers question: http://stackoverflow.com/q/50383883
type: Answer
has body: I believe need filter values, convert to numpy array and then to list: transactions = dataset.iloc[:num_rows, :num_cols].astype(str).values.tolist()
has comment: http://stackoverflow.com/comment/87784389

http://stackoverflow.com/comment/134165263
has text: This is very misleading, in case the length of the range is not divisible by `step`, the results will not be distanced by `step`. It is a significantly different behavior from arange, I don’t see how this can substitute it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/57321916
type: AnswerComment

http://stackoverflow.com/comment/87656340
comment on: http://stackoverflow.com/q/50316978
type: Comment
type: QuestionComment
score: 0
has text: this is the error: [link]https://snag.gy/SxOY7A.jpg

http://stackoverflow.com/q/50364381
has comment: http://stackoverflow.com/comment/87770454
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/46432589
has comment: http://stackoverflow.com/comment/87770194
downvote count: 1
accepted answer: http://stackoverflow.com/a/50366241
favorite count: 0
has answer: http://stackoverflow.com/a/50365170
possible better answer: http://stackoverflow.com/a/50404459
has body: I am new to Google Cloud Platform and in my whole I have been working on Python 3. I am trying to find out which version of Python is more complete for Google App Engine: Python 2.7 or Python 3. As I'm starting to work with Google App Engine I have realised that continuing using Python 3 seems too painful as basic tools like dev_appserver.py are written for Python 2 only. Now I am hitting the opposite problem: cloudstorage module seems to exist only for python3. Again, when I install it, seems the only way I can test read/write to google bucket locally is by authenticating with google.appengine.ext, which in turn only works within dev_appserver.py or remotely. This leaves me confused which environment to chose. What is a general agreement / what is the focus of Google App Engine: Python 2 or Python 3?
type: Question
linked to: http://stackoverflow.com/q/48564834
tagged with: google-app-engine
tagged with: python
linked to: http://stackoverflow.com/q/47009532
has answer: http://stackoverflow.com/a/50376996
tagged with: google-cloud-storage
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50366241
answer count: 4
has title: Best practices with google cloud app engine: Python2 or Python3?
has answer: http://stackoverflow.com/a/50404459
tagged with: google-cloud-platform
upvote count: 2

http://stackoverflow.com/q/50251877
accepted answer: http://stackoverflow.com/a/50252599
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/50252599
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a couple of strings that I want to save as a BitMap Image of resolution 264*176 for displaying on an E-ink screen(because apparently eInk displays can't show text horizontally). Please note that the blue background is only to show the dimensions of the image. The actual background will be white. I've tried PIL without success. Can someone suggest any approach in Python3?
answer count: 1
has title: Writing Strings as a Bitmap image
tagged with: bitmap
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50291225
linked to: http://stackoverflow.com/q/49053865
type: AnsweredQuestion
score: 0
tagged with: anaconda
has comment: http://stackoverflow.com/comment/87598701
tagged with: python
has body: I am installing hachoir-metadata from reference[3]. I have completed the following for the installation of hachoir-metadata: conda create -n hachoir-metadata pip python=3.5 activate hachoir-metadat pip install --upgrade hachoir-metadata I am using the software versions below: Python Version 3.5.5 Anaconda: 3.6.5 I get an error stating Command "python setup.py egg_info" failed with error code 1 in...\hachoir-metda which is shown below. I have completed the following in attempt to fix the problem: 1)Installed setuptools pip install --upgrade setuptools[1] 2)Installed ipykernel conda create -n ipykernel pip python=3.5 activate ipykernel pip install --upgrade ipykernel Non of the above work. Firstly, when analyzing the error it is due to a syntax issue. Therefore, could the error be caused by the fact that the Python version is incompatible(i.e. hachoir-metadata uses an old version of python but this should not be the case right)? What can be done to solve this issue? 1 https://github.com/facebook/prophet/issues/418 [2] http://ipython.readthedocs.io/en/stable/install/kernel_install.html [3] https://pypi.org/project/hachoir-metadata/#description
has title: Error Installing Hachoir-metadata |Command "python setup.py egg_info" failed with error code 1 in...\hachoir-metda
tagged with: hachoir-parser
accepted answer: http://stackoverflow.com/a/50292442
answer count: 1
has answer: http://stackoverflow.com/a/50292442
type: Question

http://stackoverflow.com/q/50347160
has comment: http://stackoverflow.com/comment/87710511
upvote count: 1
type: UnansweredQuestion
has body: I want to call a function in python after a mouse release button.Currently I am calling the same function after the key 'a' is pressed.Also I want to close tkinter window automatically after a option is selected. Here is my code: def onkeypress1(event): if event.key == 'a': def option_changed(*args): c=variable.get() object_list.append(c) print c return c master = Tk() variable = StringVar(master) variable.set("select") # default value variable.trace("w", option_changed) w = OptionMenu(master, variable, "INDIA", "USA", "UK") w.pack() mainloop() I want to call function onkeypress1() after the mouse release button.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87713253
has comment: http://stackoverflow.com/comment/87713624
has comment: http://stackoverflow.com/comment/87713642
has answer: http://stackoverflow.com/a/50347285
has answer: http://stackoverflow.com/a/50357567
has title: calling a function in python after mouse release & closing the tkinter window after selcting a option from it
linked to: http://stackoverflow.com/q/16548757
tagged with: python
score: 0
answer count: 2
tagged with: tkinter

http://stackoverflow.com/comment/87702679
type: QuestionComment
has text: @AChampion: The value itself is the contribution so I want to have some keys with highest values.
comment on: http://stackoverflow.com/q/50343137
score: 0
type: Comment

http://stackoverflow.com/q/50376280
has title: Got a runtime error but the actual operation executed succesfully
has comment: http://stackoverflow.com/comment/87768809
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/10397121
answer count: 0
score: 1
duplicate of: http://stackoverflow.com/q/10397121
downvote count: 0
tagged with: python-2.x
upvote count: 1
has body: I'm on the presence of a very weird behavior. Consider the following scenario: &gt;&gt;&gt; t = ([1],) &gt;&gt;&gt; t[0] [1] &gt;&gt;&gt; t[0] += [2] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment &gt;&gt;&gt; t[0] [1, 2] I have two questions: Why does t[0] += [2] fails? Why was the list updated if the assignment failed? As far as I'm aware this is happening on both Python 2.x and Python 3.x
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50339547
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50339487
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50339487
downvote count: 0
upvote count: 1
has body: It's easy to do with zip using slices, except that zip creates tuples instead of lists: &gt;&gt;&gt; list(zip(path[0:], path[1:])) [([0, 7], [167, 118]), ([167, 118], [150, 173]), ([150, 173], [37, 21]), ([37, 21], [48, 150]), ([48, 150], [0, 7])] If you absolutely need lists instead of tuples, you can create it similarly with a list comprehension. &gt;&gt;&gt; [[a, b] for a, b in zip(path[0:], path[1:])] [[[0, 7], [167, 118]], [[167, 118], [150, 173]], [[150, 173], [37, 21]], [[37, 21], [48, 150]], [[48, 150], [0, 7]]]

machine-learning
tags question: http://stackoverflow.com/q/50306214
tags question: http://stackoverflow.com/q/50374236
type: Tag
tags question: http://stackoverflow.com/q/50319066
tags question: http://stackoverflow.com/q/50361783
tags question: http://stackoverflow.com/q/50347481
tags question: http://stackoverflow.com/q/50258944
tags question: http://stackoverflow.com/q/50322857
tags question: http://stackoverflow.com/q/50245684
tags question: http://stackoverflow.com/q/50241592
tags question: http://stackoverflow.com/q/50353078
tags question: http://stackoverflow.com/q/50244662
tags question: http://stackoverflow.com/q/50362165
tags question: http://stackoverflow.com/q/50353176
tags question: http://stackoverflow.com/q/50336110
tags question: http://stackoverflow.com/q/50329109
tags question: http://stackoverflow.com/q/50244854
tags question: http://stackoverflow.com/q/50260642
tags question: http://stackoverflow.com/q/50289947
tags question: http://stackoverflow.com/q/50267414
tags question: http://stackoverflow.com/q/50247900
tags question: http://stackoverflow.com/q/50332786
tags question: http://stackoverflow.com/q/50255044
tags question: http://stackoverflow.com/q/50356091
tags question: http://stackoverflow.com/q/50288258
tags question: http://stackoverflow.com/q/50296817
tags question: http://stackoverflow.com/q/50264369
tags question: http://stackoverflow.com/q/50291549
tags question: http://stackoverflow.com/q/50274461
tags question: http://stackoverflow.com/q/50319317
tags question: http://stackoverflow.com/q/50322799
tags question: http://stackoverflow.com/q/50263007
tags question: http://stackoverflow.com/q/50361195
tags question: http://stackoverflow.com/q/50266975
tags question: http://stackoverflow.com/q/50384842
tags question: http://stackoverflow.com/q/50259290
tags question: http://stackoverflow.com/q/50369758
tags question: http://stackoverflow.com/q/50307105
tags question: http://stackoverflow.com/q/50257614
tags question: http://stackoverflow.com/q/50376990
tags question: http://stackoverflow.com/q/50267032
tags question: http://stackoverflow.com/q/50238812
tags question: http://stackoverflow.com/q/50323770
tags question: http://stackoverflow.com/q/50248736
tags question: http://stackoverflow.com/q/50343099
tags question: http://stackoverflow.com/q/50364860
tags question: http://stackoverflow.com/q/50325786
tags question: http://stackoverflow.com/q/50311901
tags question: http://stackoverflow.com/q/50306988
tags question: http://stackoverflow.com/q/50236372
tags question: http://stackoverflow.com/q/50319858
tags question: http://stackoverflow.com/q/50300412
tags question: http://stackoverflow.com/q/50300441
tags question: http://stackoverflow.com/q/50307866
tags question: http://stackoverflow.com/q/50238979
tags question: http://stackoverflow.com/q/50375207
tags question: http://stackoverflow.com/q/50317114
tags question: http://stackoverflow.com/q/50317335
tags question: http://stackoverflow.com/q/50376169
tags question: http://stackoverflow.com/q/50259009
tags question: http://stackoverflow.com/q/50380844
tags question: http://stackoverflow.com/q/50359055
tags question: http://stackoverflow.com/q/50279865
tags question: http://stackoverflow.com/q/50258960
tags question: http://stackoverflow.com/q/50282989
tags question: http://stackoverflow.com/q/50372220
tags question: http://stackoverflow.com/q/50270283
tags question: http://stackoverflow.com/q/50268691
tags question: http://stackoverflow.com/q/50260459
tags question: http://stackoverflow.com/q/50285883
tags question: http://stackoverflow.com/q/50355859
tags question: http://stackoverflow.com/q/50241216
tag name: machine-learning
tags question: http://stackoverflow.com/q/50323654
tags question: http://stackoverflow.com/q/50315140
tags question: http://stackoverflow.com/q/50277397
tags question: http://stackoverflow.com/q/50272689
tags question: http://stackoverflow.com/q/50350816
tags question: http://stackoverflow.com/q/50319788
tags question: http://stackoverflow.com/q/50325848

http://stackoverflow.com/comment/87647141
has text: Are you looking for `enumerate()` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/50315675
score: 3
type: Comment

http://stackoverflow.com/q/50267185
accepted answer: http://stackoverflow.com/a/50267205
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/16476924
answer count: 1
has body: I want to travel round the series index In [44]: type(ed1) Out[44]: pandas.core.series.Series In [43]: for _, row in ed1.iterrows(): ...: print(row.name) and I get this error: AttributeError: 'Series' object has no attribute 'iterrows' Does series has any methods like iterrows?
favorite count: 0
tagged with: series
type: Question
tagged with: python
has title: Iterate over pandas series
score: 22
upvote count: 22
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50267205

http://stackoverflow.com/q/50351011
tagged with: python
tagged with: merge
has body: I'm extremely new to python, and am having some issues attempting to merge identical excel tabs (same column labels and data) into a aggregated tab. I've been looking through various resources, and this link appears to be the best resource, but it doesn't quite mesh with the way I've been shown. I am interested in seeing if there is any part of the code below that is viable when attempting this merge, and by extension, I'm interested in seeing if there are any other resources out there that may be a potential solution or mirror the style of coding that I've been taught. Thank You! import pandas as pd #import numpy as np #Define Dataframes df_ui = pd.read_excel('U:/ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='UreaImports') df_ue = pd.read_excel('U:/ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='UreaExports') df_uani = pd.read_excel('U://ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='UANImports') df_uane = pd.read_excel('U://ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='UANExports') df_nh3i = pd.read_excel('U://ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='NH3Imports') df_nh3e = pd.read_excel('U://ABA/Data/Trade/GTIS/GTIS Trade Shell.xlsx', sheet_name='NH3Exports') #Merge Dataframes df_raw = pd.merge(df_ui,df_ue,df_uani,df_uane,df_nh3i,df_nh3e) # Sends all data tables to an excel file writer = pd.ExcelWriter('U:/ABA/Data/Trade/GTIS/GTIS Python Build.xlsx', engine='xlsxwriter') df_raw.to_excel(writer, sheet_name ='raw') writer.save()
answer count: 0
tagged with: aggregate
has title: Is there a way to merge identical excel tabs into one dataframe using python?
downvote count: 0
upvote count: 1
tagged with: excel
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1

pandas
tags question: http://stackoverflow.com/q/50240646
tags question: http://stackoverflow.com/q/50313698
tags question: http://stackoverflow.com/q/50249979
tags question: http://stackoverflow.com/q/50321527
tags question: http://stackoverflow.com/q/50260451
tags question: http://stackoverflow.com/q/50327122
tags question: http://stackoverflow.com/q/50332455
tags question: http://stackoverflow.com/q/50342525
tags question: http://stackoverflow.com/q/50240187
tags question: http://stackoverflow.com/q/50368090
tags question: http://stackoverflow.com/q/50297777
tags question: http://stackoverflow.com/q/50319311
tags question: http://stackoverflow.com/q/50301039
tags question: http://stackoverflow.com/q/50295833
tags question: http://stackoverflow.com/q/50343538
tags question: http://stackoverflow.com/q/50264334
tags question: http://stackoverflow.com/q/50302103
tags question: http://stackoverflow.com/q/50326464
tags question: http://stackoverflow.com/q/50356233
tags question: http://stackoverflow.com/q/50274771
tags question: http://stackoverflow.com/q/50373343
tags question: http://stackoverflow.com/q/50276334
tags question: http://stackoverflow.com/q/50306919
tags question: http://stackoverflow.com/q/50266487
tags question: http://stackoverflow.com/q/50302614
tags question: http://stackoverflow.com/q/50309899
tags question: http://stackoverflow.com/q/50274461
tags question: http://stackoverflow.com/q/50352386
tags question: http://stackoverflow.com/q/50378153
tags question: http://stackoverflow.com/q/50314826
tags question: http://stackoverflow.com/q/50249924
tags question: http://stackoverflow.com/q/50283900
tags question: http://stackoverflow.com/q/50300528
tags question: http://stackoverflow.com/q/50380295
tags question: http://stackoverflow.com/q/50239129
tags question: http://stackoverflow.com/q/50300679
tags question: http://stackoverflow.com/q/50258558
tags question: http://stackoverflow.com/q/50281762
tags question: http://stackoverflow.com/q/50230440
tags question: http://stackoverflow.com/q/50257586
tags question: http://stackoverflow.com/q/50378401
tags question: http://stackoverflow.com/q/50379350
tags question: http://stackoverflow.com/q/50347089
tags question: http://stackoverflow.com/q/50282197
tags question: http://stackoverflow.com/q/50370467
tags question: http://stackoverflow.com/q/50248548
tags question: http://stackoverflow.com/q/50264678
tags question: http://stackoverflow.com/q/50316797
tags question: http://stackoverflow.com/q/50346244
tags question: http://stackoverflow.com/q/50367403
tags question: http://stackoverflow.com/q/50296287
tags question: http://stackoverflow.com/q/50338849
tags question: http://stackoverflow.com/q/50249653
tags question: http://stackoverflow.com/q/50235946
tags question: http://stackoverflow.com/q/50302180
tags question: http://stackoverflow.com/q/50275077
tags question: http://stackoverflow.com/q/50263851
tags question: http://stackoverflow.com/q/50316180
tags question: http://stackoverflow.com/q/50293639
tags question: http://stackoverflow.com/q/50327507
tags question: http://stackoverflow.com/q/50306696
tags question: http://stackoverflow.com/q/50371084
tags question: http://stackoverflow.com/q/50344911
tags question: http://stackoverflow.com/q/50249340
tags question: http://stackoverflow.com/q/50345458
tags question: http://stackoverflow.com/q/50238812
tags question: http://stackoverflow.com/q/50360890
tags question: http://stackoverflow.com/q/50367703
tags question: http://stackoverflow.com/q/50319605
tags question: http://stackoverflow.com/q/50361352
tags question: http://stackoverflow.com/q/50361356
tags question: http://stackoverflow.com/q/50278300
tags question: http://stackoverflow.com/q/50297355
tags question: http://stackoverflow.com/q/50245727
tags question: http://stackoverflow.com/q/50320167
tags question: http://stackoverflow.com/q/50349287
tags question: http://stackoverflow.com/q/50279402
tags question: http://stackoverflow.com/q/50382591
tags question: http://stackoverflow.com/q/50372272
tags question: http://stackoverflow.com/q/50274005

http://stackoverflow.com/comment/87529362
comment on: http://stackoverflow.com/q/50242285
score: 0
type: Comment
type: QuestionComment
has text: OK, that's fixed....YYYY-MM-DD isn't a problem. Excel's UsedRange command was pulling in an extra column. Thanks for your help.

http://stackoverflow.com/comment/87632556
score: 0
type: AnswerComment
has text: Thank you! I'll read more on it.
type: Comment
comment on: http://stackoverflow.com/a/50307890

http://stackoverflow.com/q/50378113
has comment: http://stackoverflow.com/comment/87772995
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50378812
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/87772909
type: Question
has title: Error using scipy.io.wavfile
has comment: http://stackoverflow.com/comment/87773014
tagged with: python
has comment: http://stackoverflow.com/comment/87774133
has comment: http://stackoverflow.com/comment/87773010
has answer: http://stackoverflow.com/a/50378812
has comment: http://stackoverflow.com/comment/87772982
has body: I'm having some troubles using the function read from scipy.io.wavfile. My attempt: from scipy.io.wavfile import read import matplotlib.pyplot as plt fs, data = read('A.wav') This this the error message: The file A.wav is in the same directory as the .py file What's wrong? Thank you.
has comment: http://stackoverflow.com/comment/87773080

http://stackoverflow.com/q/50383580
tagged with: pymysql
downvote count: 0
favorite count: 0
tagged with: python-2.7
upvote count: 5
tagged with: python
tagged with: mysql
has body: lst = [{'Fruit':'Apple','HadToday':2},{'Fruit':'Banana','HadToday':8}] I have a long list of dictionaries of the form above. I have two fixed variables. person = 'Sam' date = datetime.datetime.now() I wish to insert this information into a mysql table. How I do it currently for item in lst: item['Person'] = person item['Date'] = date cursor.executemany(""" INSERT INTO myTable (Person,Date,Fruit,HadToday) VALUES (%(Person)s, %(Date)s, %(Fruit)s, %(HadToday)s)""", lst) conn.commit() Is their a way to do it, that bypasses the loop as the person and date variables are constant. I have tried lst = [{'Fruit':'Apple','HadToday':2},{'Fruit':'Banana','HadToday':8}] cursor.executemany(""" INSERT INTO myTable (Person,Date,Fruit,HadToday) VALUES (%s, %s, %(Fruit)s, %(HadToday)s)""", (person,date,lst)) conn.commit() TypeError: not enough arguments for format string
has title: Insert list of dictionaries and variable into table
type: Question
score: 5
has answer: http://stackoverflow.com/a/50384018
has comment: http://stackoverflow.com/comment/87784514
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87745582
score: 0
has text: @GordThompson I realized that thanks. Yep I am using most recent and I set fast_executemany to True yet insertion is very slow.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50359962

http://stackoverflow.com/q/50355741
has answer: http://stackoverflow.com/a/50355888
tagged with: readline
favorite count: 0
type: Question
has title: How to split out string occurrences to an individual txt file?
tagged with: split
has answer: http://stackoverflow.com/a/50355889
has answer: http://stackoverflow.com/a/50356315
upvote count: 1
tagged with: python
has body: For example I've this txt files containing these lines, chicken chicken duck duck duck parrot parrot chicken chicken chicken How can I read it line by line and split chicken (2 lines) to 1.txt, duck (3 lines) to 2.txt and parrot (2 lines) to 3.txt and the last chicken (3 lines) occurrence to a 4.txt? I've figured out until here, count = 0 with open("test.txt") as rl: for num, line in enumerate (rl, 1): s = list(line) if "chicken" in line: count += 1 finaljoin = "".join(s) print(count) with open("chicken.txt", 'a+') as f: f.write(finaljoin) But my solution above only grab the whole chicken (total 5) into one file. The actual plan was to grab the 1st two line to a txt file and the last two chicken line to another txt file. Because it is being split by another animals.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87728016
answer count: 3
accepted answer: http://stackoverflow.com/a/50356315
possible better answer: http://stackoverflow.com/a/50355888
downvote count: 1

http://stackoverflow.com/comment/87575199
score: 0
type: AnswerComment
has text: it doesn't return anything for me, just Okay word !
type: Comment
comment on: http://stackoverflow.com/a/50279298

http://stackoverflow.com/comment/100283543
score: 0
type: Comment
comment on: http://stackoverflow.com/a/56867111
type: AnswerComment
has text: Rather than linking to external URL, please add relevant code and explanation in the answer.

http://stackoverflow.com/a/50264164
has comment: http://stackoverflow.com/comment/87546453
has comment: http://stackoverflow.com/comment/87546319
answers question: http://stackoverflow.com/q/50264150
has comment: http://stackoverflow.com/comment/87546382
has comment: http://stackoverflow.com/comment/87546487
has comment: http://stackoverflow.com/comment/87546434
score: 8
has comment: http://stackoverflow.com/comment/87546389
has comment: http://stackoverflow.com/comment/87546416
has comment: http://stackoverflow.com/comment/87546397
has comment: http://stackoverflow.com/comment/87546324
has body: So you call strip on each character.... and then what? You don't update the string, because strings are immutable and i.strip is not an inplace operation. A naive improvement over your solution would filtering characters out inside a list comprehension and then doing a join on the result: vowels = {'i','o','a','u','e'} def anti_vowel(text): return ''.join([c for c in text if c not in vowels]) A small note: if your string contains mixed case, you may want to either Lowercase text, or Augment vowels to contain uppercase vowels: vowels = set('aeiouAEIOU'), or Use str.casefold (as per @Adam Smith's comment)—augmenting vowels is no longer needed in that case: return ''.join([c for c in text if c.casefold() not in vowels]) You can get even better with str.translate (this works on python-3.x): mapping = str.maketrans(dict.fromkeys(vowels, '')) # create a global mapping once def anti_vowel(text): return text.translate(mapping))
upvote count: 8
downvote count: 0
type: Answer

http://stackoverflow.com/a/50320784
has comment: http://stackoverflow.com/comment/92264594
accepted answer of: http://stackoverflow.com/q/50319066
has comment: http://stackoverflow.com/comment/92266811
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/92265628
answers question: http://stackoverflow.com/q/50319066
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92265254
has comment: http://stackoverflow.com/comment/92267888
has body: It is due to large gradient updates caused by large numbers in training data. When using a neural network, you should first ensure that the training data falls in a small range (usually [-1,1] or [0,1]) to help the optimization process and prevent disruptive gradient updates. Therefore, you should first normalize data. In this case, one good candidate would be log-normalization. Further, the 'accuracy' as a metric in Keras is used in case of a classification problem. In a regression problem, using it does not make sense, and instead it's better to use a relevant metric like "mean absolute error" or 'mae'.
has comment: http://stackoverflow.com/comment/92265750
has comment: http://stackoverflow.com/comment/92267267
has comment: http://stackoverflow.com/comment/92264840
has comment: http://stackoverflow.com/comment/92267024
type: Answer
has comment: http://stackoverflow.com/comment/92266629

http://stackoverflow.com/q/50308390
tagged with: matplotlib
answer count: 1
linked to: http://stackoverflow.com/q/48442713
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50309035
type: UnansweredQuestion
has body: I have tried to find a way to display the coordinate-axes of a 3D-space at a different location than matplotlib does by default. To show the desired situation I have provided two figures in which I draw the eight corners of a cube. Figure 1: matplotlib-default of drawing coordinate axes Figure 1 is the default presentation of the coordinate axes of matplotlib. The coordinate axes are drawn "at the ends of spaces. Figure 2: desired place when drawing coordinate axes The presentation in Figure 2 shows the coordinate axes originating from one common point. This is the desired presentation. The question is now: "How can I achieve the desired situation?" I have looked around and could not find an answer to this question. I think it may be a simple setting that is not so easy find, an therefore I have also supplied the code that generates the "matplotlib default presentation" (see below). import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot_3Dcube(): """Plots a 3D cube in a 3D-window """ #-------------------------------------- # PROCESS ARGUMENTS AND LOCAL VARIABLES #-------------------------------------- mycube = cube() # The cube to be plotted #--------------- # Setup the plot #--------------- fig = plt.figure() ax = fig.add_subplot(111,projection="3d") #--------------------------------------------- # Format the point-data and add it to the plot #--------------------------------------------- colour = (1.0, 0, 0, 1) # RGB, alpha mrkr = '^' s = 50 print (mycube) ax.scatter(mycube[:,0],mycube[:,1],mycube[:,2], c = colour, marker = mrkr ) ptnr=0 for row in mycube: ptnr += 1 ax.text(row[0],row[1],row[2],str(ptnr), size = 8, color = (0,0,0) ) #---------------- # Format the plot #---------------- ax.set_xlabel('X as') ax.set_ylabel('Y as') ax.set_zlabel('Z as') #-------------- # SHOW THE PLOT #-------------- ax.view_init(15,30) plt.show() #=-=-=-=-=-=-=-=-=-=-=- # RETURN FROM FUNCTION #=-=-=-=-=-=-=-=-=-=-…
tagged with: python
tagged with: draw
has title: How can I draw coordinate axes at a specific location?
score: 1

http://stackoverflow.com/q/50283850
has comment: http://stackoverflow.com/comment/87584370
tagged with: python
accepted answer: http://stackoverflow.com/a/50283935
upvote count: 2
type: AnsweredQuestion
has body: I'd like to create a function that has different types of enemies in it. But I do not know the amount of enemies, they will be randomly generated. Then, I want to print them out by having an input statement saying press 1 for the first enemy, 2 for the second, etc. So it'd be like, you got 3 zombies, 15 ghosts, etc But, I want it to be created in a way that I can later on add more inputs so that the user can modify it, like 'which type of enemy do you want to add/delete enemies from?. I need help on how to do this, please. Here's what I got so far, if my code can be modified to be simpler, make more sense, in a way I can learn it and understand, that'd be perfect, thanks! import random def fillEnemyField(): print("Here's your first EnemyField") zombies = [] zombies = random.randrange(0, 15) trolls = [] trolls = random.randrange(0, 15) vampires = [] vampires = random.randrange(0, 15) ghosts = [] ghosts = random.randrange(0, 15) def printEnemyField(): choice1 = int(input("Press 1 to get a new EnemyField")) choice2 = int(input("Press 2 to get a new EnemyField")) choice3 = int(input("Press 3 to get a new EnemyField")) choice4 = int(input("Press 4 to get a new EnemyField")) choice5 = int(input("Press 5 to quit")) while choice != 5: if choice ==1: choice = print(fillEnemyField(zombies)) ..............................
has answer: http://stackoverflow.com/a/50283976
possible better answer: http://stackoverflow.com/a/50283976
answer count: 2
has comment: http://stackoverflow.com/comment/87584134
has comment: http://stackoverflow.com/comment/87584314
has comment: http://stackoverflow.com/comment/87584176
has comment: http://stackoverflow.com/comment/87584123
score: 1
has title: How to store values in a function and be printed/modified from another?
downvote count: 1
has comment: http://stackoverflow.com/comment/87584159
has answer: http://stackoverflow.com/a/50283935
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87584223

http://stackoverflow.com/q/50318278
tagged with: python
has answer: http://stackoverflow.com/a/50318304
has comment: http://stackoverflow.com/comment/87652371
tagged with: class
accepted answer: http://stackoverflow.com/a/50318304
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/87652345
answer count: 1
has body: Consider the following code, I want you to explain why the code doesn't work because I have seen others to assign the class attributes outside __init__ and call the attributes in one method from another, what is wrong with mine. The following three prints all result error saying the class has no attributes whatsoever. class Person(object): def __init__(self, age, height): self.age = age self.height = height def weight_kg(self): self.weight = 60 def ratio_kg2height(self): self.ratio = self.weight / self.height return self.ratio mike = Person(23, 170) print mike.weight print mike.ratio_kg2height() print mike.ratio
favorite count: 0
type: Question
has title: Python class attributes inside a method
upvote count: 1

http://stackoverflow.com/q/50336604
has title: Is there a Celery functionality analogous to RQ's worker burst?
has body: RQ provides a .work(burst=True) method for its workers that are well-suited for integration tests, when you have code that enqueue's a task and then wants that task to be run synchronously. I cannot find any functionality on Celery that works like that. Please help!
downvote count: 0
answer count: 1
upvote count: 1
tagged with: celery
favorite count: 0
tagged with: task
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50342126
tagged with: python-rq
score: 1

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/50309702
tags question: http://stackoverflow.com/q/50253044
tags question: http://stackoverflow.com/q/50265063
tags question: http://stackoverflow.com/q/50359314
tags question: http://stackoverflow.com/q/50255366
tags question: http://stackoverflow.com/q/50313153
tags question: http://stackoverflow.com/q/50302418
tags question: http://stackoverflow.com/q/50380004
tags question: http://stackoverflow.com/q/50283612
tags question: http://stackoverflow.com/q/50321297
tags question: http://stackoverflow.com/q/50233522
tags question: http://stackoverflow.com/q/50367227
tags question: http://stackoverflow.com/q/50244721
tags question: http://stackoverflow.com/q/50265570
tags question: http://stackoverflow.com/q/50372057
tags question: http://stackoverflow.com/q/50235950
tags question: http://stackoverflow.com/q/50282309
tags question: http://stackoverflow.com/q/50325878
tags question: http://stackoverflow.com/q/50300432
tags question: http://stackoverflow.com/q/50310148
tags question: http://stackoverflow.com/q/50270199
tags question: http://stackoverflow.com/q/50265801
tags question: http://stackoverflow.com/q/50276304
tags question: http://stackoverflow.com/q/50380164
tags question: http://stackoverflow.com/q/50244024
tags question: http://stackoverflow.com/q/50294963
tags question: http://stackoverflow.com/q/50379072
tags question: http://stackoverflow.com/q/50297585
tags question: http://stackoverflow.com/q/50384261
tags question: http://stackoverflow.com/q/50323540
type: Tag
tags question: http://stackoverflow.com/q/50283124
tags question: http://stackoverflow.com/q/50354157
tag name: html
tags question: http://stackoverflow.com/q/50254906
tags question: http://stackoverflow.com/q/50319595
tags question: http://stackoverflow.com/q/50324894
tags question: http://stackoverflow.com/q/50289165
tags question: http://stackoverflow.com/q/50241365
tags question: http://stackoverflow.com/q/50330071
tags question: http://stackoverflow.com/q/50360698
tags question: http://stackoverflow.com/q/50296844
tags question: http://stackoverflow.com/q/50321100
tags question: http://stackoverflow.com/q/50311585
tags question: http://stackoverflow.com/q/50339365
tags question: http://stackoverflow.com/q/50299695
tags question: http://stackoverflow.com/q/50259807
tags question: http://stackoverflow.com/q/50239294
tags question: http://stackoverflow.com/q/50261760
tags question: http://stackoverflow.com/q/50286355
tags question: http://stackoverflow.com/q/50382559
tags question: http://stackoverflow.com/q/50382343

http://stackoverflow.com/a/50406642
type: AcceptedAnswer
has body: def multi_output_generator(hdf5_file, nb_data, batch_size): """ Generates batches of tensor image data in form of ==&gt; x, [y1, y2, y3, y4, y5] for use in a multi-output Keras model. # Arguments hdf5_file: the hdf5 file which contains the images and the annotations. nb_data: total number of samples saved in the array. batch_size: size of the batch to generate tensor image data for. # Returns A five-output generator. """ batches_list = list(range(int(ceil(float(nb_data) / batch_size)))) while True: # loop over batches for n, i in enumerate(batches_list): i_s = i * batch_size # index of the first image in this batch i_e = min([(i + 1) * batch_size, nb_data]) # index of the last image in this batch x = hdf5_file["x_train"][i_s:i_e, ...] # read labels y1 = hdf5_file["y1"][i_s:i_e] y2 = hdf5_file["y2"][i_s:i_e] y3 = hdf5_file["y3"][i_s:i_e] y4 = hdf5_file["y4"][i_s:i_e] y5 = hdf5_file["y5"][i_s:i_e] yield x, [y1, y2, y3, y4 ,y5]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50333532
upvote count: 5
answers question: http://stackoverflow.com/q/50333532
type: Answer
has comment: http://stackoverflow.com/comment/87837445
score: 5

http://stackoverflow.com/comment/87495138
type: Comment
type: QuestionComment
score: 0
has text: In general, `some_string += some_other_string` in a loop will be slow. It has quadratic complexity (although the interpreter will try to optimize it), however, you should refractor it to use a `list` with `.append` then `''.join` at the end.
comment on: http://stackoverflow.com/q/50235071

http://stackoverflow.com/a/50334760
has comment: http://stackoverflow.com/comment/87686653
has body: This is one way with csv module, which avoids explicitly accounting for some of the repetitive tasks (comma delimiter, new line, etc). from io import StringIO import csv mystr = StringIO("""1,foo,bar,1 1,foo,bar,2 21,foo,bar,8""") res = [] # replace mystr with open('file.csv', 'r') with mystr as f: reader = filter(None, csv.reader(f)) # ignore empty lines for line in reader: if line[0].isdigit(): res.append([int(line[0]), line[1], line[2], int(line[3])]) print(res) [[1, 'foo', 'bar', 1], [1, 'foo', 'bar', 2], [21, 'foo', 'bar', 8]]
answers question: http://stackoverflow.com/q/50334685
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50334685
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/50280247
linked to: http://stackoverflow.com/q/4079171
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87608147
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87577339
favorite count: 0
has comment: http://stackoverflow.com/comment/87603681
has comment: http://stackoverflow.com/comment/87603372
has comment: http://stackoverflow.com/comment/87577280
score: 1
has comment: http://stackoverflow.com/comment/87577808
has body: I have some problems with freeing memory in Tornado. My handler downloading part of big bytes file, and write it in response. But the more parallel requests the more memory is used (this is logical). But after the end of requests, memory is not free! My code: import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient, HTTPRequest AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient", max_clients=50) class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): url = "http://example.com/big_bytes_file" request = HTTPRequest(url, headers={'Range': 'bytes=0-1048576'}, method='GET') client = AsyncHTTPClient() range_resp = yield client.fetch(request) self.write(range_resp.body) def make_app(): return tornado.web.Application([(r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() app.listen(5000) tornado.ioloop.IOLoop.current().start() What I do? I'm see memory usage after start application (111 MB): memory after start Sending one request. Memory increase (114 MB): 114 MB Sending parallel requests from 25 users. Memory - 123 MB. Sending parallel requests from 50 users. Memory - 153 MB. Sending parallel requests from 100 users. Memory - 205 MB. Waiting a few minutes. Memory not decrease. Why is that? :) P.S. An example, we send requests from 80 users. After this memory increase. After that, the memory will increase only if the users is more than 80.
has comment: http://stackoverflow.com/comment/87609480
has comment: http://stackoverflow.com/comment/87607978
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/87606087
tagged with: tornado
type: Question
has title: Tornado doesn't free memory after many connections for downloading
has comment: http://stackoverflow.com/comment/87577559
answer count: 0
has comment: http://stackoverflow.com/comment/87577230

http://stackoverflow.com/q/50307793
type: AnsweredQuestion
score: 3
has title: Positional string-formatting on pandas DataFrame
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/50307857
accepted answer: http://stackoverflow.com/a/50307857
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87632526
favorite count: 0
type: Question
has body: I'm using python to automatise some processes at work. My final product has to be in excel format (formulas have to be there, and everything has to be traceable), so I work on a pandas DataFrame and then export the result to a .xlsx. What I want to do is to create a pandas DataFrame that looks like this: ID Price Quantity Total 0 A =VLOOKUP(A2;'Sheet2'!A:J;6;0) =VLOOKUP(A2;'Sheet2'!A:J;7;0) =B2*C2 1 B =VLOOKUP(A3;'Sheet2'!A:J;6;0) =VLOOKUP(A3;'Sheet2'!A:J;7;0) =B3*C3 2 C =VLOOKUP(A4;'Sheet2'!A:J;6;0) =VLOOKUP(A4;'Sheet2'!A:J;7;0) =B4*C4 3 D =VLOOKUP(A5;'Sheet2'!A:J;6;0) =VLOOKUP(A5;'Sheet2'!A:J;7;0) =B5*C5 4 E =VLOOKUP(A6;'Sheet2'!A:J;6;0) =VLOOKUP(A6;’Sheet2'!A:J;7;0) =B6*C6 As you can see in the first row, the formulas reference A2, B2 and C2; the second row references A3, B3 and C3; the 'n' row references A(n+2), B(n+2) and C(n+2). The DataFrame has about 3.000 rows. I want to generate this dataframe with a few lines of code, and i haven't got the expected result. I though using positional formatting would do: df = pd.DataFrame() df['temp'] = range(3000) df['Price'] = """=VLOOKUP(A{0};'Sheet2'!A:J;6;0)""" .format(df.index + 2) df['Quantity'] = """=VLOOKUP(A{0};'Sheet2'!A:J;7;0)""" .format(df.index + 2) df['Total'] = """=B{0}*C{0}""" .format(df.index + 2) df.drop('temp', axis=1, inplace=True) Unfortunately it doesn't work. It returns something like this: "=VLOOKUP(ARangeIndex(start=2, stop=3002, step=1);'Sheet2'!A:J;6;0)" Does anyone have any suggestion on how to do this? Thanks!
tagged with: string-formatting
answer count: 1
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87634791
has comment: http://stackoverflow.com/comment/87632929

http://stackoverflow.com/comment/87660702
comment on: http://stackoverflow.com/q/50322436
type: Comment
has text: That is because you just run one loop and then return instead of 10000 loops.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87697851
comment on: http://stackoverflow.com/q/50340734
score: 1
type: Comment
type: QuestionComment
has text: Please give us more detail. What are you having difficulty with? Do you not understand the error message, or how your code relates to it?

http://stackoverflow.com/comment/87492034
type: Comment
type: QuestionComment
has text: I check whether the process gets a PID (the answer is yes), and this lead me to realise that the problem could be some functions related to PyQt5. In Process2 I try to open a new QtWindow, and I don't know if this is possible. So the problem comes from Qt. I'm editing the question
comment on: http://stackoverflow.com/q/50237093
score: 0

http://stackoverflow.com/comment/87748416
comment on: http://stackoverflow.com/q/50366029
score: 1
type: Comment
has text: It's not clear to me what you actually want that code to do. Do you want it to print all the integers between -14.40 and 0.5 ?
type: QuestionComment

http://stackoverflow.com/comment/87777793
type: QuestionComment
has text: Can you provide an example?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50380800

http://stackoverflow.com/q/50292297
downvote count: 0
has body: Given: df = pd.DataFrame({"panum": ["PA1", "PA1", "PA1", "PA2", "PA2", "PA2"], "which": ["A", "A", "A", "B", "B", "B"], "score": [88, 80, 90, 92, 95, 99]}) df.set_index(['panum', 'which'], inplace=True) df score panum which PA1 A 88 A 80 A 90 PA2 B 92 B 95 B 99 Is it possible to write something that would create a new index entry in 'which' called max which would be the max but for the level, so it would create two new rows, PA1,Max and PA2,Max? Update I have corrected the indexes. The example above is not what I meant. panmum factor score PA1 init 90 resub 94 final 93 PA2 init 60 resub 90 final 88 And my question in this better scenario would be: "I want to create a new "panum" called mean, which would have three rows, (mean, init), (mean, resub), (mean, final)". Pseudocode would be something like df['mean'] = (df['pa1'] + df['pa2']) / 2 I know this is a different question!
has answer: http://stackoverflow.com/a/50292471
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50292341
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 2
has title: Pandas hierarchical indexes and calculations
tagged with: pandas
upvote count: 3

http://stackoverflow.com/comment/87501477
score: 0
type: Comment
has text: Could you provide reproducible code? My guess is that you should just access the vgg16 model in the same manner you access the intermediate layers of `model`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50241063

http://stackoverflow.com/comment/87734465
type: Comment
type: QuestionComment
has text: I would seriously contemplate using a database like SQLITE or Postrgres and just dumping your data into them, and using SQL to manipulate the data. It's easier, and more efficient.
score: 0
comment on: http://stackoverflow.com/q/50358812

http://stackoverflow.com/q/50300785
has comment: http://stackoverflow.com/comment/87618377
answer count: 1
tagged with: pylint
has comment: http://stackoverflow.com/comment/87625957
tagged with: python
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87618343
linked to: http://stackoverflow.com/q/36835341
has answer: http://stackoverflow.com/a/50302823
has title: VS Code : Linter Pylint Not Installed; pip install pylint not working
has comment: http://stackoverflow.com/comment/87625805
has comment: http://stackoverflow.com/comment/87626133
has comment: http://stackoverflow.com/comment/87625996
duplicate of: http://stackoverflow.com/q/36835341
has body: So I just started with Python in VS Code. I have installed Python 3.6.5, and the extension for Python on VS Code. But when I try to save my files, this appears So I do the pip install pylint command, but it does this: Basically, what this means is that it does not recognise "pip", how do I fix this? I've been searching for answer but I could not understand anything.
score: -1
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/87625915
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87625772

http://stackoverflow.com/comment/87492302
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50236770
has text: @Kasramvd did you mean `defaultdict()`?

http://stackoverflow.com/comment/87583923
type: QuestionComment
has text: @Dyz it convert feature vector to ["[-0.00369344 -0.08348401 0.29953018 ... 0.38050437 0.01184894], and save ... in csv, not whole numpy array of features.
score: 0
comment on: http://stackoverflow.com/q/50283745
type: Comment

http://stackoverflow.com/a/50338507
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50337796
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50337796
type: AcceptedAnswer
type: Answer
has body: Python string literals use the backslash as an escape character. The string literal "\b" will contain the backspace character (ASCII 0x8), just like "\n" will contain a newline. It will not contain "backslash b", as you would need for the regex to work. To get "backslash b" you need to escape the backslash in the string literal, or use a raw string, which is "\\b" or r"\b", respectively. regex = re.compile(old_name + r"\b", re.IGNORECASE) Commonly, raw strings are used for regex in Python, so you don't need to double every backslash. Read https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals Side note: "\s" works because - in contrast to "\b" or "\n" - it means nothing special in a Python string literal, so it actually becomes "backslash s" for the regex.

http://stackoverflow.com/comment/87719903
type: Comment
has text: @Ev.Kounis sorry for misinterpreting the question. I have updated my answer by using 2 list comprehensions.
type: AnswerComment
comment on: http://stackoverflow.com/a/50350826
score: 1

http://stackoverflow.com/comment/87751600
type: Comment
type: QuestionComment
score: 0
has text: Did you tried creating a validation ? For instance you could validate user's username on update, if username is different then update it, if the same then pass ?
comment on: http://stackoverflow.com/q/50365289

http://stackoverflow.com/comment/87750576
has text: Thanks, I'll try it later. The rate of convergence of tensor decomposition is very slow. Will PCA be faster？
type: AnswerComment
comment on: http://stackoverflow.com/a/50255048
type: Comment
score: 0

http://stackoverflow.com/a/50311484
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50311287
has body: First off -- you can make the code more robust by passing the table in as an argument to Names.LoadTable. That function can add names to the table without creating it fresh. Here's the cut-down version TABLE = [] class ModifiesTables: @classmethod fill_table(cls, incoming_table): # real logic would go here for n in range(100): incoming_table.append(n) ModifiesTables.fill_table(TABLE) print(TABLE) # [0,1,2.....] you will undoubtedly be told that globals are a bad idea, and they are. However if you create the table outside the function -- for example the way I did it above - it will be accessible to functions defined in the same scope without extra work. The example above could also look like this: TABLE = [] def fill_table(): for n in range(100): TABLE.append(n) However this only works in the same scope, and your example makes it look like you are declaring the 'global' table in one file and the class in another. In that case the first example is better practice because the relationship is clear, rather than implicit (and you don't need to worry if, for example, you decided to move things into different files). Although Python has a global keyword, you only need it if you are assigning to the global, instead of just using it. So this works: TABLE = [] def works(): TABLE.append("I work") #using, not assigning but this does not def does_not_work(): TABLE = [] # this declares a local with the same name, the original is ignored in that case you would need the global: def works_but_use_sparingly(): global TABLE TABLE = [] # this will replace TABLE with a new list The official explanation of this behavior is: In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar again…

http://stackoverflow.com/comment/88529013
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50711837
has text: You're right. It really is an Anaconda-specific problem it seems. I tested your code on my regular Python distribution (which unfortunately I can't use for my project), and your code works. Als, your suggestion below for RStudio 1.2 is working. Thanks!
type: Comment

http://stackoverflow.com/a/50307386
accepted answer of: http://stackoverflow.com/q/50306143
has body: The print function returns None, thus, you need to break the print and assignment operations onto two separate lines: c='http://www.uniprot.org/uniprot/?query='+a+b+'&amp;sort=score' print(c) return c Also, you need to add quotes around the href in the a tag: &lt;p&gt;&lt;a href='{{input_text}}'&gt;{{ protname_seq }}&lt;/a&gt;&lt;/p&gt;
type: AcceptedAnswer
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50306143
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/50292317
has body: It depends a bit how you define "active on Slack". If getting the date and time a user was logged in last is enough, take a look at team.accessLogs, which will give you the timestamp of the last login for every user (date_last). This will not reflect whether the user performed any activity, e.g. posting a message or uploading a file though. However, note that this API method works for paid plans only.
has comment: http://stackoverflow.com/comment/87611570
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50280153
answers question: http://stackoverflow.com/q/50280153
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/q/50373980
tagged with: python
has title: Placing a detail component in Revit using python
type: Question
has answer: http://stackoverflow.com/a/50455177
tagged with: revit-api
type: UnansweredQuestion
has body: I'm trying to create detail component buttons that run the following code. However, I need it to work for 2015-2018 possibly 2019 in the future. Currently I have the custom ribbon and buttons made, but I can't get this script to work due to commandData in the first line not working. I've tried testing this as a macro just to try and see if it will work first before continuing. FamilySymbol symbol = GetElements<FamilySymbol> (commandData.Application.ActiveUIDocument.Document) .Where(item => item.Name == "NameYouWant") .First(); commandData.Application.ActiveUIDocument.PromptForFamilyInstancePlacement(symbol); /// /// Get the collection of elements of the specified type. /// The specified type must derive from Element, or you can use Element but you get everything :) /// /// The type of element to get /// The list of elements of the specified type public IEnumerable<T> GetElements<T>(Document document) where T : Element { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(T)); return collector.Cast<T>(); } It's located in the Detail Items in the project browser Family = Break Line Type = Break Line Any help will be greatly appreciated!
score: 0
tagged with: components
answer count: 1

http://stackoverflow.com/comment/87695127
comment on: http://stackoverflow.com/q/50339451
type: Comment
has text: And your question is?
type: QuestionComment
score: 0

http://stackoverflow.com/q/50286883
has comment: http://stackoverflow.com/comment/87589758
tagged with: regex
type: AnsweredQuestion
score: 0
tagged with: filter
has answer: http://stackoverflow.com/a/50287016
answer count: 1
has body: I would like to apply mutiply keyword filter for filtering down on columns.I tried this code: df = df.filter(regex='AMP','amp','date') Error I get : df = df.filter(regex='AMP','amp','date') ^ SyntaxError: positional argument follows keyword argument. Basically,I want all the columns with these keywords contained in their column name. Thank you in advance
duplicate of: http://stackoverflow.com/q/44940683
linked to: http://stackoverflow.com/q/48541444
type: Question
has comment: http://stackoverflow.com/comment/87589841
has title: How to apply multiple column filter(String) in python
duplicate of: http://stackoverflow.com/q/48541444
accepted answer: http://stackoverflow.com/a/50287016
linked to: http://stackoverflow.com/q/44940683
tagged with: python

http://stackoverflow.com/q/50282387
accepted answer: http://stackoverflow.com/a/50282445
tagged with: python
has answer: http://stackoverflow.com/a/50282445
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87581341
has comment: http://stackoverflow.com/comment/87581337
downvote count: 0
score: 1
upvote count: 1
has title: Python dict to select function runs all of them
answer count: 1
favorite count: 0
has body: So I tried cutting down on nested if's by using a dict to select a function to run. When calling execute in a test I'm usually calling it with "execute("BACKUP","/home/src","/home/dest")" But for some reason it runs both the BACKUP option twice. What am I doing wrong? I'm using Python3 def execute(jobtype, src, dst): if jobtype == "FULL": _o_src = fs.Index(src) fs.MakeFolders(_o_src.GetFolders(), dst) fs.MakeFiles(src, dst, _o_src.GetFiles()) if jobtype == "INCREMENTAL": print("DO INCREMENTAL BACKUP " + src + " TO " + dst) # Do the things options = { "BACKUP": execute(self.jobtype, self.src, self.dst), "RESTORE": execute(self.jobtype, self.dst, self.src), } options[jobtype]()
tagged with: python-3.x
type: Question
tagged with: function

http://stackoverflow.com/comment/107986820
type: Comment
has text: ` pip install --user mysql-connector-python`
comment on: http://stackoverflow.com/q/50349562
score: 1
type: QuestionComment

http://stackoverflow.com/a/50355888
has comment: http://stackoverflow.com/comment/87728276
has body: You can try: count = 0 with open("test.txt") as readFile: previous_line = "" archive_name = "" for line in readFile: if line != previous_line: previous_line = line count += 1 archive_name = str(count)+".txt" with open(archive_name, 'a+') as f: f.write(line) That will save "chicken chicken" in 1.txt, "duck duck duck" in 2.txt, "parrot parrot" in 3.txt and "chicken chicken chicken" in 4.txt
has comment: http://stackoverflow.com/comment/87728692
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50355741

http://stackoverflow.com/comment/87777297
type: Comment
score: 0
type: AnswerComment
has text: thanks @Ajax1234, i would a list where not unique var/val are spltted in different list like in previous example. var2 is a not unique value in original list hence in new list have to be associated to var1 for every list in list
comment on: http://stackoverflow.com/a/50380400

http://stackoverflow.com/comment/87716112
type: QuestionComment
comment on: http://stackoverflow.com/q/50350164
score: 0
type: Comment
has text: Possible duplicate of [Creating Dependency Graphs in Python](https://stackoverflow.com/questions/4160746/creating-dependency-graphs-in-python)

http://stackoverflow.com/comment/87699820
type: QuestionComment
has text: @BallpointBen Got it, thanks for your help.
score: 0
comment on: http://stackoverflow.com/q/50341766
type: Comment

http://stackoverflow.com/q/50231330
has title: Why python not returns None?
tagged with: python
has answer: http://stackoverflow.com/a/50231353
score: 0
answer count: 1
upvote count: 1
has body: class tree : def __init__(self): self.val=0 self.right=None self.left=None def create_tree(): x=input() if x==-1: return None root=tree() root.val=x print(root) print(root.val) print(root.right) print(root.left) while(True): print ("reach1") root.left=create_tree() root.right=create_tree() print("reach2") break return root def main(): root=tree() root=create_tree() main() Why None is not returned when x==-1 in create_tree() ? sample output: 2 &lt;__main__.tree object at 0x7f58cbf11128&gt; 2 None None reach1 -1 &lt;__main__.tree object at 0x7f58cbf11208&gt; -1 None None reach1
downvote count: 1
has comment: http://stackoverflow.com/comment/87479947
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/87559606
type: Comment
comment on: http://stackoverflow.com/q/50271245
type: QuestionComment
has text: Do you have a starting point? Perhaps a bot already in use? Which python library are you using to connect to discord? We can't help without these pieces of information
score: 0

http://stackoverflow.com/q/50313441
tagged with: mnist
possible better answer: http://stackoverflow.com/a/59095619
tagged with: python
has answer: http://stackoverflow.com/a/59910876
has answer: http://stackoverflow.com/a/59124713
has answer: http://stackoverflow.com/a/59574148
has answer: http://stackoverflow.com/a/65321611
type: AnsweredQuestion
has body: When I import tensorflow import tensorflow as tf I don't get an error. However, I do get the error below. I'm using spyder if that helps. As per other questions, I ensured up to date (v1.8) tensorflow using both conda and then pip installs. This didn't resolve the issue. Please assist. import tensorflow.examples.tutorials.mnist.input_data as input_data ModuleNotFoundError: No module named 'tensorflow.examples'
has answer: http://stackoverflow.com/a/58783082
linked to: http://stackoverflow.com/q/33659424
has answer: http://stackoverflow.com/a/61357344
has answer: http://stackoverflow.com/a/69697927
has answer: http://stackoverflow.com/a/60067913
has answer: http://stackoverflow.com/a/72523903
has answer: http://stackoverflow.com/a/58481570
downvote count: 0
accepted answer: http://stackoverflow.com/a/50336645
has title: ModuleNotFoundError: No module named 'tensorflow.examples'
has answer: http://stackoverflow.com/a/59095619
tagged with: tensorflow
score: 30
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45271344
has answer: http://stackoverflow.com/a/50336645
answer count: 12
upvote count: 30
has comment: http://stackoverflow.com/comment/87643137

http://stackoverflow.com/comment/87648786
has text: Oh! I didn't know that.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50316363
type: QuestionComment

http://stackoverflow.com/a/50318117
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50317949
has comment: http://stackoverflow.com/comment/87652040
upvote count: 1
has comment: http://stackoverflow.com/comment/87653673
has body: Here is a solution using itertools.groupby(): data = [('A1', 'A', 342.5), ('A2', 'A', 509.70), ('A2', 'B', 119.34), ('A1', 'B', 618.42), ('A1', 'A', 173.54), ('A1', 'B', 235.21)] import itertools as it for g1 in it.groupby(sorted(data), key=lambda x: x[0]): print(g1[0], end=' ') for g2 in it.groupby(g1[1], key=lambda x: x[1]): nums = [i[2] for i in g2[1]] print('(%s %.2f)' % (g2[0], sum(nums) / len(nums)), end=' ') print() Results: A1 (A 258.02) (B 426.81) A2 (A 509.70) (B 119.34)
has comment: http://stackoverflow.com/comment/87652126
type: Answer
has comment: http://stackoverflow.com/comment/87653772
has comment: http://stackoverflow.com/comment/87653652
has comment: http://stackoverflow.com/comment/87652664
has comment: http://stackoverflow.com/comment/87652577
score: 1
answers question: http://stackoverflow.com/q/50317949
has comment: http://stackoverflow.com/comment/87653808
type: AcceptedAnswer

http://stackoverflow.com/q/50330090
accepted answer: http://stackoverflow.com/a/50331587
has comment: http://stackoverflow.com/comment/87677837
has comment: http://stackoverflow.com/comment/87677882
has title: Sampling from within Pandas groups with defined probabilities
has comment: http://stackoverflow.com/comment/87679732
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87677877
has comment: http://stackoverflow.com/comment/87677645
tagged with: python
has comment: http://stackoverflow.com/comment/87677311
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50331587
tagged with: pandas
score: 1
has body: Consider the following Pandas dataframe, df = pd.DataFrame( [ ['X', 0, 0.5], ['X', 1, 0.5], ['Y', 0, 0.25], ['Y', 1, 0.3], ['Y', 2, 0.45], ['Z', 0, 0.6], ['Z', 1, 0.1], ['Z', 2, 0.3] ], columns=['NAME', 'POSITION', 'PROB']) Notice that df defines a discrete probability distribution for each unique NAME value i.e. assert ((df.groupby('NAME')['PROB'].sum() - 1)**2 &lt; 1e-10).all() What I would like to do is sample from these probability distributions. We can think of POSITION as being the values corresponding to the probabilities. So when considering X the sample will be 0 with probability 0.5 and 1 with probability 0.5. I would like to create a new dataframe with columns ['NAME', 'POSITION', 'PROB', 'SAMPLE'] representing these samples. Each unique SAMPLE value represents a new sample. The PROB column is now always 0 or 1, representing whether the given row was selected in the given sample. For example, if I were to select 3 samples an example outcome is below, df_samples = pd.DataFrame( [ ['X', 0, 1, 0], ['X', 1, 0, 0], ['X', 0, 0, 1], ['X', 1, 1, 1], ['X', 0, 1, 2], ['X', 1, 0, 2], ['Y', 0, 1, 0], ['Y', 1, 0, 0], ['Y', 2, 0, 0], ['Y', 0, 0, 1], ['Y', 1, 0, 1], ['Y', 2, 1, 1], ['Y', 0, 1, 2], ['Y', 1, 0, 2], ['Y', 2, 0, 2], ['Z', 0, 0, 0], ['Z', 1, 0, 0], ['Z', 2, 1, 0], ['Z', 0, 0, 1], ['Z', 1, 0, 1], ['Z', 2, 1, 1], ['Z', 0, 1, 2], ['Z', 1, 0, 2], ['Z', 2, 0, 2], ], columns=['NAME', 'POSITION', 'PROB', 'SAMPLE']) Of course due to the randomness involved, this is just one of a number of possible outcomes. A unittest for the program would be that as the samples increases, by the law of large numbers, the mean number of our samples for each (NAME, POSITION) pair, should tend to the actual probability. One could calculate a confidence region based on the total samples used and then make sure the true probability lies within it. For example using a normal approximation to binomial outcomes (requires total samples n_samples to be 'large') a (-4 sd, 4 sd) region test wo…
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87557934
type: Comment
comment on: http://stackoverflow.com/a/50269831
type: AnswerComment
has text: @ramreddy Don't forget to select this answer as the correct one if you find it useful!
score: 0

http://stackoverflow.com/comment/87612628
type: Comment
type: QuestionComment
has text: Thanks, would you know how to rewrite this? sorry i didn't write this line of code, someone helped me. I don't do this type of operations very often.
comment on: http://stackoverflow.com/q/50297859
score: 0

http://stackoverflow.com/comment/87588129
comment on: http://stackoverflow.com/a/50285232
score: 0
type: AnswerComment
has text: 1) Do not use the name of [built-in functions](https://docs.python.org/3/library/functions.html) as a variable name. Just try `print(list("ABCD"))` at the end of your code to see, what I mean. 2) Do not delete list elements while iterating over it. Try your script with `['red rose','blue rose','red color', 'red ridignhood', 'yellow paper']` to illustrate the problem. 3) Please consider adding a description, when posting an answer. I suggest reading [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer)
type: Comment

http://stackoverflow.com/comment/87764087
score: 0
has text: do you mean [this](https://stackoverflow.com/questions/50353079/using-variables-from-other-python-file) question? It looks very similar.
type: Comment
comment on: http://stackoverflow.com/q/50373920
type: QuestionComment

http://stackoverflow.com/comment/87597605
type: Comment
type: QuestionComment
has text: @AzatIbrakov I don't think `frozenset` and `tuple` would help if the issue is they are being mutated. That would just throw an error.
score: 2
comment on: http://stackoverflow.com/q/50290693

http://stackoverflow.com/comment/87641624
type: AnswerComment
comment on: http://stackoverflow.com/a/50311688
score: 0
type: Comment
has text: @SamRagusa I mean the second case, i.e. start with a fresh empty array `arr = np.empty(4, 'O,i')`, `arr['f1'] = range(4)` and then do the array assignment `arr['f0'][[3,0,1,2]] = arr`. This `arr` you can still print no prob. Because while its elements are nested they are only nested one level. Which is also why `arr[0][0][0][0]` doesn't work. You can do `arr['f0'][[3,0,1,2]] = arr` repeatedly; each time will add one layer of nesting. In contrast, `for i in range(4): arr[i]['f0'] = arr[(i+1) % 4]` because it creates true references will immediately create an infinite loop.

http://stackoverflow.com/comment/87629846
has text: Try getting stderr with `shell_exec('ls 2>&1')`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50306948
score: 0

http://stackoverflow.com/a/79270379
has body: I've adjusted (and cleaned up a bit) @wahaha's answer to have a fully statically typed, stdlib-only decorator that passes in addition parameters to it. When used without parameters, no use of brackets is needed. Feel free to adjust the logger as per your needs: from __future__ import annotations import logging import time from functools import wraps from typing import TYPE_CHECKING, overload if TYPE_CHECKING: from collections.abc import Callable logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logger = logging.getLogger(name="main") @overload def retry[**P, R]( function: None = None, /, *, retries: int = 1, retry_delay: int = 3, exception_type: type[Exception] | tuple[type[Exception], ...] = Exception, ) -> Callable[[Callable[P, R]], Callable[P, R]]: ... @overload def retry[**P, R]( function: Callable[P, R], /, *, retries: int = 1, retry_delay: int = 3, exception_type: type[Exception] | tuple[type[Exception], ...] = Exception, ) -> Callable[P, R]: ... def retry[**P, R]( function: Callable[P, R] | None = None, /, *, retries: int = 1, retry_delay: int = 3, exception_type: type[Exception] | tuple[type[Exception], ...] = Exception, ) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]: """Create a decorator to retry function execution upon failure. This decorator will attempt to execute the decorated function multiple times if it raises an exception. Between attempts, it will wait for a specified delay period. Args: function (Callable, optional): The function to decorate when used without parameters. retries (int, optional): The maximum number of execution attempts. Defaults to 1. retry_delay (int, optional): The delay in seconds between retry attempts. Defaults to 3 seconds. exception_type (Exception type or a tuple of Exception types, optional): Narrow down on which exception types you would like to retry. Defaults to all exceptions. Returns: Callable: A decorator function that wraps the original funct…
answers question: http://stackoverflow.com/q/50246304
score: 0
type: Answer

http://stackoverflow.com/comment/114433253
type: Comment
comment on: http://stackoverflow.com/a/50294587
score: 0
type: AnswerComment
has text: When I click F1 > Debug open launch.json > Select Environment - there is no python option, but node, chrome, edge.. Python is installed in c:/python, in the path and the python debugger extension also.

http://stackoverflow.com/comment/87693936
has text: Possible duplicate of [Printing a string prints 'u' before the string in Python?](https://stackoverflow.com/questions/19170808/printing-a-string-prints-u-before-the-string-in-python)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50338795
score: 0

http://stackoverflow.com/a/50339224
downvote count: 1
has body: Select only object type columns df2 = df1[[x for x in df1 if df1[x].dtype == 'object']] Get the maximum length in each column max_length_in_each_col = df2.applymap(lambda x: len(x)).max()
has comment: http://stackoverflow.com/comment/136880778
score: 10
has comment: http://stackoverflow.com/comment/115289924
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/136880762
has comment: http://stackoverflow.com/comment/96488236
answers question: http://stackoverflow.com/q/50339065

http://stackoverflow.com/q/50326761
tagged with: python
linked to: http://stackoverflow.com/q/16424091
has body: import tkinter as tk from tkinter import ttk def picture(): window2 = tk.Toplevel() window2.title("Window2") window2.geometry("300x300") window2.configure(background='grey') f = "C:\\Users\\Bob\\Documents\\Python\\bb.gif" img = tk.PhotoImage(file =f) panel = ttk.Label(window2, width= 100, background = "green", image =img) panel.grid(column=1, row=1, sticky=(tk.W,tk.E)) #Start the GUI window = tk.Tk() window.title("Window1") window.geometry("300x300") window.configure(background='grey') f = "C:\\Users\\Bob\\Documents\\Python\\bb.gif" img = tk.PhotoImage(file = f) panel = ttk.Label(window, width= 100, background = "green", image =img) panel.grid(column=1, row=1, sticky=(tk.W,tk.E)) picture() window.mainloop() In the above code, Why does the picture display in window1 but not window2? It works if the image is passed as a parameter to the function! running with Python3.
score: 0
has answer: http://stackoverflow.com/a/50327425
duplicate of: http://stackoverflow.com/q/16424091
has title: displaying picture in tkinter label
type: Question
tagged with: tkinter
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/87690162
type: Comment
has text: Added a new value to next row and it seemed to help - no more errors. Strange... Thanks so much for your help though Russ! You obv know your stuff!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50334939

http://stackoverflow.com/comment/87725633
score: 0
type: QuestionComment
has text: Does `embulk` have any requirements, like an installed Java environment? Then this probably won't work on a *Python lambda*. You can typically run any executable which can run on a plain Linux distribution without additional dependencies. There are separate Lambda environments for Java…
type: Comment
comment on: http://stackoverflow.com/q/50354628

http://stackoverflow.com/q/50269680
has answer: http://stackoverflow.com/a/50276717
type: UnansweredQuestion
type: Question
score: 0
has answer: http://stackoverflow.com/a/63264834
tagged with: odoo
tagged with: odoo-8
tagged with: python
has body: I want to know how to proceed for adding in the search a product by barcode (ean 13) in sale quotations. Like the image here, I have only the name of the product and product internal reference. I try to override the model product.product like this : # -*- coding: utf-8 -*- from openerp import models, api class product_product(models.model): _inherit = "product.product" def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): res = super(product_product, self).name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100) if operator in ('ilike', 'like', '=', '=like', '=ilike'): domain = [('ean13', operator, name)] ids = self.search(cr, user, domain, limit=limit, context=context) res += self.name_get(cr, user, ids, context=context) return res self.search([('ean13', 'ilike', name)])
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/87570242
tagged with: ean-13
has title: Add Product ean13 barcode in Quotation line item search (Odoo 8)

http://stackoverflow.com/comment/87587165
comment on: http://stackoverflow.com/q/50285019
type: QuestionComment
has text: So pretty. I would like to know how you load the basemap as I can't see it from the code above.
type: Comment
score: 1

http://stackoverflow.com/comment/87592748
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50274518
has text: Ok, so [from the docs](https://django-filter.readthedocs.io/en/master/ref/filters.html#modelchoicefilter) it appears that the model in your filter `Meta` class needs to be the related model, in your case, `Shipment`, instead of `Merchant`. This will then let you filter `shipments` by `merchant`.

flask
tags question: http://stackoverflow.com/q/50261135
tags question: http://stackoverflow.com/q/50322294
tags question: http://stackoverflow.com/q/50320602
tags question: http://stackoverflow.com/q/50239017
tags question: http://stackoverflow.com/q/50298877
tags question: http://stackoverflow.com/q/50336179
tags question: http://stackoverflow.com/q/50299695
tags question: http://stackoverflow.com/q/50340784
tags question: http://stackoverflow.com/q/50347842
tags question: http://stackoverflow.com/q/50233118
tags question: http://stackoverflow.com/q/50322377
tags question: http://stackoverflow.com/q/50328918
tags question: http://stackoverflow.com/q/50327174
tags question: http://stackoverflow.com/q/50319280
tags question: http://stackoverflow.com/q/50292880
tags question: http://stackoverflow.com/q/50233828
tags question: http://stackoverflow.com/q/50262871
tags question: http://stackoverflow.com/q/50268131
tags question: http://stackoverflow.com/q/50232325
tags question: http://stackoverflow.com/q/50379547
tags question: http://stackoverflow.com/q/50275483
tags question: http://stackoverflow.com/q/50238190
tags question: http://stackoverflow.com/q/50327439
tags question: http://stackoverflow.com/q/50377105
tags question: http://stackoverflow.com/q/50370225
tags question: http://stackoverflow.com/q/50272021
tags question: http://stackoverflow.com/q/50339324
tags question: http://stackoverflow.com/q/50255349
tags question: http://stackoverflow.com/q/50325986
tags question: http://stackoverflow.com/q/50303936
tags question: http://stackoverflow.com/q/50253362
tags question: http://stackoverflow.com/q/50264831
tags question: http://stackoverflow.com/q/50377532
tags question: http://stackoverflow.com/q/50300189
tags question: http://stackoverflow.com/q/50255366
tags question: http://stackoverflow.com/q/50315481
tags question: http://stackoverflow.com/q/50326457
tags question: http://stackoverflow.com/q/50306143
tags question: http://stackoverflow.com/q/50350890
tags question: http://stackoverflow.com/q/50328615
tags question: http://stackoverflow.com/q/50290023
tags question: http://stackoverflow.com/q/50374614
tags question: http://stackoverflow.com/q/50286363
tags question: http://stackoverflow.com/q/50308014
tags question: http://stackoverflow.com/q/50308051
tags question: http://stackoverflow.com/q/50375511
tags question: http://stackoverflow.com/q/50373785
tags question: http://stackoverflow.com/q/50276076
tags question: http://stackoverflow.com/q/50279450
tags question: http://stackoverflow.com/q/50322015
tags question: http://stackoverflow.com/q/50252156
tags question: http://stackoverflow.com/q/50372057
tags question: http://stackoverflow.com/q/50361331
tags question: http://stackoverflow.com/q/50263558
tags question: http://stackoverflow.com/q/50235950
tags question: http://stackoverflow.com/q/50309545
tags question: http://stackoverflow.com/q/50263132
tags question: http://stackoverflow.com/q/50362847
tags question: http://stackoverflow.com/q/50297490
tags question: http://stackoverflow.com/q/50355293
tags question: http://stackoverflow.com/q/50298565
tags question: http://stackoverflow.com/q/50275646
tags question: http://stackoverflow.com/q/50236564
tags question: http://stackoverflow.com/q/50231564
tags question: http://stackoverflow.com/q/50355269
tags question: http://stackoverflow.com/q/50375363
tags question: http://stackoverflow.com/q/50293140
tags question: http://stackoverflow.com/q/50372642
tags question: http://stackoverflow.com/q/50267626
tags question: http://stackoverflow.com/q/50336493
tags question: http://stackoverflow.com/q/50287179
tags question: http://stackoverflow.com/q/50275675
tags question: http://stackoverflow.com/q/50233844
tags question: http://stackoverflow.com/q/50303403
tags question: http://stackoverflow.com/q/50250610
tags question: http://stackoverflow.com/q/50268887
tags question: http://stackoverflow.com/q/50276304
tags question: http://stackoverflow.com/q/50297396
tags question: http://stackoverflow.com/q/50382554
tag name: flask

http://stackoverflow.com/comment/87730759
type: AnswerComment
comment on: http://stackoverflow.com/a/50357165
has text: UnboundLocalError: local variable 'integer' referenced before assignment Exception in Tkinter callback
score: 0
type: Comment

http://stackoverflow.com/q/50351038
type: AnsweredQuestion
has body: I'm trying to plot a correlation matrix with sns.heatmap(). Specifically, the code I run is corr = train.corr() sns.heatmap(corr, cmap = "RdBu_r") This returns following image: What I want is to 0 to correspond to white, positive correlations to be in shades of red and negative to be in shades of blue. I went through the documentation of seaborn, however, I wasn't able to figure it out. Is there a way how to set this in seaborn?
tagged with: correlation
answer count: 2
downvote count: 0
upvote count: 8
favorite count: 0
has title: How to set mapping to colors in seaborn.heatmap?
type: Question
tagged with: seaborn
tagged with: python
has answer: http://stackoverflow.com/a/50351241
accepted answer: http://stackoverflow.com/a/50351241
has answer: http://stackoverflow.com/a/53041399
possible better answer: http://stackoverflow.com/a/53041399
score: 8
tagged with: heatmap

http://stackoverflow.com/q/50244910
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/50245106
has body: I understand how to make a simple meshgrid like this one: low1 = -1; high1 = 1; n_p = 20 range1 = np.linspace(low1, high1,n_p/2, endpoint=False) X = np.dstack(np.meshgrid(range1, range1)).reshape(-1, 2) But what is the best way to make a meshgrid like on the picture below? Right now I am just building 8 rectangles and stack them. What is a better way of doing it?
downvote count: 0
has answer: http://stackoverflow.com/a/50245106
upvote count: 1
has comment: http://stackoverflow.com/comment/87511347
tagged with: scipy
favorite count: 0
has title: How to make a meshgrid with holes in numpy?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87507333
tagged with: python
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87507374
possible better answer: http://stackoverflow.com/a/50245364
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50245364

http://stackoverflow.com/q/50267959
has title: Dataset directly from tf.train.SequenceExample
tagged with: tensorflow
tagged with: tensorflow-datasets
tagged with: sequences
type: Question
has body: I'm working with a NER-like sequence tagging in tensorflow and decided to try tf.data to see if I can get IO performance improvements with my model. At the moment I am employing TFRecordWriter to preprocess and save my training/validation data, which is a tf.train.SequenceExample() serialized to string. I then load it with tf.data.TFRecordDataset, parse/shuffle/padded_batch it and get on with training, which works fine. Question is: is there a convenient way to make the dataset without first serializing and saving the SeuquenceExamples to tfrecord file? It seems to be an unnecessary step when I'll be running the predictions on new data. I've tried playing with tf.data.Dataset.from_tensor_slices(), but it seems not suitable in this scenario as the inputs are sequences of different lengths that are not padded yet.
accepted answer: http://stackoverflow.com/a/50278981
tagged with: python
has answer: http://stackoverflow.com/a/50278981
answer count: 1
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50319394
favorite count: 0
type: Question
downvote count: 0
has title: Django - calling attribute from queryset with a string
tagged with: django
tagged with: django-models
tagged with: python
answer count: 1
tagged with: class
accepted answer: http://stackoverflow.com/a/50319517
has comment: http://stackoverflow.com/comment/87654516
has body: I'm trying to loop over different query sets while not repeating myself too much and have encountered a problem using the queryset class. This is not necessarily completely a Django-problem. What I'm trying to do is to use my keylist, which corresponds to a django model's column names, to create a list of the data from those column names, what i want to do is something like this: if needthisdata==1: needdata=['column1', 'column2', 'column3'] else: needdata=['column1', 'column4', 'column7'] entry=djangomodel.get.all().filter(identifier='id') dictitems=[] for n in range(0, len(needdata)): if n==0: dictitems=[entry.needdata[n]] else: dictitems.append(entry.needdata[n]) Which of course doesn't work since the queryset doesn't have a need data attribute, is there some way to call an attribute for a class with a string in this way?
has comment: http://stackoverflow.com/comment/87654992
has answer: http://stackoverflow.com/a/50319517
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/87654542
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87654530
score: 1
upvote count: 1

http://stackoverflow.com/a/59338433
type: Answer
answers question: http://stackoverflow.com/q/50330378
score: 0
has body: The way I do it is by having one variable to store the Toplevel instance into. I initialize that variable to None first, so I can only set it once (by testing if the variable is None) The variable is reset back to None when the Toplevel is destroyed (by binding the WM_DELETE_WINDOW protocol). I also noticed that in your code, you're instanciating a new Tk() object. The Tk() object should only be instanciated once, and be the root of your program. To open new windows, your should use the Toplevel object. Now for an example : import tkinter as tk class OptionsWindow(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) pass class MainWindow(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, **kwargs) self.options_toplevel = None tk.Button(self, text='open toplevel', command=self._open_toplevel).pack() def _open_toplevel(self, *args): if self.options_toplevel is None: self.options_toplevel = tk.Toplevel(self.master) self.options_toplevel.protocol('WM_DELETE_WINDOW', self.on_tl_close) gui = OptionsWindow(self.options_toplevel, width=300, height=300) gui.pack() def on_tl_close(self, *args): self.options_toplevel.destroy() self.options_toplevel = None root = tk.Tk() gui = MainWindow(root) gui.pack() root.mainloop()

http://stackoverflow.com/a/50283935
has comment: http://stackoverflow.com/comment/87584462
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87584696
has body: Your function isn't returning anything, you could return a dictionary and from that later choose what value you want, for example: Also, make sure to update choice in the while loop, or else you will be stuck in the loop forever. import random def fillEnemyField(): print("Here's your first EnemyField") return {"zombies": random.randrange(0, 15), "trolls": random.randrange(0, 15), "vampires": random.randrange(0, 15), "ghosts": random.randrange(0, 15) } def printEnemyField(): print("Press 1 to get a new EnemyField") print("Press 2 to get a new EnemyField") print("Press 3 to get a new EnemyField") print("Press 4 to get a new EnemyField") print("Press 5 to quit") choice = int(input("Enter a number: ")) while choice != 5: if choice ==1: print(fillEnemyField()['zombies'], "zombies in the field") choice = int(input("Enter a number: ")) printEnemyField() Or What is probily a better option, you can pass the choice in as an argument and then return that choise, for example: def fillEnemyField(choise): print("Here's your first EnemyField") options = {"zombies": random.randrange(0, 15), "trolls": random.randrange(0, 15), "vampires": random.randrange(0, 15), "ghosts": random.randrange(0, 15) } return options[choise] def printEnemyField(): ... choice = int(input("Enter a number: ")) while choice != 5: if choice == 1: print(fillEnemyField('zombies'), "enemies on the field") choice = int(input("Enter a number: "))
accepted answer of: http://stackoverflow.com/q/50283850
answers question: http://stackoverflow.com/q/50283850
type: Answer

http://stackoverflow.com/comment/87789239
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50375207
has text: Basically @CarsonP most of what you posted is useless for debugging. What I would have done is pull out x_train[0] and y_train[0] see if there is anything wrong with these values and try fitting whatever your model is(,which we don't know anything about btw) on it.

http://stackoverflow.com/comment/87638428
comment on: http://stackoverflow.com/a/50310074
score: 0
type: Comment
has text: @Moh If you can create another question that might be even better as this serves for future users too.
type: AnswerComment

http://stackoverflow.com/q/50327186
downvote count: 1
favorite count: 0
type: Question
tagged with: graphics
tagged with: tkinter
tagged with: canvas
tagged with: python
has comment: http://stackoverflow.com/comment/87672651
has answer: http://stackoverflow.com/a/50329253
accepted answer: http://stackoverflow.com/a/50329253
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87673075
has title: How to invert colors in tkinter's canvas?
score: 1
has body: I'm curious if there's a way how to invert colors of canvas directly in it. I have seen PIL module which allows to work with image (as file), but I want to apply changes still visible inside of the canvas, which contains shapes. e.g.: import tkinter canvas=tkinter.Canvas() canvas.pack() canvas.create_rectangle(20,20,60,60,fill='blue', outline='red') Can you please help me, what to do to invert colors?
answer count: 1

http://stackoverflow.com/a/50300501
has comment: http://stackoverflow.com/comment/87732554
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87847117
score: 3
has comment: http://stackoverflow.com/comment/87846627
accepted answer of: http://stackoverflow.com/q/50300303
has body: How do I iterate over all image tags, with tree.iterfind and a namsepace map? for img in root.iterfind('image', namespaces=root.nsmap): I am trying to turn image tags into use tags. While lxml gives me an attribute dictionary with xlinx:href it chokes on passing this to makeelement is there an elegant solution? Either of these works for me: img.makeelement('use', dict(img.items()) img.makeelement('use', img.attrib) Should I use lxml or is there something better (more straight forward)? Everybody's got an opinion. I like lxml. I find it very straightforward. Your opinion may differ. Complete program: from lxml import etree def inlineSvg(path): parser = etree.XMLParser(recover=True) tree = etree.parse(path, parser) root = tree.getroot() for img in root.iterfind('image', namespaces=root.nsmap): use = img.makeelement('use', img.attrib, nsmap=root.nsmap) print(etree.tostring(use)) inlineSvg('xx.svg') Input file (xx.svg): &lt;svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;rect x="10" y="10" height="130" width="500" style="fill: #000000"/&gt; &lt;image x="20" y="20" width="300" height="80" xlink:href="http://jenkov.com/images/layout/top-bar-logo.png" /&gt; &lt;line x1="25" y1="80" x2="350" y2="80" style="stroke: #ffffff; stroke-width: 3;"/&gt; &lt;/svg&gt; result: $ python xx.py b'&lt;use xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" height="80" width="300" x="20" y="20" xlink:href="http://jenkov.com/images/layout/top-bar-logo.png"/&gt;' Reference: http://lxml.de/api/lxml.etree._Element-class.html#iterfind http://tutorials.jenkov.com/svg/image-element.html#svg-image-example
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/87620422
answers question: http://stackoverflow.com/q/50300303

http://stackoverflow.com/comment/104621032
type: AnswerComment
has text: I can find the `input_scale` and the `kernel_scale` but where in the quantized model I can find `output_scale`?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52787541

http://stackoverflow.com/comment/87665454
type: AnswerComment
comment on: http://stackoverflow.com/a/50324544
type: Comment
has text: @Damian - Or maybe copy error from my post, I think if rewrite it it working nice.
score: 0

http://stackoverflow.com/comment/87684462
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50334096
has text: What did you do so far ? Take a look at `groupby` then `sorted` and then take the first element.

http://stackoverflow.com/q/50244202
tagged with: tkinter
tagged with: buffer
answer count: 2
has title: How can I increase Tkinter Maximum Canvas size for extremely large images?
linked to: http://stackoverflow.com/q/16188420
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50301857
has comment: http://stackoverflow.com/comment/87529850
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50301857
possible better answer: http://stackoverflow.com/a/50254029
has comment: http://stackoverflow.com/comment/87515093
linked to: http://stackoverflow.com/q/42830037
has body: I can't display images longer (height) than about 30612 pixels high. I've read that there is a maximum height to canvas. I'd like to get the source file and extend that to 90 or 100k pixels in height. Conversely, I've seen suggested that a canvas may be buffered, if this is true, I have no clue how to implement it.. Any help is appreciated! I am using code I found off Stack that is supposed to deal with large images, it does alright, but ultimately hit's the cavas height limit. Canvas Limit from tkinter import * from PIL import ImageTk from PIL import * Image.MAX_IMAGE_PIXELS = None class ScrolledCanvas(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.master.title("Spectrogram Viewer") self.pack(expand=YES, fill=BOTH) canv = Canvas(self, relief=SUNKEN) canv.config(width=400, height=500) # canv.config(scrollregion=(0,0,1000, 1000)) # canv.configure(scrollregion=canv.bbox('all')) canv.config(highlightthickness=0) sbarV = Scrollbar(self, orient=VERTICAL) sbarH = Scrollbar(self, orient=HORIZONTAL) sbarV.config(command=canv.yview) sbarH.config(command=canv.xview) canv.config(yscrollcommand=sbarV.set) canv.config(xscrollcommand=sbarH.set) sbarV.pack(side=RIGHT, fill=Y) sbarH.pack(side=BOTTOM, fill=X) canv.pack(side=LEFT, expand=YES, fill=BOTH) self.im = Image.open("Test_3.tif") width, height = self.im.size canv.config(scrollregion=(0, 0, width, height)) self.im2 = ImageTk.PhotoImage(self.im) self.imgtag = canv.create_image(0, 0, anchor="nw", image=self.im2) ScrolledCanvas().mainloop()
has answer: http://stackoverflow.com/a/50254029
score: 1
tagged with: image
favorite count: 0
type: Question

http://stackoverflow.com/comment/87649341
score: 0
has text: Please refer to examples of [isinstance](https://stackoverflow.com/questions/50153595/python-add-validation-in-form/50160963#50160963)
comment on: http://stackoverflow.com/q/50314617
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50318875
linked to: http://stackoverflow.com/q/50075117
upvote count: 2
downvote count: 0
answer count: 1
tagged with: websocket
has answer: http://stackoverflow.com/a/50333101
favorite count: 0
type: Question
tagged with: redis
tagged with: python-asyncio
type: UnansweredQuestion
has title: python aiohttp websockets closed browser tab handling
tagged with: python
linked to: http://stackoverflow.com/q/48695294
score: 2
has body: I am trying to create simple active users counter using aiohttp WebSockets and aioredis for storage. When I add a new tab in Google Chrome, my counter increments perfectly in all already opened tabs. However, when I close a tab, nothing changes in other tabs. I think I should be missing something in whole async/await machinery, but cannot find what can be wrong. Here is my app import asyncio import aiohttp from aiohttp import web import aioredis class CounterView(web.View): async def get(self): request = self.request app = request.app ws = web.WebSocketResponse() app['websockets'].append(ws) await ws.prepare(request) count = int(await app['db'].incr('counter')) for ws in app['websockets']: await ws.send_json({'msg': {'count': count}}) async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: await ws.send_str(msg.data) elif msg.type == aiohttp.WSMsgType.ERROR: print('ws connection closed with exception %s' % ws.exception()) app['websockets'].remove(ws) # Execution stops here (on await app['db'] ...) and never returns count = int(await app['db'].decr('counter')) for ws in app['websockets']: await ws.send_json({'msg': {'count': count}}) return ws async def init_app(loop): app = web.Application(loop=loop) db = await aioredis.create_redis('redis://localhost', loop=loop) app['db'] = db app['websockets'] = [] app.add_routes([ web.get('', CounterView), ]) return app if __name__ == '__main__': loop = asyncio.get_event_loop() web.run_app(init_app(loop)) And index.html template Title How many people seeing this page now: I have also tried in Firefox, and some really weird things happens there. Opened two tabs, got counter = 2 on both. Then reload first - got 1 in it and still 2 in second one. Reload first tab again - got 2. After this, each reload gives 2. Until I reload second tab - the same process (reload - 1 - reload - 2 happens there and repeats in first tab) Also i tried to apply https://stackoverflow.com/a/48695448/6627564 this answer, but nothing changed. Debugging …
tagged with: aiohttp

http://stackoverflow.com/comment/87767642
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50375594
has text: Perhaps `testscript_data.write('Test Script (Steps) – Step\n')` to make it a header for the csv? Notice that will will make it no longer a pure csv because the header isn't following the same rules as the other columns.
type: QuestionComment

http://stackoverflow.com/comment/87547878
score: 2
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50250134
has text: you can not combine it, because queryset returns same objects, but you need to return many similar objects(structure) and one with only one field(totals)

http://stackoverflow.com/q/50378135
type: Question
upvote count: 2
tagged with: markdown
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: internal-link
has body: I have the following in a jupyter notebook, although not all in the same cell. Every cell set to be markdown type, including the html. The top-most link to Introduction works fine, but the others do not. How can we get the second and third link to work properly? # Table of Contents 1. [Introduction](#Introduction) 2. [Section One](#S_One) 2. [Section Two](#STwo) # Introduction Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet dignissim ante. Vivamus faucibus iaculis quam id aliquam. Ut ligula metus, lacinia eget finibus in, dignissim nec mauris. Sed nec dolor velit. Aliquam in nisi sit amet mi sagittis egestas ac sed velit. Duis tristique vitae elit ac sagittis. # Section One Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet dignissim ante. Vivamus faucibus iaculis quam id aliquam. Ut ligula metus, lacinia eget finibus in, dignissim nec mauris. Sed nec dolor velit. Aliquam in nisi sit amet mi sagittis egestas ac sed velit. Duis tristique vitae elit ac sagittis. # Section Two Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet dignissim ante. Vivamus faucibus iaculis quam id aliquam. Ut ligula metus, lacinia eget finibus in, dignissim nec mauris. Sed nec dolor velit. Aliquam in nisi sit amet mi sagittis egestas ac sed velit. Duis tristique vitae elit ac sagittis. Nam in quam a nisl ornare suscipit in at lacus. Ut tempor mollis fringilla. Etiam eleifend nunc ut ligula condimentum, quis varius sapien convallis. Maecenas placerat turpis at libero egestas, quis lacinia sapien pulvinar. Sed ut dolor vel libero aliquet tristique. Phasellus id facilisis justo. The Actual source is shown below: { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Table of Contents\n", "\n", "1. [Introduction](#Introduction) \n", "2. [Section One](#S_One) \n", "2. [Section Two](#STwo) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "s…
has title: Jupyter Notebook: First interal link works; subsequent ones do not
has answer: http://stackoverflow.com/a/50578609
tagged with: python
favorite count: 0
tagged with: jupyter-notebook

http://stackoverflow.com/comment/87633340
has text: Thanks! Is there a way to make a separate list per server?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50307648
type: Comment

http://stackoverflow.com/comment/87721438
type: QuestionComment
comment on: http://stackoverflow.com/q/50349305
score: 0
has text: None of the files are exactly failing. All the files' first lines are read and printed. But once all of them are printed, this error is thrown
type: Comment

http://stackoverflow.com/q/50356535
has answer: http://stackoverflow.com/a/54389013
answer count: 1
linked to: http://stackoverflow.com/q/42005819
has comment: http://stackoverflow.com/comment/91777853
has comment: http://stackoverflow.com/comment/91551020
tagged with: python-pdfkit
tagged with: xsl-fo
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/122489165
has title: python-pdfkit (wkhtmltopdf) TOC overflow
upvote count: 27
has comment: http://stackoverflow.com/comment/91792280
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91552204
tagged with: python
score: 27
has body: I currently am creating a perfectly good PDF. there is nothing technically wrong with it. However, the TOC is ugly. The TOC is generated via xsl which is passed through jinja2 for simple details to the top section of the page. I have modified the XSL to match the client's branding and design precisely. However, the list keeps growing in height. Here is the current result (sorry to blur the text) you can see the toc picks up at the right spot on the new page, but there seems to be no way to apply a top margin to the new page: The code: Here is the xsl: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:outline="http://wkhtmltopdf.org/outline" xmlns="http://www.w3.org/1999/xhtml"> <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" indent="yes" /> <xsl:template match="outline:outline"> Table of Contents A title here Revision Date Table of Contents <xsl:apply-templates select="outline:item/outline:item"/> </xsl:template> <xsl:template match="outline:item"> <! begin LI> <xsl:if test="@title!=''"> <xsl:if test="@link"> <xsl:attribute name="href"><xsl:value-of select="@link"/> . </xsl:attribute> </xsl:if> <xsl:if test="@backLink"> <xsl:attribute name="name"><xsl:value-of select="@backLink"/> . </xsl:attribute> </xsl:if> <xsl:value-of select="@title" /> <xsl:value-of select="@page" /> </xsl:if> <xsl:comment>added to prevent self-closing tags in QtXmlPatterns</xsl:comment> <xsl:apply-templates select="outline:item"/> </xsl:template> </xsl:stylesheet> I have dealt with content overflows in other areas of the PDF using traditional HTML, JavaScript, and a document ready flag. The TOC however requires an XSL file instead. I tried do this with nth-child css nth-child is ignored. The question: *Is there a way within wkhtmltopdf or python pdf-kit to deal with page breaks in the TOC specifi…
tagged with: wkhtmltopdf
tagged with: xslt

http://stackoverflow.com/comment/87586116
comment on: http://stackoverflow.com/a/50284876
has text: Glad to be of help!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50265063
upvote count: 1
type: UnansweredQuestion
has body: I got a really challenging problem. I'm trying to write a Python script to send styled Dataframe to Gmails. I need to have it showing like below in Email body, which I succeed in HTML file. However, what I received in Email like this: It seems Gmail doesn't apply the CSS style for font colors. My code is below: # Load sample data import pandas as pd df = pd.read_csv('test.csv');df # Fill missing values df.fillna('-',inplace = True);df # Add 2 level column name columns=[ ('Overview', 'Date'), ('Overview', 'City'), ('Group A','col_a'), ('Group A','col_b'), ('Group B','col_a'), ('Group B','col_b'), ('Group B','col_c'), ]; df.columns=pd.MultiIndex.from_tuples(columns);df # Define function for font color def color_highlight(val): try: pct = float(val.split('(',1)[1].split('%',1)[0]) if pct<-1: color = 'red' elif pct>1: color = 'green' else: color='black' return 'color: %s' % color except IndexError: return 'color: black' # Use Pandas styler to apply UDF and export HTML string s2 = df.style.applymap(color_highlight, subset=pd.IndexSlice[: ,[ ('Group A','col_a'), ('Group A','col_b'), ('Group B','col_a'), ('Group B','col_b'), ('Group B','col_c') ]]) \ .set_table_attributes('border="1" class="dataframe" style="border-collapse: collapse;"') \ .render().split('\n') s2 = ''.join(s2) s2 html = s2 # Send email import smtplib import time from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.mime.application import MIMEApplication sender = 'alichenxiang@gmail.com' recipients = ['myboss@gmail.com','myteam@gmail.com'] msg = MIMEMultipart('alternative') msg['Subject'] = 'REMINDER: Data alert' msg['From'] = sender msg['To'] = ", ".join(recipients) #put the html into the email body html = MIMEText(html, 'html') msg.attach(html) server = smtplib.SMTP('smtp.gmail.com:587') server.connect('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() username = 'alichenxiang@gmail.com' password = 'mypassword…
has title: Why Gmail doesn't apply HTML-ized Dataframe Styler?
has comment: http://stackoverflow.com/comment/87553176
favorite count: 0
has comment: http://stackoverflow.com/comment/87548556
type: Question
has comment: http://stackoverflow.com/comment/87553099
has comment: http://stackoverflow.com/comment/87548235
has answer: http://stackoverflow.com/a/50267279
has comment: http://stackoverflow.com/comment/87553135
tagged with: pandas
score: 1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/87548594
tagged with: python
has answer: http://stackoverflow.com/a/56192273
linked to: http://stackoverflow.com/q/19572437
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50312181
accepted answer: http://stackoverflow.com/a/50312234
type: AnsweredQuestion
tagged with: django-templates
has title: Django: Showing "featured" items?
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50312234
tagged with: python-3.x
tagged with: django
tagged with: django-models
tagged with: python
has body: I'm having a little conundrum with sorting some items. I have a field called featured thats a boolean. I'm trying to display the featured coins first and then the remaining will be sorted by a different metric. In this code im using pub_date. However, when I put an if statement in my template for the featured items it's still showing those that are set to false as well. I'll post code below. index.html loops and if's {% if featured_coins_list %} {% for coin in featured_coins_list %} {{ coin.name }} Ticker: {{ coin.ticker }} {{ coin.summary }} More Info {% endfor %} {% endif %} {% if latest_coins_list %} {% for coin in latest_coins_list %} {{ coin.name }} Ticker: {{ coin.ticker }} {{ coin.summary }} More Info {% endfor %} {% else %} No coins are available. {% endif %} views.py for index def index(request): featured_coins_list = Coin.objects.order_by('-featured')[:4] latest_coins_list = Coin.objects.order_by('-pub_date')[:8] context = {'featured_coins_list': featured_coins_list, 'latest_coins_list': latest_coins_list} return render(request, 'coins/index.html', context) models.py class Coin(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) ticker = models.CharField(max_length=5) featured = models.BooleanField(default=False) logo = models.ImageField(upload_to='uploads/', verbose_name='image') website = models.URLField(max_length=200, default="https://example.com/") reddit = models.URLField(max_length=200, default="https://reddit.com/r/") twitter = models.URLField(max_length=200, default="https://twitter.com/") summary = models.CharField(max_length=500, blank=True) description = models.TextField() pub_date = models.DateTimeField('date published') def __str__(self): return self.ticker def is_featured(self): return self.featured def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) How should I go about listing the featured coins that are set to true first and then display the rema…

http://stackoverflow.com/q/50230385
downvote count: 1
favorite count: 0
type: Question
has body: How can I find the overall accuracy of the outputs that we got by running a decision tree algorithm.I am able to get the top five class labels for the active user input but I am getting the accuracy for the X_train and Y_train dataset using accuracy_score().Suppose I am getting five top recommendation . I wish to get the accuracy for each class labels and with the help of these, the overall accuracy for the output.Please suggest some idea. My python script is here: here event is the different class labels DTC= DecisionTreeClassifier() DTC.fit(X_train_one_hot,y_train) print("output from DTC:") res=DTC.predict_proba(X_test_one_hot) new=list(chain.from_iterable(res)) #Here I got the index value of top five probabilities index=sorted(range(len(new)), key=lambda i: new[i], reverse=True)[:5] for i in index: print(event[i]) Here is the sample code which i tried to get the accuracy for the predicted class labels: here index is the index for the top five probability of class label and event is the different class label. for i in index: DTC.fit(X_train_one_hot,y_train) y_pred=event[i] AC=accuracy_score((event,y_pred)*100) print(AC)
has answer: http://stackoverflow.com/a/50236459
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87493469
has comment: http://stackoverflow.com/comment/87481439
tagged with: python
has comment: http://stackoverflow.com/comment/87493672
has comment: http://stackoverflow.com/comment/87480994
has comment: http://stackoverflow.com/comment/87484264
score: 0
has comment: http://stackoverflow.com/comment/87479345
has title: How to get accuracy for all the predicted class labels
has comment: http://stackoverflow.com/comment/87480724
has comment: http://stackoverflow.com/comment/87481055
answer count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87484928
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87480215

http://stackoverflow.com/q/50237237
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87493113
has title: Crontab No module named Pandas
has comment: http://stackoverflow.com/comment/87492493
tagged with: python
has comment: http://stackoverflow.com/comment/87493138
has comment: http://stackoverflow.com/comment/87493094
has answer: http://stackoverflow.com/a/60537110
has comment: http://stackoverflow.com/comment/87493035
has comment: http://stackoverflow.com/comment/87493171
answer count: 2
has answer: http://stackoverflow.com/a/53354167
tagged with: cron
has comment: http://stackoverflow.com/comment/87516435
downvote count: 0
has comment: http://stackoverflow.com/comment/87493299
has comment: http://stackoverflow.com/comment/87494925
has body: For some reason, Cron won't process this and keeps telling me that pandas is not installed (it is whenever I normally run my code) I'm getting this mail: Subject: Cron &lt;user@Justins-MBP-4&gt; PYTHONPATH=/Users/user/Library/Python/3.6/lib/python/site-packages python ~/downloads/random/milbtrans.command X-Cron-Env: &lt;SHELL=/bin/sh&gt; X-Cron-Env: &lt;PATH=/usr/bin:/bin&gt; X-Cron-Env: &lt;LOGNAME=user&gt; X-Cron-Env: &lt;USER=user&gt; X-Cron-Env: &lt;HOME=/Users/user&gt; Date: Tue, 8 May 2018 11:18:01 -0400 (EDT) Traceback (most recent call last): File "/Users/user/downloads/random/milbtrans.command", line 2, in &lt;module&gt; import requests, csv, pandas, openpyxl, datetime, time ImportError: No module named pandas Changed Pandas to be fixed but now getting this error: Traceback (most recent call last): File "/Users/user/downloads/random/milbtrans.command", line 2, in &lt;module&gt; import requests, csv, sys, pandas, openpyxl, datetime, time File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/__init__.py", line 19, in &lt;module&gt; "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] Any help is appreciated.
favorite count: 0
has comment: http://stackoverflow.com/comment/87492385
type: Question
has comment: http://stackoverflow.com/comment/87493181
has comment: http://stackoverflow.com/comment/87493098
score: 8
upvote count: 8

http://stackoverflow.com/q/50373618
has body: I am learning the fundamentals of Python and doing some finger exercise. This one question is bogging me. I don't know where I did wrong. The question is this: Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere. My solution is: def array123(nums): arr1 = [1, 2, 3] if len(nums) &lt; 3: return False for i in range(len(nums)-2): if nums[i:i+3] == arr1: return True else: return False I realize that this will give me False as long as the first 3 characters, so I change it to: def array123(nums): arr1 = [1, 2, 3] if len(nums) &lt; 3: return False for i in range(len(nums)-2): print(nums[i:i+3]) if nums[i:i+3] == arr1: return True return False This time it works. I am wondering do I have to move the "return False" out of the sub-code section of the last if? Thanks.
type: Question
has title: Check if a certain sequence of numbers appears in an array. What's wrong with my thoughts?
answer count: 2
has answer: http://stackoverflow.com/a/50373734
type: UnansweredQuestion
tagged with: function
tagged with: arrays
has comment: http://stackoverflow.com/comment/87763745
has comment: http://stackoverflow.com/comment/87763453
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50373711
tagged with: python
favorite count: 0

http://stackoverflow.com/a/50377103
type: Answer
has comment: http://stackoverflow.com/comment/87770503
has comment: http://stackoverflow.com/comment/87770455
has comment: http://stackoverflow.com/comment/87770394
downvote count: 0
has comment: http://stackoverflow.com/comment/87770385
upvote count: 1
has body: In [402]: np.random.seed = 0 ...: mat = sparse.csr_matrix(np.random.rand(10, 12)&gt;0.7, dtype=int) In [403]: mat Out[403]: &lt;10x12 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 40 stored elements in Compressed Sparse Row format&gt; In [404]: mat.A Out[404]: array([[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0], ... [0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]], dtype=int64) In [405]: np.random.seed = 1 ...: matb = sparse.csr_matrix(np.random.rand(10, 12)&gt;0.7, dtype=int) In [407]: mat&lt;matb Out[407]: &lt;10x12 sparse matrix of type '&lt;class 'numpy.bool_'&gt;' with 27 stored elements in Compressed Sparse Row format&gt; In [408]: mat&gt;=matb /home/paul/.local/lib/python3.6/site-packages/scipy/sparse/compressed.py:295: SparseEfficiencyWarning: Comparing sparse matrices using &gt;= and &lt;= is inefficient, using &lt;, &gt;, or !=, instead. "using &lt;, &gt;, or !=, instead.", SparseEfficiencyWarning) Out[408]: &lt;10x12 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 93 stored elements in Compressed Sparse Row format&gt; In your case, neither mat or matb are particularly sparse, 40 and 36 nonzeros out of a possible 120. Even so the mat&lt;matb results in 27 nonzero (True) values, while the &gt;= test results in 93. Where ever both matrices are 0, the result is True. It's warning us that using sparse matrices isn't going to save us space or time (compared to dense arrays) if we do this kind of testing. It's not going to kill us, it just won't be as efficient.
answers question: http://stackoverflow.com/q/50376948
score: 1

http://stackoverflow.com/q/50355120
score: 1
tagged with: selenium
favorite count: 0
has answer: http://stackoverflow.com/a/60496531
type: Question
accepted answer: http://stackoverflow.com/a/50358509
tagged with: xpath
has answer: http://stackoverflow.com/a/70077834
tagged with: webdriverwait
has body: I am trying to use selenium python to auto search on yahoo finance. When I type some words a suggestion will pop out like the same on google suggestion. https://finance.yahoo.com/ I found a list element with the xpath should be the suggestions made by yahoo: //*[@id="search-assist-input"]/div[2]/ul It seems the suggestion content are hidden in this list, but it's invisible, I mean when I click to unfold it, it just goes away. I don't know if there's some sort of 'always unfold nodes' in firefox or chrome, but these elements seem very hard to reach. I tried to get all the children under this element, it shows no element can be found: from chrome_driver.chrome import Chrome driver = Chrome().get_driver() driver.get('https://finance.yahoo.com/') driver.find_elements_by_xpath("//div[@id='search-assist-input']/div/input")[0].send_keys('goog') x = driver.find_elements_by_xpath("//div[@data-reactid='56']/ul[@data-reactid='57']/*") How can I reach these auto suggestion from the search box?
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/60496531
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: How to scrape the yahoo finance search auto suggestion result with selenium python?
has answer: http://stackoverflow.com/a/50358509
answer count: 3

http://stackoverflow.com/a/50252777
type: AcceptedAnswer
has body: It's been discussed several times on StackOverflow: see here or here. According to your convolutional and pooling layer parameters, the tensor is downsampled after each Conv3D and MaxPooling3D. Here's how the model looks like just before it breaks: Layer (type) Output Shape Param # ================================================================= conv3d_1 (Conv3D) (None, 32, 38, 38, 13) 896 _________________________________________________________________ max_pooling3d_1 (MaxPooling3 (None, 32, 19, 19, 13) 0 _________________________________________________________________ conv3d_2 (Conv3D) (None, 30, 17, 17, 64) 22528 _________________________________________________________________ max_pooling3d_2 (MaxPooling3 (None, 30, 8, 8, 64) 0 _________________________________________________________________ conv3d_3 (Conv3D) (None, 28, 6, 6, 128) 221312 _________________________________________________________________ conv3d_4 (Conv3D) (None, 26, 4, 4, 128) 442496 _________________________________________________________________ max_pooling3d_3 (MaxPooling3 (None, 26, 2, 2, 128) 0 _________________________________________________________________ conv3d_5 (Conv3D) (None, 25, 1, 1, 256) 262400 The tensor (None, 25, 1, 1, 256) can't be downsampled further, hence the error. The solution is to tweak Conv3D parameters: either use padding='same' (in which case the tensor shape is preserved after the convolutions and is halved only after pooling layers) or reduce the filter sizes from 3 to 2. Example: model = Sequential() model.add(Conv3D(32, (3,3,3), activation='relu', input_shape=(1, 40, 40, 15), data_format='channels_first', padding='same')) model.add(MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))) model.add(Conv3D(64, (3,3,3), activation='relu', padding='same')) model.add(MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))) model.add(Conv3D(128, (3,3,3), activation='relu', padding='same')) model.add(Conv3D(128, (3,3,3), activation='relu', padding='same')) model.add(MaxPo…
accepted answer of: http://stackoverflow.com/q/50248736
type: Answer
answers question: http://stackoverflow.com/q/50248736
score: 0

http://stackoverflow.com/q/50344490
tagged with: subprocess
tagged with: python
has title: run os.system commands on a new terminal- Python 3
tagged with: python-os
type: AnsweredQuestion
downvote count: 0
upvote count: 1
has body: I am running a program which allows me to run terminal commands through my Python code which takes input from the user through the command line. This is the part of the code where I open Google-Chrome import sys import os os.system("google-chrome") #I have Ubuntu 16.04 It opens the browser but the problem is that the terminal on which my python code is running becomes the same as the one where Chrome is running which means that I cannot give further input to my Python code. To solve this problem I need the Chrome to run as a process on a different terminal. I tried using subprocess.call("google-chrome", shell=True) but it did not open it on a new terminal. How do I make the process run on a different terminal?
score: 1
has answer: http://stackoverflow.com/a/50344665
accepted answer: http://stackoverflow.com/a/50344665
has answer: http://stackoverflow.com/a/50344679
possible better answer: http://stackoverflow.com/a/50344679
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/comment/87545381
type: Comment
type: QuestionComment
has text: Update: I know I'm doing something wrong with the loop. I have no idea how to restart the game though without making the #Player Input portion a user defined function.
score: 0
comment on: http://stackoverflow.com/q/50263686

http://stackoverflow.com/q/50364706
has answer: http://stackoverflow.com/a/61252384
has answer: http://stackoverflow.com/a/50623053
has comment: http://stackoverflow.com/comment/97835878
tagged with: python
score: 15
upvote count: 15
has title: Massive overfit during resnet50 transfer learning
has answer: http://stackoverflow.com/a/51179743
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/50420596
has answer: http://stackoverflow.com/a/52942016
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87745893
tagged with: resnet
has comment: http://stackoverflow.com/comment/97770529
has answer: http://stackoverflow.com/a/50373006
answer count: 6
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87770660
has comment: http://stackoverflow.com/comment/87764612
favorite count: 0
type: Question
has body: This is my first attempt at doing something with CNNs, so I am probably doing something very stupid - but can't figure out where I am wrong... The model seems to be learning fine, but the validation accuracy is not improving (ever - even after the first epoch), and validation loss is actually increasing with time. It doesn't look like I am overfiting (after 1 epoch?) - must we off in some other way. typical network behaviour I am training a CNN network - I have ~100k images of various plants (1000 classes) and want to fine-tune ResNet50 to create a muticlass classifier. Images are of various sizes, I load them like so: from keras.preprocessing import image def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(IMG_HEIGHT, IMG_HEIGHT)) # convert PIL.Image.Image type to 3D tensor with shape (IMG_HEIGHT, IMG_HEIGHT, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, IMG_HEIGHT, IMG_HEIGHT, 3) and return 4D tensor return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in img_paths] #can use tqdm(img_paths) for data return np.vstack(list_of_tensors)enter code here The database is large (does not fit into memory) and had to create my own generator to provide both reading from the disk and augmentation. (I know Keras has .flow_from_directory() - but my data is not structured this way - it is just a dump of 100k images mixed with 100k metadata files). I probably should have created a script to structure them better and not create my own generators, but the problem is likely somewhere else. The generator version below doesn't do any augmentation for the time being - just rescaling: def generate_batches_from_train_folder(images_to_read, labels, batchsize = BATCH_SIZE): #Generator that returns batches of images ('xs') and labels ('ys') from the train folder #:param string filepath: Full filepath of files to read - this need…

http://stackoverflow.com/q/50374348
accepted answer: http://stackoverflow.com/a/50374889
tagged with: parsing
favorite count: 0
has answer: http://stackoverflow.com/a/50374792
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87764943
tagged with: python
has answer: http://stackoverflow.com/a/50374871
has body: I have a log file from a mathematical simulation. I tried to parse it in Python, but I am not quite satisfied with the result. Is there any "elegant" way to loop each line and sort it in order to keep only lines with physical values and ditch the rest? The goal is to perform various analyses using numpy. Knowing that the lines I need only contain numerical values, is there a way to "tell" python to keep only rows / lines with numerical values and ditch all the rows containing string? Thank your for your help. A sample of the log file is attached. 5 Host 1 -- hnode146 -- Ranks 20-39 6 Host 2 -- hnode147 -- Ranks 40-59 7 Host 3 -- hnode148 -- Ranks 60-79 8 Process rank 0 hnode145 36210 9 Total number of processes : 80 10 11 STAR-CCM+ 12.02.011 (linux-x86_64-2.5/gnu4.8-r8) 12 License build date: 10 February 2015 13 This version of the code requires license version 2017.02 or greater. 14 Checking license file: 15 Checking license file: 16 Unable to list features for license file 17 1 copy of ccmppower checked out from 18 Feature ccmppower expires in 19 Thu Apr 19 17:22:54 2018 20 21 Server::start -host h 22 Loading object database: 23 Loading module: StarMeshing 24 Loading module: MeshingSurfaceRepair 25 Loading module: CadModeler 26 Started Parasolid modeler version 29.01.131 27 Loading module: StarResurfacer 28 Loading module: StarTrimmer 29 Loading module: SegregatedFlowModel 30 Loading module: KwTurbModel 31 Loading module: StarDualMesher 32 Loading module: StarBodyFittedMesher 33 Simulation database saved by: 34 STAR-CCM+ 12.02.011 (linux-x86_64-2.5/gnu4.8-r8) Fri Mar 10 20:03:37 UTC 2017 Serial 35 Loading into: 36 STAR-CCM+ 12.02.011 (linux-x86_64-2.5/gnu4.8-r8) Fri Mar 10 20:03:37 UTC 2017 Np=80 37 Object database load completed. 39 A Zeit und Datum : 2018.04.19 at 17:23:11 40 41 Startzeit: 1524151391534 42 43 Loading/configuring connectivity (old|new partitions: 1|80) 44 Domain (index 1): 1889922 cells, 5614862 faces, 1990686 verts. 45 Configuring finished 46 Re…
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: genfromtxt
upvote count: 1
downvote count: 1
has title: Skip all rows containing strings and keep only rows with floats
possible better answer: http://stackoverflow.com/a/50374792
has answer: http://stackoverflow.com/a/50374889

http://stackoverflow.com/q/50311098
tagged with: python
has comment: http://stackoverflow.com/comment/87639740
has answer: http://stackoverflow.com/a/50311229
score: 0
has body: TL;DR What are the options on Windows 10 to run from command line a python script specified by a relative path? Can environment variables be changed to do so? How can this be done? LONG I am using Windows 10. When I follow this installation guide (written for Linux), everything is fine until I need to perform the following on Windows # From tensorflow/models/research/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim On Windows, I added the two paths (the entire, absolute, path) to PYTHONPATH. When I execute the following; I see the extra two paths added. C:\User\me&gt; python -c "import sys; print(sys.path)" However, if I create a simple test.py script print("Relative path works") and run it from the command line: C:\User\me&gt; python test.py it works if the test.py file is saved in C:\User\me\, but NOT when it is saved in the folders of PYTHONPATH. This SO Q&amp;A says that PYTHONPATH is used by the python interpreter. It is not the same as Windows' PATH environment variable. You can't use it as a search path for passing files to the interpreter on the command line. But I could not find how I can achieve what I need, using relative path of script to run it from command line. Please note that using the absolute path is not an option, because the instalation guide requires 2 folders are added to the PYTHONPATH, in order for the task to work. It should be possible but I did not find any answer - Python 3 documentation describes Command line option for running script with relative path: Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file...
answer count: 2
linked to: http://stackoverflow.com/q/12829680
type: Question
has answer: http://stackoverflow.com/a/50311205
tagged with: command-line
has title: Python: run script with relative path from command line
type: UnansweredQuestion
tagged with: windows

http://stackoverflow.com/comment/87779473
has text: Note, passing a `list` directly to `.join` is always faster in CPython, because non-sequences are converted to list internally.
type: QuestionComment
comment on: http://stackoverflow.com/q/50381530
type: Comment
score: 4

http://stackoverflow.com/a/50321892
has body: In short my impression is, that you try to restrict the year when defining yearr, but this is not used in the following code. If I understand your question right, the solution would be quite simple anyway: df_2_cond = df[(df['month']==month) &amp; (df['year']==year)] However, this is just a guess. Please post code next time as text, not as attached screenshots and add a sample of your data, so that nobody has to sherlock holmes the structure of it. For this, text passages can easily be formatted, as you can see above.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50319155
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50319155

http://stackoverflow.com/comment/87739763
type: Comment
type: AnswerComment
has text: I understand what you mean,that I cannot add report reasons until the banned user profile is created first.But I am not following where "user_reported_report" variable came from?
score: 0
comment on: http://stackoverflow.com/a/50361307

http://stackoverflow.com/comment/87535804
type: AnswerComment
comment on: http://stackoverflow.com/a/50235641
type: Comment
has text: Thanks, but I was looking for something like marshmallow.
score: 0

http://stackoverflow.com/comment/87613501
type: QuestionComment
has text: The books contain the same structure and they are in `txt` format? If that's the case, they aren't Excel files.
comment on: http://stackoverflow.com/q/50298244
score: 0
type: Comment

merge
type: Tag
tags question: http://stackoverflow.com/q/50304457
tags question: http://stackoverflow.com/q/50262171
tags question: http://stackoverflow.com/q/50262291
tags question: http://stackoverflow.com/q/50381329
tags question: http://stackoverflow.com/q/50370410
tags question: http://stackoverflow.com/q/50363115
tags question: http://stackoverflow.com/q/50351011
tags question: http://stackoverflow.com/q/50234165
tags question: http://stackoverflow.com/q/50301039
tags question: http://stackoverflow.com/q/50352047
tags question: http://stackoverflow.com/q/50331151
tag name: merge
tags question: http://stackoverflow.com/q/50353592
tags question: http://stackoverflow.com/q/50366658
tags question: http://stackoverflow.com/q/50380529
tags question: http://stackoverflow.com/q/50288815
tags question: http://stackoverflow.com/q/50368792
tags question: http://stackoverflow.com/q/50381472
tags question: http://stackoverflow.com/q/50259791
tags question: http://stackoverflow.com/q/50237248
tags question: http://stackoverflow.com/q/50257586
tags question: http://stackoverflow.com/q/50358812
tags question: http://stackoverflow.com/q/50370501

http://stackoverflow.com/a/50518201
downvote count: 1
answers question: http://stackoverflow.com/q/50298644
has body: You don't need any recursion here. You can iterate through the files in the first folder and compare the names and then copy the information from the in the first folder to the file in the second folder, some thing like that: import os folder1= "folder1" folder2 = "folder2" for root, dirs, files in os.walk(folder1): for file in files: if file in os.listdir(folder2): file_path = os.path.join(folder1, file) file1_path = os.path.join(folder2, file) if os.path.isfile(file1_path): with open(file_path) as f: lines = f.readlines() with open(file1_path, 'a') as f1: f1.writelines(lines)
type: Answer
accepted answer of: http://stackoverflow.com/q/50298644
score: -1
upvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87736614
has text: What's your expected output?
comment on: http://stackoverflow.com/q/50359216
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87982301
comment on: http://stackoverflow.com/a/50369834
type: Comment
has text: Are there more URLs in columns 1 to 4? You can't simply expect it to get all of them in one call, you would need another loop.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50282539
answers question: http://stackoverflow.com/q/50282015
score: 0
has body: You could create your own class that imports and defines them as being self names: import itertools import functools class MyTools(object): def __init__(self): self.itertools = itertools self.functools = functools You would then just have to import the file containing this class: from mytools.py import MyTools mytools = MyTools() print(mytools.functools.partial)
type: Answer

http://stackoverflow.com/comment/87606765
score: 0
type: Comment
type: QuestionComment
has text: Successfully ignored )
comment on: http://stackoverflow.com/q/50294856

http://stackoverflow.com/a/50340495
type: Answer
has body: A naive solution on bash would be to check the exit status of the last program you've run, like this: $ python foo.py $ echo $?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87697142
answers question: http://stackoverflow.com/q/50340457
score: 1
has comment: http://stackoverflow.com/comment/87697171

http://stackoverflow.com/q/50383883
has comment: http://stackoverflow.com/comment/87784446
has comment: http://stackoverflow.com/comment/87784391
has comment: http://stackoverflow.com/comment/87784135
favorite count: 0
type: Question
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87784355
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50383930
accepted answer: http://stackoverflow.com/a/50383930
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Efficient conversion of a dataframe into list in a large dataset
has body: I have the following code that reads in a csv file(into dataset DataFrame) and convert this into a list(into transactions list) to be processed by an apriori algorithm. import pandas as pd dataset = pd.read_csv('datasetFile.csv') transactions = [] num_rows = 8000 num_cols = 20 for i in range(0, num_rows): transactions.append([str(dataset.values[i,j]) for j in range(0, num_cols)]) The format of the .csv file is 8000 rows, with a maximum of 20 products in a row: bread, butter bread, milk, eggs, fruit milk eggs, milk, bread The above python code works for this small dataset. However, my current dataset has around 300k rows and 300 cols. How can I improve this piece of python code to convert the large DataFrame into a list?

http://stackoverflow.com/q/50309880
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/50310074
has title: Group all rows that fall in the same time bin in pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/87638192
type: Question
has body: I am trying to define which apps were used in different sessions. Basically, I am defining every 5 minutes as a session and would like to know how many mobile sessions are there in the dataset. Also, I would like to know which apps were launched in each session. All the rows in my data frame are time stamped. Here is an example from the dataset: timestamp App 6773 2018-04-08 09:47:57.849 Chrome 6774 2018-04-08 09:48:17.573 YouTube 6775 2018-04-08 09:48:28.538 Instagram 6776 2018-04-08 09:48:37.381 Maps 6777 2018-04-08 09:48:46.680 Netflix 6778 2018-04-08 09:48:56.672 Google Play Store 6779 2018-04-08 09:56:58.880 Google 6780 2018-04-08 09:57:25.461 DB Navigator 6781 2018-04-08 11:28:38.762 Google 6782 2018-04-08 12:58:31.455 Google 6783 2018-04-08 14:31:18.131 Google 6784 2018-04-08 14:31:29.209 Google 6785 2018-04-08 14:58:42.875 Google 6786 2018-04-08 18:18:04.757 Chrome 6787 2018-04-08 21:08:41.368 Google 6788 2018-04-11 10:53:10.744 Google 6789 2018-04-14 19:54:37.441 Google 6790 2018-04-14 19:54:59.833 Google 6791 2018-04-14 19:55:10.844 YouTube 6792 2018-04-14 19:55:34.486 Google 6793 2018-04-14 20:23:00.315 Google 6794 2018-04-15 08:23:44.873 Google 6795 2018-04-15 08:24:07.257 Google This is the desired output, where a new column named SessionID is added defining the id of the current session. timestamp App SessionID 6773 2018-04-08 09:47:57.849 Chrome 1 6774 2018-04-08 09:48:17.573 YouTube 1 6775 2018-04-08 09:48:28.538 Instagram 1 6776 2018-04-08 09:48:37.381 Maps 1 6777 2018-04-08 09:48:46.680 Netflix 1 6778 2018-04-08 09:48:56.672 Google Play Store 1 6779 2018-04-08 09:56:58.880 Google 2 6780 2018-04-08 09:57:25.461 DB Navigator 2 6781 2018-04-08 11:28:38.762 Google 3 6782 2018-04-08 12:58:31.455 Google 4 6783 2018-04-08 14:31:18.131 Google 5 6784 2018-04-08 14:31:29.209 Google 5 6785 2018-04-08 14:58:42.875 Google 6 6786 2018-04-08 18:18:04.757 Chrome 7 6787 2018-04-08 21:08:41.368 Google 8 6788 2018-04-11 10:53:10.744 Google 9 6789 2018-04-14 19:54:37.…
possible better answer: http://stackoverflow.com/a/50310073
tagged with: time-series
tagged with: binning
has answer: http://stackoverflow.com/a/50310269
has answer: http://stackoverflow.com/a/50310073
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50310074
has comment: http://stackoverflow.com/comment/87636381
answer count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/87605225
has text: Thank you. Such a newbie mistake! I spent hours researching how to do with headers before I noticed the curl option "-d"
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50294206
type: Comment

http://stackoverflow.com/a/50310513
type: Answer
has body: Value of beans, jars, crates has already been assigned by the first time you run secret_formula(). Changing start_point will update the value of the variable "start_point", not the others. By running the secret_formula() again, you will get the new values you are looking for. def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) print(f"With a starting point of: {start_point}") print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.") start_point = start_point / 10 beans, jars, crates = secret_formula(start_point) print("We can have also do that this way:") print("We'd have {} beans, {} jars, and {} crates.".format(beans, jars, crates))
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/50310469

http://stackoverflow.com/q/50295839
upvote count: 1
tagged with: tensorflow
favorite count: 0
has title: Make predictions for a single sequence using tensorflow seq2seq APIs
type: Question
has body: I have trained a sequence to sequence model using tensorflow. However, I am unable to make predictions on a single sequence using The Greedy Embedding Helper. Here is a part of the graph for reference : training_helper = tf.contrib.seq2seq.TrainingHelper(decoder_embeddings,decoder_lengths,time_major=True) start_tokens = tf.fill([1], word_to_index['&lt;go&gt;']) inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(embeddings,start_tokens,word_to_index['&lt;eos&gt;']) def decode(helper,scope,reuse=None): decoder = tf.contrib.seq2seq.BasicDecoder(decoder_cell,helper,encoder_final_state,output_layer=projection_layer) final_outputs,final_state,final_sequence_lengths = tf.contrib.seq2seq.dynamic_decode(decoder,impute_finished=True,output_time_major=False) return final_outputs training_outputs = decode(training_helper,'decode') infer_outputs = decode(inference_helper, 'decode',reuse=True) logits = training_outputs.rnn_output predictions = infer_outputs.sample_id predictions_ = tf.identity(predictions,name="predicitions") Training works fine using any batch size. Problem comes during inference, I saved my model and tried to make a prediction on a sequence where I get the following error. Traceback (most recent call last): File "/home/justdial/Codes/himanshu/tensorflow_practice/Chatbot/chat2.py", line 131, in &lt;module&gt; 'decode',reuse=True) File "/home/justdial/Codes/himanshu/tensorflow_practice/Chatbot/chat2.py", line 120, in decode final_outputs,final_state,final_sequence_lengths = tf.contrib.seq2seq.dynamic_decode(decoder,impute_finished=True,output_time_major=False) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/seq2seq/python/ops/decoder.py", line 304, in dynamic_decode swap_memory=swap_memory) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 3224, in while_loop result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/op…
tagged with: seq2seq
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/50239294
has answer: http://stackoverflow.com/a/50239350
upvote count: 2
has title: How pass a variable from html to python in an easy way?
answer count: 1
has comment: http://stackoverflow.com/comment/87495894
tagged with: variables
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87496060
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87496505
score: -3
has comment: http://stackoverflow.com/comment/87495909
tagged with: http://stackoverflow.com/tag/html
downvote count: 5
tagged with: python
has body: I would like to know the easiest way of pass a variable in html to python. I get the variable with "input" and i only want to pass it to python, python doesn´t have to send anything to html. Thank you!

http://stackoverflow.com/q/50232280
has title: How to slice a dataframe column based on another column
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50232366
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I have a df like this, Main Length Sri playnig well cricket 5 sri went out 2 Ram is in 1 Ram went to UK,US 2 I am trying to slice the df["Main"] based on df["Length"] My expected output is, Main Length Sri p 5 sr 2 R 1 Ra 2 I tried def slicer(row): for i in df["Length"]: row['Main'].slice(0,i) return row df.apply(slicer,axis=1) but I am getting, AttributeError: ("'str' object has no attribute 'slice'", 'occurred at index 0') please help.
has answer: http://stackoverflow.com/a/50232366
downvote count: 0
answer count: 1
favorite count: 0
tagged with: data-analysis
type: Question
tagged with: pandas

http://stackoverflow.com/q/50283901
tagged with: python
type: Question
score: 0
has body: I'm using the Django Sitemap Framework. You can see my sitemap here: https://dealmazing.com/sitemap.xml It seems to be picking up my blog at /blog but not my actual blog posts. it looks like it is recording the actual posts over and over again as dealmazing.com/blog but without the real URL This is my sitemaps.xml file from django.contrib import sitemaps from django.contrib.sitemaps import Sitemap from django.urls import reverse from deals.models import Deal, Category, Retailer from blog.models import Post, BlogCategory class StaticViewSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = 'daily' def items(self): return ['about', 'contact', 'disclosure', 'terms', 'privacy', 'deals:deals', 'blog:blog'] def location(self,item): return reverse(item) class BlogSitemap(Sitemap): changfreq = "daily" priority = 1.0 location ='/blog' def items(self): return Post.objects.filter(status='Published') def lastmod(self, obj): return obj.created class BlogCategorySitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return BlogCategory.objects.all() class DealCategorySitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Category.objects.all() class RetailerSitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Retailer.objects.all() class DealSitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Deal.objects.all() def lastmod(self, obj): return obj.date_added and in my urls file sitemaps = { 'static': StaticViewSitemap, 'blog': BlogSitemap, 'blog-category': BlogCategorySitemap, 'deals': DealSitemap, 'deals-category': DealCategorySitemap, 'retailers': RetailerSitemap } path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), I can't quite determine why it is not posting the full URL
answer count: 0
tagged with: django-sitemaps
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87584321
tagged with: django
has title: Django Sitemaps Not Showing My Blogposts
has comment: http://stackoverflow.com/comment/87584536

syntax
tags question: http://stackoverflow.com/q/50310254
type: Tag
tags question: http://stackoverflow.com/q/50309926
tags question: http://stackoverflow.com/q/50275129
tags question: http://stackoverflow.com/q/50358870
tags question: http://stackoverflow.com/q/50240427
tags question: http://stackoverflow.com/q/50373842
tag name: syntax
tags question: http://stackoverflow.com/q/50308036
tags question: http://stackoverflow.com/q/50307722
tags question: http://stackoverflow.com/q/50272484
tags question: http://stackoverflow.com/q/50351664

http://stackoverflow.com/comment/99464782
has text: @cs95 The performance comparison is biased since `ajax1234` and `cs0` use `str.format` while other functions use f-strings which are considerably faster (`sruthiV` even uses `+`). So effectively the performance of these functions is degraded by using a less performant formatting option. In order to provide a meaningful comparison the functions need to be updated to use the same formatting option. Also `sruthiV` should use `i//2` instead of `int(i/2)` as it is much more efficient (hence avoiding additional bias).
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50312321

http://stackoverflow.com/comment/87777826
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50380804
has text: list and dict are just python types. A list is a mutable array and a dict more closely resembles an associative array. Would be good to check the docs on python types as it can enlighten you more on the language. https://docs.python.org/2/library/types.html

http://stackoverflow.com/comment/87705923
type: AnswerComment
comment on: http://stackoverflow.com/a/50344336
type: Comment
has text: Inside the function `BnC_control()` replace the first line with `alpha = alpha/10.0`. It needs a `float` value to operate.
score: 0

http://stackoverflow.com/comment/87496955
type: QuestionComment
score: 0
has text: Capture network packets with wireshark to see the tcp exchange.
type: Comment
comment on: http://stackoverflow.com/q/50237213

http://stackoverflow.com/comment/87611570
has text: Thank you @erik It can be a reasonable solution for the moment. Otherwise, I should create an app, integrate it with Slack and use [RTM](https://api.slack.com/rtm) to track user's activity and post updates to the server whenever they connect/disconnect.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50292317

http://stackoverflow.com/q/50347844
upvote count: 1
tagged with: django-forms
score: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50347909
has title: How get instance in a method clean from some forms
has body: How can I get the Article instance in my model form's clean method? I tried too access self.instance but it is None. How do I get the previous field values? model class Article(models.Model): name = models.CharField(max_length=25) value = models.CharField(max_length=25) forms class ArticleForm(forms.ModelForm) class Meta: model = Article fields = '__all__' def clean(self): cleaned_data = super().clean() get_instance = self.instance print(get_instance) and I get None views def test(request) form = ArticleForm({'name':'test', 'value':'test'}) if form.is_valid(): print(1) else: print(form.errors)
answer count: 1
downvote count: 0
tagged with: django

http://stackoverflow.com/q/50360809
answer count: 1
has comment: http://stackoverflow.com/comment/87738780
favorite count: 0
type: Question
tagged with: interpolation
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50766633
type: UnansweredQuestion
tagged with: cubic-spline
tagged with: python
tagged with: spline
has comment: http://stackoverflow.com/comment/87738734
has body: I'm trying to interpolate using the cubic spline, but the interpolation fluctuates wildly around the data points. I don't know how to fix this. Any advice would be greatly appreciated. TY = [90.3601709789,40.5189212844,20.3763456417,10.8899070251,6.19675122846,5.23402053792,6.05144428822,9.64276229024,24.1886072903,41.5725945652,171.923304843] TX = [0.93984962406,0.90225563910,0.84586466165,0.75187969925,0.56390977444,0.37593984962,0.18796992481,0.07518796992,0.01879699248,0.00939849624,0.00187969925] ipos = TX[0:6] jpos = TY[0:6] minpos = min(jpos) maxpos = max(jpos) ineg = TX[5:11] jneg = TY[5:11] minneg = min(jneg) maxneg = max(jneg) ypos1 = interp1d(jpos,ipos) ypos2 = interp1d(jpos,ipos, kind='cubic') xpos = np.linspace(minpos,maxpos,10000,endpoint=True) yneg1 = interp1d(jneg,ineg) yneg2 = interp1d(jneg,ineg, kind='cubic') xneg = np.linspace(minneg,maxneg,10000,endpoint=True) plt.figure('T') plt.xscale('log') plt.plot(TX,TY) plt.plot(xpos,ypos2(xpos)) plt.plot(xneg,yneg2(xneg)) The positive and negative parts are because the data changes direction at the midpoint.
downvote count: 0
score: 1
upvote count: 1
has title: Python cubic spline is interpolating strangely

http://stackoverflow.com/comment/87779858
score: 0
type: AnswerComment
has text: @ebong You can write a custom template filter to achieve that. https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
type: Comment
comment on: http://stackoverflow.com/a/50365901

http://stackoverflow.com/q/50323506
favorite count: 0
tagged with: multiprocessing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87689835
answer count: 0
has body: import requests import json url = "https://s2.coinmarketcap.com/generated/search/quick_search.json" r = requests.get(url) contents = json.loads(r.content) print(contents) I want to grab all the contents of the JSON file and store it into a CSV file, but the problem is that it's taking too long to collect all the information from the file. I want to use multiprocessing Pool to cut down the time, but I don't know how to incorporate it into my code.
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87662751
has comment: http://stackoverflow.com/comment/87690390
has comment: http://stackoverflow.com/comment/87662726
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/json
has title: Incorporating pool while scraping a json file
downvote count: 1

http://stackoverflow.com/comment/87660815
has text: I do not think there is anything lazy about splitting a line in your second example: you already split the line during initialization. So, instead, just return `self._name`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50322491
type: Comment

http://stackoverflow.com/comment/87541313
comment on: http://stackoverflow.com/q/50261442
type: Comment
score: 0
has text: What's your question?
type: QuestionComment

http://stackoverflow.com/q/50292631
type: Question
has comment: http://stackoverflow.com/comment/87654263
has answer: http://stackoverflow.com/a/50437040
answer count: 2
linked to: http://stackoverflow.com/q/14607640
has comment: http://stackoverflow.com/comment/87622278
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87706300
has comment: http://stackoverflow.com/comment/87601707
has comment: http://stackoverflow.com/comment/87601572
favorite count: 0
tagged with: opencv
upvote count: 8
has comment: http://stackoverflow.com/comment/87668706
tagged with: python
has comment: http://stackoverflow.com/comment/87680730
has answer: http://stackoverflow.com/a/50365256
has title: Having three points on 3 images from 3 viewpoints how to get its coordinates in 3d space?
has body: I have 3 viewpoints locations (x,y,z coordinates on 3d grid), directions (relative to viewpoints origin points x,y,z vector) in 3d space. They all look and each does see exactly three points (markers (x,y) with filtered out background) in space (say we have a red, blue, green dot on white images). We do not know any other viewpoints-camera properties except resolution and that this are same (extremely similar) cameras. How could we get our point position in space?
score: 8
tagged with: c++

http://stackoverflow.com/comment/87704770
type: Comment
type: AnswerComment
score: 0
has text: I did, but not work
comment on: http://stackoverflow.com/a/50344176

http://stackoverflow.com/q/50348245
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50348571
answer count: 1
type: Question
has title: Create another window of same class in PySide
tagged with: pyside
has body: I am creating a small GUI program using PySide. I am having difficulty creating another object of same class. What exactly I am trying to do is that when clicked on a button on MainWindow it should create another independent window of same class. import sys from PySide import QtCore, QtGui class Sticky(QtGui.QMainWindow): def __init__(self,parent = None): QtGui.QMainWindow.__init__(self,parent) self.initUI() def initUI(self): .... self.addToolBarElements() .... self.show() def addToolBarElements(self): .... self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')),"New Note",self) self.newwindow.setStatusTip("New") self.newwindow.triggered.connect(newwindow) self.toolBar.addAction(self.newwindow) def newwindow(self): #how to create new object of same class def run(): app = QtGui.QApplication(sys.argv) notes = Sticky() sys.exit(app.exec_()) Here is what I have tried: I have tried multiprocessing but I didn't understand much. I tried calling run() method again but it gives error.
has answer: http://stackoverflow.com/a/50348571
tagged with: python

http://stackoverflow.com/a/50336242
accepted answer of: http://stackoverflow.com/q/50329629
has body: You can access the path of the currently executed module via request.node.fspath and build the path to the config.json relative to it. request is a fixture provided by pytest. Here's an example based on the directory structure you provided. # main/conftest.py import json import pathlib import pytest @pytest.fixture(autouse=True) def read_config(request): file = pathlib.Path(request.node.fspath) print('current test file:', file) config = file.with_name('config.json') print('current config file:', config) with config.open() as fp: contents = json.load(fp) print('config contents:', contents) If you copy the code above to your conftest.py and run the tests with -s, you should get an output similar to this: $ pytest -sv =============================== test session starts =============================== platform linux -- Python 3.6.5, pytest-3.4.1, py-1.5.3, pluggy-0.6.0 -- /data/gentoo64/usr/bin/python3.6 cachedir: .pytest_cache rootdir: /data/gentoo64/tmp/so-50329629, inifile: collected 2 items main/project1/test_one.py::test_spam current file: /data/gentoo64/tmp/so-50329629/main/project1/test_one.py current config: /data/gentoo64/tmp/so-50329629/main/project1/config.json config contents: {'name': 'spam'} PASSED main/project2/test_two.py::test_eggs current file: /data/gentoo64/tmp/so-50329629/main/project2/test_two.py current config: /data/gentoo64/tmp/so-50329629/main/project2/config.json config contents: {'name': 'eggs'} PASSED ============================= 2 passed in 0.08 seconds ============================ Use parsed config values You can access the parsed JSON data by returning it in the fixture and using the fixture as one of the test arguments. I slightly modified the fixture from above so it returns the parsed data and removed the autouse=True: @pytest.fixture def json_config(request): file = pathlib.Path(request.node.fspath.strpath) config = file.with_name('config.json') with config.open() as fp: return json.load(fp) Now simply use the fixture name in the tes…
has comment: http://stackoverflow.com/comment/87725438
type: Answer
has comment: http://stackoverflow.com/comment/87742090
has comment: http://stackoverflow.com/comment/88634342
upvote count: 6
has comment: http://stackoverflow.com/comment/87725763
has comment: http://stackoverflow.com/comment/88636323
has comment: http://stackoverflow.com/comment/88626077
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/87744697
answers question: http://stackoverflow.com/q/50329629
has comment: http://stackoverflow.com/comment/87756858

http://stackoverflow.com/comment/87728151
has text: The AMI environment has got standard Java installed. However, it does not have embulk installed.
comment on: http://stackoverflow.com/q/50354628
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50305634
has body: Hopefully someone can point me in the right direction here. I'm using the latest release of Anaconda (Python 2.7). I would like to use it with OpenCV with the tracking features. I've tried various versions of the cv2.pyd file including 3.0, 3.1, 3.2, 3.3 and 3.4. However, the examples I've found use one of the following commands which are not found in the module. tracker = cv2.Tracker_create(tracker_type) or tracker = cv2.TrackerKCF_create() The usage of either of these depends which OpenCV version is being used. However, neither of them work, both with the following error. 'module' object has no attribute 'Tracker_create / or TrackerKCF_create' All of the other features in OpenCV seem to work fine. Is the cv2.pyd file I'm extracting from the Windows OpenCV install limited to certain features? If I use the following in the Anaconda Prompt conda install -c menpo opencv3 it installs the tracking features I need. However, it installs v3.1 of OpenCV which is known to have bugs with the tracking features. Ideally I wan't v3.4 of OpenCV. Any help would be appreciated.
tagged with: conda
type: AnsweredQuestion
score: 0
tagged with: opencv3.0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87637428
accepted answer: http://stackoverflow.com/a/50307235
tagged with: opencv
tagged with: anaconda
has answer: http://stackoverflow.com/a/50307235
has comment: http://stackoverflow.com/comment/87629352
has title: Anaconda/OpenCV: Installing with Tracking features
has comment: http://stackoverflow.com/comment/87629612
has comment: http://stackoverflow.com/comment/87629218
tagged with: python
has comment: http://stackoverflow.com/comment/87627531

python-itertools
tags question: http://stackoverflow.com/q/50309803
tags question: http://stackoverflow.com/q/50254721
tags question: http://stackoverflow.com/q/50317610
tag name: python-itertools
type: Tag
tags question: http://stackoverflow.com/q/50289564
tags question: http://stackoverflow.com/q/50314952
tags question: http://stackoverflow.com/q/50308212

http://stackoverflow.com/q/50261847
has comment: http://stackoverflow.com/comment/87541941
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87542013
linked to: http://stackoverflow.com/q/6885164
tagged with: mysql
type: Question
tagged with: pymysql
has title: error on connecting mysql hosted locally
has body: I restored mysql dump and can be accessed in my terminal (I need to issue sudo mysql to access this db or even to start mysql) : I know this is privilege issue. But when I call mysql in python program, I get this error: OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)") I tried both ways supplying password and keeping it blank. Here is the screenshot: SOLUTION replace 'localhost' by 127.0.0.1
tagged with: python

http://stackoverflow.com/comment/101761784
score: 0
has text: Haha, lol, the data was wide, and I had to convert it too long. Pandas does this excellently thanks to stack, unstack, set_index, reset_index, and pivot
comment on: http://stackoverflow.com/a/56376124
type: Comment
type: AnswerComment

tkinter
tags question: http://stackoverflow.com/q/50236622
tags question: http://stackoverflow.com/q/50276202
tags question: http://stackoverflow.com/q/50325985
tags question: http://stackoverflow.com/q/50337598
tags question: http://stackoverflow.com/q/50310680
tags question: http://stackoverflow.com/q/50367083
tags question: http://stackoverflow.com/q/50313793
tags question: http://stackoverflow.com/q/50243679
tags question: http://stackoverflow.com/q/50279997
tags question: http://stackoverflow.com/q/50362098
tags question: http://stackoverflow.com/q/50347160
tags question: http://stackoverflow.com/q/50349656
tags question: http://stackoverflow.com/q/50368939
tags question: http://stackoverflow.com/q/50289615
tags question: http://stackoverflow.com/q/50327186
tags question: http://stackoverflow.com/q/50337901
tags question: http://stackoverflow.com/q/50297036
tags question: http://stackoverflow.com/q/50269514
tags question: http://stackoverflow.com/q/50297255
tags question: http://stackoverflow.com/q/50377085
tags question: http://stackoverflow.com/q/50305075
tags question: http://stackoverflow.com/q/50305696
tags question: http://stackoverflow.com/q/50330378
tags question: http://stackoverflow.com/q/50361705
tags question: http://stackoverflow.com/q/50373235
tags question: http://stackoverflow.com/q/50242636
tags question: http://stackoverflow.com/q/50242552
tags question: http://stackoverflow.com/q/50378788
tags question: http://stackoverflow.com/q/50376709
tags question: http://stackoverflow.com/q/50358082
tags question: http://stackoverflow.com/q/50349937
tags question: http://stackoverflow.com/q/50333573
tags question: http://stackoverflow.com/q/50280170
tags question: http://stackoverflow.com/q/50236055
tags question: http://stackoverflow.com/q/50273517
tag name: tkinter
tags question: http://stackoverflow.com/q/50273449
tags question: http://stackoverflow.com/q/50311700
tags question: http://stackoverflow.com/q/50249012
tags question: http://stackoverflow.com/q/50249633
tags question: http://stackoverflow.com/q/50269598
tags question: http://stackoverflow.com/q/50262866
tags question: http://stackoverflow.com/q/50242961
tags question: http://stackoverflow.com/q/50360837
tags question: http://stackoverflow.com/q/50310397
tags question: http://stackoverflow.com/q/50308919
tags question: http://stackoverflow.com/q/50270294
tags question: http://stackoverflow.com/q/50315936
tags question: http://stackoverflow.com/q/50308466
tags question: http://stackoverflow.com/q/50341529
tags question: http://stackoverflow.com/q/50376340
tags question: http://stackoverflow.com/q/50377577
tags question: http://stackoverflow.com/q/50237860
tags question: http://stackoverflow.com/q/50337161
tags question: http://stackoverflow.com/q/50281941
tags question: http://stackoverflow.com/q/50319159
tags question: http://stackoverflow.com/q/50234898
tags question: http://stackoverflow.com/q/50281881
tags question: http://stackoverflow.com/q/50307124
tags question: http://stackoverflow.com/q/50265479
tags question: http://stackoverflow.com/q/50230309
tags question: http://stackoverflow.com/q/50373178
tags question: http://stackoverflow.com/q/50305964
tags question: http://stackoverflow.com/q/50289748
tags question: http://stackoverflow.com/q/50326761
tags question: http://stackoverflow.com/q/50339569
tags question: http://stackoverflow.com/q/50274628
tags question: http://stackoverflow.com/q/50308612
tags question: http://stackoverflow.com/q/50270515
tags question: http://stackoverflow.com/q/50370680
tags question: http://stackoverflow.com/q/50230581
tags question: http://stackoverflow.com/q/50317948
tags question: http://stackoverflow.com/q/50270007
tags question: http://stackoverflow.com/q/50261986
tags question: http://stackoverflow.com/q/50336961
tags question: http://stackoverflow.com/q/50232750
tags question: http://stackoverflow.com/q/50372641
tags question: http://stackoverflow.com/q/50316691
tags question: http://stackoverflow.com/q/50238421
tags question: http://stackoverflow.com/q/50268186

http://stackoverflow.com/q/50270711
tagged with: pytz
has comment: http://stackoverflow.com/comment/87559037
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87558678
has title: Django timezone fields don't accept all pytz timezones
accepted answer: http://stackoverflow.com/a/50270951
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87558994
favorite count: 0
type: Question
has body: Django timezone fields are built upon pytz timezones, but some of the timezones of the latter are not valid for the fields. With a model like from django.db import models from timezone_field import TimeZoneField class TestModel(models.Model): timezone_field = TimeZoneField(default='UTC') def save(self, *args, **kwargs): self.clean() self.full_clean() super().save(*args, **kwargs) If I run (in a shell) import pytz from models import TestModel model = TestModel.objects.get(id=1) for zone in pytz.all_timezones: model.timezone = zone model.save() I get django.core.exceptions.ValidationError: {'timezone': ["Value &lt;DstTzInfo 'Africa/Asmera' LMT+2:27:00 STD&gt; is not a valid choice."]} So it fails first on 'Africa/Asmera' (it fails on others too, e.g. 'GMT+0'). Any idea of how to resolve this inconsistency? At the moment the user can select a timezone on the frontend that will give a backend error (the frontend is built in React and gets the timezones from moment timezone)
upvote count: 2
tagged with: django-timezone
tagged with: timezone
has comment: http://stackoverflow.com/comment/124170161
has comment: http://stackoverflow.com/comment/87559069
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50270951
has comment: http://stackoverflow.com/comment/87558979

http://stackoverflow.com/q/50274705
type: Question
has comment: http://stackoverflow.com/comment/87573373
has comment: http://stackoverflow.com/comment/87591846
has title: Why am I getting the error "model not found : product.print.zpl.barcode" when I try to install a module?
has comment: http://stackoverflow.com/comment/87569670
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87590993
tagged with: odoo-view
tagged with: odoo
has comment: http://stackoverflow.com/comment/87596666
tagged with: odoo-9
answer count: 1
has body: I want to install my custom module product_print_zpl_barcode, but when I press the button install it shows this error: ParseError: "Invalid view definition D\xe9tails de l'erreur : Mod\xe8le non trouv\xe9 : product.print.zpl.barcode Contexte de l'erreur : Vue `product_print_zpl_barcode.form` [view_id: 847, xml_id: n/a, model: product.print.zpl.barcode, parent_id: n/a] None" while parsing [...]/openerp/addons/product_print_zpl_barcode/views/product_print_zpl_barcode_view.xml:5, near product_print_zpl_barcode_view.xml product_print_zpl_barcode.form product.print.zpl.barcode Generate Barcode product.print.zpl.barcode form new I want to create a new model product.print.zpl.barcode but Odoo doesn't recognize the new model even though the action is created. Here is the code of
has comment: http://stackoverflow.com/comment/87570460
accepted answer: http://stackoverflow.com/a/50290340
has comment: http://stackoverflow.com/comment/87592548
has comment: http://stackoverflow.com/comment/87592791
has answer: http://stackoverflow.com/a/50290340
tagged with: http://stackoverflow.com/tag/xml

recursion
type: Tag
tags question: http://stackoverflow.com/q/50312503
tags question: http://stackoverflow.com/q/50278896
tags question: http://stackoverflow.com/q/50240100
tags question: http://stackoverflow.com/q/50308212
tags question: http://stackoverflow.com/q/50308886
tags question: http://stackoverflow.com/q/50297594
tags question: http://stackoverflow.com/q/50358784
tags question: http://stackoverflow.com/q/50270232
tags question: http://stackoverflow.com/q/50236792
tags question: http://stackoverflow.com/q/50317280
tags question: http://stackoverflow.com/q/50272214
tag name: recursion
tags question: http://stackoverflow.com/q/50234828
tags question: http://stackoverflow.com/q/50265289
tags question: http://stackoverflow.com/q/50365163
tags question: http://stackoverflow.com/q/50359534
tags question: http://stackoverflow.com/q/50275535
tags question: http://stackoverflow.com/q/50232940
tags question: http://stackoverflow.com/q/50257999
tags question: http://stackoverflow.com/q/50298644
tags question: http://stackoverflow.com/q/50368078
tags question: http://stackoverflow.com/q/50373530
tags question: http://stackoverflow.com/q/50304718

http://stackoverflow.com/a/50356050
has body: Unlike your example SWIG 3.0.12 would wrap your enum class example as Color_RED, Color_BLUE, and Color_GREEN. Here's an example that adds some additional Python code to remap that pattern into Color.RED, Color.BLUE, and Color.GREEN: %pythoncode is added to the Python portion of the SWIG wrapper. After the Python extension loads this code runs. It collects and deletes variables starting with prefix_, renames them without prefix_, then creates a class named prefix with the new variables as class variables. %module test %inline %{ namespace colors{ enum class Color{ RED = 0, BLUE = 1, GREEN = 2 }; } %} %pythoncode %{ from enum import Enum def redo(prefix): tmpD = {k:v for k,v in globals().items() if k.startswith(prefix + '_')} for k,v in tmpD.items(): del globals()[k] tmpD = {k[len(prefix)+1:]:v for k,v in tmpD.items()} # globals()[prefix] = type(prefix,(),tmpD) # pre-Enum support globals()[prefix] = Enum(prefix,tmpD) redo('Color') del redo # cleaning up the namespace del Enum %} Example use: &gt;&gt;&gt; import test &gt;&gt;&gt; dir(test) ['Color', '__builtin__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', '_test'] &gt;&gt;&gt; test.Color &lt;enum 'Color'&gt; &gt;&gt;&gt; dir(test.Color) ['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__'] &gt;&gt;&gt; test.Color.BLUE &lt;Color.BLUE: 1&gt;
type: Answer
has comment: http://stackoverflow.com/comment/87744411
has comment: http://stackoverflow.com/comment/89743988
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/50353506
accepted answer of: http://stackoverflow.com/q/50353506

http://stackoverflow.com/a/50377104
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50377067
has comment: http://stackoverflow.com/comment/87770452
has comment: http://stackoverflow.com/comment/87770566
has comment: http://stackoverflow.com/comment/87771324
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87771209
has comment: http://stackoverflow.com/comment/87770367
answers question: http://stackoverflow.com/q/50377067
has comment: http://stackoverflow.com/comment/87770647
type: Answer
has body: You can use str.join: mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']] words_to_search = ['python', 'fox'] joined_input = list(map(''.join, mat_input)) results = {i:any(i in b or i in b[::-1] for b in joined_input) for i in words_to_search} Output: {'python': True, 'fox': False}
has comment: http://stackoverflow.com/comment/87770758

http://stackoverflow.com/a/50237695
score: 4
has body: all(a != 'a' or b == 'b' for a, b in zip(list[:-1], list[1:]))
has comment: http://stackoverflow.com/comment/87493241
upvote count: 4
has comment: http://stackoverflow.com/comment/87492818
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50237645
accepted answer of: http://stackoverflow.com/q/50237645
type: Answer

http://stackoverflow.com/comment/87743545
has text: Thank you! I changed the "indir" back to fileList=glob.glob(indir), but still, when I do print(filename) , no filename output.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50363462
score: 0

http://stackoverflow.com/q/50309918
tagged with: unsupervised-learning
has comment: http://stackoverflow.com/comment/87836345
type: UnansweredQuestion
has body: I am attempting to create a genetic algorithm to train a neural network, with the goal of playing the game snake. The problem I am having is that the fitness of the generations isn't improving, it either sits still at the fitness one could expect from not giving any input to the game, or only gets worse after the first generation. I suspect it to be an issue with the Neural Network, however I am at a loss as to what it is. Neural Network setup 24 Input Nodes 2 Hidden layers 8 Nodes per layer 4 Output Nodes (One for each direction the snake can take) The input is an array of every direction the snake can see. For each direction it checks how far the distance is to either a wall, a fruit, or itself. The end result is an array with a length of 3*8 = 24. The weights and biases are random floats between -1 and 1, generated when the network is created. Genetic Algorithm setup Population size: 50000 Parents chosen per generation: 1000 Keep top per generation: 25000 (New variable, seeing better results) Mutation chance per child: 5% (I have tried many different size ratios, although I'm still not sure what a typical ratio is.) I am using single point crossover. Every array of weights and biases is crossed over between the parents, and passed on to the children (one child for each "version" of the crossover). I am using what I think is roulette selection to select parents, I will post the exact method below. The fitness of a snake is calculated with: age * 2**score (not anymore, more info in update), where age is how many turns the snake survived, and score is the amount of fruits it collected. Details Here is some pseudo-code to try to summarise how my genetic algorithm (should) work: pop = Population(size=1000) while True: # Have yet to implement a 'converged' check pop.calc_fitness() new_pop = [] for i in range(n_parents): parent1 = pop.fitness_based_selection() parent2 = pop.fitness_based_selection() child_snake1, child_snake2 = parent1.crossover(parent2) if rand() &lt;=…
downvote count: 0
tagged with: neural-network
has comment: http://stackoverflow.com/comment/87911865
has title: Genetic algorithm /w Neural Network playing snake is not improving
has answer: http://stackoverflow.com/a/61601374
has comment: http://stackoverflow.com/comment/87912195
upvote count: 24
has answer: http://stackoverflow.com/a/50556852
answer count: 3
has comment: http://stackoverflow.com/comment/87810436
tagged with: genetic-algorithm
has comment: http://stackoverflow.com/comment/87814519
tagged with: python
score: 24
has comment: http://stackoverflow.com/comment/87813388
has answer: http://stackoverflow.com/a/50567812
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50286026
has comment: http://stackoverflow.com/comment/87587997
type: Question
answer count: 2
has body: Write a program that outputs only the words in /usr/share/dict/words that start with the letters "ply". It should output the words in order, each on their own line. import re with open('words.txt', 'r') as words: pattern = re.compile(r'^ply.*') matches = pattern.match(words) for the match in matches: print(match) what am I doing wrong?
type: UnansweredQuestion
score: -2
upvote count: 1
has comment: http://stackoverflow.com/comment/87588341
has answer: http://stackoverflow.com/a/50286360
has answer: http://stackoverflow.com/a/50286208
downvote count: 3
has title: python regular expression - searching in file for the pattern
has comment: http://stackoverflow.com/comment/87588269
tagged with: python
tagged with: regex
favorite count: 0

http://stackoverflow.com/a/50241198
upvote count: 8
score: 8
accepted answer of: http://stackoverflow.com/q/50241168
type: Answer
answers question: http://stackoverflow.com/q/50241168
has comment: http://stackoverflow.com/comment/87500257
downvote count: 0
has comment: http://stackoverflow.com/comment/87499916
type: AcceptedAnswer
has body: You can use: a = np.array(sample_array) np.average(a, axis=0) Or: a.mean(0)

http://stackoverflow.com/a/73330821
answers question: http://stackoverflow.com/q/50256507
type: Answer
has body: Normally, web applications are stateless. That means every object you create should live in a request and die at the end of the request. That includes your ThreadPoolExecutor. Having an executor at the application level may work, but it will be embedded into your web application instead of running as a separate group of processes. So if you want to take the workers down or restart them, your web app will have to restart as well. And there will be stability concerns, since there is no main process watching over child processes detecting which one has gotten stale, so requires a lot of code to get multiprocessing right. Alternatively, If you want a persistent group of processes to listen to a job queue and run your tasks, there are several projects that do that for you. All you need to do is to set up a server that takes care of queueing and locking such as redis or rabbitmq, then point your project at that server and start the workers. Some projects even let you use the database as a job queue backend.
score: 0

http://stackoverflow.com/q/50307302
downvote count: 0
answer count: 1
has body: I have been recycling a bunch of code from all over the place to create a string matcher for two csv files I have. The output of my Code right now is the 3 highest matches per string. I want to additionally include cutoff below a certain match score. So that only matches above that score are shown. I thought this would be easy as according to the documentation I can just include the score_cutoff parameter into the process.extract function, but for some reason this is not an acceptable input. Here is the code I have right now: from fuzzywuzzy import process import pandas as pd import os def StringMatch (master, testfile, num_match: object = 3): master_names = master.iloc[:,3] test_names = testfile.iloc[:,0] fhp_new = [process.extract(x, master_names, limit=limit) for x in test_names] lab=" " i=1 while i&lt;=num_match: lab = lab + " " + "Match" + str(i) i = i+1 aggregated_matches = pd.DataFrame(fhp_new, columns = lab.split()) d={} for x in range (1, num_match + 1): d["Match{0}".format(x)] = [y[0] for y in aggregated_matches["Match" + str(x)]] d["test_original"] = test_names d["perfect match"] = d["Match1"] == d["test_original"] out = pd.DataFrame(data=d) out.to_csv(str(outFile + ".csv")) return (out) print ("finished") master = pd.read_csv("MasterVendorDevice.csv") testfile = pd.read_csv("testfile.csv", encoding='latin-1') limit=3 baseDir = os.path.join("/Users", "Tim", "Desktop", "String Matcher") outDir = os.path.join(baseDir, "out") if not os.path.exists(outDir): os.makedirs(outDir) outFile = os.path.join(outDir, "matches") StringMatch(master, testfile)
has answer: http://stackoverflow.com/a/50379120
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: Include a score cutoff into my Fuzzywuzzy string matching project to only include matches higher than score x
tagged with: fuzzy-search
tagged with: python
upvote count: 4
score: 4
tagged with: fuzzywuzzy

http://stackoverflow.com/a/50249779
has body: Just change: L_upper = [ L.capitalize() for i in L] in: L_upper = [ i.capitalize() for i in L]
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50249740
upvote count: 5
accepted answer of: http://stackoverflow.com/q/50249740
type: Answer
score: 5

http://stackoverflow.com/comment/87518454
comment on: http://stackoverflow.com/q/50249979
type: Comment
type: QuestionComment
has text: @jpp I guess it is considered good because the *hardest* thing in programming is naming things and method chaining helps you with that.
score: 0

http://stackoverflow.com/q/50281750
has comment: http://stackoverflow.com/comment/87580021
has answer: http://stackoverflow.com/a/50281809
has body: I have 3 different types of properties like below devices iphone ipad ipod watch city NY SFO LA NJ Company Apple Samsung Walmart Now I want create a json file using the properties. For example for devices I have done like below. I created a dictionary manually in python like below. device_dict = {'device1': 'iphone', 'device2': 'ipad', 'device3': 'ipod', 'device4': 'watch'} Then converted the dictionary to a json file like below. import json out_file = open("test.json","w") json.dump(my_dict,out_file, indent=4) out_file.close() I am able to create 3 separate json like below but How can I do for all the 3 properties into a single file.
score: 0
answer count: 1
tagged with: file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87580134
has comment: http://stackoverflow.com/comment/87580049
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87580036
tagged with: python
has title: json file creation from multiple dictionaries in python
type: Question
accepted answer: http://stackoverflow.com/a/50281809

http://stackoverflow.com/q/50247438
score: -4
has answer: http://stackoverflow.com/a/50255935
tagged with: python
accepted answer: http://stackoverflow.com/a/50255935
has title: xlwings udf function erase next cell on excel
downvote count: 4
type: AnsweredQuestion
tagged with: xlwings
upvote count: 0
has comment: http://stackoverflow.com/comment/87513812
tagged with: pandas
answer count: 1
tagged with: excel
favorite count: 0
type: Question
has body: I have a little problem on excel using xlwings and i really don't know how to fix it. When i'm using an UDF function that return for example a panda dataframe, let suppose that my dataframe is 3 colums width (no necessary condition on rows), then on the 4th columns in excel, if i write some datas on it, my panda dataframe will erase it as soon as i calculate the sheet... Although the dataframe is not using this column at all while it's 3 columns large and not 4 ... I don't know if i'm clear enough. Let me know ! thank you very much in advance. @xw.func @xw.ret(expand='table') def hello(nb): nb = int(nb) return [["hello","you"] for i in range(nb)] before recalculate the sheet after recalculate the sheet

http://stackoverflow.com/q/50302110
has title: webdriver page_source not getting the same html code as when I view the page source manualy
favorite count: 0
has comment: http://stackoverflow.com/comment/87657837
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87620758
type: Question
answer count: 0
has body: So exactly as the title says. When the webdriver opens a chrome window to browse the website i view the page source and everything's good. Then I use the page_source attribute of the webdriver object but it returns a string that is different. I don't understand what the problem is. chrome = webdriver.Chrome('./chromedriver') chrome.get('the link represents a chess match played in real time on lichess.org') with open("page_content.txt",'wb') as fd: fd.write(chrome.page_source.encode("utf-8")) My purpose is to train a neural network to play chess by analyzing the moves of two human players. I know I could do it easier (using a database), but I want to get familiar with selenium.
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
upvote count: 1

django-csrf
tags question: http://stackoverflow.com/q/50345862
tag name: django-csrf
type: Tag

http://stackoverflow.com/comment/87711574
type: Comment
type: QuestionComment
has text: You can serve html files locally on `http://localhost:8000` by using `python -m http.server 8000` in the directory containing your html files. https://docs.python.org/3/library/http.server.html#module-http.server
comment on: http://stackoverflow.com/q/50347842
score: 1

http://stackoverflow.com/comment/99477163
has text: How do i use this downloaded model ?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52330020
score: 9

http://stackoverflow.com/comment/88449457
type: Comment
score: 0
type: AnswerComment
has text: What would be the case if my Switch class took input parm with a default value? How do I change your code for that?
comment on: http://stackoverflow.com/a/50337947

radio-button
tags question: http://stackoverflow.com/q/50373250
type: Tag
tag name: radio-button

http://stackoverflow.com/a/50243147
downvote count: 0
score: 13
answers question: http://stackoverflow.com/q/50242843
has comment: http://stackoverflow.com/comment/107600964
has body: I don't see com.amazonaws.auth.profile.ProfileCredentialsProvider in the documentation. There is, however, org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider which allows you to use the key and secret along with fs.s3a.session.token which is where the token should go. The instructions on that page say: To authenticate with these: Declare org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider as the provider. Set the session key in the property fs.s3a.session.token, and the access and secret key properties to those of this temporary session. Example: fs.s3a.aws.credentials.provider org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider fs.s3a.access.key SESSION-ACCESS-KEY fs.s3a.secret.key SESSION-SECRET-KEY fs.s3a.session.token SECRET-SESSION-TOKEN
type: Answer
upvote count: 13

http://stackoverflow.com/a/50232076
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50232031
has body: You need only parameter index_col in read_csv: #by positions of columns data = pd.read_csv('data/trial.csv', index_col=[0,1]) Or: #by names of columns data = pd.read_csv('data/trial.csv', index_col=['dt', 'st']) print (data) close volume dt st 20100101 000001.sz 1 10000 000002.sz 10 50000 000003.sz 5 1000 000004.sz 15 7000 000005.sz 100 100000 20100102 000001.sz 2 20000 000002.sz 20 60000 000003.sz 6 2000 000004.sz 20 8000 000005.sz 110 110000 Why all element are all NaN when construct a multiIndex Dataframe? Reason is in DataFrame constructor: df = pd.DataFrame(data, idx, col) DataFrame called data has RangeIndex and not align with new MultiIndex, so get NaNs in data. Possible solution if always each dt has same st values is filter Dataframe by columns names and then convert to numpy array, but better are index_col and set_index solutions: df = pd.DataFrame(data[col].values, idx, col)
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50232031

http://stackoverflow.com/comment/87627536
has text: Gabriel thank you for your support! When the columns are empty, like the initial data, the left merge updates the df_cars. In case there is the need for updating the df_cars often (i.e. every week) the merge retains only the data for the period since the last update.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50301384
score: 0

http://stackoverflow.com/comment/87654763
score: 0
comment on: http://stackoverflow.com/q/50319409
type: Comment
type: QuestionComment
has text: Just tried ALollz sugestion and it returned this error: ValueError: ordinal must be >= 1

http://stackoverflow.com/comment/87741865
has text: @SpghttCd : I was waiting for someone to that put that as an answer. Maybe you can do that. I would like to accept one answer.
comment on: http://stackoverflow.com/a/50362671
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50383521
accepted answer of: http://stackoverflow.com/q/50362389
answers question: http://stackoverflow.com/q/50362389
type: Answer
score: 1
has body: A simple solution to this problem in windows 10 is to locate the file .condarc and delete all channels except the default channel. Now everything is working perfectly fine like upgrading conda and installing other libraries like tensorflow.
type: AcceptedAnswer
downvote count: 0
upvote count: 1

aws-lambda
tags question: http://stackoverflow.com/q/50278679
tags question: http://stackoverflow.com/q/50352842
type: Tag
tags question: http://stackoverflow.com/q/50258562
tags question: http://stackoverflow.com/q/50359668
tags question: http://stackoverflow.com/q/50269503
tags question: http://stackoverflow.com/q/50306675
tags question: http://stackoverflow.com/q/50233013
tags question: http://stackoverflow.com/q/50351375
tags question: http://stackoverflow.com/q/50319337
tags question: http://stackoverflow.com/q/50382396
tags question: http://stackoverflow.com/q/50232181
tags question: http://stackoverflow.com/q/50354628
tags question: http://stackoverflow.com/q/50358354
tags question: http://stackoverflow.com/q/50295964
tags question: http://stackoverflow.com/q/50279896
tag name: aws-lambda
tags question: http://stackoverflow.com/q/50352545
tags question: http://stackoverflow.com/q/50357252
tags question: http://stackoverflow.com/q/50282080

http://stackoverflow.com/comment/87616489
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50284880
has text: After spending more time with the answer above, I realized that there was a bracketing format error (error is now fixed in the answer above) and it works as advertised. Thanks.
score: 0

http://stackoverflow.com/q/50239878
has comment: http://stackoverflow.com/comment/87497750
score: 12
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50240186
has comment: http://stackoverflow.com/comment/87497434
upvote count: 12
has comment: http://stackoverflow.com/comment/87497377
has comment: http://stackoverflow.com/comment/87497650
has comment: http://stackoverflow.com/comment/87497216
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87497803
has answer: http://stackoverflow.com/a/73977633
possible better answer: http://stackoverflow.com/a/73977633
has comment: http://stackoverflow.com/comment/87497494
type: AnsweredQuestion
has body: Currently I have a DataFrame as shown below: Device TimeSec Current 1 0.1 0.02 1 0.25 0.05 1 0.32 0.07 1 0.45 0.12 1 1.32 0.34 1 2.37 2.24 2 0.22 0.56 2 0.34 0.79 2 1.87 2.76 2 3.21 3.11 3 0.16 1.87 3 1.12 2.33 3 2.45 3.21 3 3.45 5.11 ...... I would like to do the numerical integration of Current with TimeSec (∫Idt) for different Devices and collect the data into a new DataFrame as below: Device IntegratedCurrent 1 x 2 y 3 z The problem is that the time interval is not even and the number of data for each device is not even as well.
accepted answer: http://stackoverflow.com/a/50240186
has title: Pandas DataFrame column numerical integration
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/87497282

http://stackoverflow.com/a/50270302
has body: Changing frame.pack(fill=None,expand=True) to frame.pack(fill=None,expand=True, anchor="w") will align the buttons to the left side.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50270007
type: Answer
accepted answer of: http://stackoverflow.com/q/50270007

http://stackoverflow.com/q/50293170
has answer: http://stackoverflow.com/a/50294916
answer count: 5
type: UnansweredQuestion
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/50293433
has title: Given two "if" statements, execute some code if none of them is executed
favorite count: 0
has body: hey i don't know how to programm this constellation : string = " " if "abc" in string: print ("abc is in string") if "def" in string: print ("def is in string") else: print ("abc and def are not contained in string") It should go to "else" only if the 2 conditions aren't true. But if both substrings are contained in string; it should print both.
type: Question
has answer: http://stackoverflow.com/a/50305309
tagged with: if-statement
has answer: http://stackoverflow.com/a/50305009
tagged with: python
has answer: http://stackoverflow.com/a/50293234
upvote count: 6

http://stackoverflow.com/comment/87649739
type: Comment
has text: hello, thanks for your answer. The code that you put at the end of your answer displays the text, but now it doesn't display the image. adding label.pack() as the bottom line of the happy function makes both the image and text appear but it also causes an error although everything works. The error is "AttributeError: 'NoneType' object has no attribute 'pack'" . Any ideas to fix this? thanks for the help so far.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50316703

http://stackoverflow.com/comment/87696016
type: Comment
comment on: http://stackoverflow.com/q/50339569
type: QuestionComment
score: 0
has text: I can't reproduce that "window doesn't appear" thing. That code works just fine.

loops
tags question: http://stackoverflow.com/q/50276718
tags question: http://stackoverflow.com/q/50252083
tags question: http://stackoverflow.com/q/50289925
tags question: http://stackoverflow.com/q/50353277
tags question: http://stackoverflow.com/q/50364221
tags question: http://stackoverflow.com/q/50309338
tags question: http://stackoverflow.com/q/50340791
tags question: http://stackoverflow.com/q/50348096
tags question: http://stackoverflow.com/q/50254180
tags question: http://stackoverflow.com/q/50256344
tags question: http://stackoverflow.com/q/50274484
tags question: http://stackoverflow.com/q/50289484
tags question: http://stackoverflow.com/q/50297336
tags question: http://stackoverflow.com/q/50346664
tags question: http://stackoverflow.com/q/50239123
tags question: http://stackoverflow.com/q/50265969
tags question: http://stackoverflow.com/q/50325985
tags question: http://stackoverflow.com/q/50320803
tags question: http://stackoverflow.com/q/50338713
tags question: http://stackoverflow.com/q/50230801
tags question: http://stackoverflow.com/q/50266855
tag name: loops
tags question: http://stackoverflow.com/q/50361919
tags question: http://stackoverflow.com/q/50242564
tags question: http://stackoverflow.com/q/50262856
tags question: http://stackoverflow.com/q/50375098
tags question: http://stackoverflow.com/q/50344917
tags question: http://stackoverflow.com/q/50319942
tags question: http://stackoverflow.com/q/50232725
tags question: http://stackoverflow.com/q/50260676
tags question: http://stackoverflow.com/q/50305696
tags question: http://stackoverflow.com/q/50283547
tags question: http://stackoverflow.com/q/50290030
tags question: http://stackoverflow.com/q/50333432
tags question: http://stackoverflow.com/q/50379740
tags question: http://stackoverflow.com/q/50297954
tags question: http://stackoverflow.com/q/50338038
tags question: http://stackoverflow.com/q/50267427
tags question: http://stackoverflow.com/q/50348107
tags question: http://stackoverflow.com/q/50342428
tags question: http://stackoverflow.com/q/50262569
tags question: http://stackoverflow.com/q/50377351
tags question: http://stackoverflow.com/q/50307050
tags question: http://stackoverflow.com/q/50283794
type: Tag
tags question: http://stackoverflow.com/q/50291216
tags question: http://stackoverflow.com/q/50339216
tags question: http://stackoverflow.com/q/50239408
tags question: http://stackoverflow.com/q/50345780
tags question: http://stackoverflow.com/q/50255373
tags question: http://stackoverflow.com/q/50379088
tags question: http://stackoverflow.com/q/50320095
tags question: http://stackoverflow.com/q/50283987
tags question: http://stackoverflow.com/q/50233411
tags question: http://stackoverflow.com/q/50258511

http://stackoverflow.com/q/50276843
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: global
has answer: http://stackoverflow.com/a/50277291
tagged with: string
favorite count: 0
type: Question
has title: Str is already defined as a global variable
upvote count: 2
has comment: http://stackoverflow.com/comment/87570311
possible better answer: http://stackoverflow.com/a/50277047
has comment: http://stackoverflow.com/comment/87570287
accepted answer: http://stackoverflow.com/a/50276865
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/50277047
has answer: http://stackoverflow.com/a/50276865
has body: I noticed something really strange while working with functions. It looks like the variable name 'str' is already defined as a global variable. Take a look: def Example(x): str = input() return str print (Example(str)) #When typing 'Hello!' Output --&gt; Hello! The variable str is defined in the function Example. So why is there no NameError: name 'str' is not defined? When I call the variable x or something else ( In this case 'bar'): def Example(x): bar = input() return bar print (Example(bar)) #Output: NameError: name 'bar'is not defined Why does a variable with the name 'str' act as a global variable?
score: 2

http://stackoverflow.com/q/50309792
tagged with: gpu
has comment: http://stackoverflow.com/comment/87643593
has comment: http://stackoverflow.com/comment/87653880
linked to: http://stackoverflow.com/q/9985912
linked to: http://stackoverflow.com/q/5643178
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87650600
has comment: http://stackoverflow.com/comment/87640784
tagged with: vector
duplicate of: http://stackoverflow.com/q/5643178
type: UnansweredQuestion
tagged with: numba
has body: I get confuser reading about setting proper values for number of threads and blocks for cuda programming. After reading several guide and many tips i don't get answer that i search. My GPU: Nvidia GT645M Compute capability: 3.0 For what i know: The maximum number of threads per block is in my case 1024 (32 x 32) The maximum number of block in grid is in my case 2**31 - 1 = 4294967295 blocks Multi processor count = 2 The number of block is depending on input data = (input data)/(number of threads per block) For input data like [1,2,....10] + [1,2,....10] i need 10 threads and 1 block. My computing problem: For example i have input data like this: n = 10 x = np.arange(n).astype(np.float32) y = x + 1 I try make actions on this vector like: '+', '-', '*' by value Question 1: My knowledge: The GPU cuda calculations working like this: for each value in numpy array --> cuda block is used with one thread. I mean (x = [0,1,....9]) + (y = [1,2,....10]) = x[0] + y[0] in: block(0,0),thread(0,0), then x[1] + y[1] in: block(0,0),thread(1,0) and so on. Is that correct? Question 2: Let say: thread count = 5 block count = 1 then all threads in this one block will by running 2 times for x + y? Question 3: How many block can running simultaneously in one time? If you can explain step by step calculation on cuda by simple vector example, that will by nice. Thanks for all you help, please don't give any links to cuda guide i get confused reading them. Please give simple examples :)
upvote count: 1
tagged with: python
tagged with: cuda
has title: How much blocks and threads can I use on CUDA GPU
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87646591

http://stackoverflow.com/a/54814220
upvote count: 1
answers question: http://stackoverflow.com/q/50288983
has body: When I faced this issue (system: Windows - 64 bit OS) after upgrading Anaconda to the latest version (yesterday), I saw that Anaconda was trying to load the package from a location different from the default site-packages. Hence: I fist checked the path my jupyter notebook was defaulting to as mentioned in one of the git hub posts (sorry I don't remember which one) using: import sys print(sys.path) Since this path is not the default site-packages folder, I uninstalled Anaconda completely from add or remove programs - Anaconda (this will take some time to uninstall) Anaconda will also remove jupyter notebook from your system. Hence, just reinstall jupyter notebook alone and open it from command line using jupyter notebook When you now try to import the matplotlib.pyplot in your notebook, it should not give any errors and you can use the same sys.path to check the path it is defaulting to. It should look something like: Now, it is importing from the site-packages folder. I am yet to investigate why and how this issue was caused but removing the upgraded Anaconda version helped me.
type: Answer
has comment: http://stackoverflow.com/comment/96414174
downvote count: 0
score: 1

http://stackoverflow.com/comment/87778144
has text: @BeginnerKruman hm, I wrote that quickly and used unix syntax in the glob argument. Try using windows syntax. I don't really have a windows box to experiment with atm...
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50379088
type: QuestionComment

http://stackoverflow.com/q/50273650
upvote count: 1
tagged with: computer-vision
tagged with: scipy
favorite count: 0
type: Question
tagged with: opencv
has body: I have a reference image captured from a cc-camera and need to capture current image from the cc-camera to check if the camera is shifted or not at regular intervals. If shifted, the shift angle must also be needed. How can I achieve this using python? Is the cv2.phaseCorrelate() function be helpful for this. Please give me some suggestions. Thank you.
tagged with: python
accepted answer: http://stackoverflow.com/a/50737007
tagged with: image-processing
has answer: http://stackoverflow.com/a/50737007
type: AnsweredQuestion
score: 1
has title: python: Find camera shift angle using a reference image and current image from the camera
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50337996
tagged with: invoke
linked to: http://stackoverflow.com/q/3652554
has answer: http://stackoverflow.com/a/50353761
tagged with: java
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87692614
has comment: http://stackoverflow.com/comment/87693196
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: function
answer count: 1
has body: I have java application on windows , that contains lot of .class files(so I cant see the name of the function and what they do). I want to invoke to apply 1 function from outside of the application while the application I running (I prefer do it on python). I search so much but not found any way to do it. is that passable?
has comment: http://stackoverflow.com/comment/87692653
downvote count: 1
favorite count: 0
has title: Invoke to java function outside the application

http://stackoverflow.com/comment/87712632
type: QuestionComment
comment on: http://stackoverflow.com/q/50348347
type: Comment
score: 1
has text: I think your dict has one (key, value) because you do assignment in each iteration rather than updating the dict with new values. Am i missing something?

http://stackoverflow.com/q/50365336
accepted answer: http://stackoverflow.com/a/50366832
has body: Suppose I have a dataframe called df as follows: A_column B_column C_column 0 Apple 100 15 1 Banana 80 20 2 Orange 110 10 3 Apple 150 16 4 Apple 90 13 [Q] How to list the index [0,3,4] for Apple in A_column?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: indexing
has title: Find the index of multi-rows
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: row
has comment: http://stackoverflow.com/comment/87749873
has comment: http://stackoverflow.com/comment/87747346
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50366832

http://stackoverflow.com/q/50295995
has title: PyKafka metadata in bytes instead of strings
upvote count: 5
accepted answer: http://stackoverflow.com/a/50326220
tagged with: python
has answer: http://stackoverflow.com/a/50326220
answer count: 2
score: 5
tagged with: pykafka
downvote count: 0
possible better answer: http://stackoverflow.com/a/50340190
has body: I see an unusual behaviour with PyKafka, a client that I just recently began to use. The error is the following: Failed to connect newly created broker for b'4758e4ee1af6':9092 {0: &lt;pykafka.broker.Broker at 0x7f319e19be10 (host=b'4758e4ee1af6',port=9092, id=0)&gt;} The source of the error is in this lines: self.client = KafkaClient(hosts=BROKER_ADDRESS, broker_version="0.10.1.0") consumer = self.client.topics[bytes(self.input_topic,"UTF-8")].get_balanced_consumer( consumer_group=bytes(self.consumer_group,"UTF-8"), auto_commit_enable=True ) Debugging I saw that the client use the correct string IP to connect to the seed broker but when the list of brokers is retrieved, their IP are in binary and when PyKafka tries to connect again to create a consumer, these IPs obviously don't work. Another problem, possibly connected, is that I need to convert topic names and consumer groups names to bytes by myself (like with other clients) but all the examples in the docs show the usage of strings. Kafka broker version: 0.10.1.0 PyKafka version: 2.7.0
has answer: http://stackoverflow.com/a/50340190
favorite count: 0
type: Question
tagged with: apache-kafka
type: AnsweredQuestion

http://stackoverflow.com/q/50380468
accepted answer: http://stackoverflow.com/a/50381010
tagged with: python
has answer: http://stackoverflow.com/a/50381010
type: Question
tagged with: c++
score: 2
has body: I am using python to extend lldb by a custom command gm, which calls a C++ - function cli(const char* params) then. So one can pause xcode (thereby launching lldb) and type... (lldb) gm set value to trigger a call cli("set value") then. C++-function cli can make use of std::cout to print some state, but I cannot make this function "interactive", i.e. consuming user input: void cli(const char* params) { std::cout &lt;&lt; "params: " &lt;&lt; params &lt;&lt; std::endl; // works std::string userInput; std::cin &gt;&gt; userInput; // does not work; is simply ignored } Question: How can I make cli interactive in a sense that it consumes (and further processes) user input? To further show what I'd like to achieve: There are built in lldb-commands like expr (without arguments) which enter into an interactive mode: (lldb) expr Enter expressions, then terminate with an empty line to evaluate: 1 2+2 2 (int) $0 = 4 I'd like to have similar behaviour in my own command, i.e. typing in gm and being then asked interactively for params: (lldb) gm Enter generic model parameters; Terminate interactive mode with "end": 1 set value 2 params: set value 3 end Just for completeness, see the python script currently used for calling the cli-function: def gm(debugger, command, result, internal_dict): cmd = "po cli(\""+command+"\")" lldb.debugger.HandleCommand(cmd) # And the initialization code to add your commands def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand('command script add -f gm.gm gm') print 'The "gm" python command has been installed and is ready for use.' and the line in the .lldbinit-file registering this script: command script import ~/my_commands.py
upvote count: 2
tagged with: lldb
has title: lldb: implement custom command taking user input
answer count: 1
downvote count: 0
favorite count: 0
type: AnsweredQuestion
tagged with: xcode

http://stackoverflow.com/q/50247574
has title: Unable to display data from model in template
type: AnsweredQuestion
answer count: 3
has body: I am trying to display data from a model inside my post.html which worked before but now dosen't for some reason I can't figure out. urls.py urlpatterns = [ path('', ListView.as_view( queryset=Tutorials.objects.all().order_by("-date")[:25], template_name="tutorials/blog.html" )), path('<int:pk>', DetailView.as_view( model=Tutorials, template_name="tutorials/post.html")), ] blog.html {% block python %} {% for Tutorials in object_list %} {% if Tutorials.categories == "pythonbasics" %} {{ Tutorials.title }} Created On : {% endif %} {% endfor %} {% endblock %} post.html {% block content %} {{ Tutorials.title }} on {{ Tutorials.datetime }} {% endblock %}
downvote count: 0
has answer: http://stackoverflow.com/a/50249899
possible better answer: http://stackoverflow.com/a/50249899
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50247613
accepted answer: http://stackoverflow.com/a/50247613
has comment: http://stackoverflow.com/comment/87512505
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87512526
has answer: http://stackoverflow.com/a/70317639
tagged with: django
tagged with: python

http://stackoverflow.com/comment/87523131
has text: The first custom `print()` function overwrites the file for every message.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50250595

http://stackoverflow.com/comment/87756391
has text: To one another. For 75 its 60,70,60
comment on: http://stackoverflow.com/q/50368078
score: 0
type: QuestionComment
type: Comment

iso-8859-15
tags question: http://stackoverflow.com/q/50279749
type: Tag
tag name: iso-8859-15

http://stackoverflow.com/comment/87481027
has text: urlx is not defined and even if it was in some code earlier, it doesn't change its value in the loop `while urlx < 591:`. This will lead to an infinite loop.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50231746
score: 0

http://stackoverflow.com/a/50382139
upvote count: 1
has body: mysql.connector uses %s instead of ? as the parameter marker, but you are circumventing it by using Python string formatting. Try this: sql = "select idip from ip where ip=%s and mask=%s" cursor.execute(sql, (long(next_hop), 'DEFAULT')) idnext_hop = cursor.fetchone()[0]
score: 1
has comment: http://stackoverflow.com/comment/87780271
type: Answer
accepted answer of: http://stackoverflow.com/q/50381839
has comment: http://stackoverflow.com/comment/87780434
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50381839

http://stackoverflow.com/comment/87691783
type: AnswerComment
comment on: http://stackoverflow.com/a/50312463
has text: Yes, Python 2.7 is the version it points to when I enter my terminal and type 'python'. How do I change it so that the default version is python 3?
type: Comment
score: 0

http://stackoverflow.com/comment/87484251
type: QuestionComment
has text: No worries as Sayse says, you also need to decrement `ind` *inside* your loop
comment on: http://stackoverflow.com/q/50233337
score: 0
type: Comment

http://stackoverflow.com/q/50281723
has title: Convolutional layer - defining output tensorflow
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87581198
has comment: http://stackoverflow.com/comment/87581057
has comment: http://stackoverflow.com/comment/87580593
has comment: http://stackoverflow.com/comment/87580703
type: AnsweredQuestion
score: 2
tagged with: conv-neural-network
has body: The code runs as follow: import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) def cnn_model_fn(features, labels, mode): '''Model function for CNN''' #Input Layer #Reshape X to 4-D tensor: [batch_size, width, height, channels] input_layer = tf.reshape(features['x'],[-1, 28, 28, 1]) #Convolutional Layer #Computes 3 features maps using 5x5 filter with sigmoid activation #Input Tensor Shape: [batch_size, 28, 28, 1] #Output Tensor Shape: [batch_size, 24, 24, 20] conv = tf.layers.conv2d( inputs = input_layer, filters = 20, kernel_size = [5,5], activation = tf.nn.sigmoid) #Pooling Layer #Max pooling layer with a 2x2 flter and stride of 2 #Input Tensor Shape: [batch_size, 24, 24, 20] #Output Tensor Shape: [batch_size, 12, 12, 20] pool = tf.layers.max_pooling2d( inputs = conv, pool_size = [2, 2], strides = 1) #Flatten tensor into a batch of vectors #Input Tensor Shape: [batch_size, 12, 12, 20] #Output Tensor Shape: [batch_size, 12 * 12 * 20] pool_flat = tf.reshape(pool, [-1, 12 * 12 * 20]) #Fully Connected Layer = dense layer # #Input Tensor Shape: [batch_size, 12 * 12 * 20] #Output Tensor Shape: [batch_size, 100] fully_cnted = tf.layers.dense( inputs = pool_flat, units = 100, activation = tf.nn.sigmoid) #Output Layer #Softmax #Input Tensor Shape: [batch_size, 100] #Output Tensor Shape: [batch_size, 10] logits = tf.layers.dense( inputs = fully_cnted, units = 10, activation = tf.nn.softmax) predictions = { #Generate predictions (for PREDICT and EVAL mode) "classes":tf.argmax(input = logits, axis = 1), #Add `softmax_tensor` to the graph. It is used for PREDICT and by the #`logging_hook´. "probabilities": tf.nn.softmax(logits, name = "softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) #Calculate Loss (for both TRAIN and EVAL modes) loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) #Configura the Training Op (for TRAIN mode) if mode == tf.esti…
accepted answer: http://stackoverflow.com/a/50282375
has comment: http://stackoverflow.com/comment/87580984
has comment: http://stackoverflow.com/comment/87581018
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50282375

http://stackoverflow.com/comment/87652021
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50310613
type: QuestionComment
has text: yea i can get away with ffmpeg for screen recording, for that i will have to use it as sub process in python i guess. but what i want to do is capture the frames and send it through socket to other host like teamviewer does and plot it on remote computer.

http://stackoverflow.com/q/50310699
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/26937153
type: AnsweredQuestion
upvote count: 0
tagged with: python
tagged with: string
has answer: http://stackoverflow.com/a/50310749
tagged with: str-replace
favorite count: 0
linked to: http://stackoverflow.com/q/25500098
has title: replace character in string in python
type: Question
linked to: http://stackoverflow.com/q/26937153
has body: I am trying to write a program that allows a user to play hangman. If the user guesses a certain letter, say 'p', I want to replace the underscores in 'word' at the correct indices. I am unsure how to replace the underscores with the letters correctly guessed. Thank you for your help! e.g. secretWord='apple' word='_ _ _ _ _' #user guesses 'p' #word='_ p p _ _' (how word changes when the correct letters are guessed)
accepted answer: http://stackoverflow.com/a/50310749
answer count: 1
downvote count: 1
score: -1

http://stackoverflow.com/q/50327665
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50328277
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/50328204
has answer: http://stackoverflow.com/a/50328204
tagged with: plot
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87671493
score: -2
has title: Python plt plotting while in for loop - not working
has body: I am trying to plot a simple self defined sinc function defined as follows (adapted from an old paper of Oliphant about Python for Scientific Computing): from math import sin, pi import NumPy as np def sinc(x): '''Compute the sinc function: sin(pi*x)/pi*x''' try: return sin(x)/x except ZeroDivisionError: return 1.0 output = [sinc(x) for x in input] To plot it (point by point, re-drawn/updated after each newly computed sinc value) i tried the following code: pl = np.zeros(1001) for x in range(1,1001,1): pl[x]=sinc(x) plt.plot(pl[x],c='blue') plt.pause(0.05) plt.show() where plt is the usual matplotlib.pyplot, pl is a NumPy. I can see the matplotlib frame with the axes and the axis limits increasing but the plot is simply not plotted/drawn/printed/shown(as in next picture) Image
tagged with: matplotlib
tagged with: python
possible better answer: http://stackoverflow.com/a/50328277

http://stackoverflow.com/comment/87770315
comment on: http://stackoverflow.com/q/50360053
score: 0
type: Comment
has text: I guess I'm asking how to process the audio_data. Mostly what do the numbers mean? I understand what fft does, but applying fft to what is to me an array of numbers without meaning does nothing. I guess I might be asking the wrong community, and should be targeting signal processing instead. Only turning here since I can't seem to dig up anyone explicitly explaining what the audio_data being returned is for someone who has never worked with sound before.
type: QuestionComment

http://stackoverflow.com/a/50381420
has comment: http://stackoverflow.com/comment/87809191
answers question: http://stackoverflow.com/q/50360428
has body: On one level, this is pretty simple. You can always add gui elements to a Maya layout if you have a string reference to it, using the setParent() command to tell Maya where the new stuff goes. In a case like this you just need to pass the shared layout to a bunch of functions --- it doesn't matter where they come froms -- and have each of them call 'setParent` to make the layout active and add to it. Here's an example of how it would go, using separate functions instead of separate modules -- it would not make a difference if these different functions had different module origins. def button_section(parent): cmds.columnLayout(adj=True) cmds.frameLayout(label='buttons') cmds.columnLayout(adj=True) cmds.rowLayout(nc=2, cw = (200,200)) cmds.button(label = 'red', backgroundColor=(1,0.5,0.5), width=100) cmds.button(label = 'blue', backgroundColor =(0.5, 0.5, 1), width=100) def text_section(parent): cmds.separator() cmds.text(label = 'time:') cmds.text(label = 'It is currently ' + str(datetime.datetime.now())) cmds.text(label = 'main layout is ' + parent) cmds.separator() def object_section(parent): cmds.columnLayout(adj=True) cmds.frameLayout(label = 'scene') cmds.columnLayout(adj=True, rs = 12, columnAttach = ('both', 8) ) for object in cmds.ls(type='transform'): select_the_thing = lambda b: cmds.select(object) cmds.button(label = object, c = select_the_thing) def create_window(*sections): window = cmds.window(title = 'example') main_layout = cmds.columnLayout(adj=True) for each_section in sections: cmds.setParent(main_layout) each_section(main_layout) cmds.setParent(main_layout) cmds.columnLayout(adj=1, columnAttach = ('both', 8)) cmds.separator() cmds.text(label = 'here is a footer') cmds.showWindow(window) create_window(button_section, text_section, object_section) If you're not familiar with the syntax the create_window function with a * takes any number of arguments. In this case it's just taking the three individual section functions. You could, however write it t…
type: Answer
has comment: http://stackoverflow.com/comment/87809814
has comment: http://stackoverflow.com/comment/87809194
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50360428

http://stackoverflow.com/comment/87649315
type: AnswerComment
comment on: http://stackoverflow.com/a/50314511
has text: if I have a string variable `path = 'C:\apps\python'`, how do I generate the raw string of `path` ? is there a function I can apply on `path` to do that ? I do not want to type `r'C:\apps\python'` everywhere in my code.
score: 0
type: Comment

http://stackoverflow.com/q/50289743
has answer: http://stackoverflow.com/a/50289849
has answer: http://stackoverflow.com/a/50289869
type: AnsweredQuestion
score: 0
tagged with: split
has comment: http://stackoverflow.com/comment/87595586
has answer: http://stackoverflow.com/a/50289826
has body: The following code takes a string such as abcd#1234, removes the '#' and splits it into abcd and 1234 import sys import re print("User ID: {0}").format(sys.argv[1]) print("User Type: {0}").format(sys.argv[2]) sub = re.sub('[#]', '', sys.argv[1]) split = re.match(r"([a-z]+)([0-9]+)", sub, re.I) print(split.groups()) The output from print(split.groups()) is &lt;'abcd', '1234'> How can I take an individual section of the split such as abcd and just output that?
tagged with: string
has title: Print individual split strings
type: Question
has answer: http://stackoverflow.com/a/50289872
accepted answer: http://stackoverflow.com/a/50289826
tagged with: python
possible better answer: http://stackoverflow.com/a/50289849
answer count: 4

http://stackoverflow.com/comment/87721320
has text: Yes. I have 58 files and all of them are text files
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50349305
score: 0

http://stackoverflow.com/comment/87498254
score: 0
type: Comment
type: QuestionComment
has text: Appertly you have 10 classes. And changing the last layer to ten outputs will solve this error. Also 600 datapoints divided by 10 classes nets you 60 data points per class. You really have too small a data set for deep learning. You should consider a simpler model
comment on: http://stackoverflow.com/q/50240354

http://stackoverflow.com/a/58817570
score: 0
has body: By slighly modifying Ali Yilmaz's solution as following (href=True): for url in soup.find_all('article'): if "Gonz Logo" in url.get_text(): if "Black" in url.get_text(): for child_a in url.find_all('a', href=True): print(child_a['href']) It works fine
answers question: http://stackoverflow.com/q/50320433
type: Answer

http://stackoverflow.com/q/50319273
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87654350
has body: Say, I have this tiny flask app if the user has a valid token when he posts something I give him something else. When he doesn't I want to silently drop his connection. How do I do that? Here's some sample code to help you visualize what I want to do @app.route("/do_action", methods=('POST',)) def do_action(): if request.form['TOKEN'] not in valid_tokens: drop_connection() # how? else: return get_action_result() To be clear, I don't want to throw an error or politely close the connection I want to just drop the user request, let him hit the timeout.
has answer: http://stackoverflow.com/a/50319608
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87654541
has title: How to drop a connection with flask

http://stackoverflow.com/q/50262612
upvote count: 1
favorite count: 0
type: Question
tagged with: performance
has title: Parallelise string replace in pandas
tagged with: numba
has body: I have two pandas dataframes. One contains text, the other a set of terms i'd like to search for and replace within the text. There are many permutations of the text where the same word can appear multiple times in the text and have multiple terms. I have created a loop which is able to replace each word in the text with a term however it's very slow, especially given that it is working over a large corpus. My question is: Is there a way of running the below function in a parallelised for speed? Alternatively could the function use Numba or some other type of optimisation to speed it up? NB note the fact that there can be many permutations within the text that need replacing. Example text dataframe: d = {'ID': [1, 2, 3], 'Text': ['here is some random text', 'random text here', 'more random text']} text_df = pd.DataFrame(data=d) Example terms dataframe: d = {'Replace_item': ['&lt;RANDOM_REPLACED&gt;', '&lt;HERE_REPLACED&gt;', '&lt;SOME_REPLACED&gt;'], 'Text': ['random', 'here', 'some']} replace_terms_df = pd.DataFrame(data=d) Example of current solution: def find_replace(text, terms): for _, row in terms.iterrows(): term = row['Text'] item = row['Replace_item'] text.Text = text.Text.str.replace(term, item) return text find_replace(text_df, replace_terms_df) Please let me know if anything above requires clarifying. Thank you,
tagged with: python
accepted answer: http://stackoverflow.com/a/50262648
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50262648
tagged with: pandas
score: 1
answer count: 1
downvote count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/50359314
tags question: http://stackoverflow.com/q/50256912
tags question: http://stackoverflow.com/q/50287283
tags question: http://stackoverflow.com/q/50308028
tags question: http://stackoverflow.com/q/50332338
tags question: http://stackoverflow.com/q/50344216
tags question: http://stackoverflow.com/q/50251870
type: Tag
tags question: http://stackoverflow.com/q/50264078
tags question: http://stackoverflow.com/q/50317825
tags question: http://stackoverflow.com/q/50338108
tags question: http://stackoverflow.com/q/50310021
tags question: http://stackoverflow.com/q/50316901
tags question: http://stackoverflow.com/q/50326662
tags question: http://stackoverflow.com/q/50366439
tags question: http://stackoverflow.com/q/50256979
tags question: http://stackoverflow.com/q/50301750
tags question: http://stackoverflow.com/q/50239023
tags question: http://stackoverflow.com/q/50328617
tags question: http://stackoverflow.com/q/50266014
tags question: http://stackoverflow.com/q/50308403
tags question: http://stackoverflow.com/q/50280564
tags question: http://stackoverflow.com/q/50319091
tags question: http://stackoverflow.com/q/50384704
tags question: http://stackoverflow.com/q/50254397
tags question: http://stackoverflow.com/q/50320433
tags question: http://stackoverflow.com/q/50259807
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/50312172
tags question: http://stackoverflow.com/q/50236117
tags question: http://stackoverflow.com/q/50279436
tags question: http://stackoverflow.com/q/50313107
tags question: http://stackoverflow.com/q/50270232
tags question: http://stackoverflow.com/q/50310082
tags question: http://stackoverflow.com/q/50317384
tags question: http://stackoverflow.com/q/50288193
tags question: http://stackoverflow.com/q/50346414
tags question: http://stackoverflow.com/q/50313767
tags question: http://stackoverflow.com/q/50292718
tags question: http://stackoverflow.com/q/50361640
tags question: http://stackoverflow.com/q/50249574
tags question: http://stackoverflow.com/q/50356584
tags question: http://stackoverflow.com/q/50323540
tags question: http://stackoverflow.com/q/50343117
tags question: http://stackoverflow.com/q/50363291
tags question: http://stackoverflow.com/q/50291180
tags question: http://stackoverflow.com/q/50248527
tags question: http://stackoverflow.com/q/50302072
tags question: http://stackoverflow.com/q/50282121
tags question: http://stackoverflow.com/q/50303405
tags question: http://stackoverflow.com/q/50287133
tags question: http://stackoverflow.com/q/50318973
tags question: http://stackoverflow.com/q/50243711
tags question: http://stackoverflow.com/q/50323186
tags question: http://stackoverflow.com/q/50341704
tags question: http://stackoverflow.com/q/50354407
tags question: http://stackoverflow.com/q/50265145
tags question: http://stackoverflow.com/q/50280742
tags question: http://stackoverflow.com/q/50330126
tags question: http://stackoverflow.com/q/50241365
tags question: http://stackoverflow.com/q/50281247
tags question: http://stackoverflow.com/q/50308423
tags question: http://stackoverflow.com/q/50360698
tags question: http://stackoverflow.com/q/50321100
tags question: http://stackoverflow.com/q/50342923
tags question: http://stackoverflow.com/q/50372017
tags question: http://stackoverflow.com/q/50278762
tags question: http://stackoverflow.com/q/50339365
tags question: http://stackoverflow.com/q/50377524
tags question: http://stackoverflow.com/q/50294494
tags question: http://stackoverflow.com/q/50274517
tags question: http://stackoverflow.com/q/50306251
tags question: http://stackoverflow.com/q/50339004
tags question: http://stackoverflow.com/q/50335492
tags question: http://stackoverflow.com/q/50304607
tags question: http://stackoverflow.com/q/50299479
tags question: http://stackoverflow.com/q/50260744
tags question: http://stackoverflow.com/q/50243572
tags question: http://stackoverflow.com/q/50342085

http://stackoverflow.com/q/50279436
has comment: http://stackoverflow.com/comment/87576539
has comment: http://stackoverflow.com/comment/87577070
has title: Scraping stopping at first line
type: AnsweredQuestion
score: 0
tagged with: screen-scraping
answer count: 1
has comment: http://stackoverflow.com/comment/87575871
tagged with: web-scraping
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/87575466
has body: I need to scrap a website to obtain some information like Film's title and the relative links. My code run correctly but it stops at the first line of the website. This is my code, thank you in advance for your help and sorry if this is not a smart question but I'm a novice. import requests from bs4 import BeautifulSoup URL= 'http://www.simplyscripts.com/genre/horror-scripts.html' def scarica_pagina(URL): page = requests.get(URL) html = page.text soup = BeautifulSoup(html, 'lxml') l films = soup.find_all("div",{"id": "movie_wide"}) for film in films: link = film.find('p').find("a").attrs['href'] title = film.find('p').find("a").text.strip('&gt;') print (link) print(title)
has answer: http://stackoverflow.com/a/50280192
accepted answer: http://stackoverflow.com/a/50280192
has comment: http://stackoverflow.com/comment/87575929
tagged with: python
has comment: http://stackoverflow.com/comment/87575497

http://stackoverflow.com/q/50366851
answer count: 2
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50367066
tagged with: decorator
has answer: http://stackoverflow.com/a/50368355
has title: Postpone function execution syntactically
has answer: http://stackoverflow.com/a/50367066
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50368355
tagged with: python
tagged with: generator
score: 2
tagged with: numpy
type: AnsweredQuestion
has body: I've got a quite extensive simulation tool written in python, which requires the user to call functions to set up the environment in a strict order since np.ndarrays are at first created (and changed by appending etc.) and afterwards memory views to specific cells of these arrays are defined. Currently each part of the environment requires around 4 different function calls to be set up, with easily &gt;&gt; 100 parts. Thus I need to combine each part's function calls by syntactically (not based on timers) postponing the execution of some functions until all preceding functions have been executed, while still maintaining the strict order to be able to use memory views. Futhermore all functions to be called by the user use PEP 3102 style keyword-only arguments to reduce the probability of input-errors and all are instance methods with self as the first parameter, with self containing the references to the arrays to construct the memory views to. My current implementation is using lists to store the functions and the dict for each function's keyworded arguments. This is shown here, omitting the class and self parameters to make it short: def fun1(*, x, y): # easy minimal example function 1 print(x * y) def fun2(*, x, y, z): # easy minimal example function 2 print((x + y) / z) fun_list = [] # list to store the functions and kwargs fun_list.append([fun1, {'x': 3.4, 'y': 7.0}]) # add functions and kwargs fun_list.append([fun2, {'x':1., 'y':12.8, 'z': np.pi}]) fun_list.append([fun2, {'x':0.3, 'y':2.4, 'z': 1.}]) for fun in fun_list: fun[0](**fun[1]) What I'd like to implement is using a decorator to postpone the function execution by adding a generator, to be able to pass all arguments to the functions as they are called, but not execute them, as shown below: def postpone(myfun): # define generator decorator def inner_fun(*args, **kwargs): yield myfun(*args, **kwargs) return inner_fun fun_list_dec = [] # list to store the decorated functions fun_list_dec.append(postpone(fu…

http://stackoverflow.com/comment/87785494
comment on: http://stackoverflow.com/q/50384614
score: 0
has text: Just a clarification: I would like to take the first line in File1, and iterate thru each of the lines in File2 to see if Timestamp falls within the first Range1. Then take the second line in File1, and iterate again thru each line in File2, then take third line in File1, and iterate again thru each line in File2 etc...
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50339020
tagged with: python
type: AnsweredQuestion
has body: I want to use dynamic url in Django to match my dynamic href in template, which is assembled from addresses, such as below: ../details/0-TIFFANY-CRES ../details/1-Airport-PKY I am a layman of regular expression, the current url I want to match is : &lt;pre&gt; path('details/(?P&lt;addline&gt;[-\w]+)/$', details), &lt;/pre&gt; it didn't work(of course). In addition, I want to use the address in the urls in my views, how can I convert this address to my new views function? How can I match the urls? If there is any unclear parts, please tell me and I will try to explain more.
answer count: 1
upvote count: 1
score: 1
has title: How to use regular expression to match a string include transverse line?
has answer: http://stackoverflow.com/a/50339050
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87694365
downvote count: 0
accepted answer: http://stackoverflow.com/a/50339050
tagged with: django

http://stackoverflow.com/q/50304010
has comment: http://stackoverflow.com/comment/87624549
has body: How do I count the number of times the same integer occurs? My code so far: def searchAlgorithm (target, array): i = 0 #iterating through elements of target list q = 0 #iterating through lists sublists via indexes while q &lt; 4: x = 0 #counting number of matches for i in target: if i in array[q]: x += 1 else: x == 0 print(x) q += 1 a = [8, 12, 14, 26, 27, 28] b = [[4, 12, 17, 26, 30, 45], [8, 12, 19, 24, 33, 47], [3, 10, 14, 31, 39, 41], [4, 12, 14, 26, 30, 45]] searchAlgorithm(a, b) The output of this is: 2 2 1 3 What I want to achieve is counting the number of times '1', '2' '3' matches occurs. I have tried: v = 0 if searchAlgorithm(a, b) == 2: v += 1 print(v) But that results in 0
has comment: http://stackoverflow.com/comment/87624577
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87624414
has comment: http://stackoverflow.com/comment/87624599
has answer: http://stackoverflow.com/a/50304061
tagged with: python
tagged with: counting
has title: Count total number of occurrences of given list of integers in another
has comment: http://stackoverflow.com/comment/87624454
has answer: http://stackoverflow.com/a/50311433
type: Question
score: 0
answer count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87624455
has answer: http://stackoverflow.com/a/50304137
has comment: http://stackoverflow.com/comment/87624648
has comment: http://stackoverflow.com/comment/87624629
has comment: http://stackoverflow.com/comment/87624658

http://stackoverflow.com/comment/87775972
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50379654
has text: You can do `get_id_fields(__qualname__)`
score: 1

http://stackoverflow.com/comment/87585387
score: 1
type: Comment
type: QuestionComment
has text: By default it looks to be configured to run tests on save. You can set it to manual and assign a key to initiate the testing. https://packagecontrol.io/packages/PyTest explains how. Let us know what you tried and what result you got.
comment on: http://stackoverflow.com/q/50284208

http://stackoverflow.com/q/50331918
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87685436
has comment: http://stackoverflow.com/comment/87680015
has answer: http://stackoverflow.com/a/50332098
has comment: http://stackoverflow.com/comment/87680841
downvote count: 0
favorite count: 0
type: Question
has title: How does numpy addition work?
has comment: http://stackoverflow.com/comment/87692660
upvote count: 8
has comment: http://stackoverflow.com/comment/87681121
has body: I have the following unexpected behaviour import numpy as np class Test: def __radd__(self, other): print(f'value: {other}') [1,2,3] + Test() # prints: value: [1,2,3] np.array([1,2,3]) + Test() # prints # value: 1 # value: 2 # value: 3 I would expect the second addition to behave in the same way as the first one, but it doesn't. The only logical explanation I can see is that the numpy + operator somehow iterates over the arguments first, and tries to add each one of them to Test(), and the second addition (int + Test) falls back to the Test.__radd__ So is there any other explanation that I'm missing? if not, how does a + b work in numpy is it equivalent to np.add(a, b)?
has answer: http://stackoverflow.com/a/50332118
has comment: http://stackoverflow.com/comment/87685324
tagged with: python
score: 8
tagged with: numpy
has answer: http://stackoverflow.com/a/50336029
answer count: 3

http://stackoverflow.com/comment/87493565
has text: Please provide a [mcve]. `len` is almost certainly greater than the size of the dictionary as the error says. Rename `len` to `length` or something and then try `print(length, len(dictionary))` (that's `len` as in the built in function).
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50238070

http://stackoverflow.com/q/50314243
has body: I want to perform numerically Fourier transform of Gaussian function using fft2. Under this transformation the function is preserved up to a constant. I create 2 grids: one for real space, the second for frequency (momentum, k, etc.). (Frequencies are shifted to zero). I evaluate functions and eventually plot the results. Here is my code import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft2, ifft2 from mpl_toolkits.mplot3d import Axes3D """CREATING REAL AND MOMENTUM SPACES GRIDS""" N_x, N_y = 2 ** 11, 2 ** 11 range_x, range_y = np.arange(N_x), np.arange(N_y) dx, dy = 0.005, 0.005 # real space grid vectors xv, yv = dx * (range_x - 0.5 * N_x), dy * (range_y - 0.5 * N_y) dk_x, dk_y = np.pi / np.max(xv), np.pi / np.max(yv) # momentum space grid vectors, shifted to center for zero frequency k_xv, k_yv = dk_x * np.append(range_x[:N_x//2], -range_x[N_x//2:0:-1]), \ dk_y * np.append(range_y[:N_y//2], -range_y[N_y//2:0:-1]) # create real and momentum spaces grids x, y = np.meshgrid(xv, yv, sparse=False, indexing='ij') kx, ky = np.meshgrid(k_xv, k_yv, sparse=False, indexing='ij') """FUNCTION""" f = np.exp(-0.5 * (x ** 2 + y ** 2)) F = fft2(f) f2 = ifft2(F) """PLOTTING""" fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_surface(x, y, np.abs(f), cmap='viridis') # for other plots I changed to # surf = ax.plot_surface(kx, ky, np.abs(F), cmap='viridis') # surf = ax.plot_surface(x, y, np.abs(f2), cmap='viridis') plt.show() So, the plots for gaussian, fourier(gaussian), inverse_fourier(fourier(gaussian)) are the following:Initial, Fourier, Inverse Fourier Using plt.imshow(), I additionally plot fourier of gaussian: plt.imshow(F) plt.colorbar() plt.show() The result is as follows: imshow That doesn't make sense. I expect see the same gaussian function as the initial up to some constant order of unity. I would be very glad if someone could clarify this for me.
accepted answer: http://stackoverflow.com/a/50316395
upvote count: 2
has comment: http://stackoverflow.com/comment/87645790
has answer: http://stackoverflow.com/a/50316395
linked to: http://stackoverflow.com/q/19975030
tagged with: python
has comment: http://stackoverflow.com/comment/87647677
type: AnsweredQuestion
has title: Fourier Transform in Python 2D
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87647446
tagged with: scipy
favorite count: 0
tagged with: fft
linked to: http://stackoverflow.com/q/70768384
type: Question
tagged with: numpy

http://stackoverflow.com/q/50312760
type: Question
tagged with: lag
has title: Pygame OpenGL 3D Cube Lag
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50314047
accepted answer: http://stackoverflow.com/a/50314047
favorite count: 0
type: AnsweredQuestion
has body: I am following a tutorial series that is rather old on pyOpenGL and I am doing exactly as he does. However I am experiencing lag - I have AMD FX-6300 with 8gb ram, GTX-1050ti and files are stored on a flashdrive. I have read some places that using glBegin and glEnd cause issues? What should I use instead and how would I do it in this code: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * import random """ - A Cube has 8 Nodes/Verticies - 12 Lines/connections - 6 Sides """ vertices = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) edges = ( #Contains vertexes/nodes (0, 1), (0, 3), (0, 4), (2, 1), (2, 3), (2, 7), (6, 3), (6, 4), (6, 7), (5, 1), (5, 4), (5, 7) ) surfaces = ( (0,1,2,3), (3,2,7,6), (6,7,5,4), (4,5,1,0), (1,5,7,2), (4,0,3,6), ) colors = ( (1,0,0), (0,1,0), (0,0,1), (0,0,0,), (1,1,1), (0,1,1), (1,0,0), (0,1,0), (0,0,1), (0,0,0,), (1,1,1), (0,1,1), ) def set_vertices(max_distance): #Create change between each cube x_value_change = random.randrange(-10, 10) y_value_change = random.randrange(-10, 10) z_value_change = random.randrange(-1 * max_distance, -20) new_vertices = [] for vert in vertices: new_vert = [] new_x = vert[0] + x_value_change new_y = vert[1] + y_value_change new_z = vert[2] + z_value_change new_vert.append(new_x) new_vert.append(new_y) new_vert.append(new_z) new_vertices.append(new_vert) #Appends (1, 1, 1) return new_vertices def Cube(veritces): glBegin(GL_QUADS) for surface in surfaces: x = 0 for vertex in surface: x += 1 glColor3fv((colors[x])) glVertex3fv(vertices[vertex]) glEnd() glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(vertices[vertex]) #Draws vertex's in position given according to vertices array glEnd() def main(): pygame.init() display = (1000, 800) pygame.display.set_mode(display, DOUBLEBUF|OPENGL) gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) #FOV, aspect ratio. clipping plane min, max glTranslatef(ra…
score: 1
tagged with: pygame
tagged with: pyopengl

http://stackoverflow.com/q/50281383
downvote count: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50281435
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87579437
has comment: http://stackoverflow.com/comment/87579355
has title: Need max length of a word output
score: 0
tagged with: max
has body: def report_stat(word_dict): max_word = max(word_dict, key = word_dict.get) print('Longest word is:', max_word) # getting sorted list of word dict by value and printing 5 most common print('Five most common words are:') counter = 1 for each_list in sorted(word_dict.items(), key=lambda x: x[1], reverse=True): # printing the 5 most commonly used words if counter &gt; 5: break print(each_list[0], each_list[1]) counter += 1 # opening the file out.xt in write mode #and writing word and their count sorted alphabetically with open('out.txt', 'w') as fp: for each_word in sorted(word_dict): print(each_word, word_dict[each_word], file=fp) The area I'm getting wrong is the Longest word is: the shown below. It is printing the most-used word, not the longest word. Enter the filename: pride.txt Longest word is: the Five most common words are: the 4322 to 4126 of 3596 and 3531 her 2181
tagged with: output
upvote count: 1
answer count: 1

cmd
tags question: http://stackoverflow.com/q/50260574
tags question: http://stackoverflow.com/q/50362043
type: Tag
tags question: http://stackoverflow.com/q/50317667
tags question: http://stackoverflow.com/q/50296601
tags question: http://stackoverflow.com/q/50328058
tags question: http://stackoverflow.com/q/50284010
tag name: cmd

http://stackoverflow.com/comment/87543432
has text: Dictionary items do not have a defined order. If you want to preserve order you need to use an OrderedDict.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50262652

http://stackoverflow.com/q/50320803
downvote count: 0
tagged with: loops
accepted answer: http://stackoverflow.com/a/50320828
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50320828
tagged with: if-statement
score: 5
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50320829
answer count: 4
has answer: http://stackoverflow.com/a/50320840
possible better answer: http://stackoverflow.com/a/50320838
type: AnsweredQuestion
has body: I'm relatively new to python, so I'm not even sure if I'm approaching this in the correct way. But I haven't found a good solution anywhere. In order to avoid very ugly and repetitive code, i want to loop the elif part of the if statement. This is the ugly code i want to fix: def codeToChar(code): chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm" if code == ord(chars[0]): ##### SUPER UGLY return chars[0] elif code == ord(chars[1]): return chars[1] elif code == ord(chars[2]): return chars[2] elif code == ord(chars[3]): return chars[3] elif code == ord(chars[4]): return chars[4] elif code == ord(chars[5]): return chars[5] ..... etc ..... else: return "wat" As you can see, the index is incrementing by one, so I thought looping would be very simple. However, when I tried the following, it didn't work because this must be formulated as an if, elif, elif, else statement, and not many if statements. My failed attempt: for x in xrange(0,len(chars)-1): if code == ord(chars[x]): return chars[x] else: return "wat" How would I go about looping this? Note: if it's of any relevance, I'm coding this using the curses module, building a keyboard interface for a project. Many thanks
tagged with: for-loop
has answer: http://stackoverflow.com/a/50320838
has title: Python: Loop through the elif section of an if statement

http://stackoverflow.com/comment/87727156
type: Comment
score: 0
has text: Hello Kevin, and welcome to the site. Your question will have more opinion-based answers than this site is meant for, but you might have some luck asking it here: https://softwareengineering.stackexchange.com/
type: QuestionComment
comment on: http://stackoverflow.com/q/50355330

http://stackoverflow.com/a/50279484
has comment: http://stackoverflow.com/comment/87579166
has comment: http://stackoverflow.com/comment/87582297
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50279083
score: 3
answers question: http://stackoverflow.com/q/50279083
type: Answer
has body: From the indexing perspective there is no difference: both None and '' are actual values that the property will then have (as opposed to the value not being set at all) and thus the entity will be indexed. See also: Does NDB still index with default=None or properties set to None? Setting a StringProperty to None (if even allowed) will require additional type checking when it is used, since it could contain both string and None type values. Setting its default value to '' will not need such checks as '' is a string - so the property will always contain string values.

http://stackoverflow.com/comment/87671491
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50327242
type: QuestionComment
has text: The problem is that the `with` could theoretically swallow the exception. `transaction.atomic` doesn't do that but pycharm doesn't know that.

http://stackoverflow.com/comment/87687771
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50335638
has text: Hi think I did not explain it well, I updated my post to explain it better.
type: Comment

http://stackoverflow.com/a/50280298
answers question: http://stackoverflow.com/q/50277215
type: AcceptedAnswer
type: Answer
upvote count: 1
downvote count: 1
score: 0
has body: I still don't understand why would want to convert images to decimal values. Nevertheless there is a naïve approach. As mentioned in the code provided by you, first obtain the imcode: import cv2 import base64 image = cv2.imread(path + 'date.jpg') (tmp,buffer) = cv2.imencode('.jpg', image) imcode = base64.b64encode(buffer) Then you can obtain the ASCII value of each character in imcode using: ascii_value = [ord(c) for c in imcode] Now ascii_value is a list of integers which you can convert to decimal values. I would suggest you to have a look at THIS LINK as well
accepted answer of: http://stackoverflow.com/q/50277215

http://stackoverflow.com/comment/87668333
type: Comment
score: 0
type: QuestionComment
has text: @jpp why did you reopen? I'm tempted to close again.
comment on: http://stackoverflow.com/q/50325658

http://stackoverflow.com/a/50302758
answers question: http://stackoverflow.com/q/50302732
type: Answer
score: 17
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87622423
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50302732
has body: .astype() is a method within numpy.ndarray, as well as the Pandas Series class, so can be used to convert vectors, matrices and columns within a DataFrame. However, int() is a pure-Python function that can only be applied to scalar values. For example, you can do int(3.14), but can't do (2.7).astype('int'), because Python native types don't have any such method. However, numpy.array([1.1, 2.2, 3.3]).astype('int') is valid. (Strictly, it is also possible to define an __int__() method within one's own classes, which would allow int() to be applied to non-native types. Thanks to @juanpa.arrivillaga for pointing this out.)
upvote count: 17

http://stackoverflow.com/q/50282638
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87583473
linked to: http://stackoverflow.com/q/42846309
has answer: http://stackoverflow.com/a/50282662
type: UnansweredQuestion
upvote count: 5
tagged with: python
tagged with: copy
has body: Is there any situation where I would want to use NumPy's np.copy() over Python's copy.copy() method? As far as I can tell, both create shallow copies, but NumPy is limited to arrays. Is there any performance or special handling by NumPy that's not accounted for by copy?
tagged with: numpy
answer count: 2
score: 5
has title: Python copy.copy() vs NumPy np.copy()
has comment: http://stackoverflow.com/comment/87581770
downvote count: 0
has comment: http://stackoverflow.com/comment/87583706
has answer: http://stackoverflow.com/a/65038270
has comment: http://stackoverflow.com/comment/87583526

http://stackoverflow.com/a/50469560
score: 0
answers question: http://stackoverflow.com/q/50293763
upvote count: 1
downvote count: 1
has body: it's just impossible for me to reproduce the list-error... import numpy as np a = np.ma.masked_array([[0,0,0], [1,2,3],[4,5,6]], mask=[[True,True, True], [True,True, False],[False,False,True]]) a.compressed() array([3, 4, 5])
type: Answer

http://stackoverflow.com/comment/87646765
has text: @Javonne: Think carefully about how and when your `while` condition gets evaluated. :) If it helps, work through a couple of iterations of your loop using pen and paper, and hopefully things will become clear.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50315426
type: AnswerComment

http://stackoverflow.com/a/57941428
has body: For novice users, you can go in the Applications folder and expand the Python 3.7 folder. Now first run (or double click) the Install Certificates.command and then Update Shell Profile.command
upvote count: 27
downvote count: 0
score: 27
type: Answer
answers question: http://stackoverflow.com/q/50236117

http://stackoverflow.com/a/50264370
answers question: http://stackoverflow.com/q/50263712
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/50263712
has body: Because you have 2 columns you may plot 2 scatter plots, each with its own label. import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({"name": ["Alice", "Alice", "Charles", "Charles", "Kumar", "Kumar"], "height": [124, 126, 169, 170, 175, 174], "weight": [100, 105, 123, 125, 139, 140]}) plt.scatter(df.name, df.height, label="height") plt.scatter(df.name, df.weight, label="weight") plt.legend() plt.show() Having more columns, you may of course loop over them for col in ["height", "weight"]: plt.scatter(df.name, df[col], label=col)
type: Answer

http://stackoverflow.com/a/50278459
downvote count: 0
has body: So you can just use format and specify that you want 20 decimal places but that will be pretty ugly. &gt;&gt;&gt; format(2.3e-06, ".20f") '0.00000230000000000000' But what you can do is use that string and then clean up all of the zeros on the right side using rstrip &gt;&gt;&gt; format(2.3e-06, ".20f").rstrip("0") '0.0000023' &gt;&gt;&gt; format(2.3e-16, ".20f").rstrip("0") '0.00000000000000023' Then the only thing left is to figure out if a number is less than 10^-20 and if it is then just print it using the normal exponential formatting that Python will do anyway. def format_for_up_to_n_decimal_places(num, n_decimal_places): if num &lt; 10**-n_decimal_places: return str(num) else: return format(num, ".{}f".format(n_decimal_places)).rstrip('0') Example: &gt;&gt;&gt; format_for_up_to_n_decimal_places(2.3e-6, 20) '0.0000023' &gt;&gt;&gt; format_for_up_to_n_decimal_places(2.3e-50, 20) '2.3e-50'
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50278183
score: 2
accepted answer of: http://stackoverflow.com/q/50278183
type: AcceptedAnswer

http://stackoverflow.com/comment/87605664
has text: pstatix, I did update it I have 3.6.5 installed
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50284847

http://stackoverflow.com/q/50331797
answer count: 1
has answer: http://stackoverflow.com/a/50333419
has body: I want to set user_id field using JWT token and store in database table when new reservation is created. there can be single or multiple reservation request. whenever user create reservation i want to store there user_id in our table. currently there is no foreign key associated with it. it is simply an integer field. I am able to fetch user_id from JWT.but its not updating in database I know this question had been asked previously i tried all the answer of previous post but its not working for me. i dont know why model.py class reservations(models.Model): pet_id=models.IntegerField() user_id=models.IntegerField(default=0) location=models.PositiveSmallIntegerField() arrival=models.DateTimeField() depature=models.DateTimeField() comments=models.TextField(max_length=200) view.py class requestReservation(CreateAPIView): serializer_class = requestReservationSerailizer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): serializer = requestReservationSerailizer(data=request.data,context={'user_id': request.user.id}, many=True) if not serializer.is_valid(raise_exception=False): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK) serializer.py class requestReservationSerailizer(ModelSerializer): user_id = SerializerMethodField('set_user_id') class Meta: model=reservations fields = [ 'pet_id', 'user_id', 'location', 'arrival', 'depature', 'comments', ] def set_user_id(self, obj): obj.user_id = self.context.get("user_id") return obj.user_id currently it is simply storing user_id as 0 which is default set in model.
type: Question
type: AnsweredQuestion
score: 0
has title: How to set user_id field using JWT in DRF
linked to: http://stackoverflow.com/q/10291997
tagged with: django
tagged with: python
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/50333419

http://stackoverflow.com/q/50376697
has comment: http://stackoverflow.com/comment/87773181
has answer: http://stackoverflow.com/a/50398950
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87774036
score: 6
has body: I'm attempting to get an RS485 adapter connected at the UART to communicate via modbus on a Raspberry Pi. My end goal is to have all this working with a Node application, but so far my dev has been with Python. My hardware connection looks like: [Modbus-Device] &lt;===> [RS485 chip &lt;==> Raspberry PI GPIO] pins. The RS485 has three wires (Transmit, Receive, Direction) they are connected as follows RaspiPi &lt;=> Adapter GPIO 14 (8) - Tx &lt;=> Data+ GPIO 15 (10)- Rx &lt;=>- Data- GPIO 18 (12) - Direction The RS485 isn't a typical 9-pin adapter. I have three wires running off a chip. A twisted pair that serves as differential set and a ground wire. I have been able to send serial communications between this adpater and a USB-RS485 adapter by manually flipping GPIO18 for send/recieve. (Code below)[1]. This code is purely for proving the adapter works I'm stuck at getting modbus to work on GPIO adapter. I've tried using minimalmodbus, which works well with the USB-RS485 adapter, but fails with the GPIO adapter. I suspect this is because the direction pin isn't being set. The ideal resolution would be to find an RS485 driver for GPIO on the pi, but short of that I see three options 1 - Make my own driver (Something I am completely unfamiliar with) 2 - Somehow get a modbus library to flip the GPIO pin in Kernel space 3 - Manually send modbus messages over serial and adjust the GPIO pin in user space. This seems the easiest but also the worst in terms of speed and reliability. My code attempt is below [2] Any advice on this topic would be very appreciated. If someone has done something similar before and could weigh in on my options that would be helpful. I've never worked on software at this level so I wouldn't find it surprising if there were some obvious answer I'm completely overlooking. [1] This code communicates with another RS485 adapter on the raspberry pi connected with USB. This was written to prove the GPIO adapter is working and that I can control direction …
tagged with: python
has comment: http://stackoverflow.com/comment/87805292
upvote count: 6
tagged with: rs485
has comment: http://stackoverflow.com/comment/87771582
has comment: http://stackoverflow.com/comment/87771252
answer count: 1
tagged with: gpio
downvote count: 0
has comment: http://stackoverflow.com/comment/87773081
favorite count: 0
type: Question
has title: Raspberry Pi RS485/Uart Modbus
has comment: http://stackoverflow.com/comment/87776276
has comment: http://stackoverflow.com/comment/87771926
tagged with: raspberry-pi
tagged with: modbus

http://stackoverflow.com/a/50379628
has body: With your example I can access quite easily to any range of tuples: #!/usr/bin/python num_list = [('A1', 4, 'FF', 977.98), ('A4', 14, 'CC', 249.12), ('A1', 14, 'EE', 386.42), ('A9', 19, 'BB', 919.21), ('A4', 14, 'CC', 109.80)] print [item for item in num_list if item[1] &lt; 19 ] Output: mortiz@alberta:~/Documents/projects/python$ python tuples.py [('A1', 4, 'FF', 977.98), ('A4', 14, 'CC', 249.12), ('A1', 14, 'EE', 386.42), ('A4', 14, 'CC', 109.8)] If you want a range then change it using range(): print [item for item in num_list if item[1] in range(5,19) ] Output: mortiz@alberta:~/Documents/projects/python$ python tuples.py [('A4', 14, 'CC', 249.12), ('A1', 14, 'EE', 386.42), ('A4', 14, 'CC', 109.8)] Finally, the highest value of the selected range: #!/usr/bin/python num_list = [('A1', 4, 'FF', 977.98), ('A4', 14, 'CC', 249.12), ('A1', 14, 'EE', 386.42), ('A9', 19, 'BB', 919.21), ('A4', 14, 'CC', 109.80)] result=[item for item in num_list if item[1] in range(5,19)] highest=[item[3] for item in result] print max(highest) Output (highest value) mortiz@alberta:~/Documents/projects/python$ python tuples.py 386.42 Is that what you want?
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50379319

http://stackoverflow.com/comment/87600513
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50292155
score: 0
has text: I think this package can be useful for you [xmljson](https://pypi.org/project/xmljson/)

http://stackoverflow.com/q/50379437
has body: I need to automate the process of shifting data around in a dataframe to justify all the valuable information (i.e. not NaN) to the topmost empty cell. The catch here is that I don't know off the cuff what my input looks like until the user inputs it. Thus, I may have NaN's embedded anywhere in the data above, below, or between data sets. What I have: a b c d e f g h i j k l m o 0 0 0 0 0 0 0 NaN NaN NaN NaN NaN NaN NaN 1 1 1 1 1 1 1 NaN NaN NaN NaN NaN NaN NaN 0 0 0 1 0 0 1 NaN NaN NaN NaN NaN NaN NaN 0 0 1 0 1 0 0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1 1 0 1 0 0 1 Desired Output: a b c d e f g h i j k l m o 0 0 0 0 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 NaN NaN NaN NaN NaN NaN NaN 0 0 0 1 0 0 1 NaN NaN NaN NaN NaN NaN NaN 0 0 1 0 1 0 0 NaN NaN NaN NaN NaN NaN NaN What I want to do is to efficiently (ie. not line by line) shift the values in row 4 columns h to o up to the top. I was able to hardcode this with the following lines of code: &gt; df= df.set_index(['a', 'b', 'c', 'd', 'e', 'f','g']).shift(-4).iloc[0:5].reset_index() &gt; df= df.reindex(np.arange(4)) The problem with hard coding is, as I said above, you don't know what the dataset looks like until the user inputs it. As well, the application for this would be data with over 100k rows of data. Any suggestions as to how I may automate the shifting process? Preferably using pandas.
tagged with: pandas
has comment: http://stackoverflow.com/comment/87807040
duplicate of: http://stackoverflow.com/q/47897166
has title: How to justify data to the top of a dataframe in pandas
type: Question
has comment: http://stackoverflow.com/comment/87775510
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87775762
tagged with: python
has comment: http://stackoverflow.com/comment/87775560
has comment: http://stackoverflow.com/comment/87775302
linked to: http://stackoverflow.com/q/47897166
score: 0
linked to: http://stackoverflow.com/q/33530601
has comment: http://stackoverflow.com/comment/87807042

http://stackoverflow.com/comment/87662419
type: QuestionComment
type: Comment
has text: The order may change from data frame 1 and 2. But each pin will have unique site and department.
score: 0
comment on: http://stackoverflow.com/q/50323360

http://stackoverflow.com/a/50316750
answers question: http://stackoverflow.com/q/50316656
has body: You can use list comprehension on df.columns like this: df.columns = [c.replace('.', '') for c in df.columns] For example: df = pd.DataFrame({'foo': [1], 'bar.z': [2]}) &gt;&gt;&gt; df.columns Index(['bar.z', 'foo'], dtype='object') df.columns = [c.replace('.', '') for c in df.columns] &gt;&gt;&gt; df barz foo 0 2 1
has comment: http://stackoverflow.com/comment/87649297
type: Answer
has comment: http://stackoverflow.com/comment/87649267
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50316656

collada
tags question: http://stackoverflow.com/q/50321153
type: Tag
tag name: collada

http://stackoverflow.com/comment/87497203
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50239725
has text: Ah thank you, I´m really new to python. My mistake.
score: 0

http://stackoverflow.com/a/50277258
answers question: http://stackoverflow.com/q/50276835
score: 0
has body: Just parse the whole date string and then just use what you need, e.g.: In []: from datetime import datetime, timedelta def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)): yield start_date + timedelta(n) start_date = datetime.strptime(max_data,"%Y-%m-%dT%H:%M:%S.%f%z") end_date = datetime.now(start_date.tzinfo) for single_date in daterange(start_date, end_date): print(single_date.strftime("%Y-%m-%d")) Out[]: 2018-05-04 2018-05-05 2018-05-06 2018-05-07 2018-05-08 2018-05-09 Note: you need to pass in the tzinfo to now() to get a tz aware datetime object (instead of using date.today()) Note: in Py3.7 the standard library has added, datetime.fromisoformat().
has comment: http://stackoverflow.com/comment/106231037
type: Answer

http://stackoverflow.com/q/50302639
has answer: http://stackoverflow.com/a/50309345
has answer: http://stackoverflow.com/a/50308172
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: sympy
tagged with: symbolic-math
downvote count: 0
has title: Factoring a SymPy expression into groups that involve one symbol only
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50309345
possible better answer: http://stackoverflow.com/a/50308172
has body: Suppose I have an expression in sympy that only consists of a single term. This expression either has subexpressions that depend on a symbol x, on a symbol y, or on neither x nor y. I would like sympy to return three expressions, the first depends only on x, the second only on y, and the third on neither, such that the product of the three expressions is the original expression. E.g. expr = x^2*cos(x)*2/sin(y)/y should return x^2 * cos(x) and 1/sin(y)/y and 2. Is this possible?

http://stackoverflow.com/comment/87952549
type: Comment
has text: @BearBrown, Oh okay.. As far as I understand he needs the symmetry to always happens. What do you think?
type: AnswerComment
comment on: http://stackoverflow.com/a/50468648
score: 1

http://stackoverflow.com/comment/87688948
has text: @ekhumoro yes, it get called. it usually returns (int, None, QMenu object)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50328202
type: Comment

http://stackoverflow.com/a/50260856
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50250264
has body: Yes, add the 3.4.x migration dependency if your plugin needs to work with 3.4.x. The newer migrations on 3.5 don't change any plugin schema.
type: Answer
accepted answer of: http://stackoverflow.com/q/50250264

http://stackoverflow.com/comment/87570090
score: 0
has text: because 7 = 4+2+1 and 5 = 3+2 -- sums of all the elements in this row.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50276334

http://stackoverflow.com/comment/87577974
has text: Efficient than what I had. `s=df.T.apply(lambda x: x.nunique(), axis=1)` then, `list(s[s!=1].index)`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50280704
type: Comment

http://stackoverflow.com/q/50377124
type: AnsweredQuestion
tagged with: python
tagged with: pygame
favorite count: 0
linked to: http://stackoverflow.com/q/48450396
has body: My code runs with no errors, but the background image does not display and neither does the caption at the top of the window. I have checked that my script is importing the correct pygame module, and tried different images. I have Python 3.6.2 on a Mac. import pygame pygame.init() gameDisplay = pygame.display.set_mode((400, 433)) pygame.display.set_caption('Pac Man') clock = pygame.time.Clock() background = pygame.image.load('/Users/MyMacbook/Desktop/pac-man/background.png') gameDisplay.blit(background, (100, 0)) run = True while run: gameDisplay.blit(background, (0, 0)) pygame.display.update() pygame.quit() quit()
type: Question
accepted answer: http://stackoverflow.com/a/50378669
downvote count: 0
has answer: http://stackoverflow.com/a/50378669
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87773928
answer count: 1
has title: Python- Pygame won't display images or captions
has comment: http://stackoverflow.com/comment/87772186

http://stackoverflow.com/q/50312352
tagged with: argparse
score: 1
linked to: http://stackoverflow.com/q/28477917
has comment: http://stackoverflow.com/comment/87641139
tagged with: command-line-arguments
linked to: http://stackoverflow.com/q/10448200
has comment: http://stackoverflow.com/comment/87642672
has comment: http://stackoverflow.com/comment/87642566
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87641407
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87640945
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/39644246
has comment: http://stackoverflow.com/comment/87641291
linked to: http://stackoverflow.com/q/48013977
downvote count: 0
has body: I am trying to do this: $ myfile.py config --user 'abc1' --password 'def1' --configname 'first' config config --user 'abc2' --password 'def2' --configname 'second' config is a subcommand (as described in argparse.ArgumentParser documentation adding subcommands in argparse). This should allow me to collect individual confignames, username and password for any number of configs (in this case 2) from commandline. These I will persist as $ cat first [user] abc1 [password] def1 $ cat second [user] abc2 [password] def2 When I tried this I got error: unrecognized arguments: How can I achieve similar functionality. Here is my code: &gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG') &gt;&gt;&gt; subparsers = parser.add_subparsers(help='sub-command help') &gt;&gt;&gt; # create the parser for the "a" command ... parser_a = subparsers.add_parser('config', help='a help') &gt;&gt;&gt; parser_a.add_argument('--user', required=True) _StoreAction(option_strings=['--user'], dest='user', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) &gt;&gt;&gt; parser_a.add_argument('--password', required=True) _StoreAction(option_strings=['--password'], dest='password', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) &gt;&gt;&gt; parser_a.add_argument('--configname', required=True) _StoreAction(option_strings=['--configname'], dest='configname', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) &gt;&gt;&gt; parser.parse_args(['config', '--user', 'abc1', '--password', 'def1', '--configname', 'first']) Namespace(configname='first', password='def1', user='abc1') &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG') &gt;&gt;&gt; subparsers = parser.add_subparsers(help='sub-command help') &gt;&gt;&gt; # create the parser for the "a" command ... parser_a = subparsers.add_parser('…
upvote count: 1
tagged with: python
has title: Specify same option multiple times to collect several sub values (python argparse subcommands)
duplicate of: http://stackoverflow.com/q/10448200

http://stackoverflow.com/q/50282082
has comment: http://stackoverflow.com/comment/87581128
has comment: http://stackoverflow.com/comment/87582223
has body: hey guys so i have this txt files which is like the following: parent text \n -reply to first text\n --reply to second text now what i want is that something like the following: parent text\n - reply to parent text\n -reply to parent text \n -- reply to second text\n i know i can do this in python: group = re.findall(r"--",data) which will get all the -- without the text following it but since i have multiple "-" in each text this make me confuse on how to process the data any kind of insight ? edit1: This is my data Why can\'t I find a girlfriend?\n-/u/remainenthroned \n-try tinder\n--r/incels\n--Maybe you should find a TreeHugger.\n---Got friendzoned there once, so nah\n----Trees are not so good with motion, you know.\n-----try grindr\n which after .split \n is like : "Why can't I find a girlfriend?", '-/u/remainenthroned ', '-try tinder', '--r/incels', '--Maybe you should find a TreeHugger.', '---Got friendzoned there once, so nah', '----Trees are not so good with motion, you know.', '-----try grindr', what i would want is : "Why can't I find a girlfriend?" -/u/remainenthroned, "Why can't I find a girlfriend?" -try tinder' -/u/remainenthroned --r/incels',', so on and so forth
upvote count: 0
has comment: http://stackoverflow.com/comment/87607543
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/50282324
has title: Python string, using finding specific word then copy the word and pasting it
answer count: 1
tagged with: information-retrieval
score: -1
has comment: http://stackoverflow.com/comment/87581375
tagged with: nlp
has comment: http://stackoverflow.com/comment/87607535
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87580754

http://stackoverflow.com/q/50254667
has title: How to indent multiple JSON files via terminal
has answer: http://stackoverflow.com/a/50254725
tagged with: python
has body: Is there a quick way to indent a given set of JSON files under a current directory via terminal, similarly to using "Pretty JSON" or "Indent JSON" plugins on Sublime text? Either by a shell script or python script, etc. ?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50254725
score: 0
tagged with: bash
tagged with: indentation
tagged with: http://stackoverflow.com/tag/json
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87717522
type: AnswerComment
has text: Thank you, that's exactly what i needed.
type: Comment
comment on: http://stackoverflow.com/a/50253319
score: 0

http://stackoverflow.com/q/50269598
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50271335
has body: from tkinter import * class fidgetSpinner: def spin(): status_str = float(click_entry.get()) window = Tk() # Create a window window.title("11.2 GUI") mainframe = Frame(window) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) click_entry = Entry(mainframe, width=20) click_entry.grid(column=2, row=1, sticky=(W, E)) click = click_entry.get() status_str = StringVar() Label(mainframe, textvariable=status_str).grid(column=2, row=2, sticky=(W, E)) Button(mainframe, text="Fidget Click!", command=spin).grid(column=2, row=3, sticky=W) Label(mainframe, text="Enter Click Count:").grid(column=1, row=1, sticky=W) Label(mainframe, text="status:").grid(column=1, row=2, sticky=E) Label(mainframe, text=click).grid(column=2, row=2, sticky=E) window.mainloop() # Create an event loop myWidgets = fidgetSpinner() # Create GUI myWidgets = fidgetSpinner() # Create GUI When I run this program and enter some text and when I input some number into click_entry = Entry(mainframe, width=20) and click Fidget Click! it just says Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1699, in __call__ return self.func(*args) File "/Users/kalib/OneDrive - University of Tasmania/Programming introduction KIT001/11.2dn GUI/11.2dn GUI.py", line 7, in spin status_str = float(click_entry.get()) NameError: name 'click_entry' is not defined Also I didn't want to make a program about a fidget spinner that's just what we were meant to call the program.
has comment: http://stackoverflow.com/comment/87557098
has comment: http://stackoverflow.com/comment/87558960
type: Question
has answer: http://stackoverflow.com/a/50269832
score: 0
has answer: http://stackoverflow.com/a/50270044
tagged with: python
tagged with: python-3.x
tagged with: tkinter
has title: NameError: name 'click_entry' is not defined (Python)
answer count: 3
has comment: http://stackoverflow.com/comment/87559852

http://stackoverflow.com/comment/87590799
score: 0
type: AnswerComment
has text: You're right. The code now works. However, it doesn't do anything (as in, there is no csv file as an output). Should I replace the "json_file_path", "json_file", "csv_file_path" and "csv_file" with paths and names of the file? I know it's a very basic question, but I'm not familiar with it. Thank you so much for your help!!!
type: Comment
comment on: http://stackoverflow.com/a/50273508

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/50335597
type: Tag
tags question: http://stackoverflow.com/q/50327186
tags question: http://stackoverflow.com/q/50281708
tags question: http://stackoverflow.com/q/50302743

http://stackoverflow.com/a/50377917
has comment: http://stackoverflow.com/comment/87807803
has comment: http://stackoverflow.com/comment/87809831
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87809851
has comment: http://stackoverflow.com/comment/87809790
has comment: http://stackoverflow.com/comment/87809868
accepted answer of: http://stackoverflow.com/q/50377269
has comment: http://stackoverflow.com/comment/87772024
has comment: http://stackoverflow.com/comment/87772946
has body: Use meta field to put item forward to next callback def parse_page1(self, response): item = MyItem(main_url=response.url) request = scrapy.Request("http://www.example.com/some_page.html", callback=self.parse_page2) request.meta['item'] = item return request def parse_page2(self, response): item = response.meta['item'] item['other_url'] = response.url return item UPD: to process all rows use a yield in your loop for row in response.xpath('//table[@class="member-table"]//tr[position() &gt; 1]'): item = FinalItem() website = row.xpath('./td[2]//a/@href/text()').extract_first() item['name'] = row.xpath('./td[2]//a/text()').extract_first() request = scrapy.Request(website, callback=self.parse_page2) request.meta['item'] = item yield request
type: Answer
answers question: http://stackoverflow.com/q/50377269
score: 0
has comment: http://stackoverflow.com/comment/87783756

http://stackoverflow.com/comment/87583007
comment on: http://stackoverflow.com/q/50283057
type: QuestionComment
type: Comment
score: 0
has text: `_maxpool_list.append(MaxPooling2D()(_activ))`?

http://stackoverflow.com/a/50384685
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87785477
has body: If you mean the second rank is the second index then, my_list = [[0, 0], [1, 3], [2, 5], [3, 4]] for index in range(len(my_list)): if my_list[index][1] == 2: print("True") else: print("False")
has comment: http://stackoverflow.com/comment/87785058
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50384598

aiohttp
tags question: http://stackoverflow.com/q/50318875
type: Tag
tags question: http://stackoverflow.com/q/50243393
tag name: aiohttp
tags question: http://stackoverflow.com/q/50243031
tags question: http://stackoverflow.com/q/50238258
tags question: http://stackoverflow.com/q/50355944

http://stackoverflow.com/comment/87694147
score: 0
has text: OK. Any reason you _need_ to use 32-bit Python? What platform are you on?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50338311

http://stackoverflow.com/a/50378157
accepted answer of: http://stackoverflow.com/q/50322377
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87810254
answers question: http://stackoverflow.com/q/50322377
has body: It's hard to pinpoint exactly what the problem is without knowing what your cas variable is, in __init__.py. However I suspect the error you have might be because cas is a class, rather than an instance of that class. To show you what I mean: &gt;&gt;&gt; class MyCAS: ... @property ... def name(self): ... return 'Monjur' ... &gt;&gt;&gt; MyCAS.name &lt;property object at 0x109cf1cc8&gt; &gt;&gt;&gt; MyCAS().name 'Monjur' In the first case, I have not instantiated the class (no parenthesis), so the return value is the property object. In the second case (with parenthesis), I see the actual name of the instance. If your cas object is indeed supposed to be an object instantiated from a class (e.g. flask.ext.cas.CAS), make sure you create it like this: from flask.ext.cas import CAS cas = CAS() # With parenthesis :) and not like this: from flask.ext.cas import CAS cas = CAS # No parenthesis :(
has comment: http://stackoverflow.com/comment/87779938
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/87595170
has text: It seems that the optimizer got stuck in a local minimum due to bad initial solution. You did not provide a *p0* argument to *curve_fit*, so your trapezoid parameters are all initialized to 1. You might want to find a way to properly initialize your parameters, otherwise you better use a global optimizer such as SciPy's *differential_evolution*.
comment on: http://stackoverflow.com/q/50289220
type: Comment
type: QuestionComment
score: 0

sql
tags question: http://stackoverflow.com/q/50362013
tags question: http://stackoverflow.com/q/50317889
tags question: http://stackoverflow.com/q/50358481
tags question: http://stackoverflow.com/q/50285392
tags question: http://stackoverflow.com/q/50338341
tags question: http://stackoverflow.com/q/50254976
tags question: http://stackoverflow.com/q/50253723
tags question: http://stackoverflow.com/q/50279896
tags question: http://stackoverflow.com/q/50283980
tags question: http://stackoverflow.com/q/50237082
tags question: http://stackoverflow.com/q/50258168
tags question: http://stackoverflow.com/q/50275767
tags question: http://stackoverflow.com/q/50270511
tags question: http://stackoverflow.com/q/50357142
tags question: http://stackoverflow.com/q/50352178
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/50244721
tags question: http://stackoverflow.com/q/50245422
tags question: http://stackoverflow.com/q/50378390
tags question: http://stackoverflow.com/q/50381839

http://stackoverflow.com/comment/87552530
score: 0
type: AnswerComment
type: Comment
has text: This is of great help, thank you. Especially insightful is your comment on how to reduce to `O(n+m)` operations, I wasn't aware of this kind of consideration. As someone suggested in the comments, I've transfered this question to code review. I wonder how we can transfer your answer there (and I guess delete this post in order not to have two posts on the same subject) - https://codereview.stackexchange.com/q/194023/105140
comment on: http://stackoverflow.com/a/50260501

http://stackoverflow.com/comment/87683459
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50333573
has text: This code doesn't run. Please provide a [mcve] that actually runs. This uses a variable named `labelText` but never defines a variable with that name.

tensorflow
tags question: http://stackoverflow.com/q/50262913
tags question: http://stackoverflow.com/q/50325336
tags question: http://stackoverflow.com/q/50319749
tags question: http://stackoverflow.com/q/50375207
tags question: http://stackoverflow.com/q/50316789
tags question: http://stackoverflow.com/q/50238512
type: Tag
tags question: http://stackoverflow.com/q/50338301
tags question: http://stackoverflow.com/q/50267959
tags question: http://stackoverflow.com/q/50317335
tags question: http://stackoverflow.com/q/50308173
tags question: http://stackoverflow.com/q/50280440
tags question: http://stackoverflow.com/q/50377737
tags question: http://stackoverflow.com/q/50295839
tags question: http://stackoverflow.com/q/50272802
tags question: http://stackoverflow.com/q/50313441
tags question: http://stackoverflow.com/q/50306536
tags question: http://stackoverflow.com/q/50276275
tags question: http://stackoverflow.com/q/50358448
tags question: http://stackoverflow.com/q/50285097
tags question: http://stackoverflow.com/q/50319500
tags question: http://stackoverflow.com/q/50307985
tags question: http://stackoverflow.com/q/50341408
tags question: http://stackoverflow.com/q/50280624
tags question: http://stackoverflow.com/q/50288416
tags question: http://stackoverflow.com/q/50355365
tags question: http://stackoverflow.com/q/50359055
tags question: http://stackoverflow.com/q/50230544
tags question: http://stackoverflow.com/q/50271548
tags question: http://stackoverflow.com/q/50246723
tags question: http://stackoverflow.com/q/50318876
tags question: http://stackoverflow.com/q/50310496
tags question: http://stackoverflow.com/q/50379359
tags question: http://stackoverflow.com/q/50372220
tags question: http://stackoverflow.com/q/50369003
tags question: http://stackoverflow.com/q/50260653
tags question: http://stackoverflow.com/q/50242361
tags question: http://stackoverflow.com/q/50275833
tags question: http://stackoverflow.com/q/50298058
tags question: http://stackoverflow.com/q/50285883
tags question: http://stackoverflow.com/q/50381004
tags question: http://stackoverflow.com/q/50283207
tags question: http://stackoverflow.com/q/50297594
tags question: http://stackoverflow.com/q/50339622
tags question: http://stackoverflow.com/q/50283741
tags question: http://stackoverflow.com/q/50323756
tags question: http://stackoverflow.com/q/50243334
tags question: http://stackoverflow.com/q/50315140
tags question: http://stackoverflow.com/q/50317769
tags question: http://stackoverflow.com/q/50296384
tags question: http://stackoverflow.com/q/50255044
tags question: http://stackoverflow.com/q/50262703
tags question: http://stackoverflow.com/q/50359526
tags question: http://stackoverflow.com/q/50303372
tags question: http://stackoverflow.com/q/50304156
tags question: http://stackoverflow.com/q/50329855
tags question: http://stackoverflow.com/q/50312519
tags question: http://stackoverflow.com/q/50306863
tags question: http://stackoverflow.com/q/50249205
tags question: http://stackoverflow.com/q/50362045
tags question: http://stackoverflow.com/q/50312896
tags question: http://stackoverflow.com/q/50287399
tags question: http://stackoverflow.com/q/50252720
tags question: http://stackoverflow.com/q/50383844
tags question: http://stackoverflow.com/q/50291549
tags question: http://stackoverflow.com/q/50315932
tags question: http://stackoverflow.com/q/50237887
tags question: http://stackoverflow.com/q/50256841
tags question: http://stackoverflow.com/q/50250004
tags question: http://stackoverflow.com/q/50328921
tags question: http://stackoverflow.com/q/50284898
tags question: http://stackoverflow.com/q/50277373
tags question: http://stackoverflow.com/q/50266975
tags question: http://stackoverflow.com/q/50299831
tags question: http://stackoverflow.com/q/50240354
tags question: http://stackoverflow.com/q/50382613
tags question: http://stackoverflow.com/q/50361246
tags question: http://stackoverflow.com/q/50369758
tags question: http://stackoverflow.com/q/50267291
tags question: http://stackoverflow.com/q/50383746

http://stackoverflow.com/q/50302049
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87620594
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50302157
has answer: http://stackoverflow.com/a/50302157
has title: Trying to return search results from a txt file to GUI
tagged with: python
has comment: http://stackoverflow.com/comment/87620706
type: AnsweredQuestion
has body: So I am trying to write some code that needs to search through a .txt file and return the results to a basic GUI I have created. Here is my code so far. When I click the "search" button in the GUI, nothing happens. My code so far: import re from tkinter import * def query(): search = lookfor.get() datafile = open("data.txt", "r") for line in datafile.readlines(): if re.query(search, line, re.I): findings.insert(INSERT) datafile.close() root = Tk() lookfor = Entry(root) lookfor.pack() Button(root, text = "Search", command = query).pack() findings = Text(root) findings.pack() root.mainloop() I've also tried a different way of searching the txt file: import re from tkinter import * def query(): datafile = open("data.txt", "r") for line in datafile: line = line.strip() elements = line.split("\t") if str(lookfor.get()) in elements[0]: findings.insert(INSERT, elements[1]) elif str(lookfor.get()) in elements[1]: findings.insert(INSERT, elements[0]) findings.insert(END, '\n') datafile.close() root = Tk() lookfor = Entry(root) lookfor.pack() Button(root, text = "Search", command = query).pack() findings = Text(root) findings .pack() root.mainloop()

http://stackoverflow.com/comment/87777571
type: Comment
has text: @DirkHorsten not exactly
score: 0
comment on: http://stackoverflow.com/q/50371683
type: QuestionComment

http://stackoverflow.com/a/50291119
score: 0
answers question: http://stackoverflow.com/q/50290762
has body: This error has appeared before and has been identified as an incompatibility between Pandas and PyLDAvis in some versions. Here they claim a specific version should fix it. Duplicate of #76 its fixed in version 2.1.0. Install that specific version pip install pyldavis==2.1.0 I didn't check it though.
type: Answer
has comment: http://stackoverflow.com/comment/87598764
has comment: http://stackoverflow.com/comment/87602002

http://stackoverflow.com/q/50246479
favorite count: 0
has title: Mergesort code hangs
has answer: http://stackoverflow.com/a/50246675
has comment: http://stackoverflow.com/comment/87510629
has answer: http://stackoverflow.com/a/50248022
answer count: 2
downvote count: 0
tagged with: mergesort
upvote count: 1
tagged with: python
type: UnansweredQuestion
type: Question
has body: I'm trying to implement mergesort. I have a working merge subfunction that works on sorted lists, and just need to manage the merging of all the lists properly. def mergesort(alist): alist = [[i] for i in alist] def merge(clist, dlist): #assume inputs are sorted merged = [] while True: if len(clist) == 0: return merged + dlist elif len(dlist) == 0: return merged + clist elif clist[0] &lt; dlist[0]: merged.append(clist[0]) del clist[0] elif clist[0] &gt; dlist[0]: merged.append(dlist[0]) del dlist[0] return merged while True: if len(alist) % 2 == 0 and len(alist) &gt; 2: alist = [merge(alist[2*i], alist[2 * i + 1]) for i in range(int(len(alist)/2))] elif len(alist) == 2: print('ayyy') alist = merge(alist[0], alist[-1]) return alist elif len(alist) % 2 == 1 and len(alist) &gt; 1: tag = alist[-1] del alist[-1] alist = [merge(alist[2 * i], alist[2 * i + 1]) for i in range(int(len(alist)/2))] alist.append(tag) else: return alist print(mergesort([10, 5, 8, 16, 258, 11, 1, 20, 489, 10, 5, 3, 12])) The function works fine until it's down to the last two lists. It prints 'ayyy', which means it made it into the first elif statement, then does nothing else. The program doesn't terminate, it just spins its wheels. Debugger shows that the value of alist isn't updated either.
score: 1

http://stackoverflow.com/comment/87602852
has text: But the cloud still has the words: https://drive.google.com/file/d/1O3YfVsgLMaWetkqAhtPvC8Ob5CffSOKg/view?usp=sharing
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50292745
type: Comment

http://stackoverflow.com/comment/87686363
has text: Did I get the error because it is getting to the end of the column, realising it is blank and failing? FYI - It created my folders then popped up the error.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50334939
type: Comment

http://stackoverflow.com/q/50361705
type: Question
tagged with: python
tagged with: optgroup
accepted answer: http://stackoverflow.com/a/50362202
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50362202
has body: I want to create a dropdown menu using tkinter from a dictionary of arrays, where I want the keys to represent higher-level groups for the menu choices, and strings inside the value arrays to represent the actual choices available to the user. In other words, when the dropdown is clicked, the dropdown should resemble one created in HTML using the optgroup tag, where there are both unselectable labels functioning as group titles and selectable labels functioning as the actual choices. My dictionary looks something like this: ingredients = { "Herbs": ["basil", "oregano", "thyme"], "Meats": ["chicken", "beef", "venison",], "Spices": ["pepper", "salt", "chilli powder", "cumin"] } The user should be able to choose 'basil', 'beef', 'salt' etc. from the dropdown but not 'Herbs', 'Meats', or 'Spices', which should only be present as static titles for the different groups of ingredients. Is this possible using just tkinter/ttk?
tagged with: tkinter
answer count: 1
has title: Possible to create a dropdown menu in tkinter/ttk with HTML optgroup-style grouping of options?

http://stackoverflow.com/q/50292080
downvote count: 3
tagged with: dataframe
has title: Eliminating "days" keyword when I subtract two dates in python
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/18215317
score: -2
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50292172
duplicate of: http://stackoverflow.com/q/18215317
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50292172
tagged with: datetime
answer count: 1
has body: I have two dates column, and i need a thirdcolumn which gives the days(integer like 2,3) between first two columns. I just implemented Date2-Date1 which gave me this output. Date1 | Date2 | Days 2017-10-24 | 2017-10-25 | 1 days 2017-11-24 | 2017-11-29 | 4 days Days column is of timedelta64[ns] type . How to get rid of days keyword in Days column so that i get just an integer in Days column.

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

http://stackoverflow.com/comment/87614854
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50299060
has text: Probably you may just use [`re.findall(r'\w+\([^()]*\)', line)`](http://rextester.com/XVJ59414)
type: Comment

http://stackoverflow.com/comment/87509872
comment on: http://stackoverflow.com/a/50246057
score: 0
type: Comment
has text: Yes! Thank you. I didnt know that the difference between index tuple and index array mattered. Can you please point me to some explanation as to how those two differ? Thanks!
type: AnswerComment

http://stackoverflow.com/a/50243796
type: AcceptedAnswer
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/50243740
downvote count: 0
has body: You can sort the lists in place using the list.sort method d = {'AAA': {'A1': [(0, ('a', 'b')), (3, ('c', 'd')), (2, ('a', 'b'))], 'B1': [(3, ('a', 'b')), (2, ('a', 'b')), (1, ('c', 'd'))]}, 'BBB': {'A1': [(4, ('a', 'b')), (2, ('c', 'd')), (1, ('a', 'b'))], 'B1': [(3, ('c', 'd')), (2, ('a', 'b')), (1, ('a', 'b'))]}} for subd in d.values(): for l in subd.values(): l.sort() from pprint import pprint pprint(d) {'AAA': {'A1': [(0, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))], 'B1': [(1, ('c', 'd')), (2, ('a', 'b')), (3, ('a', 'b'))]}, 'BBB': {'A1': [(1, ('a', 'b')), (2, ('c', 'd')), (4, ('a', 'b'))], 'B1': [(1, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))]}}
answers question: http://stackoverflow.com/q/50243740

http://stackoverflow.com/q/50370467
has comment: http://stackoverflow.com/comment/87756827
possible better answer: http://stackoverflow.com/a/50370756
accepted answer: http://stackoverflow.com/a/50370606
favorite count: 0
has answer: http://stackoverflow.com/a/50370756
has title: Deleting dataFrame row in Pandas if a combination of column values equals a tuple in a list
has answer: http://stackoverflow.com/a/50370606
type: Question
tagged with: pandas
score: 3
tagged with: python
answer count: 5
has answer: http://stackoverflow.com/a/50371938
has answer: http://stackoverflow.com/a/50371226
has answer: http://stackoverflow.com/a/50370924
type: AnsweredQuestion
upvote count: 3
has body: I currently do this to delete a row that has a specific column 'some_column' value that is found in a list removal_list df = df[~df['some_column'].isin(removal_list)] How can I do this if I want to compare a combination of values in say a list of tuples ? (doesn't necessarily need to be a list of tuples if there is a better way to achieve this) for example: removal_list = [(item1,store1),(item2,store1),(item2,store2)] if df['column_1'] and df['column_2'] of a specific row have values item1 and store1 (or any other tuple in removal_list), then delete that row also, it might be that there are more than two columns that need to be assessed EDIT better example: client account_type description 0 1 2 photographer 1 2 2 banker 2 3 3 banker 3 4 2 journalist 4 5 4 journalist remove_list = [(2,journalist),(3,banker)] check on columns account_type and description Output: client account_type description 0 1 2 photographer 1 2 2 banker 4 5 4 journalist
downvote count: 0

optgroup
tag name: optgroup
tags question: http://stackoverflow.com/q/50361705
type: Tag

http://stackoverflow.com/q/50264065
tagged with: machine-learning
tagged with: python
tagged with: keras
has title: Correct Keras/TensorFlow Activation Functions for simple numeric input/output
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50265163
has answer: http://stackoverflow.com/a/50265163
has comment: http://stackoverflow.com/comment/87546347
answer count: 1
tagged with: tensorflow
type: Question
has body: I have a input layer of 98 float values -5.0 &lt; x &lt; 5.0 and a single node float output with a value of -5.0 &lt; x &lt; 5.0 The dataset is very large at 10GB and can easily be expanded to a much larger size. The part I am having most trouble with is the activation functions. With input and output values of -5.0 &lt; x &lt; 5.0 what would be the best activation functions to use. Also if you have an idea of what type of neural net (LSTM, CNN), dropout, # of hidden layers, batch_size and optimizer are best to use for such a dataset, that would also be appreciated. Despite the amount of examples and information out there, I am having quite a bit of trouble trying to get all these parameters correct for my dataset.
has comment: http://stackoverflow.com/comment/87546368
has comment: http://stackoverflow.com/comment/87546155

http://stackoverflow.com/q/50271354
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50271718
has body: Consider the following python snippet (I am running Python 3) name = "Sammy" def greet(): name = 'johny' def hello(): print('hello ' + name) # gets 'name' from the enclosing 'greet' hello() greet() This produces the output hello johny as expected However, x = 50 def func1(): x = 20 def func2(): print("x is ", x) # Generates error here x = 2 print("Changed the local x to ",x) func2() func1() print("x is still ",x) generates an UnboundLocalError: local variable 'x' referenced before assignment. Why does the first snippet work, whereas the second doesn't?
accepted answer: http://stackoverflow.com/a/50271529
has answer: http://stackoverflow.com/a/50271718
has answer: http://stackoverflow.com/a/50271529
upvote count: 5
score: 5
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
has title: Scoping rules in python

http://stackoverflow.com/q/50308214
has answer: http://stackoverflow.com/a/50308545
tagged with: pickle
downvote count: 1
has body: Is there a short enough way to call the __init__ constructor of a class during unpickling in Python 3? The usual way to do this was using __getinitargs__ like so from __future__ import print_function import pickle class Car: def __init__(self, model, number): self.model = model self.number = number print("constructed with", model, number) # many other things to do def __getstate__(self): # intentionally returns None pass def __setstate__(self, state): pass def __getinitargs__(self): # save some information when pickling # (will be passed to the constructor upon unpickling) return self.model, self.number c = Car("toyota", 1234) d = pickle.loads(pickle.dumps(c)) print("reconstructed with", d.model, d.number) However, the __getinitargs__ will be ignored in new style classes and in Python 3+, all classes can only be new style classes. There is the __getnewargs__ but it will pass the arguments only to the __new__ class method which is not the same. A python 2 call of the above illustrative example will result in >> constructed with toyota 1234 >> constructed with toyota 1234 >> reconstructed with toyota 1234 while a python 3 call will error out >> constructed with toyota 1234 Traceback (most recent call last): File "test.py", line 26, in <module> print("reconstructed with", d.model, d.number) AttributeError: 'Car' object has no attribute 'model' and ignore the __getinitargs__ method. I don't think Python 3 will easily regress in that regard so hopefully I am missing something obvious. EDIT: Replacing __getinitargs__ with __getnewargs__ does not solve the issue.
type: AnsweredQuestion
upvote count: 8
score: 7
answer count: 1
has comment: http://stackoverflow.com/comment/87632486
tagged with: python
has title: Python 3 alternatives for __getinitargs__
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50308545
has comment: http://stackoverflow.com/comment/87632497

http://stackoverflow.com/a/56250854
has comment: http://stackoverflow.com/comment/99119211
has body: def fun1(): l = [] while True: s = input("Enter a name or '-1' to quit: ") if s=='-1': break l.append(s) l.sort() print("The sorted names or numbers(whatever) are:") print(l) fun1()
answers question: http://stackoverflow.com/q/50301594
type: Answer
score: 0

http://stackoverflow.com/comment/87706786
comment on: http://stackoverflow.com/q/50324400
type: Comment
type: QuestionComment
has text: If module not installed Error comes something like this: ImportError: No module named sqlite3
score: 0

http://stackoverflow.com/comment/87615130
type: Comment
comment on: http://stackoverflow.com/a/50299165
has text: The `as` is not strictly redundant in that example because without the `as`, `concurrent` is introduced in the namespace, not `futures`.
type: AnswerComment
score: 1

http://stackoverflow.com/a/50341827
upvote count: 1
answers question: http://stackoverflow.com/q/50341704
type: Answer
has comment: http://stackoverflow.com/comment/87845098
has body: You can do something like this - print (cell.text) This will get you text inside the cell skipping all the tags init.
score: 1
has comment: http://stackoverflow.com/comment/87811536
downvote count: 0

http://stackoverflow.com/comment/88168244
type: Comment
comment on: http://stackoverflow.com/a/50376836
score: 0
type: AnswerComment
has text: That means if a layer have train-able parameters, I should put it into `__init__` function? I noticed that softmax, relu and sigmoid don't have any train-able parameters, so I got this question.

http://stackoverflow.com/comment/87618490
has text: oh I'm using windows
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50300681
score: 0

http://stackoverflow.com/q/50309076
has title: PyCharm not detecting Django installed applications
downvote count: 1
favorite count: 0
type: Question
has body: PyCharm version: Professional 2018.1 Django version: 2.0 virtualenv: pipenv I have setup project interpreter to the virtual environment created using pipenv File > Default settings > Project interpreter can see installed applications like djangorestframework import from Django seems to be working but not from djangorestframework same happens with other installed apps. Also installing from terminal within the PyCharm pipenv install package_name installs the application at root instead of virtualenv
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/50339674
has comment: http://stackoverflow.com/comment/87634960
accepted answer: http://stackoverflow.com/a/50432249
has comment: http://stackoverflow.com/comment/87695302
has answer: http://stackoverflow.com/a/50339674
tagged with: python
has answer: http://stackoverflow.com/a/50432249
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87695335
has comment: http://stackoverflow.com/comment/87634768
upvote count: 1

http://stackoverflow.com/comment/87752704
has text: Where is the timestamp here? Please take another look at the OP's requirements - they need an id based on time
type: Comment
type: AnswerComment
score: 4
comment on: http://stackoverflow.com/a/50368265

http://stackoverflow.com/a/50407053
score: 0
has comment: http://stackoverflow.com/comment/88670358
has comment: http://stackoverflow.com/comment/88674709
has comment: http://stackoverflow.com/comment/88602592
has comment: http://stackoverflow.com/comment/88492018
has comment: http://stackoverflow.com/comment/88629693
has comment: http://stackoverflow.com/comment/88671187
has comment: http://stackoverflow.com/comment/88635496
answers question: http://stackoverflow.com/q/50370929
has comment: http://stackoverflow.com/comment/88575064
has comment: http://stackoverflow.com/comment/88049244
has comment: http://stackoverflow.com/comment/88670781
type: Answer
has comment: http://stackoverflow.com/comment/88030037
has comment: http://stackoverflow.com/comment/88632591
has comment: http://stackoverflow.com/comment/88030428
has body: Now that I can test the code, because the CASError as mentioned in Github is gone at least for today, I get a "ValueError: Unsupported type for value None on elem " when I run the code. My code is: subfolder = Folder(parent=account.inbox, name="RFS") subsubfolder = Folder(parent=subfolder, name="RFS_1150-1199") subsubfolder.save() folder = Folder(parent=subsubfolder, name=wordfile) folder.save() item.move(folder)

http://stackoverflow.com/a/50306001
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50305965
has body: You can try something like this: flag = False info = [] # your desired information will be appended as a string in list with open(your_file, 'r') as file: for line in file.readlines(): if '&lt;start point&gt;' in line: # Pointer reached the start point flag = True if '&lt;end point&gt;' in line: # Pointer reached the end point flag = False if flag: # this line is between the start point and endpoint info.append(line) &gt;&gt; info ['Number=12', 'Word=Hello']
downvote count: 0

botframework
tags question: http://stackoverflow.com/q/50278649
tag name: botframework
type: Tag

http://stackoverflow.com/q/50279083
type: Question
has answer: http://stackoverflow.com/a/50279484
tagged with: google-app-engine
has body: I have a question about the None and '' value when I use DataStore in Google Cloud. e.g. class User(ndb.Model): age = ndb.IntegerProperty(default=None) name = ndb.StringProperty(default='') address = ndb.StringProperty(default=None) I sets the default value because I wanna index and retrieve a list of entities that one of the properties doesn't been put value. What's the difference to set StringProperty default value as '' or None? Which one is better and Why?
has title: What's the difference to set default value None or '' in Google cloud DataStore models?
tagged with: python
accepted answer: http://stackoverflow.com/a/50279484
type: AnsweredQuestion
tagged with: google-cloud-datastore
score: 0
tagged with: app-engine-ndb
answer count: 1
linked to: http://stackoverflow.com/q/21767951

http://stackoverflow.com/comment/87750704
has text: You misunderstand the error. You get the error because you didn't assign any value to `a`.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50367102

http://stackoverflow.com/comment/87478741
comment on: http://stackoverflow.com/q/50230503
score: 0
has text: @quemrana , he want to get the first line of the text
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87477385
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [Reading the target of a .lnk file in Python?](https://stackoverflow.com/questions/397125/reading-the-target-of-a-lnk-file-in-python)
comment on: http://stackoverflow.com/q/50229993

http://stackoverflow.com/comment/87779197
has text: so guest_list = pyperclip.paste().split('\n') ? like that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50381448
score: 0

http://stackoverflow.com/q/50370297
has body: I wrote a script that loads a 3D point cloud in ply format converts it to an np array and then draws the point cloud with mayavi. This process works But the color of the vertices is not taken into account. There is a function that dye all points the same but I would like to use the colors for each point from the ply file like in meshlab. Thanks in advance best Max
score: 1
downvote count: 0
upvote count: 1
tagged with: mayavi
favorite count: 0
type: Question
tagged with: ply
type: UnansweredQuestion
tagged with: mayavi.mlab
tagged with: python
has comment: http://stackoverflow.com/comment/87987779
has title: Mayavi Python How to dye each 3D vertex differently
answer count: 0

http://stackoverflow.com/a/50245804
accepted answer of: http://stackoverflow.com/q/50245727
has body: Use transform for means per group of filtered values with same size as original df, so is possible replace by condition by numpy.where: a = df.groupby(['Category','Brand'])['Sales'].transform(lambda x: x[x &gt;= 20].mean()) df['Sales'] = np.where(df['Sales'] &lt; 20, a, df['Sales']) Alternative solution: a = df[df['Sales']&gt;= 20].groupby(['Category','Brand'])['Sales'].mean() b = df.drop('Sales', 1).join(a, on=['Category','Brand'])['Sales'] df['Sales'] = np.where(df['Sales'] &lt; 20, b, df['Sales']) print (df) Category Brand Sales 0 Food pp 100 1 Food pp 200 2 Food pp 150 3 Cream xy 40 4 Cream xy 50 5 Cream xy 60
answers question: http://stackoverflow.com/q/50245727
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87557340
score: 3
upvote count: 3

http://stackoverflow.com/a/50314736
answers question: http://stackoverflow.com/q/50314202
type: Answer
has body: If you want the float values and not their string representations: import re list( filter( None, map( float, re.findall(r"\S+(?=\s0\.0+e)", my_string) ))) re.findall(r"\S+(?=\s0\.0+e)", my_string) : finds all occurences of non-white-space character sequences before a white-space and 0.00000…e map(float, ^ ) : assume all of the above matches can be converted to float filter(None, ^ ) : filter out all zero floats list( ^ ) : make the above into a list (a no-op in Python 2, conversion of the generator into a list in Python 3) Result: &gt;&gt;&gt; list(filter(None, map(float, re.findall(r"\S+(?=\s0\.0+e)", my_string)))) [1.4401016530699866e+26, 8.07936288357622e+25] However, if you still want the string values themselves, let me know; in that case, the map &amp; filter subexpressions need to be modified.
score: 0

http://stackoverflow.com/a/50320396
upvote count: 1
score: 1
type: Answer
has body: I made a small test script with the size you mentioned. With my computer, array creation (memory error if floats, thats why booleans) and selection are slow, but finding zeros seems to be rather fast: if __name__ == '__main__': arr = np.ones((1756020, 28, 28, 4), dtype=bool) for i in range(0,1756020,2): arr[i] = 0 print(arr[:5]) s = arr.shape t0 = time.time() arr2 = arr.reshape((s[0], np.prod(s[1:]))) ok = np.any(arr2, axis=1) print(time.time()-t0) arr_clean = arr2[ok] print(time.time()-t0) arr_clean = arr_clean.reshape((np.sum(ok), *s[1:])) print(time.time()-t0) print('end') Output: 0.4846000671386719 # Find of zeros is fast 29.750200271606445 # Removing zeros is slow 29.797000408172607 # Reshape to original shapes [1:] is fast
downvote count: 0
answers question: http://stackoverflow.com/q/50320098

http://stackoverflow.com/comment/87770503
has text: I'm not trying to use an optimizer because I'm not looking for an optimal solution. However, I need to run that Ax <= b check frequently
type: Comment
comment on: http://stackoverflow.com/a/50377103
type: AnswerComment
score: 0

http://stackoverflow.com/q/50343108
accepted answer: http://stackoverflow.com/a/50344238
has answer: http://stackoverflow.com/a/50344238
upvote count: 1
tagged with: python
downvote count: 1
has title: Number of training images required for face recognition using opencv with python
tagged with: opencv
type: AnsweredQuestion
score: 0
has body: I am able to detect as well as recognize the faces using python and opencv. But not satisfied with the accuracy. I tried using 20 images for the first trial. then 30 and finally 500. but the accuracy of recognizing the faces is not that much satisfactory. I shows wrong recognition for some faces. I tried using confidence threshold too. if id_ == 1 and confidence &lt; 60: show_profile(1) elif id_ == 2 and confidence &lt; 60: show_profile(2) elif id_ == 3 and confidence &lt; 60: show_profile(3) Here is the code for displaying the recognized image. get_profile fetches the info from database. def show_profile(profile_id): # shows id related information on image cv2.putText(frame, 'Name: ' + get_profile(profile_id)[1], (x, y + h + 30), font, 0.5, (0, 200, 0), 1) cv2.putText(frame, 'Age: ' + str(get_profile(profile_id)[2]), (x, y + h + 50), font, 0.5, (0, 200, 0), 1) cv2.putText(frame, 'Gender: ' + str(get_profile(profile_id)[3]), (x, y + h + 70), font, 0.5, (0, 200, 0), 1) cv2.putText(frame, 'Designation: ' + str(get_profile(profile_id)[4]), (x, y + h + 90), font, 0.5, (0, 200, 0), 1)
answer count: 1
tagged with: face-recognition
favorite count: 0
type: Question

http://stackoverflow.com/q/50256440
upvote count: 1
tagged with: python
score: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50256635
linked to: http://stackoverflow.com/q/17323336
has answer: http://stackoverflow.com/a/50256635
tagged with: jupyter
tagged with: ipython
tagged with: jupyter-notebook
favorite count: 0
type: Question
has title: Playing multiple sounds in one Jupyter Notebook cell
has body: The question is similar to Automatically play sound in IPython notebook - the diffrence is I need to play the sound several times. At the browser side - not the server. The most naive approach: IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True) time.sleep(10) IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True) does not work as it plays the sound once. Moreover, it seems that it is necessary for IPython.display.Audio object to be the output of the cell, as: IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True) None plays no sound. Splitting the code into several cells is not an option.
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50337609
type: Answer
downvote count: 0
upvote count: 1
has body: Not possible. The use of floats is hardcoded all over the place, and many numeric routines literally can't operate on anything else, particularly stuff written in C.
answers question: http://stackoverflow.com/q/50336008
score: 1

http://stackoverflow.com/comment/87709247
type: QuestionComment
score: 0
has text: ok. then lets try fake migrate. I will upload answer
type: Comment
comment on: http://stackoverflow.com/q/50346326

http://stackoverflow.com/a/50521563
score: 0
answers question: http://stackoverflow.com/q/50232891
has body: Django is in Python and there is python-cloudant which is well-maintained and might help you use CouchDB with Python.
type: Answer

http://stackoverflow.com/q/50243495
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/87504707
upvote count: 1
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/87504760
type: AnsweredQuestion
has body: I have a document called words, and each line has a new word. I want to turn each one of these words into a list of its constituent characters. I do this by just doing list(x) where x is the word. This is what I am doing, but I want a way to parallelize this: split = [] with open('wordprob.txt','rt') as lines: for line in lines: split.append(list(line)) I am using this approach so that I do not have to load the entire file (over 3 gb) into memory. When parallelizing it by loading the file first, my memory usage goes over 16 gb. How can I parallelize it without loading the file into memory, just like in the loop above? Thanks! EDIT: Below it was pointed out that the list will take up lots of memory. Instead, how would I store each list of characters (originally from a single word) as a space delimited string on a new line of a new document. Again, I'm looking for a parallelized solution.
accepted answer: http://stackoverflow.com/a/50246767
has answer: http://stackoverflow.com/a/50246767
answer count: 1
has title: Iterate over lines of document in parallel
score: 1
favorite count: 0

http://stackoverflow.com/a/50307408
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87630757
has body: This has nothing to do with static variables. All attributes in Ruby classes are private. If you want to access then from outside, you need an accessor method - which is why the errors talk about missing methods. A shortcut to creating an accessor is to use the attr_accessor method.
type: Answer
answers question: http://stackoverflow.com/q/50307256

http://stackoverflow.com/q/50374192
upvote count: 3
score: 3
answer count: 2
downvote count: 0
has body: I have the following code in my models.py: class ApiLog(models.Model): ... incoming_data = models.TextField('incoming data', null=True, blank=True) In serializers.py class ApiLogSerializer(serializers.ModelSerializer): class Meta: model = ApiLog fields = ('incoming_data',) In views.py: class ApiLogViewSet(APIView): def post(self, request, format=None): serializer = ApiLogSerializer(data=request.data) if serializer.is_valid(): serializer.save() In POST-request I send: data = {..., 'incoming_data':{"key1":"value1","key2":"value2"} } When in view trying serializer.is_valid() I have error: {"incoming_data":["Not a valid string."]} Maybe it's because I try to save dictionary to TextField? Is it possible to save this dictionary to TextField? Suggestions are appreciated.
has comment: http://stackoverflow.com/comment/87764789
favorite count: 0
type: Question
has title: "Not a valid string." - error when trying save dict to TextField in Django Rest Framework
has answer: http://stackoverflow.com/a/50374662
accepted answer: http://stackoverflow.com/a/50374662
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/87764790
has answer: http://stackoverflow.com/a/50374293
possible better answer: http://stackoverflow.com/a/50374293
type: AnsweredQuestion

http://stackoverflow.com/q/50381267
has title: How to extract all the -1's and 1's from a text file using python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50381297
score: 0
has answer: http://stackoverflow.com/a/50381297
type: Question
has comment: http://stackoverflow.com/comment/87778635
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/87778696
has body: I have a text file that follows a pattern like this: train_00000.png -1 train_00001.png -1 train_00002.png 1 train_00003.png 1 train_00004.png -1 train_00005.png -1 train_00006.png 1 train_00007.png 1 train_00008.png -1 train_00009.png -1 train_00010.png -1 train_00011.png 1 train_00012.png -1 train_00013.png 1 train_00014.png -1 train_00015.png -1 train_00016.png -1 train_00017.png -1 train_00018.png -1 train_00019.png -1 train_00020.png -1 train_00021.png 1 train_00022.png 1 train_00023.png -1 train_00024.png 1 train_00025.png -1 train_00026.png 1 train_00027.png 1 train_00028.png 1 train_00029.png 1 train_00030.png -1 train_00031.png 1 I am trying to extract all the -1's and 1's from this text file and then list them in an array using python. I am new to python and struggle in implementing a method to achieve this goal. Can anyone help me with this? Thanks in advance! Edit: Sorry for not making this question clear. My intent is to extract all the -1's and 1's from the text file(not the 1's contained in the image name, i.e., the 1 in "train_00001.png" should not be extracted) and put these -1's and 1's into a new array. So my output array should be [-1, -1, 1, 1, -1, -1...]. I do apologize for the ambiguity in my original question but really appreciate your answers!

http://stackoverflow.com/a/50383621
accepted answer of: http://stackoverflow.com/q/50383444
upvote count: 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50383444
score: 2
downvote count: 0
has body: Option 1 shift with loc df.loc[df.Recession_start &amp; df.Recession_start.shift(-1), 'Quarter'] Option 2 astype(int) with diff df.loc[~df.Recession_start.astype(int).diff().ne(1), 'Quarter'] Both result in: 2 2000q3 Name: Quarter, dtype: object Python 3.6.4, Pandas 0.22.0

http://stackoverflow.com/q/50273021
tagged with: python-requests
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87563225
tagged with: python
has body: I'm trying to login into this IoT device using python-requests. But I noticed that response headers are empty. Further investigation and I think I found the reason: double headers on response. Response captured with wireshark: HTTP/1.0 200 OK HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 ... It seems that requests reads only the first "HTTP/1.0 200 OK" and nothing more as trying to run for example this: import requests r = requests.get('http://10.0.0.10/cgi-bin/index') print(r.headers) returns this: {} I need to receive "Set-cookie" header in order to manage the device. What should I do? Should I try to read raw http response and try to parse the "Set-cookie" header?
score: 0
has title: Python-requests response headers are empty when response contains double headers
answer count: 0
has comment: http://stackoverflow.com/comment/87563362

http://stackoverflow.com/q/50308562
duplicate of: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/87634819
tagged with: class
duplicate of: http://stackoverflow.com/q/2612802
has body: See full working directory here: https://github.com/sharpvik/python-libs/tree/alpha/Testing So I was working on some Graph theory and coding stuff in Python. I created a class called Graph as follows (don't worry about indentation, in the file itself it's fine): class Graph: # undirected graph; no values for the edges; def __init__(self): self.nodes_counter = 0 self.nodes_dict = dict() def node_add(self, name): # name(int / str) -- name of the node; self.nodes_dict.update( { name : list() } ) self.nodes_counter += 1 return name def node_del(self, name): # name(int / str) -- name of the node; self.nodes_dict.pop(name, None) for each in self.nodes_dict: self.nodes_dict[each].remove(name) self.nodes_counter -= 1 return name def connection_add(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to connect; self.nodes_dict[one].append(two) self.nodes_dict[two].append(one) return [one, two] def connection_del(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to disconnect; self.nodes_dict[one].remove(two) self.nodes_dict[two].remove(one) return [one, two] def nodes_count(self): # --&gt; function returns the number of nodes in the graph; return self.nodes_counter def nodes_return(self): # --&gt; function returns the whole dict containing nodes and their connections; return self.nodes_dict def node_return(self, name): # name(int / str) -- name of the node you're checking; # --&gt; function returns connections of the given node; return self.nodes_dict[name] # search ## --&gt; breadth first search using class Queue def bfs( self, final, queue=Queue(None), checked=list() ): # final(int / str) -- name of the node you're trying to establish connection with; # queue(class Queue) -- Queue containing the element you are beginning with (format: element); # checked(list) -- leave empty *** internal use ***; # --&gt; function returns True if the two nodes are connected, otherwise it returns False; if queue.length() == 0: return False tem…
favorite count: 0
has comment: http://stackoverflow.com/comment/87634867
type: Question
has comment: http://stackoverflow.com/comment/87634898
tagged with: graph-theory
answer count: 0
type: UnansweredQuestion
score: 0
linked to: http://stackoverflow.com/q/2612802
upvote count: 1
has title: Class method inherits list from its previous execution (Python)
tagged with: python
downvote count: 1

http://stackoverflow.com/q/50382642
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: How to automatically check if there is any possible exceptions in Python?
tagged with: execution
score: 2
has comment: http://stackoverflow.com/comment/87782657
tagged with: exception
has body: I'm refactoring a non-trivial python project, there could be many exceptions to be thrown. sometimes it's hard to catch all of them if you don't just try...except the whole program. In order to achieve a fine-grained exception handling, I want to systematically get a list(preferably a graph) of all possible exceptions( and their types) that could be thrown in different location of execution flow. Is such a thing even[sic] possible?
has comment: http://stackoverflow.com/comment/87784994
favorite count: 0
type: Question

http://stackoverflow.com/q/50246592
type: UnansweredQuestion
has body: I wrote my own zipline bundle to ingest cryptocurrency prices from my exchange. The ingestion runs smoothly and I checked the database and saw my minute data in it. I tried to run a really simple algorithm to verify my bundle, but I ran into an exception. My algorithm looks like this: def initialize(context): # I tried to run it without this line as well context.sim_params._emission_rate = 'minute' def handle_data(context, data): order(symbol('ETHBTC'), 10) record(ETHBTC=data.current(symbol('ETHBTC'), 'price')) The last line gives me the following exception: File "python3.5/site-packages/zipline/data/us_equity_pricing.py", line 710, in sid_day_index offset = day_loc - self._calendar_offsets[sid] KeyError: Equity(0 [ETHBTC]) I looked into this further and found that zipline uses the daily bar reader to get a calendar offset for the symbol "ETHBTC". But my daily bar data is empty since I am just ingesting minutely data. According to the zipline documentation, ingesting daily bar data is not mandatory from which I concluded that zipline will resample the minute data to daily data if needed. Has anyone experienced this before? Is there something I have to do start the resampling of minute to daily bar data? Cheers!
downvote count: 0
upvote count: 1
favorite count: 0
has title: No calendar offset when using custom data bundle for minute data in zipline
score: 1
tagged with: zipline
tagged with: python
type: Question
answer count: 0

http://stackoverflow.com/q/50286010
tagged with: pandas
has title: Get first and last elements with pd.Grouper()
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: time-series
tagged with: python
has body: I have a time series that I am resampling to 5s windows like such: INDEX size price 2018-05-07 21:53:13.731 0.365127 9391.800000 2018-05-07 21:53:16.201 0.666127 9391.800000 2018-05-07 21:53:18.038 0.143104 9391.800000 2018-05-07 21:53:18.243 0.025643 9391.800000 2018-05-07 21:53:18.265 0.640484 9391.800000 2018-05-07 21:53:18.906 -0.100000 9391.793421 2018-05-07 21:53:19.829 0.559516 9391.800000 2018-05-07 21:53:19.846 0.100000 9391.800000 2018-05-07 21:53:19.870 0.006560 9391.800000 2018-05-07 21:53:20.734 0.666076 9391.800000 2018-05-07 21:53:20.775 0.666076 9391.800000 2018-05-07 21:53:28.607 0.100000 9391.800000 2018-05-07 21:53:28.610 0.041991 9391.800000 2018-05-07 21:53:29.283 -0.053518 9391.793421 2018-05-07 21:53:47.322 -0.046302 9391.793421 2018-05-07 21:53:49.182 0.100000 9391.800000 def tick_features(x): volume = np.abs(x['size']).sum() num_trades = x['size'].count() return pd.Series([volume,num_trades], index=['volume','num_trades']) tick = tick.groupby(pd.Grouper(freq='5S')).apply(tick_features) How would I go about getting the first and last elements of each 5S via pd.Grouper() and .apply()? I could do similar things with .resample().agg() and {'price':'first'} but for other reasons I'd like to do it via pd.Grouper() if possible.
accepted answer: http://stackoverflow.com/a/50286075
score: 2
has answer: http://stackoverflow.com/a/50286075
upvote count: 2

http://stackoverflow.com/q/50312860
has comment: http://stackoverflow.com/comment/87641987
score: 2
has title: NoneType in sqlite3
has answer: http://stackoverflow.com/a/50313375
tagged with: sqlite
has comment: http://stackoverflow.com/comment/87641926
tagged with: python
has comment: http://stackoverflow.com/comment/87642046
has body: I have a table like this c.execute("""CREATE TABLE IF NOT EXISTS Voting(id unique, name text ,Zone text ,is_voted integer)""") I have a iD,whose row I want to fetch and I have that in my database. id=int(iD) c.execute("SELECT * FROM Voting WHERE id={}".format(id)) Iden=c.fetchone() print(Iden) identification,user_name,dep_Money,Is=Iden I tried all solutions and it still show this TypeError: 'NoneType' object is not iterable Insertion into DB c.execute("INSERT INTO Voting VALUES(?,?,?,?)",(self.id_label.text(),self.name_label.text(),self.zone_label.text(),0)) I checked the database and iD for that row is there.I dont know its showing Nonetype.Please help me
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87642067
has comment: http://stackoverflow.com/comment/87642244

http://stackoverflow.com/comment/87745241
type: AnswerComment
comment on: http://stackoverflow.com/a/50362431
score: 0
has text: @muthikin yes, it means that those strings never added to `c`, so they repeated zero times, it means never.
type: Comment

http://stackoverflow.com/comment/87712807
comment on: http://stackoverflow.com/q/50348125
type: QuestionComment
has text: instead of updating the bullet position as `posy+speedy*timestep` you could update it on the vector between the current position of the bullet and the targeted enemy
type: Comment
score: 1

global
type: Tag
tags question: http://stackoverflow.com/q/50243762
tag name: global
tags question: http://stackoverflow.com/q/50276843
tags question: http://stackoverflow.com/q/50367102
tags question: http://stackoverflow.com/q/50311287

http://stackoverflow.com/q/50316656
has body: My DataFrame has around 9K columns, and I want to remove the . from every column name, see example column names below: `traffic.seas1` `traffic.seas2` `traffic.seas3` These are just three, I have 9K columns, some do not have . but many do. How can I remove them efficiently, as the rename function is too manual.
possible better answer: http://stackoverflow.com/a/50316673
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50316673
upvote count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/50316750
score: 2
type: AnsweredQuestion
has title: Remove '.' from Thousands of Column Heads [python]
has answer: http://stackoverflow.com/a/50316750
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/50324400
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87751944
has body: New to Python, sorry if my Question found stupid but need help. I Need to install sqlite devel on my server. but when i am trying to run sudo yum install sqlite3 libsqlite3-dev its giving the following error [pythondemo@panel python3.6]$ sudo yum install sqlite3 libsqlite3-dev Loaded plugins: fastestmirror, universal-hooks Setting up Install Process Loading mirror speeds from cached hostfile * EA4: 69.72.212.11 * cpanel-addons-production-feed: 69.72.212.11 * base: mirror.jaleco.com * epel: mirror.texas3006.com * extras: mirror.jaleco.com * ius: ius.mirror.constant.com * updates: mirror.jaleco.com No package sqlite3 available. No package libsqlite3-dev available.
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87751406
tagged with: python
has comment: http://stackoverflow.com/comment/87746332
has comment: http://stackoverflow.com/comment/87706786
has comment: http://stackoverflow.com/comment/87741308
has comment: http://stackoverflow.com/comment/87671822
has comment: http://stackoverflow.com/comment/87699794
has title: No package sqlite3 available
answer count: 0
has comment: http://stackoverflow.com/comment/87751246
tagged with: sqlite

http://stackoverflow.com/comment/87703100
type: AnswerComment
has text: @Sraw Where is the proposed solution?
type: Comment
comment on: http://stackoverflow.com/a/50325234
score: 0

http://stackoverflow.com/comment/87678186
type: Comment
comment on: http://stackoverflow.com/q/50331029
type: QuestionComment
has text: Did you try anything?
score: 1

http://stackoverflow.com/comment/87635797
has text: What specifically are you attempting to read from the page?
score: 0
comment on: http://stackoverflow.com/q/50309948
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87674215
type: QuestionComment
score: 3
type: Comment
comment on: http://stackoverflow.com/q/50329176
has text: if you get a response Code 200 it all went fine. Try to output the text like this: `print r.text`

servicebus
tags question: http://stackoverflow.com/q/50349492
tag name: servicebus
type: Tag

http://stackoverflow.com/a/50375850
type: Answer
has body: Feeding your dictionary values into pd.DataFrame is one way. Here we use next(iter(some_view)) syntax to extract the only key and only value. This is an efficient solution where you can guarantee your dictionary only has one key and the value is a list of lists. df = pd.DataFrame(next(iter(dict1.values())), columns=['userid', 'score', 'related'])\ .assign(memberid=next(iter(dict1.keys()))) print(df) userid score related memberid 0 a 5.4 b 808 1 c 4.1 b 808 2 d 3.7 f 808
score: 0
answers question: http://stackoverflow.com/q/50375640

http://stackoverflow.com/q/50378405
downvote count: 0
duplicate of: http://stackoverflow.com/q/24577688
upvote count: 1
duplicate of: http://stackoverflow.com/q/5434891
has answer: http://stackoverflow.com/a/50378497
possible better answer: http://stackoverflow.com/a/50378497
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87773041
linked to: http://stackoverflow.com/q/24577688
has answer: http://stackoverflow.com/a/50378578
accepted answer: http://stackoverflow.com/a/50378578
tagged with: python
has body: pretty simple question I guess, sorry I'm pretty new to Python. So I have a given list and want to iterate through it. I want to compare every item in the list to the upcoming one. Unfortunately it does not work for me. values = [45, 24, 35, 31, 40, 38, 11] for i in values: if values(i+1) &gt; values(i): print(str(i+1) + " &gt; " + str(i)) else: print(str(i+1) + " &lt; " + str(i)) (As an example, for the first step I would want to have 45 compared to 24)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50378498
has comment: http://stackoverflow.com/comment/87773078
answer count: 3
score: 1
linked to: http://stackoverflow.com/q/5434891
has title: Referencing the next variable in a list in Python

http://stackoverflow.com/a/50314323
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50311732
upvote count: 3
answers question: http://stackoverflow.com/q/50311732
type: AcceptedAnswer
has body: Spark DataFrame don't have strict order so indexing is not meaningful. Instead we use SQL-like DSL. Here you'd use where (filter) and select. If data looked like this: import pandas as pd import numpy as np from pyspark.sql.functions import col, sum as sum_ np.random.seed(1) df = pd.DataFrame({ c: np.random.randn(1000) for c in ["column_A", "column_B", "column_C"] }) amount would be amount # 0.9334143225687774 and Spark equivalent is: sdf = spark.createDataFrame(df) (amount_, ) = (sdf .where(sdf.column_A &gt; 0.0) .select(sum_(sdf.column_B * sdf.column_C) / sum_(sdf.column_C)) .first()) and results are numerically equivalent: abs(amount - amount_) # 1.1102230246251565e-16 You could also use conditionals: from pyspark.sql.functions import when pred = col("column_A") &gt; 0.0 amount_expr = sum_( when(pred, col("column_B")) * when(pred, col("column_C")) ) / sum_(when(pred, col("column_C"))) sdf.select(amount_expr).first()[0] # 0.9334143225687773 which look more Pandas-like, but are more verbose.
downvote count: 0

http://stackoverflow.com/comment/87754972
comment on: http://stackoverflow.com/q/50369050
type: QuestionComment
score: 0
has text: `conda update python` ty @OliverCharlesworth
type: Comment

http://stackoverflow.com/q/50274201
tagged with: pygame
has comment: http://stackoverflow.com/comment/87566215
type: AnsweredQuestion
has title: AttributeError: 'pygame.Rect' object has no attribute 'up' and 'down'
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has body: I'm having an issue where I can't seem to move the character on my screen up and down. When I run the code and press the down key, I get this error: AttributeError: 'pygame.Rect' object has no attribute 'down' When I run the code and press the up key, I get this error: AttributeError: 'pygame.Rect' object has no attribute 'up' Code: import pygame class Character(): def __init__(self, ai_settings, screen): self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load("character.jpg") self.rect = self.image.get_rect() self.screen_rect = screen.ge_rect() self.rect.centerx = self.screen_rect.centerx self.rect.centery = self.screen_rect.centery self.center = float(self.rect.centerx) self.center1 = float(self.rect.centery) self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False def update(self): if self.moving_right and self.rect.right &lt; self.screen_rect.right: self.center += self.ai_settings.char_speed_factor if self.moving_left and self.rect.left &gt; 0: self.center -= self.ai_settings.char_speed_factor if self.moving_up and self.rect.up &lt; self.screen_rect.up: self.center1 += self.ai_settings.char_speed_factor if self.moving_down and self.rect.down &gt; 0: self.center1 -= self.ai_settings.char_speed_factor self.rect.centerx = self.center self.rect.centery = self.center1 def blitme(self): self.screen.blit(self.image, self.rect) This is just the character class python file and not the main file. There is a game functions file which checks for keyboard input and then sets the self.moving variables to True. The definitions in the gamefunctions file are then called in the main file. I am very confused as to why this is happening because I have no trouble with getting the character to move left and right.
type: Question
has comment: http://stackoverflow.com/comment/87569619
accepted answer: http://stackoverflow.com/a/50276100
has comment: http://stackoverflow.com/comment/87569169
has answer: http://stackoverflow.com/a/50276100
tagged with: python

http://stackoverflow.com/comment/87606754
has text: No you don't have to delete it, but you may if you wish. Think about it in terms of if and how this can be useful for future readers. If you come to the conclusion that future readers do not make such silly mistakes, you may delete it. Else, you may edit the question and answer to include a bit more detail on what the problem was and why you were not able to solve it initially. Use words that would then allow people to find this through search in similar cases.
comment on: http://stackoverflow.com/a/50282949
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50278183
type: Question
has body: How are floating point numbers handled in python. I am using a simple telegram bot. import telegram value=0.0000023 bot.send_message(chat_id=chat_id, text=value) I am getting 2.3e-06. Even print also gives 2.3e-06. How do I get 0.0000023. How can I handle decimal values out to at least 20 zeros.
upvote count: 0
has title: Python decimal value handling
has comment: http://stackoverflow.com/comment/87573109
score: -3
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50278459
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50278459
answer count: 1
downvote count: 3
linked to: http://stackoverflow.com/q/8568233
favorite count: 0
has comment: http://stackoverflow.com/comment/87573469

datetime
tags question: http://stackoverflow.com/q/50336676
tags question: http://stackoverflow.com/q/50326962
tags question: http://stackoverflow.com/q/50246105
tags question: http://stackoverflow.com/q/50360954
tags question: http://stackoverflow.com/q/50326425
tags question: http://stackoverflow.com/q/50377293
tags question: http://stackoverflow.com/q/50336251
tags question: http://stackoverflow.com/q/50233436
tag name: datetime
tags question: http://stackoverflow.com/q/50348141
tags question: http://stackoverflow.com/q/50359885
tags question: http://stackoverflow.com/q/50367656
tags question: http://stackoverflow.com/q/50276044
tags question: http://stackoverflow.com/q/50276835
tags question: http://stackoverflow.com/q/50287690
tags question: http://stackoverflow.com/q/50352569
tags question: http://stackoverflow.com/q/50362886
tags question: http://stackoverflow.com/q/50380295
tags question: http://stackoverflow.com/q/50280579
tags question: http://stackoverflow.com/q/50347089
tags question: http://stackoverflow.com/q/50380203
tags question: http://stackoverflow.com/q/50292080
tags question: http://stackoverflow.com/q/50293639
tags question: http://stackoverflow.com/q/50323705
tags question: http://stackoverflow.com/q/50361352
tags question: http://stackoverflow.com/q/50293764
tags question: http://stackoverflow.com/q/50250022
tags question: http://stackoverflow.com/q/50249281
tags question: http://stackoverflow.com/q/50279491
type: Tag
tags question: http://stackoverflow.com/q/50270181
tags question: http://stackoverflow.com/q/50320955
tags question: http://stackoverflow.com/q/50347734
tags question: http://stackoverflow.com/q/50339364
tags question: http://stackoverflow.com/q/50270434
tags question: http://stackoverflow.com/q/50356337
tags question: http://stackoverflow.com/q/50236669
tags question: http://stackoverflow.com/q/50298705
tags question: http://stackoverflow.com/q/50371649
tags question: http://stackoverflow.com/q/50369338
tags question: http://stackoverflow.com/q/50338849
tags question: http://stackoverflow.com/q/50265555
tags question: http://stackoverflow.com/q/50277935
tags question: http://stackoverflow.com/q/50370433
tags question: http://stackoverflow.com/q/50260481
tags question: http://stackoverflow.com/q/50256825
tags question: http://stackoverflow.com/q/50379914
tags question: http://stackoverflow.com/q/50324848
tags question: http://stackoverflow.com/q/50304415

http://stackoverflow.com/a/50789460
downvote count: 0
upvote count: 1
has body: Even cleaner than turning l1 into a set, use the keys of the dictionary you're building. Like this d = {x: [] for x in l1} k = None for x in l2: if x in d: k = x elif k is not None: d[k].append(x) This is because (in the worst case) your code would be iterating over all the values in l1 for every value in l2 on the if x in l1: line, because checking if a value is in a list takes linear time. Checking if a value is in a dictionary's keys is constant time in the average case (same with sets, as already suggested by Eric Duminil). I set k to None and check for it because your code would've returned d with '': ['x','q','we','da','po'], which is presumably not what you want. This assumes l1 can't contain None. My solution also assumes it's okay for the resulting dictionary to contain keys with empty lists if there are items in l1 that never appear in l2. If that's not okay, you can remove them at the end with final_d = {k: v for k, v in d.items() if v}
type: Answer
answers question: http://stackoverflow.com/q/50350456
score: 1

http://stackoverflow.com/q/50319858
type: Question
has body: So I'm pretty new to both Machine Learning and Python but have managed to be able to classify my data and print the confusion matrix with various classifiers with the code below: def classify_data(df, feature_cols, file): nbr_folds = 5 attributes = df.loc[:, feature_cols] # Also known as x class_label = df['task'] # Class label, also known as y. file.write("\nFeatures used: ") for feature in feature_cols: file.write(feature + ",") print("Features used", feature_cols) print("MLP") file.write("MLP") mlp = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) class_label_predicted = cross_val_predict(mlp, attributes, class_label, cv=nbr_folds) conf_mat = confusion_matrix(class_label, class_label_predicted) print(conf_mat) accuracy = accuracy_score(class_label, class_label_predicted) print("\nRows classified: " + str(len(class_label_predicted))) print("\nAccuracy: {0:.3f}%\n".format(accuracy * 100)) file.write("\nClassifier settings:" + str(mlp) + "\n") file.write("\nRows classified: " + str(len(class_label_predicted))) file.write("\nAccuracy: {0:.3f}%\n".format(accuracy * 100)) file.writelines('\t'.join(str(j) for j in i) + '\n' for i in conf_mat) print("RandomForest") file.write("\nRandomForest") #sv = svm.SVC(kernel="linear") clf = RandomForestClassifier(max_depth=2, random_state=0) class_label_predicted = cross_val_predict(clf, attributes, class_label, cv=nbr_folds) conf_mat = confusion_matrix(class_label, class_label_predicted) print(conf_mat) accuracy = accuracy_score(class_label, class_label_predicted) print("Rows classified: " + str(len(class_label_predicted))) print("Accuracy: {0:.3f}%\n".format(accuracy * 100)) file.write("\nClassifier settings:" + str(clf) + "\n") file.write("\nRows classified: " + str(len(class_label_predicted))) file.write("\nAccuracy: {0:.3f}%\n".format(accuracy * 100)) file.writelines('\t'.join(str(j) for j in i) + '\n' for i in conf_mat) However, I am starting to wonder if I am doing something wrong here as…
type: UnansweredQuestion
tagged with: python
score: 2
has title: Sci kit learn confusion matrix always look almost the same
tagged with: confusion-matrix
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50320152
downvote count: 0
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/96384819
favorite count: 0

http://stackoverflow.com/q/50230797
has answer: http://stackoverflow.com/a/50246728
score: 1
accepted answer: http://stackoverflow.com/a/50246728
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to build a Sphinx documentation for a package but I keep getting errors and could use some help. My project directory is bb_lite and the codes are located in the backend folder. bb_lite ├── 1.0\ docs ├── 2.0\ data ├── README.md └── backend This is how my backend folder looks like . ├── README.md ├── __init__.py ├── __pycache__ │ └── __init__.cpython-36.pyc ├── archive │ ├── cont_pca_transform_w_original_func.py │ └── model_tuner.py ├── automl_pipeline │ ├── __init__.py │ ├── flow.py │ └── input_json.json ├── data_preparation │ ├── __init__.py │ ├── cat_multiclass_label_index_encoding.py │ ├── cross_validator.py │ ├── data_samplers.py │ └── train_test_validator I cd to the bb_lite folder, create a docs folder and cd to docs. From there I run sphinx-quickstart. When it asks to separate the source and build directories, I type y and press enter. When it asks for the autodoc extension, I enter y and complete others. My docs looks like- . ├── Makefile ├── build ├── make.bat └── source ├── _static ├── _templates ├── conf.py └── index.rst Once this is done, I open the conf.py file inside and uncomment the first three lines import os import sys sys.path.insert(0, os.path.abspath('backend')) With the docs folder as my working directory, I run the following sphinx-apidoc -f -o source/ ../backend/ which gives me Creating file source/backend.rst. Creating file source/backend.automl_pipeline.rst. Creating file source/backend.data_preparation.rst. Creating file source/backend.explain.rst. Creating file source/backend.explain.k_limes.rst. Creating file source/backend.explain.surrogate_models.rst. Creating file source/backend.feature_extraction.rst. Creating file source/backend.model_tuner.rst. Creating file source/backend.parameter_tuning.rst. Creating file source/backend.profiling.rst. Creating file source/backend.tests.rst. Creating file source/backend.utilities.rst. Creating file source/modules.rst. Finally I run make html (from the docs directory) which leaves me w…
tagged with: python-sphinx
tagged with: python
has comment: http://stackoverflow.com/comment/87481268
has comment: http://stackoverflow.com/comment/87481463
upvote count: 2
type: AnsweredQuestion
has title: Error during make html because of sys.path

http://stackoverflow.com/comment/87802858
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50360105
has text: I launched the script without parenthesis around the whole expression and it really worked the same. I have one more question. First you assign `matched` to `False` and then it becomes a mask-like series containing a boolean for each `weekly_units` row. Does this work because of numpy broadcasting?
score: 0

http://stackoverflow.com/comment/87680614
type: Comment
type: AnswerComment
has text: :thank you for educational answer and the lovely solution, shlex.quote. I love it.
comment on: http://stackoverflow.com/a/50316847
score: 0

http://stackoverflow.com/q/50375544
has comment: http://stackoverflow.com/comment/87767994
tagged with: gzip
has comment: http://stackoverflow.com/comment/87769656
has title: How to know if a file is being compressed
tagged with: python
has comment: http://stackoverflow.com/comment/87767854
score: 1
tagged with: compression
answer count: 1
downvote count: 0
tagged with: http://stackoverflow.com/tag/tar
has comment: http://stackoverflow.com/comment/87767623
upvote count: 1
has answer: http://stackoverflow.com/a/50376834
favorite count: 0
type: Question
has body: From a set of files, I'm creating a tar file and, from the tar file, a tar.gz file (using python). The creation of the compressed file could take time, so: I'd like to know if there is a way to know that the "process to create a compressed file" is "on-going". Maybe checking by some temp file or similar? Thanks
has comment: http://stackoverflow.com/comment/87767808
type: UnansweredQuestion

android
tags question: http://stackoverflow.com/q/50247582
tags question: http://stackoverflow.com/q/50378849
tags question: http://stackoverflow.com/q/50249481
tags question: http://stackoverflow.com/q/50355139
tags question: http://stackoverflow.com/q/50240485
tag name: android
type: Tag
tags question: http://stackoverflow.com/q/50263705

http://stackoverflow.com/q/50268442
answer count: 1
downvote count: 0
tagged with: jupyter
upvote count: 1
favorite count: 0
tagged with: jupyter-notebook
type: Question
has answer: http://stackoverflow.com/a/52163755
tagged with: sas
has title: saspy sas kernel not visible in jupyter
type: UnansweredQuestion
tagged with: python
has body: I can run this code fine using a Python kernel: import saspy sas = saspy.SASsession() sas cars = sas.sasdata('cars', 'sashelp') cars.head() Unfortunately, I cannot chose a SAS kernel anymore. I re-installed saspy and the sas kernel and as you can see the sas kernel (?) is working from Python. This: jupyter kernelspec list only returns my python and r kernel: Available kernels: ir C:\ProgramData\Anaconda3\share\jupyter\kernels\ir python3 C:\ProgramData\Anaconda3\share\jupyter\kernels\python3 Can I somehow refresh (?) manual register the sas kernel?
tagged with: anaconda
score: 1

http://stackoverflow.com/q/50280711
type: Question
has title: Pandas: select rows were a column has lists that are not empty
has comment: http://stackoverflow.com/comment/87578297
tagged with: python
linked to: http://stackoverflow.com/q/49700794
has answer: http://stackoverflow.com/a/50280805
type: AnsweredQuestion
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/49700794
tagged with: select
has body: I have a data frame with a column that values are lists. I need to select rows where these lists are not empty: import pandas as pd data = [('words', ['foo', 'bar', 'baz', 'foobar', 'helter', 'skelter']), ('counts', [[1,2,3], [], [5,8], [13,21,34,55], [89], [] ]) ] df = pd.DataFrame.from_items(data) df Output: words counts 0 foo [1, 2, 3] 1 bar [] 2 baz [5, 8] 3 foobar [13, 21, 34, 55] 4 helter [89] 5 skelter [] Selecting this way fails: df[df['counts'] != []] --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-3-db8067c8ac7b&gt; in &lt;module&gt;() ----&gt; 1 df[df['counts'] != []] /Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(self, other, axis) 859 860 with np.errstate(all='ignore'): --&gt; 861 res = na_op(values, other) 862 if is_scalar(res): 863 raise TypeError('Could not compare %s type with Series' % /Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y) 763 764 if is_object_dtype(x.dtype): --&gt; 765 result = _comp_method_OBJECT_ARRAY(op, x, y) 766 else: 767 /Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in _comp_method_OBJECT_ARRAY(op, x, y) 741 y = y.values 742 --&gt; 743 result = lib.vec_compare(x, y, op) 744 else: 745 result = lib.scalar_compare(x, y, op) pandas/_libs/lib.pyx in pandas._libs.lib.vec_compare (pandas/_libs/lib.c:14284)() ValueError: Arrays were different lengths: 6 vs 0 Other things like df.query do not work in this case as well. Any ideas how to solve this? Why it is not possible to compare pandas cell value with an empty list?
answer count: 1
has comment: http://stackoverflow.com/comment/87577961
has comment: http://stackoverflow.com/comment/135186155
accepted answer: http://stackoverflow.com/a/50280805

http://stackoverflow.com/q/50288258
tagged with: keras
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87594206
tagged with: neural-network
tagged with: loss-function
tagged with: python
has comment: http://stackoverflow.com/comment/87615252
has body: I want to make following loss function in keras: Loss = mse + double_derivative(y_pred,x_train) I am not able to incorporate the derivative term. I have tried K.gradients(K.gradients(y_pred,x_train),x_train) but it does not help. I am getting error message: AttributeError: 'NoneType' object has no attribute 'op' def _loss_tensor(y_true, y_pred,x_train): l1 = K.mean(K.square(y_true - y_pred), axis=-1) sigma = 0.01 lamda = 3 term = K.square(sigma)*K.gradients(K.gradients(y_pred,x_train),x_train) l2 = K.mean(lamda*K.square(term),axis=-1) return l1+l2 def loss_func(x_train): def loss(y_true,y_pred): return _loss_tensor(y_true,y_pred,x_train) return loss def create_model_neural(learning_rate, num_layers, num_nodes, activation): model_neural = Sequential() x_train = model_neural.add(Dense(num_nod, input_dim=num_input, activation=activation)) for i in range(num_layers-1): model_neural.add(Dense(num_nodes,activation=activation,name=name)) model_neural.add(Dense(1, activation=activation)) optimizer = SGD(lr=learning_rate) model_loss = loss_func(x_train=x_train) model_neural.compile(loss=model_loss,optimizer=optimizer) return model_neural
has comment: http://stackoverflow.com/comment/87617492
has comment: http://stackoverflow.com/comment/87593841
score: 4
has title: Derivative in loss function in Keras
upvote count: 4
accepted answer: http://stackoverflow.com/a/50311103
has answer: http://stackoverflow.com/a/50311103
type: AnsweredQuestion
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/comment/87782593
comment on: http://stackoverflow.com/q/50383432
score: 0
type: Comment
has text: what does `obj` stand for in your template?
type: QuestionComment

http://stackoverflow.com/comment/87724622
type: AnswerComment
type: Comment
has text: Thank you for your answer. Helped with clarifying things a lot
comment on: http://stackoverflow.com/a/50354058
score: 0

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

http://stackoverflow.com/q/50334743
answer count: 2
has answer: http://stackoverflow.com/a/50334933
has body: I have a very large number (20 digits), which I need to find. So in a range between 0 and 99999999999999999999. I can perform a check if the number is larger or smaller than the guessed number, so for example: is_smaller(12341234123412341234) # True is_smaller(98769876987698769876) # False However, how the function is_smaller works is unknown, but the value for a number is constant. Could this be solved with a binary search - I'm not quite sure how I can implement this as I only ever know If the number is smaller/larger. Most implementations of the binary search I've come across, use it to find a given number in an array, which doesn't work for me as the number is unknown. How could I use binary search in this scenario, or would another method be better suited? The goal is to find the highest possible value, that still returns True for is_smaller. edit: I do not have a way of telling if the number is bigger, so I have no is_bigger function. So in a smaller range (e.g. 0 to 10), if the number of interest is 6, the function I have would return: [...] is_smaller(4) # True is_smaller(5) # True is_smaller(6) # True is_smaller(7) # False is_smaller(8) # False I have to admit the functions name in the question was very poorly chosen.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50334969
tagged with: python
tagged with: binary-search
linked to: http://stackoverflow.com/q/9501337
score: 0
tagged with: numbers
has title: Binary search to find the highest possible value in Python
type: Question
tagged with: binary-search-tree

http://stackoverflow.com/comment/87584780
comment on: http://stackoverflow.com/q/50284233
type: Comment
has text: It is possible. But it's a lot easier to keep track of what you printed to the console than to read characters from the console. It's easier still to just overwrite all the characters, whether they're the same or not. And it's much, much easier to not even think about it as a character-addressable console, and just print a CR without NL to whatever stdout is, and rewrite the whole line.
type: QuestionComment
score: 5

http://stackoverflow.com/a/50247613
answers question: http://stackoverflow.com/q/50247574
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87512694
type: AcceptedAnswer
has body: You should use object name in template: {% block content %} &lt;h3&gt;{{ object.title }}&lt;/h3&gt; &lt;h6&gt; on {{ object.datetime }}&lt;/h6&gt; &lt;div class = "code"&gt; &lt;/div&gt; {% endblock %} Or if you want to use Tutorial variable, you need to pass context_object_name=Tutorials to the view: path('&lt;int:pk&gt;', DetailView.as_view( model=Tutorials, template_name="tutorials/post.html", context_object_name='Tutorials')),
accepted answer of: http://stackoverflow.com/q/50247574
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87512566

web-scraping
tags question: http://stackoverflow.com/q/50282121
tags question: http://stackoverflow.com/q/50232555
tags question: http://stackoverflow.com/q/50383545
tags question: http://stackoverflow.com/q/50302737
tags question: http://stackoverflow.com/q/50319579
tags question: http://stackoverflow.com/q/50318606
tags question: http://stackoverflow.com/q/50330126
tags question: http://stackoverflow.com/q/50241365
tags question: http://stackoverflow.com/q/50363321
tags question: http://stackoverflow.com/q/50377269
tags question: http://stackoverflow.com/q/50318656
tags question: http://stackoverflow.com/q/50308423
tags question: http://stackoverflow.com/q/50360698
tags question: http://stackoverflow.com/q/50280564
tags question: http://stackoverflow.com/q/50302097
tags question: http://stackoverflow.com/q/50325878
tag name: web-scraping
tags question: http://stackoverflow.com/q/50314709
tags question: http://stackoverflow.com/q/50319663
tags question: http://stackoverflow.com/q/50310674
tags question: http://stackoverflow.com/q/50322340
tags question: http://stackoverflow.com/q/50381189
tags question: http://stackoverflow.com/q/50382559
tags question: http://stackoverflow.com/q/50249514
tags question: http://stackoverflow.com/q/50268279
tags question: http://stackoverflow.com/q/50299868
tags question: http://stackoverflow.com/q/50303654
tags question: http://stackoverflow.com/q/50383210
tags question: http://stackoverflow.com/q/50302209
tags question: http://stackoverflow.com/q/50323614
tags question: http://stackoverflow.com/q/50376214
tags question: http://stackoverflow.com/q/50286885
tags question: http://stackoverflow.com/q/50266500
tags question: http://stackoverflow.com/q/50274643
tags question: http://stackoverflow.com/q/50312432
tags question: http://stackoverflow.com/q/50251719
tags question: http://stackoverflow.com/q/50287283
tags question: http://stackoverflow.com/q/50332338
tags question: http://stackoverflow.com/q/50261869
type: Tag
tags question: http://stackoverflow.com/q/50264078
tags question: http://stackoverflow.com/q/50278818
tags question: http://stackoverflow.com/q/50291180
tags question: http://stackoverflow.com/q/50310021
tags question: http://stackoverflow.com/q/50303405
tags question: http://stackoverflow.com/q/50240423
tags question: http://stackoverflow.com/q/50281108
tags question: http://stackoverflow.com/q/50256979
tags question: http://stackoverflow.com/q/50239023
tags question: http://stackoverflow.com/q/50328617
tags question: http://stackoverflow.com/q/50289353
tags question: http://stackoverflow.com/q/50244970
tags question: http://stackoverflow.com/q/50319091
tags question: http://stackoverflow.com/q/50384704
tags question: http://stackoverflow.com/q/50382306
tags question: http://stackoverflow.com/q/50309021
tags question: http://stackoverflow.com/q/50236117
tags question: http://stackoverflow.com/q/50279436
tags question: http://stackoverflow.com/q/50270232
tags question: http://stackoverflow.com/q/50339004
tags question: http://stackoverflow.com/q/50288193
tags question: http://stackoverflow.com/q/50294963
tags question: http://stackoverflow.com/q/50249305
tags question: http://stackoverflow.com/q/50260744
tags question: http://stackoverflow.com/q/50249574
tags question: http://stackoverflow.com/q/50317869
tags question: http://stackoverflow.com/q/50256912
tags question: http://stackoverflow.com/q/50294318
tags question: http://stackoverflow.com/q/50339055
tags question: http://stackoverflow.com/q/50343117
tags question: http://stackoverflow.com/q/50363291
tags question: http://stackoverflow.com/q/50284830

http://stackoverflow.com/comment/87553473
has text: @Ben10 in my case, "import flask" and "import kivy" in new_project still work. Maybe I installed these before creating the virtual environment, I don't remember. I will test it again tomorrow. Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50267732

http://stackoverflow.com/q/50305326
has body: In my input file I have many lines, I am searching only one, which meets my requirements. And that's already done. But I need to print a line after this line which has been already found. Example of input: line 1 x line 2 a line 3 a line 3 a I am searching for line where is x inside. for lines in input: if 'x' in lines: print (lines) Result: line 1 x So now I need to show one line after my result Expected result: line 1 x line 2 a I also tried: for lines in input: if 'x' in lines: print (lines, '\n', lines[lines.index(lines) + 0:100])
tagged with: printing
score: 5
has comment: http://stackoverflow.com/comment/87626911
has title: Python: How to print one more line after my result from file?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50305370
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/50305370
type: AnsweredQuestion

http://stackoverflow.com/q/50337468
score: 2
downvote count: 0
has title: Python 3.6: Moving around words within a string
has answer: http://stackoverflow.com/a/50337566
has body: I know that this function moves around characters in a string, as such: def swapping(a, b, c): x = list(a) x[b], x[c] = x[c], x[b] return ''.join(x) Which allows me to do this: swapping('abcde', 1, 3) 'adcbe' swapping('abcde', 0, 1) 'bacde' But how can I get it to do something like this, so I'm not just moving around letters? This is what I want to accomplish: swapping("Boys and girls left the school.", "boys", "girls") swapping("Boys and girls left the school.", "GIRLS", "bOYS") should both have an output: "GIRLS and BOYS left the school." # Basically swapping the words that are typed out after writing down a string
answer count: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50338373
has answer: http://stackoverflow.com/a/50337791
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50338373
upvote count: 2
possible better answer: http://stackoverflow.com/a/50337566
tagged with: python
has comment: http://stackoverflow.com/comment/87692171
has comment: http://stackoverflow.com/comment/87691281
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50337565

http://stackoverflow.com/q/50261651
tagged with: matplotlib
tagged with: dataframe
has answer: http://stackoverflow.com/a/50261748
type: Question
has answer: http://stackoverflow.com/a/50261714
answer count: 2
type: UnansweredQuestion
has title: How to plot Pandas Dataframe data categorically instead of numerically in Python
tagged with: python
score: 0
has body: print(final) OUTPUT: intent sex age 2 Suicide F 21.0 3 Suicide M 60.0 4 Suicide M 64.0 5 Suicide M 31.0 7 Undetermined M 48.0 9 Accidental M 50.0 11 Suicide M 30.0 13 Suicide M 43.0 15 Homicide M 27.0 17 Suicide M 55.0 20 Suicide M 51.0 22 Suicide F 52.0 24 Suicide M 19.0 25 Homicide M 51.0 26 Homicide M 41.0 28 Suicide M 21.0 29 Suicide M 56.0 30 Homicide M 43.0 32 Suicide M 55.0 34 Suicide M 27.0 pro = final['intent'] == 'Suicide' suicide_df = final[pro] suicide_df.plot.bar('sex') plt.ylabel('age') plt.xlabel('sex') plt.show() So I just recently started taking some online classes for Data Science using Python and we're on the Panadas library now. I took a dataset from a csv file of Death rate and now have it in the form of a pandas dataframe that is represented as shown above... I wish to make the bar graph be categorized by gender so only showing two bars (one for male and one for female) and indicating how many of each died instead of how it is in the image attached. Any guidance appreciated.Graph of what displays so far
tagged with: pandas

http://stackoverflow.com/a/50383569
answers question: http://stackoverflow.com/q/50383554
score: 3
downvote count: 0
type: Answer
has body: You can do so with np.where: df['SKU_CB'] = np.where(df['ClosingBalance'] &gt; 1, df['SKU'], np.nan) Alternatively, in your use of np.select, you seem to have a problem with the second parameter: choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as condlist. So it probably should be df['SKU_CB'] = np.select(conditions, [df['SKU']], default=np.nan)
accepted answer of: http://stackoverflow.com/q/50383554
upvote count: 3
type: AcceptedAnswer

iterator
tags question: http://stackoverflow.com/q/50376618
tag name: iterator
tags question: http://stackoverflow.com/q/50234355
tags question: http://stackoverflow.com/q/50241838
tags question: http://stackoverflow.com/q/50338713
tags question: http://stackoverflow.com/q/50353330
tags question: http://stackoverflow.com/q/50320095
type: Tag

http://stackoverflow.com/comment/87762164
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50370443
has text: Yeah this would work if we want to run from any directory... But then I figured out that I have to cd into the directory containing manage.py and run the command it works equally
type: Comment

pygame
tags question: http://stackoverflow.com/q/50343013
tags question: http://stackoverflow.com/q/50378902
tags question: http://stackoverflow.com/q/50377124
tags question: http://stackoverflow.com/q/50312760
tag name: pygame
tags question: http://stackoverflow.com/q/50303616
tags question: http://stackoverflow.com/q/50280505
tags question: http://stackoverflow.com/q/50299695
tags question: http://stackoverflow.com/q/50324413
tags question: http://stackoverflow.com/q/50306351
tags question: http://stackoverflow.com/q/50344672
tags question: http://stackoverflow.com/q/50275846
tags question: http://stackoverflow.com/q/50373036
tags question: http://stackoverflow.com/q/50288147
tags question: http://stackoverflow.com/q/50235025
tags question: http://stackoverflow.com/q/50232714
tags question: http://stackoverflow.com/q/50280553
tags question: http://stackoverflow.com/q/50361308
tags question: http://stackoverflow.com/q/50242597
tags question: http://stackoverflow.com/q/50261024
tags question: http://stackoverflow.com/q/50257565
tags question: http://stackoverflow.com/q/50378111
tags question: http://stackoverflow.com/q/50311708
tags question: http://stackoverflow.com/q/50287124
tags question: http://stackoverflow.com/q/50336853
tags question: http://stackoverflow.com/q/50260349
tags question: http://stackoverflow.com/q/50283552
tags question: http://stackoverflow.com/q/50318132
tags question: http://stackoverflow.com/q/50274201
tags question: http://stackoverflow.com/q/50301399
tags question: http://stackoverflow.com/q/50376112
tags question: http://stackoverflow.com/q/50348125
tags question: http://stackoverflow.com/q/50341569
tags question: http://stackoverflow.com/q/50305133
tags question: http://stackoverflow.com/q/50351500
tags question: http://stackoverflow.com/q/50253465
tags question: http://stackoverflow.com/q/50375742
tags question: http://stackoverflow.com/q/50263472
tags question: http://stackoverflow.com/q/50309671
tags question: http://stackoverflow.com/q/50280864
tags question: http://stackoverflow.com/q/50300681
tags question: http://stackoverflow.com/q/50242122
tags question: http://stackoverflow.com/q/50239200
tags question: http://stackoverflow.com/q/50280144
type: Tag
tags question: http://stackoverflow.com/q/50375708

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

http://stackoverflow.com/q/50284753
score: 72
has answer: http://stackoverflow.com/a/53919435
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14814201
has answer: http://stackoverflow.com/a/50285851
has answer: http://stackoverflow.com/a/71481849
has body: While I am running Flask code from my command line, a warning is appearing: Serving Flask app "hello_flask" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. What does this mean?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/97001491
has answer: http://stackoverflow.com/a/76285048
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50820008
has answer: http://stackoverflow.com/a/62026968
tagged with: flask
answer count: 13
has answer: http://stackoverflow.com/a/54552194
has answer: http://stackoverflow.com/a/53918402
upvote count: 72
has title: Warning message while running Flask
has answer: http://stackoverflow.com/a/70952831
has answer: http://stackoverflow.com/a/53166103
has answer: http://stackoverflow.com/a/57957012
has answer: http://stackoverflow.com/a/70619952
has answer: http://stackoverflow.com/a/51627468

http://stackoverflow.com/a/50257119
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87532523
has body: Using isin df.apply(lambda x : x.str.split('_').str[0],1).isin(l).sum(1).eq(2).sum() Out[923]: 3 Adding value_counts df.apply(lambda x : x.str.split('_').str[0],1).isin(l).sum(1).value_counts() Out[925]: 2 3 0 2 dtype: int64
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/87532771
answers question: http://stackoverflow.com/q/50256344
has comment: http://stackoverflow.com/comment/87532735

http://stackoverflow.com/comment/87571009
type: QuestionComment
comment on: http://stackoverflow.com/q/50277215
has text: Can you add an example of what you are expecting? Bas64 will just provide a representation for the raw data.
score: 1
type: Comment

http://stackoverflow.com/comment/87551359
type: AnswerComment
comment on: http://stackoverflow.com/a/50264458
score: 0
type: Comment
has text: Recommend passing `many=True` as an argument to `UserFilteredPrimaryKeyRelatedField` to enable multi-select. Currently it only allows you to select just one Tag from a dropdown.

http://stackoverflow.com/comment/87625694
score: 0
type: Comment
type: QuestionComment
has text: Lines read from files end with an *eoln*. Isn't the rest of the text printed on the next line?
comment on: http://stackoverflow.com/q/50304647

http://stackoverflow.com/q/50340629
has answer: http://stackoverflow.com/a/50340636
tagged with: exit
has comment: http://stackoverflow.com/comment/87697628
has comment: http://stackoverflow.com/comment/87698070
tagged with: python
has comment: http://stackoverflow.com/comment/87697425
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87698170
answer count: 2
downvote count: 4
upvote count: 0
type: UnansweredQuestion
has body: I am trying to stop my program in a specific spot and it won't shut. I used this to stop the program: Raise SystemExit(0)
score: -4
has title: Can't get out of the program through code
favorite count: 0
has answer: http://stackoverflow.com/a/50340681

http://stackoverflow.com/comment/87634960
type: QuestionComment
has text: I have even restarted my PC multiple times. The main issue is not with terminal window as I can use main terminal but the import. packages are not being detected even after setting interpreter
score: 0
comment on: http://stackoverflow.com/q/50309076
type: Comment

http://stackoverflow.com/q/50350496
possible better answer: http://stackoverflow.com/a/50350592
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50350554
has answer: http://stackoverflow.com/a/50350592
favorite count: 0
type: AnsweredQuestion
tagged with: apache-spark
score: 1
has body: I wanted to do a simple thing. I wanted to bucket all event counts into timestamps of say 2 minutes. It works fine. df = df.groupBy(window(df["time_value"], "2 minutes")).count() df.show() +--------------------+-----+ | window|count| +--------------------+-----+ |[2018-04-10 15:00...| 770| |[2018-04-10 00:42...| 100| |[2018-04-10 04:14...| 54| |[2018-04-06 15:54...| 36| |[2018-04-10 04:46...| 304| |[2018-04-10 20:36...| 347| |[2018-04-10 03:26...| 41| |[2018-04-10 21:10...| 85| |[2018-04-10 11:44...| 426| |[2018-04-10 12:32...| 754| |[2018-04-10 00:28...| 61| |[2018-04-10 05:36...| 478| |[2018-04-06 07:04...| 18| |[2018-04-10 22:14...| 195| |[2018-04-10 23:40...| 175| |[2018-04-10 00:20...| 229| |[2018-04-10 03:10...| 209| |[2018-04-10 01:28...| 67| |[2018-04-09 18:52...| 9| |[2018-04-10 19:06...| 3548| +--------------------+-----+ only showing top 20 rows But now that I write it, df.write.csv("good_loc.csv") An error occurred while calling o161.csv. : java.lang.UnsupportedOperationException: CSV data source does not support struct&lt;start:timestamp,end:timestamp&gt; data type. at org.apache.spark.sql.execution.datasources.csv.CSVUtils$.org$apache$spark$sql$execution$datasources$csv$CSVUtils$$verifyType$1(CSVUtils.scala:127) at org.apache.spark.sql.execution.datasources.csv.CSVUtils$$anonfun$verifySchema$1.apply(CSVUtils.scala:131) at org.apache.spark.sql.execution.datasources.csv.CSVUtils$$anonfun$verifySchema$1.apply(CSVUtils.scala:131) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.IterableLike$class.foreach(IterableLike.scala:72) at org.apache.spark.sql.types.StructType.foreach(StructType.scala:98) at org.apache.spark.sql.execution.datasources.csv.CSVUtils$.verifySchema(CSVUtils.scala:131) at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat.prepareWrite(CSVFileFormat.scala:65) at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(Fil…
accepted answer: http://stackoverflow.com/a/50350554
type: Question
tagged with: apache-spark-sql
answer count: 2
has title: Apache Spark: Can't save Grouped Data as CSV
downvote count: 0
tagged with: pyspark

http://stackoverflow.com/comment/87599031
type: Comment
has text: @OderaOkonkwo copy paste the above code. It should work.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50285748

http://stackoverflow.com/comment/87640527
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ “can” in what context?
score: 0
comment on: http://stackoverflow.com/q/50311985
type: Comment

http://stackoverflow.com/q/50308479
has body: I have a pre-trained net I want to use in order to evaluate loss in my Keras net. The pre-trained network was trained using TensorFlow and I just want to use it as part of my loss calculation. The code of my custom loss function is currently: def custom_loss_func(y_true, y_pred): # Get saliency of both true and pred sal_true = deep_gaze.get_saliency_map(y_true) sal_pred = deep_gaze.get_saliency_map(y_pred) return K.mean(K.square(sal_true-sal_pred)) Where deep_gaze is an object that is ment to manage the access to the external pre-trained net I am using. It is defined this way: class DeepGaze(object): CHECK_POINT = os.path.join(os.path.dirname(__file__), 'DeepGazeII.ckpt') # DeepGaze II def __init__(self): print('Loading Deep Gaze II...') with tf.Graph().as_default() as deep_gaze_graph: saver = tf.train.import_meta_graph('{}.meta'.format(self.CHECK_POINT)) self.input_tensor = tf.get_collection('input_tensor')[0] self.log_density_wo_centerbias = tf.get_collection('log_density_wo_centerbias')[0] self.tf_session = tf.Session(graph=deep_gaze_graph) saver.restore(self.tf_session, self.CHECK_POINT) print('Deep Gaze II Loaded') ''' Returns the saliency map of the input data. input format is a 4d array [batch_num, height, width, channel] ''' def get_saliency_map(self, input_data): log_density_prediction = self.tf_session.run(self.log_density_wo_centerbias, {self.input_tensor: input_data}) return log_density_prediction When I run this I get the error: TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles. What am I doing wrong? Is there a way to evaluate a net on a TensorFlow object coming for a different net (that was made by Keras with a TensorFlow backend). Thanks in advance.
type: UnansweredQuestion
tagged with: python
tagged with: keras
has title: How to use a pre-trained TensorFlow net in Keras loss function
score: 0
tagged with: deep-learning
answer count: 1
tagged with: loss-function
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50310930
type: Question

sqlite
tags question: http://stackoverflow.com/q/50323204
tags question: http://stackoverflow.com/q/50327559
tags question: http://stackoverflow.com/q/50309626
tags question: http://stackoverflow.com/q/50372753
tags question: http://stackoverflow.com/q/50238190
tags question: http://stackoverflow.com/q/50294159
tags question: http://stackoverflow.com/q/50280523
tags question: http://stackoverflow.com/q/50357142
tags question: http://stackoverflow.com/q/50235979
tags question: http://stackoverflow.com/q/50329807
tags question: http://stackoverflow.com/q/50310338
type: Tag
tags question: http://stackoverflow.com/q/50322966
tags question: http://stackoverflow.com/q/50302589
tags question: http://stackoverflow.com/q/50295900
tags question: http://stackoverflow.com/q/50298315
tags question: http://stackoverflow.com/q/50257851
tags question: http://stackoverflow.com/q/50284691
tags question: http://stackoverflow.com/q/50374307
tags question: http://stackoverflow.com/q/50313386
tags question: http://stackoverflow.com/q/50324400
tags question: http://stackoverflow.com/q/50312860
tags question: http://stackoverflow.com/q/50346372
tags question: http://stackoverflow.com/q/50342960
tag name: sqlite
tags question: http://stackoverflow.com/q/50350535
tags question: http://stackoverflow.com/q/50381616
tags question: http://stackoverflow.com/q/50376345

input
tags question: http://stackoverflow.com/q/50241171
tags question: http://stackoverflow.com/q/50311959
tags question: http://stackoverflow.com/q/50352493
tags question: http://stackoverflow.com/q/50361325
tags question: http://stackoverflow.com/q/50237523
tags question: http://stackoverflow.com/q/50294906
tags question: http://stackoverflow.com/q/50366439
tags question: http://stackoverflow.com/q/50381530
tag name: input
tags question: http://stackoverflow.com/q/50301594
type: Tag
tags question: http://stackoverflow.com/q/50288583
tags question: http://stackoverflow.com/q/50279114
tags question: http://stackoverflow.com/q/50255556
tags question: http://stackoverflow.com/q/50249166

http://stackoverflow.com/q/50243130
has answer: http://stackoverflow.com/a/50259126
accepted answer: http://stackoverflow.com/a/50259126
has comment: http://stackoverflow.com/comment/87510898
answer count: 1
has body: I'm running PyCharm 2018.2 on a Mac and executing a pyspark program. Spark was installed in the virtualenv. I need to use external jars (specifically, the AWS s3 jars) in my pyspark script, so I use the following to declare the maven dependancy: import os os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages "org.apache.hadoop:hadoop-aws:2.7.3" pyspark-shell' conf = SparkConf() \ .setMaster("local[2]") \ .setAppName("pyspark-unittests") \ .set("spark.sql.parquet.compression.codec", "snappy") sc = SparkContext(conf=conf) On my home network, this works great. On my corporate network, there is an SSL inspector between me and the internet that swaps the SSL certificates on the HTTPS requests to Maven Central. This results in the below error message: Server access error at url https://repo1.maven.org/maven2/joda-time/joda-time/maven-metadata.xml (javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target) I know this is because the SSL certificates that the SSL inspector signed the HTTPS response with are not trusted by the JVM executed by pyspark. I have .cer copies of the intermediate certificates that are signing the HTTPS response. Which JVM is being used in this specific case (python/pyspark running in PyCharm) and how can I update the certificates in that JVM's trust store?
has comment: http://stackoverflow.com/comment/87532572
favorite count: 0
has title: How do I update the Java keystore used by pyspark running in PyCharm on Mac?
type: Question
linked to: http://stackoverflow.com/q/11617210
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87532425
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/87535732
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/50294143
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87606074
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87606957
answers question: http://stackoverflow.com/q/50293970
has comment: http://stackoverflow.com/comment/87607098
has comment: http://stackoverflow.com/comment/87606865
accepted answer of: http://stackoverflow.com/q/50293970
has comment: http://stackoverflow.com/comment/87607194
type: Answer
has body: If you have set app_name in your core/urls.py or set a namespace when including the urls then you'll need to include this. For example: path('&lt;slug:slug&gt;/', RedirectView.as_view(pattern_name='core:deal_detail', permanent=False))
has comment: http://stackoverflow.com/comment/87606256
has comment: http://stackoverflow.com/comment/87606508
score: 1

http://stackoverflow.com/a/50365207
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50365138
has comment: http://stackoverflow.com/comment/87746860
answers question: http://stackoverflow.com/q/50365138
type: Answer
has body: A trivial solution might be, OS.write(ip + re.search(version, data).group(0).rjust(30 - len(ip)) + '\n')
score: 0
has comment: http://stackoverflow.com/comment/87746700

http://stackoverflow.com/comment/87663316
has text: One of best describtions about Hilbert's curve: https://www.youtube.com/watch?v=3s7h2MHQtxc Each node in the grid is one partition of your cache and Hilbert's curve guides you trough each "node coordinate".
comment on: http://stackoverflow.com/q/50323760
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50326506
score: 4
answers question: http://stackoverflow.com/q/50318247
has comment: http://stackoverflow.com/comment/87689857
type: AcceptedAnswer
has body: It happens because your image is in RGBA mode (your background is transparent). so you need to read your image in RGBA mode as: image = cv2.imread('path/to/image.png',-1) or: from scipy.ndimage import imread rgba = imread('path/to/image.png', mode='RGBA') the result:
upvote count: 4
has comment: http://stackoverflow.com/comment/87672784
accepted answer of: http://stackoverflow.com/q/50318247
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87754987
comment on: http://stackoverflow.com/a/50367621
type: AnswerComment
score: 0
has text: @Triguna: `glob` is in the *standard library*, just like `os` and `os.path` are. But sure, under the hood, the implementation is not much different from what the other answer proposes, but that version only covers the 'matching extension' case, while mine covers the general pattern matching case. For example, the moment you want to extend your pattern to include a prefix such as `foobar*.csv`, matching the various parts manually becomes more cumbersome without `glob.glob()`.
type: Comment

sendkeys
tags question: http://stackoverflow.com/q/50287106
type: Tag
tag name: sendkeys
tags question: http://stackoverflow.com/q/50310148

http://stackoverflow.com/comment/87481920
comment on: http://stackoverflow.com/q/50231627
has text: Unfortunately, it is not possible to use fixtures as parametrization source, see [this issue](https://github.com/pytest-dev/pytest/issues/349). There exists a plugin that implements this feature: [`pytest-lazy-fixture`](https://github.com/TvoroG/pytest-lazy-fixture), you can try that out if you want. However, in your particular example, the `values` fixture has no args and can be easily used as a plain function, so you can just mark the test with `@pytest.mark.parametrize('value', values())`.
type: QuestionComment
type: Comment
score: 4

http://stackoverflow.com/q/50231166
has answer: http://stackoverflow.com/a/50231530
upvote count: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/87480018
has comment: http://stackoverflow.com/comment/87480119
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to extract the rows from a webpage into a dataframe. I get an error because I do not understand how to put the code for the first element and the last element in the find_element partю I do understand this exists, but I still do not get it how to actually extract the table from the link. I am using Сhrome, so I do right-click and inspect. But I do not know where to take it from there to actually get the right code to put it in the find_element to extract the rows of results. What am I trying to do? I am trying to extract the rows in the search result and put it in a dataframe/table in Python. What do I put in these parts to be able to extract all the columns and rows of the link: elem = browser.find_elements_by_class_name("") post_elems = browser.find_elements_by_class_name("") The output will be the following table with its data: Products Released | Lifecycle Start Date | Mainstream Support End Date |Extended Support End Date |Service Pack Support End Date | Notes
has title: How to Extract Rows of Data into a DataFrame using Selenium
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50231530
has comment: http://stackoverflow.com/comment/87479937
has comment: http://stackoverflow.com/comment/87479955

http://stackoverflow.com/comment/87506914
has text: @Wizard there are actually two ways to represent a heap as an array. A 0-based approach where the children of n are located at 2n+1 and 2n+2 and a 1-based approach, as you stated with children at 2n and 2n+1.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50234921
score: 0

http://stackoverflow.com/comment/87700592
score: 0
has text: I see you still have a missing `/` in your url patterns: `url(r'^equipment/(?P<pk>\d+)/$', views.EquipmentDetailView.as_view(), name='equipment-detail')`. You are still missing a `slash(/)` after `url(r'^equipment`
comment on: http://stackoverflow.com/a/50281825
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87506062
has text: How does this come to be in the first-place? Anyway, use [this answer](https://stackoverflow.com/questions/32468402/how-to-explode-a-list-inside-a-dataframe-cell-into-separate-rows?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) to "explode" the lists into the data-frame. But first, use `import ast` and `df['Elements'] = df.Elements.map(ast.literal_eval)`. Note that this will be slow, and you'll feel it on huge data-frames, but this is unavoidable unless you fix the situation that got you into this in the first place (I suspect this is an X-Y problem to begin with)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50244149
score: 0

http://stackoverflow.com/q/50238135
score: 1
tagged with: signals
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87494546
type: Question
has comment: http://stackoverflow.com/comment/87495026
tagged with: exception
tagged with: windows
tagged with: python
has title: Could not interrupt threaded Python console app using keyboard Ctrl+C on Windows
accepted answer: http://stackoverflow.com/a/50238989
has body: I could not interrupt my threaded Python production app using Ctrl+C on Windows, it continues running, tried both exception and signal handling. Here is very simplified version of code, that does not interrupts. Single thread app terminates fine, same as multithreaded Linux version. Could anybody help with this trouble? Thanks in advance. import threading import time class FooThread(threading.Thread): stop_flag = False def __init__(self): threading.Thread.__init__(self) def run(self): while not self.stop_flag: print(1) time.sleep(1) t = FooThread() t.start() try: t.join() except KeyboardInterrupt: t.stop_flag = True t.join()
has answer: http://stackoverflow.com/a/50238989
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87494120

http://stackoverflow.com/q/50285479
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50363024
has comment: http://stackoverflow.com/comment/87587218
tagged with: chat
type: AnsweredQuestion
has body: I am using Python 3.6 ,Django 1.11 and chennels=2. I am following this tutorial and it works fine till tutorial part 2: http://channels.readthedocs.io/en/stable/tutorial/part_2.html When i moved to tutorial part 3 and changed ChatConsumer file accordingly: http://channels.readthedocs.io/en/stable/tutorial/part_3.html I am facing this issue ImportError: cannot import name 'AsyncWebsocketConsumer' Consumer.py: from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) Error: Any kind of will be appreciated!
answer count: 2
has title: How to solve the error ImportError: cannot import name 'AsyncWebsocketConsumer'?
possible better answer: http://stackoverflow.com/a/50285500
has comment: http://stackoverflow.com/comment/87587852
has answer: http://stackoverflow.com/a/50285500
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87587590
has comment: http://stackoverflow.com/comment/87587291
has comment: http://stackoverflow.com/comment/87742262
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87587411
tagged with: django-channels
accepted answer: http://stackoverflow.com/a/50363024
has comment: http://stackoverflow.com/comment/87589427

http://stackoverflow.com/a/50525113
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50294375
has body: I have resolved the issue: simply i have to convert right ascension and declination from degree to radian. Now, the method works.
type: Answer
accepted answer of: http://stackoverflow.com/q/50294375
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50308629
favorite count: 0
type: Question
has body: I have pandas like below: Runner time 1 A 3.05.3 #( 3 minute 5 second and 3 millisecond) 2 B 2.50.2 #( 2 minute 50 second and 2 millisecond) Actually I want to compare the time so I want to change to time column to second unit or millisecond unit. How can I do it in pandas? I am thinking if can I strptime?
has answer: http://stackoverflow.com/a/50308720
answer count: 2
has answer: http://stackoverflow.com/a/50311112
possible better answer: http://stackoverflow.com/a/50311112
downvote count: 0
tagged with: timedelta
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/50308720
tagged with: pandas
upvote count: 3
tagged with: python
has title: Python pandas column convert minutes to second

http://stackoverflow.com/a/50355066
type: Answer
answers question: http://stackoverflow.com/q/50323471
has body: In your template: {% url 'admin:reconcileConfirm'%} in urls.py: urlpatterns = [ url(r'^reconcileConfirm/', views.ReconcileConfirm, name='ReconcileConfirm') ] Note that ReconcileConfirm is different from reconcileConfirm. This is probably the first error to fix in order to achieve what you want to.
score: 0

http://stackoverflow.com/comment/87671055
score: 0
comment on: http://stackoverflow.com/q/50327518
has text: Take a look at https://stackoverflow.com/questions/10445176/how-to-write-a-query-to-get-find-value-in-a-json-field-in-django
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50336290
has comment: http://stackoverflow.com/comment/87728949
has body: plt.errorbar() generates a three separate objects: the line between points, the lines for each errorbar cap (if any), and a matplotlib.collections.LineCollection containing the errorbar lines themselves. The ecolor argument is ultimately passed to matplotlib.collections.LineCollection.set_color(), which accepts a: Matplotlib color argument (all patches have the same color) or a sequence of rgba tuples; if it is a sequence the patches will cycle through the sequence. Your array cc is neither of these. The method receives a sequence, so it tries to set the color of each line in the collection to each element of the sequence. But those elements are just single floats, which are not valid matplotlib colors. To fix this, generate a list of tuples, with each tuple specifying the RGB[A] color of the line segments for each errrorbar. For example, using the other data you specified in your question, the colors can be set as: cc = np.random.rand(aa.size, 3) # Random colors, RGB tuples uniform on (0, 1) collections = plt.errorbar(aa, bb, yerr=e_bb, xerr=e_aa, fmt='none', ecolor=cc) This generates a plot like so:
score: 2
has comment: http://stackoverflow.com/comment/87729725
type: Answer
has comment: http://stackoverflow.com/comment/87729178
has comment: http://stackoverflow.com/comment/87736562
answers question: http://stackoverflow.com/q/50335544
upvote count: 2
has comment: http://stackoverflow.com/comment/87739414
downvote count: 0

http://stackoverflow.com/q/50361720
favorite count: 0
type: Question
has body: shutil.move(src, dst) is what I feel will do the job, however, as per the Python 2 documentation: shutil.move(src, dst) Recursively move a file or directory (src) to another location (dst). If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. This is a little bit different than my case as below: Before the move: https://snag.gy/JfbE6D.jpg shutil.move(staging_folder, final_folder) After the move: https://snag.gy/GTfjNb.jpg This is not what I want, I want all the content in the staging folder be moved over to under folder "final" , I don't need "staging" folder itself.
has answer: http://stackoverflow.com/a/50361767
possible better answer: http://stackoverflow.com/a/68509894
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50425385
answer count: 3
has title: Move folder contents without moving the source folder
has answer: http://stackoverflow.com/a/50425385
has answer: http://stackoverflow.com/a/68509894
downvote count: 0
tagged with: shutil

http://stackoverflow.com/a/50370598
upvote count: 2
downvote count: 0
has body: GNU awk solution using 2d arrays, ARGIND and column -t for pretty printing. It supports more than two files: $ awk ' { a[$1][ARGIND]=$2 } # hash to 2d array END { for(i in a) { # iterate all a printf "%s",i # output key for(j=1;j&lt;=ARGIND;j++) # iterate all data in a printf "%s%s", OFS, (a[i][j]==""?"-":a[i][j]) # output print "" # finish with a newline } }' file1 file2 file1 file2 | column -t # pretty print C1-C2-C3 59.78 59.95 59.78 59.95 O4-C3 1.4104 - 1.4104 - S4-C3 - 1.7976 - 1.7976 C3-C1 1.4991 1.5037 1.4991 1.5037 C3-C2 1.49 1.505 1.49 1.505 C2-C1 1.5183 1.5052 1.5183 1.5052
type: Answer
score: 2
answers question: http://stackoverflow.com/q/50368838

http://stackoverflow.com/comment/87764271
type: QuestionComment
has text: ya tried it above solution , it was not working , it will also give errors nested serializer write operations is not allowed for phone and email
score: 0
comment on: http://stackoverflow.com/q/50367739
type: Comment

http://stackoverflow.com/q/50265993
linked to: http://stackoverflow.com/q/42266737
has answer: http://stackoverflow.com/a/50266037
type: AnsweredQuestion
tagged with: cross-validation
has comment: http://stackoverflow.com/comment/87549882
tagged with: grid-search
tagged with: python
has title: Alternate different models in Pipeline for GridSearchCV
has body: I want to build a Pipeline in sklearn and test different models using GridSearchCV. Just an example (please do not pay attention on what particular models are chosen): reg = LogisticRegression() proj1 = PCA(n_components=2) proj2 = MDS() proj3 = TSNE() pipe = [('proj', proj1), ('reg' , reg)] pipe = Pipeline(pipe) param_grid = { 'reg__c': [0.01, 0.1, 1], } clf = GridSearchCV(pipe, param_grid = param_grid) Here if I want to try different models for dimensionality reduction, I need to code different pipelines and compare them manually. Is there an easy way to do it? One solution I came up with is define my own class derived from base estimator: class Projection(BaseEstimator): def __init__(self, est_name): if est_name == "MDS": self.model = MDS() ... ... def fit_transform(self, X): return self.model.fit_transform(X) I think it will work, I just create a Projection object and pass it to Pipeline, using names of the estimators as parameters for it. But to me this way is a bit chaotic and not scalable: it makes me to define new class each time I want to compare different models. Also to continue this solution, one could implement a class that does the same job, but with arbitrary set of models. It seems overcomplicated to me. What is the most natural and pythonic way to compare different models?
favorite count: 0
type: Question
score: 12
tagged with: pipeline
answer count: 2
possible better answer: http://stackoverflow.com/a/54024093
upvote count: 12
has answer: http://stackoverflow.com/a/54024093
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50266037

http://stackoverflow.com/comment/87726766
has text: BTW, redirecting stderr changes the way bash behaves in some respects that might be more substantial than you intend. stderr is where the prompt is printed, for example.
comment on: http://stackoverflow.com/q/50354155
type: Comment
type: QuestionComment
score: 0

always-on-top
tags question: http://stackoverflow.com/q/50314646
tag name: always-on-top
type: Tag

http://stackoverflow.com/comment/87522123
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50239245
has text: so `np.subtract(rgb_images, mean, out=rgb_images)` works? Or would it cause problems to write into the same array as the one used as the first argument? And what is the difference compared to `rgb_images -= mean`?

http://stackoverflow.com/comment/87503259
has text: You could try `import matplotlib.pyplot as plt` and instead of last two lines: `plt.savefig('test2.png')`
score: 2
comment on: http://stackoverflow.com/q/50242695
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50322699
has body: I was trying to run a python tool called "read_fast5_basecaller.py". It throws an error which is "AttributeError: module 'h5py.tests.old' has no attribute 'MODULES'" read_fast5_basecaller.py Traceback (most recent call last): File "/home/kokep/bin/bin/read_fast5_basecaller.py", line 73, in &lt;module&gt; from albacore.fast5_fastq_data_handler import Fast5FastQDataHandler File "/home/kokep/bin/lib/python3.6/site-packages/albacore/fast5_fastq_data_handler.py", line 14, in &lt;module&gt; from albacore.fast5_data_handler import Fast5DataHandler File "/home/kokep/bin/lib/python3.6/site-packages/albacore/fast5_data_handler.py", line 15, in &lt;module&gt; from albacore.read_metadata import ReadMetadata File "/home/kokep/bin/lib/python3.6/site-packages/albacore/read_metadata.py", line 5, in &lt;module&gt; from ont_fast5_api.fast5_file import Fast5File File "/home/kokep/bin/lib/python3.6/site-packages/ont_fast5_api/fast5_file.py", line 5, in &lt;module&gt; import h5py File "/home/kokep/bin/lib/python3.6/site-packages/h5py/__init__.py", line 62, in &lt;module&gt; from .tests import run_tests File "/home/kokep/bin/lib/python3.6/site-packages/h5py/tests/__init__.py", line 17, in &lt;module&gt; MODULES = old.MODULES + hl.MODULES AttributeError: module 'h5py.tests.old' has no attribute 'MODULES' I was wondering if old module of h5py is needed. Should I install the older version of the h5py module? Thank you.
type: UnansweredQuestion
tagged with: python
has title: AttributeError: module 'h5py.tests.old' has no attribute 'MODULES'
score: 2
answer count: 0
upvote count: 2
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/50382120
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/87782620
answers question: http://stackoverflow.com/q/50382014
has body: Well, the network performance of the t2.medium instances is very poor, and the CPU usage is burstable so if you use all your credits the performance goes down, and the system becomes slow. Consider using an instance with better performance. To diagnosticate the package loss issue the best way is to activate the vpc-flow-logs this is like a sniffer put in your network so you could track all the packages to do it see https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/flow-logs.html
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87781594
accepted answer of: http://stackoverflow.com/q/50382014
upvote count: 3

http://stackoverflow.com/q/50337243
has title: How to extract the n-th elements equal to a value from a list of tuples in python
favorite count: 0
type: Question
tagged with: tuples
possible better answer: http://stackoverflow.com/a/50337298
has answer: http://stackoverflow.com/a/50337298
has comment: http://stackoverflow.com/comment/87690798
tagged with: python
has comment: http://stackoverflow.com/comment/87690735
accepted answer: http://stackoverflow.com/a/50337310
has body: I'm trying to obtain the nth elements from a list of tuples in python equal to a certain value I have a much larger list of something like this num = [('A15', 2, 'BC', 721.16), ('A21', 3, 'AB', 631.31), ('A42', 4, 'EE', 245.43)] I wish to extract only the tuples with the 2nd element of the tuple equal to a given value i.e. 2 in this example and from those find the largest 4th element Currently my code looks like the following for ((x[1] for x in num) = 1): num_max = max(num_list,key=lambda item:item[3]) the problem's something to do with setting the list comprehension equal to a value as that's what's giving me a syntax error Apologies if this has already been answered but I couldn't find it
has comment: http://stackoverflow.com/comment/87690696
type: AnsweredQuestion
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/50337310
answer count: 2
upvote count: 2
tagged with: max
has comment: http://stackoverflow.com/comment/87690715
downvote count: 0

http://stackoverflow.com/a/50293460
downvote count: 0
answers question: http://stackoverflow.com/q/50293407
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87604936
accepted answer of: http://stackoverflow.com/q/50293407
has comment: http://stackoverflow.com/comment/87603584
has comment: http://stackoverflow.com/comment/87603409
score: 6
upvote count: 6
type: Answer
has body: strip removes all the given characters from both ends of your string, whatever order they occur in. If your string is c.gcom, then strip('.gcom') removes all the characters ., g, c, o and m from the ends of your string, leaving nothing left. It doesn't stop stripping until it hits a character that is not ., g, c, o or m (or removes everything). If you have a string ending in .gcom, and you just want to remove that ending, you can use: z = file[:-5] or, using your com_ext variable com_ext = '.gcom' ... if file.endswith(com_ext): z = file[:-len(com_ext)]

http://stackoverflow.com/comment/87496061
has text: I think the issue is with Canopy - I have to install curl and pycurl as a package inside Canopy, else the python script errors out on the import statement. Command line python curl to https now works fine, but not from within Canopy.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50234607

http://stackoverflow.com/q/50239408
type: Question
has answer: http://stackoverflow.com/a/50241929
type: UnansweredQuestion
has title: Python: Pandas Dataframe Create Individual Horizontal Bar charts for Each Distinct Category In Dataframe
tagged with: bar-chart
tagged with: python
score: 0
answer count: 1
tagged with: categories
tagged with: loops
has body: I have the following dataframe: Mon Year Ratio Value Category Jan 2016 0.024454035 A 2017 0.048216976 A 2018 0.064599633 A Feb 2016 0.039955399 A 2017 0.038249422 A 2018 0.040955116 A Mar 2016 0.047335373 A 2017 0.095655431 A 2018 0.018486543 A Jan 2016 0.014454035 B 2017 0.018216976 B 2018 0.064599633 B Feb 2016 0.039955399 B 2017 0.083824942 B 2018 0.080955116 B Mar 2016 0.047335373 B 2017 0.035655431 B 2018 0.078486543 B Jan 2016 0.024454035 C 2017 0.018216976 C 2018 0.024599633 C Feb 2016 0.039955399 C 2017 0.023824942 C 2018 0.080955116 C Mar 2016 0.037335373 C 2017 0.035655431 C 2018 0.008486543 C I want to create a bar chart in Python (one chart per distinct category). So I would have three separate charts A, B, C. I want the y-axis to show 'Mon' column and the three years associated with the month. I want the horizontal axis (x-axis) to show the ratio value. Below is a hypothetical sample of one of the charts I want to produce (numbers do not match my example provided): Since I have three categories in my dataframe, I would have three of these charts. I have scoured Google but couldn't find anything to help me get this.

http://stackoverflow.com/comment/87482985
has text: Thank you for your feedback ! but i'm a beginner and i haven't find in visual studio 2017 where to change the encoding to utf-8 ?
type: Comment
comment on: http://stackoverflow.com/a/50232246
score: 0
type: AnswerComment

http://stackoverflow.com/q/50236792
upvote count: 0
has comment: http://stackoverflow.com/comment/87491112
downvote count: 2
has comment: http://stackoverflow.com/comment/87491315
answer count: 1
has comment: http://stackoverflow.com/comment/87491151
has body: Writing a recursive function that only takes ints that are a power of 2, and should print this pattern: &gt;&gt;&gt; pattern(1) 1 &gt;&gt;&gt; pattern(2) 112 &gt;&gt;&gt; pattern(4) 1121124 &gt;&gt;&gt; pattern(8) 112112411211248 I have the following: def pattern(n): if n == 1: print(1) else: pattern(n-1) print(n,end='') pattern(n-1) The pattern is outputting an incorrect format...I'm not sure how to phrase the else statement above. the output I get is: &gt;&gt;&gt; pattern(1) 1 &gt;&gt;&gt; pattern(2) 1 2 1
has comment: http://stackoverflow.com/comment/87491196
has comment: http://stackoverflow.com/comment/87490952
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87490958
tagged with: recursion
type: UnansweredQuestion
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/50237014
has comment: http://stackoverflow.com/comment/87491158
has title: Python recursive function that prints a pattern

http://stackoverflow.com/comment/87772289
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50377905
score: 1
has text: You forget to register your app, by adding it inside `settings.INSTALLED_APPS`

http://stackoverflow.com/comment/89546664
has text: but mask is not displayed, no one answer me i don't know what to do
score: 0
comment on: http://stackoverflow.com/q/50288416
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87739983
has text: I was asking as I am getting an **AttributeError at /admin/api/profile/ 'Banned_User' object has no attribute 'user_reported_report'** with the code `banned_user = profile.banned_profile.create(profile=profile) for report in user_reports: banned_user.user_reported_report.add(user_reported=profile,sent_by=report.sent_by)`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50361307
type: Comment

http://stackoverflow.com/comment/87779512
comment on: http://stackoverflow.com/a/50381592
has text: I didn't say there was anything wrong with using a `for` loop per se, @juanpa.arrivillaga. I simply asked the OP why, in this case, he was using one, since there were better options.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50267567
has body: It looks like the actual error that is happening is: scp: /tmp: not a regular file Which is likely due to /tmp/ being a directory and not a file on the remote server. You should be able to recursively copy files by passing the -r argument to scp. See this question for more details.
has comment: http://stackoverflow.com/comment/87586158
type: Answer
answers question: http://stackoverflow.com/q/50266925
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/50289947
type: AnsweredQuestion
has title: Visualize a SVM model having100 attributes in 2D plot python
accepted answer: http://stackoverflow.com/a/50290731
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/50290731
tagged with: text-classification
has body: I am using SVM for text classification (tf-idf score based classification). Is it possible to plot SVM having more than 100 attributes and 10 labels. Is there any way to reduce the features and then plot the same multiclass SVM.
tagged with: plot
favorite count: 0
type: Question
score: 1
tagged with: python
tagged with: svm

http://stackoverflow.com/comment/106315098
has text: Does this answer your question? [How do I get Flake8 to work with F811 errors?](https://stackoverflow.com/questions/43746413/how-do-i-get-flake8-to-work-with-f811-errors)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50268284
score: 0

http://stackoverflow.com/a/50301228
has comment: http://stackoverflow.com/comment/87619980
has comment: http://stackoverflow.com/comment/87620009
has comment: http://stackoverflow.com/comment/87619918
has comment: http://stackoverflow.com/comment/87620023
has body: This should work: def square(n): import math if (n &lt; 0): return False if (int(math.sqrt(n)) == math.sqrt(n)): return True else: return False
answers question: http://stackoverflow.com/q/50300877
has comment: http://stackoverflow.com/comment/87620040
type: Answer
score: 0

http://stackoverflow.com/comment/87577388
comment on: http://stackoverflow.com/q/50280265
has text: @RafaelC When you include {{ }} inside a {% %}, doesn't it throw a remainder error or something like that?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50304879
answers question: http://stackoverflow.com/q/50304858
score: 0
has body: Indent your definitions, as so: def __unicode__(self): # return self.title def __str__(self): return self.title
type: Answer

import
tags question: http://stackoverflow.com/q/50311731
type: Tag
tags question: http://stackoverflow.com/q/50309334
tags question: http://stackoverflow.com/q/50375660
tag name: import
tags question: http://stackoverflow.com/q/50343062
tags question: http://stackoverflow.com/q/50376987
tags question: http://stackoverflow.com/q/50268960
tags question: http://stackoverflow.com/q/50358742
tags question: http://stackoverflow.com/q/50242220
tags question: http://stackoverflow.com/q/50340754

http://stackoverflow.com/q/50335544
linked to: http://stackoverflow.com/q/10208814
has body: This is a rather simple issue at first glance, but I haven't been able to find a solution. There's a similar (old) question here but the closest answer given does not seem to apply to error bars in both dimensions. I need to generate an "errorbar" plot where both error bars (in the x and y dimensions) are colored according to the values in the cc array. The code: import numpy as np import matplotlib.pyplot as plt # Some random data aa = np.array([3.581, -0.721, 0.137, 0.645, 0.12, 0., -3.236, 0.248, -5.687, 0.816]) e_aa = np.array([0.111, 0.991, 0.446, 0.07, 0.814, 0., 0.088, 0.805, 0.178, 0.552]) bb = np.array([6.671, 1.219, 0.119, -1.972, 1.834, 0., 4.93, 1.833, -11.542, -0.439]) e_bb = np.array([0.143, 1.316, 0.609, 0.094, 1.127, 0., 0.116, 1.227, 0.216, 0.726]) # The color array cc = np.array([0.50344083, 0.49961867, 0.5055576, 0.48970365, 0.5078516, 0.49643923, 0.50089907, 0.50129157, 0.49627974, 0.5052376]) plt.errorbar(aa, bb, yerr=e_bb, xerr=e_aa, fmt='none', ecolor=cc) plt.show() fails with a: ValueError: Invalid RGBA argument: 0.50344083 whether I use the ecolor or color argument. Is there any way around this?
has answer: http://stackoverflow.com/a/50356377
tagged with: color-mapping
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: matplotlib
tagged with: python
type: UnansweredQuestion
has title: Color errorbars in 2D according to colormap
score: 2
has answer: http://stackoverflow.com/a/50336290
downvote count: 0

http://stackoverflow.com/comment/87626394
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50304873
type: Comment
has text: Count the total palindrome substrings. Look the comments in End

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

http://stackoverflow.com/comment/87739360
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50361368
has text: Ahhh I see. I missed that section.
type: Comment

http://stackoverflow.com/comment/87743358
type: QuestionComment
has text: You can't save an ssh session to reload in another process. Security depends on the session establishment handshake. That said, 30 seconds? It should be less than a second per session and you could do those in parallel in multiple threads. Something is amiss in your network or perhaps your code.
comment on: http://stackoverflow.com/q/50363444
score: 1
type: Comment

http://stackoverflow.com/a/55275333
score: 0
has body: Following code is working for me. import numpy as np import pandas as pd import sqlite3 from sqlalchemy import create_engine DIR = 'C:/Users/aslams/Desktop/checkpoint/' FILE = 'SUBSCRIBER1.csv' file = '{}{}'.format(DIR, FILE) csv_database = create_engine('sqlite:///csv_database.db') chunksize = 10000 i = 0 j = 0 for df in pd.read_csv(file, chunksize=chunksize, iterator=True): df = df.rename(columns= {c: c.replace(' ', '') for c in df.columns}) df.index +=3 df.to_sql('data_use', csv_database, if_exists = 'append') j = df.index[-1]+1 print('| index: {}',format(j))
type: Answer
answers question: http://stackoverflow.com/q/50283980

http://stackoverflow.com/comment/87981965
comment on: http://stackoverflow.com/q/50378906
type: QuestionComment
has text: what's that last comment supposed to do? scare away possible contributors??
type: Comment
score: 2

http://stackoverflow.com/comment/87624966
type: QuestionComment
comment on: http://stackoverflow.com/q/50304063
type: Comment
score: 0
has text: Do you need to scroll page down to load more entries?

http://stackoverflow.com/comment/87801771
comment on: http://stackoverflow.com/q/50374779
score: 0
has text: `100.045` is really `100.0450000000000017053025658242404460906982421875` which , mathematically, should round to 2 digits to `100.05`. To solve this problem, in general, with float64 requires higher precision. I am unfamiliar with NumPy to help more.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50260840
has answer: http://stackoverflow.com/a/50261201
answer count: 1
duplicate of: http://stackoverflow.com/q/18027042
has comment: http://stackoverflow.com/comment/87540529
has body: I'm trying to find out what exactly the asterisk(*) means on the SQLAlchemy query below. Could anyone clarify please? import uuid from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import or_ from sqlalchemy_utils.types.uuid import UUIDType class House(Base): id = Column(Integer, primary_key=True) street = Column(UUIDType, default=uuid.uuid4, nullable=False, unique=True) zip_code = Column(UUIDType, index=True) # Shell session $: [...] query = request.dbsession.query(House) query = query.filter(or_(*[(getattr(Building, k) == getattr(self, k)) for k in ('street', 'zip_code') if getattr(self, k) is not None]))
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/50261201
has comment: http://stackoverflow.com/comment/87539920
type: Question
has title: SQL Alchemy ORM and the meaning of asterisk(*)
linked to: http://stackoverflow.com/q/36901
tagged with: python
has comment: http://stackoverflow.com/comment/87539846
has comment: http://stackoverflow.com/comment/87540394
duplicate of: http://stackoverflow.com/q/36901
linked to: http://stackoverflow.com/q/18027042
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50349856
has comment: http://stackoverflow.com/comment/87716156
type: Question
linked to: http://stackoverflow.com/q/22241420
has title: Ignore python module when running with -m flag
has comment: http://stackoverflow.com/comment/87715803
answer count: 0
has comment: http://stackoverflow.com/comment/87715904
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87715743
favorite count: 0
has comment: http://stackoverflow.com/comment/87715571
tagged with: python
has body: I have a python package called 'my_package'. The structure is as follows my_package my_package __init__.py __main__.py my_package.py some_other_file.py run_script setup.py 'run_script' is just a shell script that calls the package as a module using the virtual environment that is specified in the script, roughly: #!/bin/bash /path/to/myenv/bin/python -m my_package 'my_package' is obviously installed into myenv beforehand. The problem is this: When the script is called, despite '-m' flag is specified, python still calls 'my_package.py' instead of importing 'my_package' from the environment. Is there a way to override this? Somehow make it so that python doesn't use my_package.py file? My solution would be just to rename my_package.py file. But I would hope to find something better.

testing
tags question: http://stackoverflow.com/q/50359575
type: Tag
tags question: http://stackoverflow.com/q/50304873
tags question: http://stackoverflow.com/q/50360981
tags question: http://stackoverflow.com/q/50329629
tags question: http://stackoverflow.com/q/50375837
tag name: testing
tags question: http://stackoverflow.com/q/50323580
tags question: http://stackoverflow.com/q/50240315
tags question: http://stackoverflow.com/q/50332266
tags question: http://stackoverflow.com/q/50251377
tags question: http://stackoverflow.com/q/50231627
tags question: http://stackoverflow.com/q/50364178

python-2.7
tags question: http://stackoverflow.com/q/50311010
tags question: http://stackoverflow.com/q/50272334
tags question: http://stackoverflow.com/q/50328506
tags question: http://stackoverflow.com/q/50271399
tags question: http://stackoverflow.com/q/50312924
tags question: http://stackoverflow.com/q/50378788
tags question: http://stackoverflow.com/q/50318549
tags question: http://stackoverflow.com/q/50241145
tags question: http://stackoverflow.com/q/50318330
tags question: http://stackoverflow.com/q/50263472
tags question: http://stackoverflow.com/q/50278332
tags question: http://stackoverflow.com/q/50376081
tags question: http://stackoverflow.com/q/50260409
tags question: http://stackoverflow.com/q/50347089
tags question: http://stackoverflow.com/q/50367748
tags question: http://stackoverflow.com/q/50271439
tags question: http://stackoverflow.com/q/50363356
tags question: http://stackoverflow.com/q/50234265
tags question: http://stackoverflow.com/q/50340629
tags question: http://stackoverflow.com/q/50307593
tags question: http://stackoverflow.com/q/50337569
tags question: http://stackoverflow.com/q/50335283
tags question: http://stackoverflow.com/q/50307256
tags question: http://stackoverflow.com/q/50311700
tags question: http://stackoverflow.com/q/50247500
tags question: http://stackoverflow.com/q/50380776
tags question: http://stackoverflow.com/q/50349609
tags question: http://stackoverflow.com/q/50361502
tags question: http://stackoverflow.com/q/50291583
tags question: http://stackoverflow.com/q/50335812
tags question: http://stackoverflow.com/q/50333690
tags question: http://stackoverflow.com/q/50251307
tags question: http://stackoverflow.com/q/50259107
tags question: http://stackoverflow.com/q/50313325
tags question: http://stackoverflow.com/q/50326532
tags question: http://stackoverflow.com/q/50235071
tags question: http://stackoverflow.com/q/50283458
type: Tag
tags question: http://stackoverflow.com/q/50384598
tags question: http://stackoverflow.com/q/50312991
tags question: http://stackoverflow.com/q/50295078
tags question: http://stackoverflow.com/q/50278105
tags question: http://stackoverflow.com/q/50308466
tags question: http://stackoverflow.com/q/50325261
tags question: http://stackoverflow.com/q/50335057
tags question: http://stackoverflow.com/q/50318309
tags question: http://stackoverflow.com/q/50242754
tags question: http://stackoverflow.com/q/50267458
tags question: http://stackoverflow.com/q/50235224
tags question: http://stackoverflow.com/q/50350379
tags question: http://stackoverflow.com/q/50230377
tags question: http://stackoverflow.com/q/50331744
tags question: http://stackoverflow.com/q/50341267
tags question: http://stackoverflow.com/q/50354407
tags question: http://stackoverflow.com/q/50258067
tags question: http://stackoverflow.com/q/50348347
tags question: http://stackoverflow.com/q/50362253
tags question: http://stackoverflow.com/q/50352888
tags question: http://stackoverflow.com/q/50250025
tags question: http://stackoverflow.com/q/50356572
tags question: http://stackoverflow.com/q/50256995
tags question: http://stackoverflow.com/q/50372558
tags question: http://stackoverflow.com/q/50291216
tags question: http://stackoverflow.com/q/50370571
tags question: http://stackoverflow.com/q/50257542
tags question: http://stackoverflow.com/q/50323693
tags question: http://stackoverflow.com/q/50262312
tags question: http://stackoverflow.com/q/50337605
tags question: http://stackoverflow.com/q/50279442
tags question: http://stackoverflow.com/q/50238052
tags question: http://stackoverflow.com/q/50380624
tags question: http://stackoverflow.com/q/50276735
tags question: http://stackoverflow.com/q/50282476
tags question: http://stackoverflow.com/q/50233709
tags question: http://stackoverflow.com/q/50323656
tags question: http://stackoverflow.com/q/50302229
tags question: http://stackoverflow.com/q/50324413
tags question: http://stackoverflow.com/q/50238432
tags question: http://stackoverflow.com/q/50345470
tags question: http://stackoverflow.com/q/50337655

http://stackoverflow.com/a/50264681
upvote count: 1
answers question: http://stackoverflow.com/q/50264597
has body: If the banned_words has many items, You can transform it from list to set. And check if all the words in the sentence are not in the banned_words: banned_words = set(["facebook", "Facebook", "netflix"]) if all(word not in banned_words for word in sentence.split()): pass
has comment: http://stackoverflow.com/comment/87547569
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87547486
has comment: http://stackoverflow.com/comment/87547441
has comment: http://stackoverflow.com/comment/87547511
downvote count: 0

http://stackoverflow.com/q/50320519
has comment: http://stackoverflow.com/comment/87659777
tagged with: python
tagged with: discord
has comment: http://stackoverflow.com/comment/87657107
has title: Discord.py "self is a required argument that is missing"
has comment: http://stackoverflow.com/comment/87659706
score: 0
type: UnansweredQuestion
answer count: 1
has body: I continue to get this error when I use a specific command with Discord.py to make my bot: raise MissingRequiredArgument('{0.name} is a required argument that is missing.'.format(param)) discord.ext.commands.errors.MissingRequiredArgument: self is a required argument that is missing. My current code is: @bot.command() async def about(self): """Tells you information about the bot itself.""" result = ['**About Me:**'] result.append('- Author: AmusedGrape [ID: 401792058970603539]') result.append('- Library: discord.py (Python)') result.append('- Latest Change: 2.0 Update') result.append('- Uptime: {}'.format(get_bot_uptime())) result.append('- Servers: {}'.format(len(bot.servers))) result.append('- Commands Run: {}'.format(sum(bot.commands_used.values()))) total_members = sum(len(s.members) for s in bot.servers) total_online = sum(1 for m in bot.get_all_members() if m.status != discord.Status.offline) unique_members = set(bot.get_all_members()) unique_online = sum(1 for m in unique_members if m.status != discord.Status.offline) channel_types = Counter(c.type for c in bot.get_all_channels()) voice = channel_types[discord.ChannelType.voice] text = channel_types[discord.ChannelType.text] result.append('- Total Members: {} ({} online)'.format(total_members, total_online)) result.append('- Unique Members: {} ({} online)'.format(len(unique_members), unique_online)) result.append('- {} text channels, {} voice channels'.format(text, voice)) result.append('') result.append('Tex server: https://discord.gg/~~~~~~') await bot.say('\n'.join(result)) I based the code off of this site: https://www.programcreek.com/python/example/107401/discord.py I am not a master at Python but I know a small amount. Thanks for any help! EDIT: Full traceback Ignoring exception in command about Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/usr/local/lib/python3.6/site-pac…
has comment: http://stackoverflow.com/comment/87656985
type: Question
has comment: http://stackoverflow.com/comment/87660848
has answer: http://stackoverflow.com/a/61133207
tagged with: discord.py
has comment: http://stackoverflow.com/comment/87659588

http://stackoverflow.com/a/50285809
accepted answer of: http://stackoverflow.com/q/50284972
downvote count: 0
has body: Build your regex once, sorting by longest phrase so you encompass the **s around the longest matching phrases rather than the shortest, perform the substitution and filter out those that have no substitution made, eg: phrases = [ "phrase1", "phrase2", "phrase with spaces", 'can be really really', 'characters', 'some sentences' # ... ] sentences = [ "sentence", "some sentences are longer", "some sentences can be really really ... really long, about 1000 characters.", # ... ] # Build the regex string required rx = '({})'.format('|'.join(re.escape(el) for el in sorted(phrases, key=len, reverse=True))) # Generator to yield replaced sentences it = (re.sub(rx, r'**\1**', sentence) for sentence in sentences) # Build list of paired new sentences and old to filter out where not the same results = [new_sentence for old_sentence, new_sentence in zip(sentences, it) if old_sentence != new_sentence] Gives you a results of: ['**some sentences** are longer', '**some sentences** **can be really really** ... really long, about 1000 **characters**.']
answers question: http://stackoverflow.com/q/50284972
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87620775
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/comment/87722899
type: Comment
type: QuestionComment
has text: @BramVanroy So the return of this is None for a lot of matches because they dont fit my criteria of a score of atleast 95. But I would still like to display this. The result I want is to have the columns Match 1,2,3 and Display all the matches that match this criteria in there. If no match is found, just leave this row empty or if thats not possible jump over it. I guess the error is created because Python doesnt want to do that, so thats the workaround I was looking for.
comment on: http://stackoverflow.com/q/50351524
score: 0

http://stackoverflow.com/comment/87567205
type: Comment
score: 0
has text: @Norrius I've edited it to include what I think is the Run Configuration.
type: QuestionComment
comment on: http://stackoverflow.com/q/50274927

http://stackoverflow.com/comment/87608750
has text: can you simply combine the two options examples you have here? the replica set is indicated by the list of ip:port strings. try adding the SSL flag as well as your certfile flag. replica sets with SSL are not uncommon, I'd think the solution would be straightforward.
comment on: http://stackoverflow.com/q/50293129
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50291028
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87598249
has title: Pivot csv file in python
has comment: http://stackoverflow.com/comment/87598677
has answer: http://stackoverflow.com/a/50291769
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50291769
has body: I have the following data format in a csv file: 1,01,ABC,This is abc101,This is another abc101 1,01,DEF,This is def101,This is another def101 1,02,ABC,This is abc102,This is another abc102 1,02,DEF,This is def102,This is another def102 1,02,GHI,This is ghi102,This is another ghi102 2,01,ABC,This is abc201,This is another abc201 2,01,DEF,This is def201,This is another def201 2,01,GHI,This is ghi201,This is another ghi201 2,03,GHI,This is ghi203,This is another ghi203 3,02,ABC,This is abc302,This is another abc302 3,02,ABC,This is abc302,This is another abc302 3,02,ABC,This is abc302,This is another abc302 4,01,ABC,This is abc401,This is another abc401 4,01,DEF,This is def401,This is another def401 4,01,ABC,This is abc401,This is another abc401 4,02,DEF,This is def402,This is another def402 4,02,DEF,This is def402,This is another def402 also I have a variable list = ['ABC','ABC_2','GHI','GHI_2'] the csv file header list = ['ID1','ID2','Var_name','var_value1','var_value2'] I need to pivot the above data like the below format [['ID1','ID2','ABC','ABC_2','GHI','GHI_2'], [1,01,'This is abc101','This is another abc101','',''], [1,02,'This is abc102','This is another abc102','This is ghi102','This is another ghi102']] ..like that If the variable list = ['GHI','GHI_2','ABC','ABC_2'] The output will be: [['ID1','ID2','GHI','GHI_2','ABC','ABC_2'], [1,01,'','','This is abc101','This is another abc101'], [1,02,'This is ghi102','This is another ghi102','This is abc102','This is another abc102']] ..like that That means the list should: populate the data for all the IDs create null string for those variables which are not present in the above dataset. The csv file has no header we have a seperate header list populate the nested list, maintaining the same order as the Header list populate only those header value i.e. the header list only has values 'ABC','GHI' so the nested list should only populate the values 'ABC' and 'GHI', and should ignore 'DEF' rows from the above dataset. For…
has comment: http://stackoverflow.com/comment/87598674
has comment: http://stackoverflow.com/comment/87598349
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87598368
upvote count: 1
has comment: http://stackoverflow.com/comment/87599498
has comment: http://stackoverflow.com/comment/87598659

http://stackoverflow.com/q/50248319
has answer: http://stackoverflow.com/a/50251532
upvote count: 0
has comment: http://stackoverflow.com/comment/87514183
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: how to change this recursive to loop
has comment: http://stackoverflow.com/comment/87513940
tagged with: python
score: -1
has body: I want to write all base-26 numbers (with letters of the alphabet as digits) of a certain length into an ASCII-file. For length = 4 this would look like aaaa aaab aaac ... zzzx zzzy zzzz I achieved this with the following recursive code: def fuz(data, ll_str): ll_str += 1 def for_once(data_once, ll_str_once): tmp_str = ll_str_once tmp_str -= 1 new_data = [] for m in data_once: for i1 in range(97, 123): new_data.append(m + chr(i1)) if tmp_str != 0: return for_once(new_data, tmp_str) else: return data_once return for_once(data, ll_str) if __name__ == '__main__': ll = 4 test = [''] file_output = open("out.txt", 'a') out_data = fuz(test, ll) for out in out_data: file_output.write(out + '\n') file_output.close() However, for any length > 4, this solution runs out of memory on my machine. Therefore I look for an alternative without recursion - can anybody give me a hint how to do this?

http://stackoverflow.com/a/50258379
answers question: http://stackoverflow.com/q/50258337
score: 20
upvote count: 20
type: Answer
has body: What you can do is: var_1 = data.get("var_1", None) fun_kwargs = {'some_arg': var_1} if var_1 else {} some_function(**fun_kwargs) If you have multiple parameters you could do: fun_kwargs = {} if var1: fun_kwargs['some_arg1'] = var_1 if var2: fun_kwargs['some_arg2'] = var_2 if var3: fun_kwargs['some_arg3'] = var_3 some_function(**fun_kwargs)
has comment: http://stackoverflow.com/comment/87534894
accepted answer of: http://stackoverflow.com/q/50258337
downvote count: 0
has comment: http://stackoverflow.com/comment/87534810
type: AcceptedAnswer

http://stackoverflow.com/comment/87581463
has text: You are getting building supplies results for an Italian Food query? That makes me think Yelp isn't understanding your query string. Even more so since you get the same results each time. Maybe try running the yelp query manually to make sure you have the request set up correctly.
score: 0
comment on: http://stackoverflow.com/q/50278473
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87665240
score: 0
type: Comment
has text: if see a problem with the construction of the list : you append each number `i` every time you find a number in the primetest range that is not a divisor of `i`
type: QuestionComment
comment on: http://stackoverflow.com/q/50324604

http://stackoverflow.com/comment/87533636
type: QuestionComment
comment on: http://stackoverflow.com/q/50257830
has text: `b[0:N,0:N,:N] = a[0:N,0:N,0:N]`
score: 2
type: Comment

http://stackoverflow.com/comment/87768441
comment on: http://stackoverflow.com/q/50365835
type: Comment
score: 0
type: QuestionComment
has text: You can customize the action as suggested, but is that any less error prone? The primary purpose of `argparse` is to figure out what your user wants. Massaging the results after parsing is quite acceptable, and often easier. When would have a list instead of a tuple cause problems? Who in their right mind wants to enter a whole `numpy` array via the commandline? :)

http://stackoverflow.com/comment/87811819
comment on: http://stackoverflow.com/q/50378688
has text: Could you have a look if [this](https://stackoverflow.com/a/48062299/2454357) or [this](https://stackoverflow.com/a/48626078/2454357) helps you? If not, please provide your shapefile and I can try to write up an answer for you.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87666874
type: QuestionComment
comment on: http://stackoverflow.com/q/50273979
score: 0
type: Comment
has text: @Nrzonline what do you mean with "not yet properly configured" Can you help me configure it?

http://stackoverflow.com/comment/87643719
type: QuestionComment
comment on: http://stackoverflow.com/q/50313114
type: Comment
has text: It's not really the randomness, rather how unexpected each value is given the other values. Thus, it is related to the amount of information present in the image.
score: 1

http://stackoverflow.com/a/50383534
type: Answer
answers question: http://stackoverflow.com/q/50333432
has body: You need to broadcast input arrays to make it element-wise computation. def bcast(x, y, xp): return (xp.broadcast_to(x[:, None], (1000, 1000)), xp.broadcast_to(y, (1000, 1000))) x, y = bcast(x, y, np) with timer(' CPU '): c = (x - y) ** 2 x_gpu, y_gpu = bcast(x_gpu, y_gpu, cp) with timer(' GPU '): c_gpu2 = squared_diff(x_gpu, y_gpu)
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/q/50366293
has comment: http://stackoverflow.com/comment/113593673
tagged with: topic-modeling
favorite count: 0
upvote count: 4
has answer: http://stackoverflow.com/a/51226612
type: Question
answer count: 2
has title: How to classify a sentence into one of the pre-defined topic bucket using an unsupervised approach
has answer: http://stackoverflow.com/a/50370136
downvote count: 0
has body: I am working on a project to classify customer feedback into buckets based on the topic of the feedback comment. So , I need to classify the sentence into one of the topics among a list of pre-defined topics. For example : "I keep getting an error message every time I log in" has to be tagged with "login" as the topic. "make the screen more colorful" has to be tagged with "improvements" as the topic. So the topics are very specific to the product and the context. LDA doesn't seem to work for me(correct me if i'm wrong). It detects the topics in a general sense like "Sports" , "Politics" , "Technology" etc. But I need to detect specific topics as mentioned above. Also , I don't have labelled data for training. All I have is the comments. So supervised learning approach doesn't look like an option. What I have tried so far: I trained a gensim model with google news corpus (its about 3.5 gb). I am cleaning the sentence by removing stop words , punctuation marks etc. I am finding , to what topic among the set of topics each word is closest to and tag the word to that topic. With an idea that the sentence might contain more words closer to the topic it is referring to than not , I am picking up the topic(s) to which maximum number of words in the sentence is mapped to. For example: If 3 words in a sentence is mapped to "login" topic and 2 words in the sentence is mapped to "improvement" topic , I am tagging the sentence to "login" topic. If there is a clash between the count of multiple topics , I return all the topics with the maximum count as the topic list. This approach is giving me fair results. But its not good enough. What will be the best approach to tackle this problem?
tagged with: machine-learning
type: UnansweredQuestion
tagged with: python
score: 4
tagged with: gensim
tagged with: nlp

http://stackoverflow.com/q/50381820
score: 3
answer count: 3
linked to: http://stackoverflow.com/q/61176552
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50518676
has answer: http://stackoverflow.com/a/61904385
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/63161176
tagged with: visual-studio-code
type: UnansweredQuestion
has title: How do I simplify the outputed path in visual studio code when running python
has body: In visual studion code, after installing python, I added a debug configuration provide by visual studio code (called 'current configuration') that lets me run python. I'd like the output of my executed python code to be clean and NOT show this long path every time (in blue text). How can I do this? See image attached.
tagged with: python
has comment: http://stackoverflow.com/comment/116804372

http://stackoverflow.com/q/50365414
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I would like to create a new column (I.e. Winning_Time) as shown below table. All the Time_diff at Match_state ( Winning) will be stored in the new column Winning_Time. The rest rows will be filled with NaN or zero. How can I do that? gsm_id Goal_Flag Union_Level Team_SR Match_state Time_diff Wining_Time 2462796 First goal Scored Burnley Winning 0 days 00:23:15.00 0 days 00:23:15.00 2462796 First goal Conceded Chelsea Losing 0 days 00:23:15.00 NaN 2462796 Other goals Scored Burnley Winning 0 days 00:15:20.00 0 days 00:15:20.00 2462796 Other goals Conceded Chelsea Losing 0 days 00:15:20.00 NaN 2462796 Other goals Scored Burnley Winning 0 days 00:03:34.00 0 days 00:03:34.00 2462796 Other goals Conceded Chelsea Losing 0 days 00:03:34.00 NaN 2462796 Other goals Scored Chelsea Losing 0 days 00:25:59.00 NaN 2462796 Other goals Conceded Burnley Winning 0 days 00:25:59.00 0 days 25:59.00 2462796 Last goal Scored Chelsea Losing 0 days 00:19:11.00 NaN 2462796 Last goal Conceded Burnley Winning 0 days 00:19:11.00 0 days 00:19:11.00 2462795 First goal Scored City Winning 0 days 01:09:15.00 0 days 01:09:15.00 2462795 First goal Conceded Brighton Losing 0 days 01:09:15.00 NaN 2462795 Last goal Scored City Winning 0 days 00:05:21.00 0 days 00:05:21.00 2462795 Last goal Conceded Brighton Losing 0 days 00:05:21.00 NaN Your advice is much appreciated.
answer count: 1
tagged with: series
type: Question
tagged with: python-3.x
tagged with: python
has title: Creating a new column based on value of existing column
has answer: http://stackoverflow.com/a/50365615
accepted answer: http://stackoverflow.com/a/50365615
tagged with: numpy

http://stackoverflow.com/a/50377477
accepted answer of: http://stackoverflow.com/q/50377105
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50377105
has body: You can use a thread for register_word function: from flask import current_app def register_word_async(app, word): with app.app_context(): register_word(word) # call your function def call_register_word(word): # ... app = current_app._get_current_object() thr = Thread(target=register_word_async, args=[app, word]) thr.start() return thr @app.route("/dictionary/&lt;string:word&gt;", methods=["GET"] def search_word(word): call_register_word(word) return find_word(word) While your find_word search at the same time register_word will run.
has comment: http://stackoverflow.com/comment/87784726
type: Answer
has comment: http://stackoverflow.com/comment/87785647
score: 1

http://stackoverflow.com/a/50328605
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50328482
has comment: http://stackoverflow.com/comment/87673319
type: AcceptedAnswer
downvote count: 0
has body: The problem is that p[preceding-sibling::br] means that paragraph has line break sibling while br is actually a child of p - not a sibling So you can update your XPath as //div[@class="sys_key-facts"]/p[strong[contains(text(), "Part-time")] and br]/text()[last()] or try below XPath to get required output: //div[@class="sys_key-facts"]//strong[.="Part-time"]/following-sibling::text()
answers question: http://stackoverflow.com/q/50328482
score: 3

http://stackoverflow.com/q/50264453
has body: How to search a string in JS file (multiple lines) in python? with open(file, 'r') as f: for file_contents in f: if ('search_string_1' in file_contents) or ('search_string_2' in file_contents): print('match found!') f.close()
has comment: http://stackoverflow.com/comment/87546997
duplicate of: http://stackoverflow.com/q/4940032
score: 0
has comment: http://stackoverflow.com/comment/87547090
answer count: 0
has comment: http://stackoverflow.com/comment/87547016
linked to: http://stackoverflow.com/q/4940032
has comment: http://stackoverflow.com/comment/87546968
has title: How to search a string in JS file (multiple lines) in python?
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/87679322
has text: can you show the code, then?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50328918
type: Comment

http://stackoverflow.com/a/50283739
has comment: http://stackoverflow.com/comment/87584011
answers question: http://stackoverflow.com/q/50283660
has body: This has nothing to do with your custom partial function. The problem is that, as explained in the docs, you need to put your top-level code in __main__ block: if __name__ == '__main__': with Pool(4) as pool: list(pool.map(SecPartialF(f, 10), range(10))) Otherwise, each child process in the pool will try to create another pool of 4 more children before doing anything else. Note that this only happens with the spawn and forkserver start methods—but Windows defaults to spawn (other platforms default to fork), so it happens to you.
upvote count: 6
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/50283660
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87541798
score: 0
type: Comment
has text: Thank you so much, this is exactly what i was hoping for. I ran this code, but it was only able to store 1 dictionary. Do you perhaps know why? there are 29 dictionaries holding similar data
comment on: http://stackoverflow.com/a/50261774
type: AnswerComment

http://stackoverflow.com/a/50352616
has comment: http://stackoverflow.com/comment/87723153
has comment: http://stackoverflow.com/comment/87722693
has comment: http://stackoverflow.com/comment/87723261
has comment: http://stackoverflow.com/comment/87722097
has comment: http://stackoverflow.com/comment/87721985
answers question: http://stackoverflow.com/q/50352386
has comment: http://stackoverflow.com/comment/87724040
has comment: http://stackoverflow.com/comment/87721617
has comment: http://stackoverflow.com/comment/87721831
has comment: http://stackoverflow.com/comment/87723990
type: Answer
has comment: http://stackoverflow.com/comment/87723107
has comment: http://stackoverflow.com/comment/87721802
has comment: http://stackoverflow.com/comment/87723192
has comment: http://stackoverflow.com/comment/87721488
has comment: http://stackoverflow.com/comment/87722501
score: 0
has comment: http://stackoverflow.com/comment/87723620
has body: The solution depends on what empty means. If it is just an empty string, as in '', the code to find the index would be: empty = '' idx_first_empty_row = reading_book.index[reading_book.iloc[:, 0] == empty][0] This works if the first column is empty. If for example "empty" means NaN, then replace the line with: idx_first_empty_row = reading_book.index[np.isnan(reading_book.iloc[:, 0])] This works if the dtype of the rows is any numeric numpy type, like np.float64. If the dtype is not any numpy numeric type, try the following: idx_first_empty_row = np.where(reading_book.iloc[:, 0].isnull().values == True) You can also, depending on the types of data in your rows, try this: idx_first_empty_row = reading_book.index[reading_book.iloc[:, 0].isnull().values]
has comment: http://stackoverflow.com/comment/87723568
has comment: http://stackoverflow.com/comment/87723564

http://stackoverflow.com/comment/87651001
comment on: http://stackoverflow.com/a/50317552
type: Comment
score: 0
type: AnswerComment
has text: Thanks.. It is working now. And yaa still I am getting the warning..Thanks for the explanation.

http://stackoverflow.com/q/50317073
has comment: http://stackoverflow.com/comment/93346371
tagged with: python
tagged with: nlp
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: tensorflow
favorite count: 0
has title: reshape a batch of tensors with dynamic max length in tensorflow
has body: In natural language processing, it is common to pad a batch of sequences. Here is the padding function. def pad_sequences(sequences, pad_tok=0): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length a list record original length of sequences """ sequence_padded, sequence_length = [], [] sequence_padded = tf.keras.preprocessing.sequence.pad_sequences(sequences, padding='post', value=pad_tok) max_sen_len = 0 for seq in sequences: seq = list(seq) if len(seq) &gt; max_sen_len: max_sen_len = len(seq) return sequence_padded, max_sen_len Input is a batch of sentences of variable length. Each sentence is a list of ids, each id represents one word in vocabulary. Here is the feeddict word_ids_left, maxlen_left = pad_sequences(word_ids_left) pos1_ids_left, _ = pad_sequences(pos1_ids_left, pad_tok=499) pos2_ids_left, _ = pad_sequences(pos2_ids_left, pad_tok=499) word_ids_mid, maxlen_mid = pad_sequences(word_ids_mid) pos1_ids_mid, _ = pad_sequences(pos1_ids_mid, pad_tok=499) pos2_ids_mid, _ = pad_sequences(pos2_ids_mid, pad_tok=499) word_ids_right, maxlen_right = pad_sequences(word_ids_right) pos1_ids_right, _ = pad_sequences(pos1_ids_right, pad_tok=499) pos2_ids_right, _ = pad_sequences(pos2_ids_right, pad_tok=499) # build feed dictionary feed = { self.word_ids_left: word_ids_left, self.pos1_ids_left: pos1_ids_left, self.pos2_ids_left: pos2_ids_left, self.word_ids_mid: word_ids_mid, self.pos1_ids_mid: pos1_ids_mid, self.pos2_ids_mid: pos2_ids_mid, self.word_ids_right: word_ids_right, self.pos1_ids_right: pos1_ids_right, self.pos2_ids_right: pos2_ids_right, self.maxlen_left: maxlen_left, self.maxlen_mid: maxlen_mid, self.maxlen_right: maxlen_right } I prefer to build embeddings with dynamic max sentence length in each batch. Here is my embedding function def add_sentence_embeddings_op(self, word_ids, pos1_ids, pos2_ids, maxlen): """Defines sentence_embeddings If self.config.embeddings is not Non…

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/50381324
tags question: http://stackoverflow.com/q/50349287
tags question: http://stackoverflow.com/q/50376341
type: Tag
tags question: http://stackoverflow.com/q/50347808
tags question: http://stackoverflow.com/q/50239706
tags question: http://stackoverflow.com/q/50346992
tags question: http://stackoverflow.com/q/50271557
tags question: http://stackoverflow.com/q/50324565
tags question: http://stackoverflow.com/q/50376540
tags question: http://stackoverflow.com/q/50384614
tags question: http://stackoverflow.com/q/50319733
tags question: http://stackoverflow.com/q/50289938
tags question: http://stackoverflow.com/q/50361669
tags question: http://stackoverflow.com/q/50359002
tags question: http://stackoverflow.com/q/50297534
tags question: http://stackoverflow.com/q/50344429
tags question: http://stackoverflow.com/q/50293992
tags question: http://stackoverflow.com/q/50381329
tags question: http://stackoverflow.com/q/50352411
tags question: http://stackoverflow.com/q/50240423
tags question: http://stackoverflow.com/q/50318160
tags question: http://stackoverflow.com/q/50366439
tags question: http://stackoverflow.com/q/50236960
tags question: http://stackoverflow.com/q/50264879
tags question: http://stackoverflow.com/q/50315058
tags question: http://stackoverflow.com/q/50284933
tag name: csv
tags question: http://stackoverflow.com/q/50332909
tags question: http://stackoverflow.com/q/50263129
tags question: http://stackoverflow.com/q/50293545
tags question: http://stackoverflow.com/q/50351908
tags question: http://stackoverflow.com/q/50244592
tags question: http://stackoverflow.com/q/50359589
tags question: http://stackoverflow.com/q/50260488
tags question: http://stackoverflow.com/q/50279292
tags question: http://stackoverflow.com/q/50298009
tags question: http://stackoverflow.com/q/50330355
tags question: http://stackoverflow.com/q/50272334
tags question: http://stackoverflow.com/q/50374348
tags question: http://stackoverflow.com/q/50375594
tags question: http://stackoverflow.com/q/50342234
tags question: http://stackoverflow.com/q/50314826
tags question: http://stackoverflow.com/q/50324942
tags question: http://stackoverflow.com/q/50316797
tags question: http://stackoverflow.com/q/50293639
tags question: http://stackoverflow.com/q/50344911
tags question: http://stackoverflow.com/q/50347906
tags question: http://stackoverflow.com/q/50358812
tags question: http://stackoverflow.com/q/50342517
tags question: http://stackoverflow.com/q/50314757
tags question: http://stackoverflow.com/q/50317869
tags question: http://stackoverflow.com/q/50238785
tags question: http://stackoverflow.com/q/50322035
tags question: http://stackoverflow.com/q/50259649
tags question: http://stackoverflow.com/q/50367594
tags question: http://stackoverflow.com/q/50379453
tags question: http://stackoverflow.com/q/50286190
tags question: http://stackoverflow.com/q/50362707
tags question: http://stackoverflow.com/q/50375067
tags question: http://stackoverflow.com/q/50364584
tags question: http://stackoverflow.com/q/50304435
tags question: http://stackoverflow.com/q/50346372
tags question: http://stackoverflow.com/q/50316737
tags question: http://stackoverflow.com/q/50246166
tags question: http://stackoverflow.com/q/50351426
tags question: http://stackoverflow.com/q/50309510
tags question: http://stackoverflow.com/q/50353522
tags question: http://stackoverflow.com/q/50247055
tags question: http://stackoverflow.com/q/50333757
tags question: http://stackoverflow.com/q/50283745
tags question: http://stackoverflow.com/q/50359777
tags question: http://stackoverflow.com/q/50381203
tags question: http://stackoverflow.com/q/50233819
tags question: http://stackoverflow.com/q/50355334
tags question: http://stackoverflow.com/q/50305723
tags question: http://stackoverflow.com/q/50319155
tags question: http://stackoverflow.com/q/50271664
tags question: http://stackoverflow.com/q/50273261
tags question: http://stackoverflow.com/q/50294237

http://stackoverflow.com/comment/87674872
type: Comment
has text: @JamesPhillips That's an excellent point. Dimensional analysis is a simple, powerful (and easily overlooked!) problem solving tool. If `data` and `model` have some dimension, `weights` should have 1/dimension.
comment on: http://stackoverflow.com/a/50311771
type: AnswerComment
score: 0

http://stackoverflow.com/q/50232794
has comment: http://stackoverflow.com/comment/87486256
has body: I am new to python problem is I have different formatted dates I want all to convert into yyyy/mm/dd format. I have tried following: from dateutil.parser import parse a = parser("19/04/2018") finnal_date = a.strftime('%y/%m/%d') working fine which is :- 18/04/19 but when I am trying :- from dateutil.parser import parse a = parser("03/04/2018") finnal_date = a.strftime('%y/%m/%d') Output is :- 18/03/04 which should be 18/04/03
has comment: http://stackoverflow.com/comment/87482959
linked to: http://stackoverflow.com/q/27800775
type: Question
tagged with: python-3.x
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/27800775
has comment: http://stackoverflow.com/comment/87486270
tagged with: python
has title: Python convert string date to YYYY/MM/DD date time object
score: 0
answer count: 0
tagged with: pandas

http://stackoverflow.com/comment/87556350
type: QuestionComment
has text: As I say, see the [--natural-primary](https://docs.djangoproject.com/en/2.0/ref/django-admin/#cmdoption-dumpdata-natural-primary) and [--natural-foreign](https://docs.djangoproject.com/en/2.0/ref/django-admin/#cmdoption-dumpdata-natural-foreign) options for dumpdata.
type: Comment
comment on: http://stackoverflow.com/q/50269153
score: 0

http://stackoverflow.com/comment/87734382
score: 0
type: Comment
type: AnswerComment
has text: For instance add `datetime.datetime(1800, 7, 9)` to your `df` Nothing wrong happens.
comment on: http://stackoverflow.com/a/50358710

http://stackoverflow.com/q/50234921
type: AnsweredQuestion
tagged with: heap
tagged with: algorithm
has body: I am trying to implement a function that turns a list into a MinHeap. I cannot see where I am going wrong. def min_heapify(nums): n = len(nums) - 1 i = n // 2 # last parent while i &gt;= 1: k = i v = nums[k] min_heap = False while not min_heap and 2 * k &lt;= n: j = 2 * k if j + 1 &lt;= n: if nums[j + 1] &lt; nums[j]: j += 1 if nums[k] &lt; nums[j]: min_heap = True else: nums[k] = nums[j] k = j nums[k] = v i -= 1 Example Input: a_list = [0, 5, 2, 3, 4] min_heapify(a_list) Output (the 4 is incorrect): print("Min Heapify", a_list) # Min Heapify [0, 2, 5, 3, 4]
has comment: http://stackoverflow.com/comment/87506617
tagged with: python
has comment: http://stackoverflow.com/comment/87506739
has comment: http://stackoverflow.com/comment/87507599
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87506820
tagged with: min-heap
accepted answer: http://stackoverflow.com/a/50244768
has comment: http://stackoverflow.com/comment/87506914
has title: Array based MinHeap
type: Question
has answer: http://stackoverflow.com/a/50244768

http://stackoverflow.com/q/50258986
score: 0
tagged with: pandas
has title: API stops working after a while
answer count: 1
accepted answer: http://stackoverflow.com/a/50309755
has body: I wrote an API that takes a directory as an input and it will load every text file (.txt) inside that folder (and its sub-folders) into a Postgres DB. The API works for a few files (around 3) but when it gets down to "reading" the fourth file, regardless of the file, the program crashes. I even separated the files into chunks of three and the API stopped anyway. This is the error I get: ERROR:tornado.application:Uncaught exception Traceback (most recent call last): File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/tornado/http1connection.py", line 237, in _read_message delegate.finish() File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/tornado/httpserver.py", line 230, in finish self.request_callback(self.request) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/tornado/wsgi.py", line 276, in __call__ WSGIContainer.environ(request), start_response) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/bottle.py", line 979, in __call__ return self.wsgi(environ, start_response) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/bottle.py", line 954, in wsgi out = self._cast(self._handle(environ)) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/bottle.py", line 862, in _handle return route.call(**args) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/bottle.py", line 1740, in wrapper rv = callback(*a, **ka) File "my_api_clientes_cuentas.py", line 63, in read_txt index=False) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pandas/core/generic.py", line 1534, in to_sql chunksize=chunksize, dtype=dtype) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site- packages/pandas/io/sql.py", line 473, in to_sql chunksize=chunksize, dtype=dtype) File "/home/rvelez/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pandas/io/sql.py", line 1156, in to_sql table.insert(chunksize) File "/home/rvelez/.pyenv/versions/3.6.0/lib/pyt…
type: Question
tagged with: postgresql
tagged with: linux
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/50309755
type: AnsweredQuestion

http://stackoverflow.com/comment/87566379
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50274884
type: Comment
has text: What exactly is a dict? I'm still a student so the skills we are taught are quite limited

http://stackoverflow.com/q/50312544
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I've been programming with python 3 for over about 3 - 4 months now. I'm currently learning Object Oriented Programming, analysis and design. So as I went through the journey, I saw special methods. I'm a little confused. I don't understand them. I know that __init__ is a special method and it runs every time we create an instance. I was just wondering if the other special methods runs the same way as the __init__ method or like a normal method Thanks
has comment: http://stackoverflow.com/comment/87641478
tagged with: python
linked to: http://stackoverflow.com/q/1418825
has comment: http://stackoverflow.com/comment/87649645
duplicate of: http://stackoverflow.com/q/1418825
has comment: http://stackoverflow.com/comment/87643915
has comment: http://stackoverflow.com/comment/87643795
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87643793
has title: Python3. What's special methods? What does it do?
tagged with: methods

http://stackoverflow.com/a/50264764
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50264688
upvote count: 1
answers question: http://stackoverflow.com/q/50264688
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87548324
has body: You can search for strings that start with a digit and a .: import re quoteTitle = ['\r\n ', ' ', '\r\n ', '\r\n ', '\r\n ', '\r\n ', '\r\n ', '30. Loyalty', '29. Speed Scale', '28. Security', '27. Every Position', '26. Superior Brain Power', '25. A Long Line of Fighters', '24. Dwight Surveillance', '23. Friends ', '22. Pull the Plug ', '21. Second Life', '20. Accidentally vs. On Purpose', '19. Menstruation Wishes ', '18. Ideal Choice', '17. Healthcare in the Wild', '16. Superior Cousins', '15. Regular Ideas', '14. Immunity Logic', '13. The Person You Least, Medium and Most Suspect', '12. Real Heroes ', '11. Water Cooler Gossip', '10. Stress', '9. All These People!', '8. The “R” Sound', '7. A Woman’s Defects ', '6.Werewolf Hunting Experience ', '5. An Ideal World ', '4. Attention', '3. The Thing About Bear Attacks ', '2. Resume Critiquing', '1. Yeast Infections ', 'Tags', 'Recently in TV', '5/8/2018 3:45:00 PM', '5/3/2018 2:00:00 PM', '5/3/2018 12:00:00 PM', 'Most Popular', '5/3/2018 11:00:00 AM', '5/3/2018 12:00:00 PM', '5/8/2018 3:45:00 PM', '4/13/2018 5:00:00 PM', '4/18/2018 8:22:31 PM', '5/3/2018 2:00:00 PM', '5/8/2018 6:02:54 PM', '5/7/2018 4:52:04 PM', '5/7/2018 2:57:00 PM', '5/3/2018 5:04:43 PM', '5/3/2018 1:06:18 PM', 'Music', '5/3/2018 12:00:00 AM', 'Music', '5/3/2018 12:00:00 AM', 'Music', '5/2/2018 12:00:00 AM', '11/28/2017 8:00:00 AM', '11/30/2017 11:00:00 AM', '5/3/2018 11:00:00 AM', '5/3/2018 2:00:00 PM', '5/3/2018 12:00:00 PM', '12/11/2017 1:00:00 PM', '12/15/2017 8:00:00 AM', '1/9/2018 3:00:00 PM', '1/4/2017 12:30:00 PM', '4/13/2013 12:13:00 PM', 'TV', '4/3/2018 10:00:00 AM', 'TV', '4/3/2018 9:25:00 AM', 'Comedy', '3/22/2018 1:00:28 PM', 'TV', '3/15/2018 10:00:00 AM', 'Comedy', '3/13/2018 2:00:00 PM', 'TV', '3/10/2018 10:00:00 AM', 'TV', '3/2/2018 11:00:00 AM', 'TV', '2/25/2018 10:30:00 PM', 'TV', '2/23/2018 1:00:00 PM', '5/3/2018 11:00:00 AM', '5/3/2018 12:00:00 PM', '5/8/2018 3:45:00 PM', '4/13/2018 5:00:00 PM', '4/18/2018 8:22:31 PM', '5/3/2018 2:…
has comment: http://stackoverflow.com/comment/87548606

http://stackoverflow.com/comment/87725060
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50337326
has text: @wvxvw Honestly, it’s starting to feel like you’re more interested in arguing that it’s impossible even though every other C extension in the world does it. It’s as simple as it looks, no hidden gotchas, just a lot of manual refcounting that we all sometimes get wrong for the same stupid reasons we get malloc and free wrong, and debugging it isn’t significantly different. Honestly, if you can’t use Cython, it really is a lot easier to use C++ or Rust or some other language with helpers to do all this crap for you, but if you hate that idea, the only other choice is to buckle down and write it.
score: 1

http://stackoverflow.com/q/50339187
score: 1
answer count: 1
favorite count: 0
type: Question
has body: Alright, so I've got a setup which consists of Apache 2.4, Django 2.0.5, Python3.5, mod_wsgi, all running on Debian. When I go to edit a CSS file on my production server, the file doesn't update until I entirely reboot the server it's on. As you can imagine this is tedious and time consuming, so I'd like to find a solution. Edit: My browser's cache is not the issue. I've tried clearing cache and multiple browsers, definitely a server-side issue. Here are some config files: Apache configuration: <IfModule mod_ssl.c> ServerName 7aptget.com Redirect permanent / https://7aptget.com/ RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ ServerAdmin w@w.com ServerName 7aptget.com ServerAlias 7aptget.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/letsencrypt/live/7aptget.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/7aptget.com/privkey.pem SSLOptions +StdEnvVars SSLOptions +StdEnvVars BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown\ LoadModule wsgi_module "/home/kaden/development/websites/homepage/env/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so" #Django Application Alias /media /home/kaden/development/websites/homepage/media Alias /static /home/kaden/development/websites/homepage/static Require all granted Require all granted Require all granted LogLevel info WSGIDaemonProcess 7aptget.com python-path=/home/kaden/development/websites/homepage python-home=/home/kaden/development/websites/homepage/env WSGIProcessGroup 7aptget.com WSGIScriptAlias / /home/kaden/development/websites/homepage/website/wsgi.py Django wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") application = get_wsgi_application() Django settings.py: import os # Build paths inside the project li…
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
tagged with: python
has title: Issue with Django, Apache, mod_wsgi, and caching CSS files
has comment: http://stackoverflow.com/comment/87694912
has answer: http://stackoverflow.com/a/50353364
has comment: http://stackoverflow.com/comment/87694845

http://stackoverflow.com/q/50363232
has comment: http://stackoverflow.com/comment/87742780
type: Question
type: UnansweredQuestion
has title: Kill C++ process in python using ctrl + C
tagged with: python
tagged with: c++
score: 0
has answer: http://stackoverflow.com/a/50363336
has body: I have a python wrapper for a c++ program using Python.h In C++, the code contains an infinite loop as service: for (;;) { ... } The python wrapper invokes this service and jumps into this loop. When I call ctrl+c, the program can't be killed. (It seems that the python program has been killed and the c++ program not) How can I kill both of the python and c++ program using ctrl+c?
answer count: 1

http://stackoverflow.com/q/50323654
tagged with: python
has title: I have to different data frames. How to find the match and merge the dataframe
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87663186
has answer: http://stackoverflow.com/a/50324319
answer count: 1
tagged with: machine-learning
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I have two different data frames which are as shown df1 ================================== KEYWORD TICKET Burst of bit errors 89814 sync and stand-by reload 66246 Port sub-modules modelling 70946 wires stop passing traffic 60245 Ignore Net flow 59052 df2 ========================== TEXT_DATA Burst of bit errors due to stop passing traffic which are having partial matching. Please help me on this. here is the piece of code which i developed import pandas as pd Standard_Data = pd.read_excel('bOOK2.xlsx',usecols=[0,1]) print(Standard_Data) #Standard_Data ================================== KEYWORD TICKET Burst of bit errors 89814 sync and stand-by reload 66246 Port sub-modules modelling 70946 wires stop passing traffic 60245 Ignore Net flow 59052 keyword_data = Standard_Data['KEYWORD'].values.tolist() input_data = pd.read_excel('book1.xlsx',usecols=[1]) print(input_data) input_data ========================== TEXT_DATA Burst of bit errors due to stop passing traffic #simply df1 = Standard_Data , df2 = input_Data sentenced_data = input_data['Text_Data'].values.tolist() df = pd.DataFrame({'sentenced_data':sentenced_data}) print(df) df['MATCHED_KEYWORD'] = (df['sentenced_data'].apply(lambda x: [w for i in keyword_data for w in i.split(' ') if w in (x)])) df['KEYWORD'] = df['MATCHED_KEYWORD'].apply(','.join) df['KEYWORD'] = df['KEYWORD'].str.replace(',',' ') Z = Standard_Data.merge(df,on='KEYWORD',how='right') print(Z) i'm getting the result like KEYWORD TICKET sentenced_data Burst of bit errors NaN Burst of bit errors due to stop passing traffic NaN stop passing traffic But my Desired Result should be look like this KEYWORD sentenced_data TICKET Burst of bit errors Burst of bit errors due to 89814 wires stop passing traffic stop passing traffic 66246 Please anyone help me on resolving this issue
has comment: http://stackoverflow.com/comment/87663512

http://stackoverflow.com/q/50331702
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50332680
has title: Output duplication
has comment: http://stackoverflow.com/comment/87679533
has comment: http://stackoverflow.com/comment/87680452
favorite count: 0
accepted answer: http://stackoverflow.com/a/50331928
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50331928
has comment: http://stackoverflow.com/comment/87679465
upvote count: 0
score: -2
downvote count: 2
has body: I have run into a issue as my outputs have been been duplicated. I have a slight idea as to why it duplicates the way it does however I don't know how the issue is being caused. Currently the output is duplicated by 3 (The amount of values that the array gen_coms contains. The following snippets of code are what is related to this issue(Please disregard ALL comments in the code): The First function: gen_coms = [] def getCommands(): for file in os.listdir(com_dir): if file.endswith(com_ext): global gen_coms a = gen_coms.append(file[:-len(com_ext)]) # Looks good however formats output as ['a','b','c'] is there a way to format it as 'a','b','c' or a,b,c ? The 2nd function: def genTerm(): while True: gin = raw_input('&gt; ') for commands in gen_coms: # Prints out 3 vars. This didn't happen before but I am assuming thats because gen_coms now technically has a value of 3? if gin in gen_coms: print gin else: print('Unrecognized command!') An example input/output to help show what the issue I am getting looks like: &gt; a # This is the input -&gt; a a # Here down is output a a The input a is entered and the correct output which is also a is printed only instead of the single time I would expect it has become 3. This isn't limited to just a but every output. Non-Important side notes: Sorry if the format of this question isn't the best, I am having a very hard time focusing and thinking in general at the moment due to lack of sleep and will make a edit correcting grammar, spelling, and overall layout in a minute or two. Thank you as well for taking the time to read this lengthy and most likely repetitive question.
tagged with: python
has comment: http://stackoverflow.com/comment/87679516
possible better answer: http://stackoverflow.com/a/50332680
type: AnsweredQuestion

http://stackoverflow.com/comment/87582504
type: Comment
type: QuestionComment
score: 0
has text: It's because the question is too broad. I'm voting to close.
comment on: http://stackoverflow.com/q/50282015

http://stackoverflow.com/a/50451672
type: Answer
answers question: http://stackoverflow.com/q/50300432
accepted answer of: http://stackoverflow.com/q/50300432
type: AcceptedAnswer
score: 0
has body: Selenium is the package I was looking for. But There is and headless format with phantomJS, exactly what I wanted. Still, I think there would be better ways to fetch information from a website database rather than interfacing it.

http://stackoverflow.com/q/50331792
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87686545
has comment: http://stackoverflow.com/comment/87679764
score: 1
has comment: http://stackoverflow.com/comment/87679603
has answer: http://stackoverflow.com/a/50333451
has comment: http://stackoverflow.com/comment/87681046
has comment: http://stackoverflow.com/comment/87679677
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87680028
has comment: http://stackoverflow.com/comment/87679702
has body: I am trying to do some face detection here and using the standard cascades, which can be found here, the following code should draw rectangles over eyes and the face, either the cascades aren't working at all or something's wrong with my code that's supposed to draw over the frame. Also would it be possible to grab the video feed and not have it inverted? import numpy as np import cv2 face_cascade = cv2.CascadeClassifier(r'A:\scripts\opencvstuff\haarcascade_frontalcatface.xml') eye_cascade = cv2.CascadeClassifier(r'A:\scripts\opencvstuff\haarcascade_eye.xml') cap = cv2.VideoCapture(0) while 1: ret, img = cap.read() 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] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.imshow('img',img) k = cv2.waitKey(30) &amp; 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
upvote count: 1
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has title: Haarcascades don't work in OpenCV
accepted answer: http://stackoverflow.com/a/50333451

http://stackoverflow.com/a/50338564
has comment: http://stackoverflow.com/comment/87693905
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: desired={} for k, v in first.items(): if (float(second[k])) &gt; (1.5*float(first[k])): desired[k] = v Assuming that you have the same keys in first and second dictionaries.
accepted answer of: http://stackoverflow.com/q/50338434
has comment: http://stackoverflow.com/comment/87693630
has comment: http://stackoverflow.com/comment/87722879
has comment: http://stackoverflow.com/comment/87693828
has comment: http://stackoverflow.com/comment/87693479
answers question: http://stackoverflow.com/q/50338434
type: Answer
has comment: http://stackoverflow.com/comment/87694265
has comment: http://stackoverflow.com/comment/87694151
score: 1

http://stackoverflow.com/a/72385796
type: Answer
downvote count: 0
upvote count: 1
has body: Both answers below using dict comprehension: So Question 1: How to get maximum column length for each columns in the data frame max_length_all_cols = {col: df.loc[:, col].astype(str).apply(len).max() for col in df.columns} Question 2: How to get maximum length of each column for only object type columns max_length_object_cols = {col: df.loc[:, col].astype(str).apply(len).max() for col in df.select_dtypes([object]).columns}
answers question: http://stackoverflow.com/q/50339065
score: 1

http://stackoverflow.com/a/50380333
has body: The solution is to use to_datetime s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000']) s 0 3/11/2000 1 3/12/2000 2 3/13/2000 dtype: object pd.to_datetime(s) 0 2000-03-11 1 2000-03-12 2 2000-03-13 dtype: datetime64[ns] So in your situation, you could write df['StartingDate2'] = pd.to_datetime(XY['StartingDate'], format='%m/%d/%Y') and in fact you can neglect the format keyword here. But if you provide it, you will get a huge speed increase. Benchmarks s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000']*1000) Without format %%timeit pd.to_datetime(s) 453 ms ± 3.05 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) With format %%timeit pd.to_datetime(s, format='%m/%d/%Y') 9.68 ms ± 44.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Note for me: Always provide the format string if possible Answer for updated question You can use date times floor function df = pd.DataFrame(pd.to_datetime(['2015-09-29T14:34:39.000000000', '2015-10-07T14:13:03.000000000', '2015-10-07T19:17:50.000000000', '2017-12-05T14:06:42.000000000', '2017-12-06T16:36:44.000000000', '2017-12-06T18:26:49.000000000']), columns=['A']) df['B'] = df['A'].dt.floor('d') df.dtypes A datetime64[ns] B datetime64[ns] dtype: object df A B 0 2015-09-29 14:34:39 2015-09-29 1 2015-10-07 14:13:03 2015-10-07 2 2015-10-07 19:17:50 2015-10-07 3 2017-12-05 14:06:42 2017-12-05 4 2017-12-06 16:36:44 2017-12-06 5 2017-12-06 18:26:49 2017-12-06
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50380203
type: Answer
has comment: http://stackoverflow.com/comment/87778879
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87805479
has comment: http://stackoverflow.com/comment/87817656
has comment: http://stackoverflow.com/comment/87825004
answers question: http://stackoverflow.com/q/50380203

http://stackoverflow.com/a/50254347
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50254018
type: Answer
has body: A Python solution. data = """3074 88, 3074 1935, 3478-3480 3074, 3478-3479 27015-27030, 27036-27037 4380, 27000-27031, 27036""" delimiters = "\n\r\t," for d in delimiters: data = data.replace(d, ' ') lines = data.split(' ') numbers = [] i = 0 for line in lines: if line == '': continue elif '-' in line: t = line.split('-') numbers += range(int(t[0]), int(t[1]) + 1) else: numbers.append(int(line)) Out: [3074, 88, 3074, 1935, 3478, 3479, 3480, 3074, 3478, 3479, 27015, 27016, 27017, 27018, 27019, 27020, 27021, 27022, 27023, 27024, 27025, 27026, 27027, 27028, 27029, 27030, 27036, 27037, 4380, 27000, 27001, 27002, 27003, 27004, 27005, 27006, 27007, 27008, 27009, 27010, 27011, 27012, 27013, 27014, 27015, 27016, 27017, 27018, 27019, 27020, 27021, 27022, 27023, 27024, 27025, 27026, 27027, 27028, 27029, 27030, 27031, 27036]
answers question: http://stackoverflow.com/q/50254018
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87746981
score: 0
has text: Did the changes apply to you console session? Check with `env` on the console!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50365268

http://stackoverflow.com/comment/87693174
has text: what is the value for your `n`?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50338307

http://stackoverflow.com/q/50241048
has answer: http://stackoverflow.com/a/50241225
answer count: 1
has title: Python - Print readable format from String containing \n and other unicodes?
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/87499560
tagged with: format
score: 0
tagged with: readable
type: Question
has body: this message was originally a set and then i converted into string with str(a) a = "Let’s trade! An Old Friendship, A New Day! Here comes the old, visiting at your home. It comes with a new story, about how to live the present, about how in his past he did wrong. The new day shines andx2" and for some reason when I print it print(a) it keeps all the and ’s and doesn't format it into a new line or ’ into " ' " right quotation mark.. so it just shows as this in plaintext Let’s trade! An Old Friendship, A New Day! Here comes the old, visiting at your home. It comes with a new story, about how to live the present, about how in his past he did wrong. The new day shines andx2 normally if i do print("Let’s trade! An Old Friendship, A New Day! Here comes the old, visiting at your home. It comes with a new story, about how to live the present, about how in his past he did wrong. The new day shines andx2") it will output it as Let’s trade! An Old Friendship, A New Day! Here comes the old, visiting at your home. It comes with a new story, about how to live the present, about how in his past he did wrong. The new day shines and how do i fix this?
has comment: http://stackoverflow.com/comment/87499586
type: UnansweredQuestion

http://stackoverflow.com/comment/87537701
comment on: http://stackoverflow.com/a/50259805
type: Comment
type: AnswerComment
has text: `(mytable.groupby('meet_id') .label.transform(lambda x: list(x.cumsum())) .apply(lambda x: sorted(set(x))))` gets back OP's sorted list. I like this solution. +1
score: 1

http://stackoverflow.com/comment/87524531
type: QuestionComment
has text: @DanielF I appreciate your comment. However, I teach first-year students linear algebra and ask them to use Numpy. They find it frustrating to remember the arguments. Sometimes they forget about it, and Python could occupy the whole memory trying to create a 1M x 1M matrix, for example.
comment on: http://stackoverflow.com/q/50248804
type: Comment
score: 0

http://stackoverflow.com/q/50293689
has comment: http://stackoverflow.com/comment/87684663
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/24833130
has comment: http://stackoverflow.com/comment/87685207
type: Question
has comment: http://stackoverflow.com/comment/87844308
has comment: http://stackoverflow.com/comment/87610454
answer count: 0
has comment: http://stackoverflow.com/comment/87684701
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87672520
has body: I have Series where the index and column name are stocked. I want to print only the index and column from Series and not whole dataframe. Series 0 wkeans 1 wContour 2 wDarkBand 3 wContour Dataframe wContour wDarkBand wkeans 0 92.000000 0.0 94.0 1 90.000000 88.0 84.0 2 84.000000 86.0 84.0 3 84.000000 0.0 102.0 I want to have : I.e. : 94.0 90.0 86.0 84.0 dfW.loc[myseries], dfW.loc[s.index, s.values] do not work, any suggestion ? Thanks
tagged with: python
has title: Dataframe loc from series, python
has comment: http://stackoverflow.com/comment/87678728
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/24833130

http://stackoverflow.com/a/50242048
answers question: http://stackoverflow.com/q/50241742
type: Answer
has body: In Python there is a notion of "better to ask for forgiveness than permission". In other words, just try what you think might work and then recover from it if it doesn't, rather than try check that it might work in the first place. An example would be trying to access a list index that doesn't exist, rather than checking the length of the list first. There are debates about how far this goes e.g. here among many others. The simplest example here would be: command = '!help' split_string = command.split() try: modifiers = split_string[1] except IndexError: # Well, seems it didn't work modifiers = None It's not a good idea to just blanket except all errors. Although you're recovering from a failure, you know beforehand what might go wrong here so you should catch that specific error.
upvote count: 6
score: 4
downvote count: 2

http://stackoverflow.com/comment/87673145
type: Comment
type: QuestionComment
has text: No you are not missing anything, I meant, eventually I want to run a selenium script using CGI but for now just to make sure it is working, I am testing it with a hello world script.
score: 0
comment on: http://stackoverflow.com/q/50301696

http://stackoverflow.com/q/50382347
tagged with: python
has body: This is my first time use python, i want to know how do i post body like below thanks. POST /httpTest/cityCountry.asp HTTP/1.1 Host: www.chilkatsoft.com Content-Type: application/x-www-form-urlencoded Content-Length: 25 city=Paris&amp;country=France
score: 0
has title: Python post application/x-www-form-urlencoded questions
answer count: 0
tagged with: post
has comment: http://stackoverflow.com/comment/87780630
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87780598

http://stackoverflow.com/comment/87633573
type: QuestionComment
type: Comment
has text: Possible duplicate of [Why does json.dumps escape non-ascii characters with "\uxxxx"](https://stackoverflow.com/questions/32411965/why-does-json-dumps-escape-non-ascii-characters-with-uxxxx)
score: 0
comment on: http://stackoverflow.com/q/50307593

http://stackoverflow.com/q/50337070
tagged with: conditional-statements
tagged with: list
has answer: http://stackoverflow.com/a/50337207
tagged with: filter
has answer: http://stackoverflow.com/a/50416554
answer count: 3
has body: I'm trying to create a new list from another list based on condition: lst = [("Id01","Code1",1),("Id01","#instr1",1),("Id01","#instr2",1),("Id01","#instr4",1), ("Id01","Code2",1),("Id01","#instr3",1),("Id01","#instr2",1),("Id02","Code2",1), ("Id02","#instr2",1),("Id02","#instr5",1)] table, instrlist = '', ''; code, instructions = [], []; qty = 0 for idx, l in enumerate(lst): table = l[0] if not l[1].startswith('#'): code = l[1]; qty = l[2]; instructions = [] else: instructions.append(l[1]) print idx, table, code, instructions, qty Every time the code is present on the tuples after a tuple containing '#', I need to transmit the correct line in to another part of the program and reset to start processing another one. I've put a series of conditions and I got this result: 0 Id01 Code1 [] 1 1 Id01 Code1 ['#instr1'] 1 2 Id01 Code1 ['#instr1', '#instr2'] 1 3 Id01 Code1 ['#instr1', '#instr2', '#instr4'] 1 4 Id01 Code2 [] 1 5 Id01 Code2 ['#instr3'] 1 6 Id01 Code2 ['#instr3', '#instr2'] 1 7 Id02 Code2 [] 1 8 Id02 Code2 ['#instr2'] 1 9 Id02 Code2 ['#instr2', '#instr5'] 1 However the result I really need is 3 Id01 Code1 ['#instr1', '#instr2', '#instr4'] 1 6 Id01 Code2 ['#instr3', '#instr2'] 1 9 Id02 Code2 ['#instr2', '#instr5'] 1 Of what condition I need to filter again? I'm not skilled enough to use list comprehension or a built-in filter, and I would like to leave the code as much readable as possible (for a newbie), at least until I will learn more. UPDATE: The solution offered by jpp seems to be the most efficient and readable: from collections import defaultdict from itertools import count, chain lst = [("Id01","Code1",1),("Id01","#instr1",1),("Id01","#instr2",1),("Id01","#instr4",1), ("Id01","Code2",1),("Id01","#instr3",1),("Id01","#instr2",1),("Id02","Code2",1), ("Id02","#instr2",1),("Id02","#instr5",1)] d = defaultdict(list) enums = [] c = count() for ids, action, num in lst: if not action.startswith('#'): my_ids, my_action = ids, action enums.append(next(c)) else: d[(…
score: 1
possible better answer: http://stackoverflow.com/a/50337207
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50337849
has title: Create a new list from another list based on condition
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50416554
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/50315060
downvote count: 0
upvote count: 1
has body: Just use sorted over mapping capitalize: with open("test.txt", "r") as f: result = sorted(map(lambda x: x.capitalize().split(":"), f.readlines())) Here you have a live example
answers question: http://stackoverflow.com/q/50315029
score: 1
type: Answer

http://stackoverflow.com/q/50316488
has answer: http://stackoverflow.com/a/50316948
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87648743
has comment: http://stackoverflow.com/comment/87648771
type: Question
has title: After I exit from the remote server(CentOS-7), the `python3 manage.py runserver` will not work
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87648792
has comment: http://stackoverflow.com/comment/87648957
has body: I use the python3 manage.py runserver run the APIs of my Django-Rest-Framework project in my remote server(CentOS-7). But after I exit from the remote server(CentOS-7), the APIs will not service. If I login again to the remote server, APIs still not work, but I list the runserver command, it is there. [root@www ~]# ps aux | grep runserver lll 26439 0.0 0.5 275884 41704 ? S 07:29 0:00 python3 manage.py runserver lll 26443 3.1 1.0 380044 83264 ? S 07:29 10:22 /home/lll/repo/Qit/venv_dist/bin/python3 manage.py runserver root 32575 0.0 0.0 112680 972 pts/1 S+ 12:56 0:00 grep --color=auto runserver My question is, when I login the remote server to runserver the django, the APIs works, but I logout the remote server, the APIs can not access now. My settings of wsgi.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Qn.settings") import django print("django.setup()") django.setup() from socketio import Middleware from qn_admin_website_chat.views import sio django_app = get_wsgi_application() application = Middleware(sio, django_app) import eventlet import eventlet.wsgi eventlet.wsgi.server(eventlet.listen(('', 8000)), application) Some friends said can use eventlet.wsgi.server as distribute server, so I use this way to deployment my project.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87648721

http://stackoverflow.com/comment/87847673
score: 0
comment on: http://stackoverflow.com/q/50321158
has text: Please post your code at the end of your question above. Maybe someone will look at improving it for you!
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50351099
upvote count: 1
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87720645
accepted answer of: http://stackoverflow.com/q/50350944
has body: Your while loop prevents anything else to happen indeed. What you want here is to put your isGoal() checks in the move_&lt;XXX&gt; event handlers and let turtle's own main loop run. EDIT: for your second question: However I need to press any key a second time in order for that reset to happen the reason is quite simple: you should call isGoal() after you move the player's turtle, not before: def move_left(): x = player.xcor() x -= playerspeed if x &lt; -175: x = -175 player.setx(x) isGoal()
answers question: http://stackoverflow.com/q/50350944
has comment: http://stackoverflow.com/comment/87721067
downvote count: 0
score: 1

http://stackoverflow.com/a/51681805
upvote count: 2
has body: I raised myself a similar question which confused me for quite sometime. And I think I found a possible explanation: If you look at the file_download_and_convert_voc2012.sh, there are lines marked by "# Remove the colormap in the ground truth annotations". This part process the original SegmentationClass files and produce the raw segmented image files, which have each pixel value between 0 : 20. (If you may ask why, check this post: Python: Use PIL to load png file gives strange results)
downvote count: 0
answers question: http://stackoverflow.com/q/50250332
type: Answer
score: 2

numpy
tags question: http://stackoverflow.com/q/50365310
tags question: http://stackoverflow.com/q/50321978
tags question: http://stackoverflow.com/q/50261473
tags question: http://stackoverflow.com/q/50323360
tags question: http://stackoverflow.com/q/50335176
tags question: http://stackoverflow.com/q/50319788
tags question: http://stackoverflow.com/q/50341162
tags question: http://stackoverflow.com/q/50276044
tags question: http://stackoverflow.com/q/50315932
tags question: http://stackoverflow.com/q/50236427
tags question: http://stackoverflow.com/q/50368824
tags question: http://stackoverflow.com/q/50276329
tags question: http://stackoverflow.com/q/50283008
tags question: http://stackoverflow.com/q/50338311
tags question: http://stackoverflow.com/q/50276851
tags question: http://stackoverflow.com/q/50237761
tags question: http://stackoverflow.com/q/50348504
tags question: http://stackoverflow.com/q/50271399
tags question: http://stackoverflow.com/q/50367451
tags question: http://stackoverflow.com/q/50315982
tags question: http://stackoverflow.com/q/50317305
tags question: http://stackoverflow.com/q/50309668
tags question: http://stackoverflow.com/q/50298506
tags question: http://stackoverflow.com/q/50327440
tags question: http://stackoverflow.com/q/50261680
tags question: http://stackoverflow.com/q/50344370
tags question: http://stackoverflow.com/q/50295457
tags question: http://stackoverflow.com/q/50255668
tags question: http://stackoverflow.com/q/50382717
tags question: http://stackoverflow.com/q/50289136
tags question: http://stackoverflow.com/q/50277199
tags question: http://stackoverflow.com/q/50278332
tags question: http://stackoverflow.com/q/50233649
tags question: http://stackoverflow.com/q/50306145
tags question: http://stackoverflow.com/q/50302529
tags question: http://stackoverflow.com/q/50305175
tags question: http://stackoverflow.com/q/50231266
tags question: http://stackoverflow.com/q/50330112
tags question: http://stackoverflow.com/q/50374409
tags question: http://stackoverflow.com/q/50375377
tags question: http://stackoverflow.com/q/50298570
tags question: http://stackoverflow.com/q/50374672
tags question: http://stackoverflow.com/q/50368416
tags question: http://stackoverflow.com/q/50251408
tags question: http://stackoverflow.com/q/50294355
tags question: http://stackoverflow.com/q/50365414
tags question: http://stackoverflow.com/q/50303560
tags question: http://stackoverflow.com/q/50274072
tags question: http://stackoverflow.com/q/50374882
tags question: http://stackoverflow.com/q/50235377
tags question: http://stackoverflow.com/q/50305976
tags question: http://stackoverflow.com/q/50271519
tags question: http://stackoverflow.com/q/50312082
tags question: http://stackoverflow.com/q/50261604
tags question: http://stackoverflow.com/q/50325658
tags question: http://stackoverflow.com/q/50233954
tags question: http://stackoverflow.com/q/50239099
tags question: http://stackoverflow.com/q/50272134
tags question: http://stackoverflow.com/q/50346006
tags question: http://stackoverflow.com/q/50275057
tags question: http://stackoverflow.com/q/50312426
tags question: http://stackoverflow.com/q/50328545
tags question: http://stackoverflow.com/q/50319661
tags question: http://stackoverflow.com/q/50320525
tags question: http://stackoverflow.com/q/50278105
tags question: http://stackoverflow.com/q/50325541
type: Tag
tags question: http://stackoverflow.com/q/50378820
tags question: http://stackoverflow.com/q/50358310
tags question: http://stackoverflow.com/q/50244910
tags question: http://stackoverflow.com/q/50304457
tags question: http://stackoverflow.com/q/50351264
tags question: http://stackoverflow.com/q/50264196
tags question: http://stackoverflow.com/q/50261684
tags question: http://stackoverflow.com/q/50310345
tags question: http://stackoverflow.com/q/50266996
tags question: http://stackoverflow.com/q/50239640
tags question: http://stackoverflow.com/q/50336735
tags question: http://stackoverflow.com/q/50248804
tags question: http://stackoverflow.com/q/50257687

http://stackoverflow.com/q/50316691
favorite count: 0
has answer: http://stackoverflow.com/a/50316920
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87649612
tagged with: python
score: -1
has title: when I click a button, color string will change dynamically & print on the screen
has body: I have two button for print their color on the screen. button1 = tk.Button(frame,height = 1, width = 2,bg="Red") button1.pack() button2 = tk.Button(frame,height = 1, width = 2,bg="Blue") button2.pack() So when i click Button1, my string (colorchange) will include "Red". when i print that then it will write on the screen as ==>> Red.
type: Question
tagged with: python-3.x
tagged with: tkinter
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50316920
downvote count: 1

http://stackoverflow.com/a/50344425
upvote count: 3
has comment: http://stackoverflow.com/comment/87704624
type: AcceptedAnswer
downvote count: 0
has body: Keyword arguments always use the fixed identifier as the key. Use keyword expansion instead. new_dict.update(**{key: val}) Or if new_dict really is a dict, just pass the dict itself. new_dict.update({key: val})
accepted answer of: http://stackoverflow.com/q/50344376
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50344376

http://stackoverflow.com/a/50348594
upvote count: 1
has body: galmeriol is right. Go for as he has suggested. &gt;&gt;&gt; a.all() {'a': 1} &gt;&gt;&gt;&gt; a.all()['a'] 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50348504
downvote count: 0

http://stackoverflow.com/q/50375793
has comment: http://stackoverflow.com/comment/87771543
has comment: http://stackoverflow.com/comment/87771174
has comment: http://stackoverflow.com/comment/87783435
tagged with: python-3.x
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87771225
linked to: http://stackoverflow.com/q/1950414
has title: elegant way to have an almost-copy-constructor that allows to update some members
tagged with: python-3.6
has body: i have an instance of a container class that serves as basis for several other instances. it is called data0 in the example. i would like to be able to make copies of that and then update some of the members of the copies. yes, that could be done using the copy module, creating a copy and assigning the new values for the members. but what if the container class is immutable? i was hoping to be able to implement what is needed to turn the class into a mapping (keys and __getitem__) and make __init__ accept the base class plus some modifications. this was probably inspired by the way you can update a dictionary: x = {'a': 0, 'b': 1, 'c': 2} y = {'b': 7} z = {**x, 'b': 7} print(z) # {'a': 0, 'b': 7, 'c': 2} so what i would like to be able to do is this: data3 = Container(**data0, b=7) print(data3) here is what i tried: class Container: KEYS = ('a', 'b', 'c') def __init__(self, a=None, b=None, c=None): self._a = a self._b = b self._c = c @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c def keys(self): return Container.KEYS def __getitem__(self, key): if key not in Container.KEYS: raise KeyError(key) return getattr(self, key) def __str__(self): return f'{self.__class__.__name__}(a={self.a}, b={self.b}, c={self.c})' data0 = Container(a=1, b=2, c=3) print(data0) # Container(a=1, b=2, c=3) data1 = Container(**data0) # 'copy constructor' print(data1) # Container(a=1, b=2, c=3) data2 = Container(**{**data0, 'b':7}) print(data2) # Container(a=1, b=7, c=3) the last method works but is ugly... as stated above: what i would like to be able to do is this: data3 = Container(**data0, b=7) print(data3) but this (understandably) fails with the error message TypeError: type object got multiple values for keyword argument 'b' how can i fix that? or is there a more obvious way to create a new instance from a given basis with updated members? or is the standard way to go just to inherit from that class with the desired value…
favorite count: 0
linked to: http://stackoverflow.com/q/50384549
type: Question
has comment: http://stackoverflow.com/comment/87768437
score: 1
tagged with: python

http://stackoverflow.com/a/50317171
downvote count: 0
upvote count: 1
has body: You can write your own exception, and raise it: class InvalidCard(ValueError): pass (...) for card in hand: if card.isdigit(): result += int(str) elif card == "X": result += 10 elif card == "A": result += 11 num_aces += 1 else: raise InvalidCard(card + " is invalid")
type: Answer
answers question: http://stackoverflow.com/q/50317126
score: 1
has comment: http://stackoverflow.com/comment/87650130

http://stackoverflow.com/comment/87653860
score: 0
comment on: http://stackoverflow.com/q/50317173
type: Comment
has text: I am not a regular windows user too, and I really appreciate the effort. I have added pics now. If the question is still unclear I can explain further.
type: QuestionComment

http://stackoverflow.com/comment/87695945
comment on: http://stackoverflow.com/q/50338912
has text: The question [I wrote this in response to](https://stackoverflow.com/questions/50321642/in-discord-py-how-do-i-make-it-so-the-bot-only-works-in-one-server/50321784#50321784) was on how to leave all servers but one. You'll want to change `!=` to `==` (assuming `'server id'` is the `id` of the server you want to leave)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50378491
tagged with: io
has comment: http://stackoverflow.com/comment/87773178
has comment: http://stackoverflow.com/comment/87773312
upvote count: 1
tagged with: python
score: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/87773432
has comment: http://stackoverflow.com/comment/87773604
has comment: http://stackoverflow.com/comment/87773156
has body: I always make these bash commands to adjust files where I have to either: (1) copy from stdout; or (2) create a file to copy from that I will never use again. Is it possible to use some type of file object that actually dumps the output into the clipboard? # In Python with someclipboardfileobject as f: for i in range(10): print(i, file=f) # Open up TextEdit # Paste 0 1 2 3 4 5 6 7 8 9
has comment: http://stackoverflow.com/comment/87773368
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/87773389
linked to: http://stackoverflow.com/q/11063458
favorite count: 0
has comment: http://stackoverflow.com/comment/87773486
has answer: http://stackoverflow.com/a/50378559
type: Question
has title: Is it possible to write to clipboard with `print` in Python?
duplicate of: http://stackoverflow.com/q/11833428
has comment: http://stackoverflow.com/comment/87773367
tagged with: clipboard
has comment: http://stackoverflow.com/comment/87773149
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/11063458
has comment: http://stackoverflow.com/comment/87773148

http://stackoverflow.com/comment/87612362
has text: Sorry, I have seen your comment below now
comment on: http://stackoverflow.com/a/50293110
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87788656
type: Comment
type: AnswerComment
has text: Hi, you could use something like this: df.groupby('ID').last() it gives you the last item for every user id, and then you could take a subset of the id's in your list (or the other way around)
comment on: http://stackoverflow.com/a/50384124
score: 0

matplotlib
tags question: http://stackoverflow.com/q/50239331
tags question: http://stackoverflow.com/q/50310059
tags question: http://stackoverflow.com/q/50384961
tags question: http://stackoverflow.com/q/50372299
tags question: http://stackoverflow.com/q/50287490
tags question: http://stackoverflow.com/q/50334782
tags question: http://stackoverflow.com/q/50288983
tags question: http://stackoverflow.com/q/50346801
tags question: http://stackoverflow.com/q/50369623
tags question: http://stackoverflow.com/q/50297863
tags question: http://stackoverflow.com/q/50373178
tags question: http://stackoverflow.com/q/50245325
tags question: http://stackoverflow.com/q/50333477
tags question: http://stackoverflow.com/q/50285037
tags question: http://stackoverflow.com/q/50342255
tags question: http://stackoverflow.com/q/50264841
tags question: http://stackoverflow.com/q/50239503
tags question: http://stackoverflow.com/q/50261651
tags question: http://stackoverflow.com/q/50366368
tags question: http://stackoverflow.com/q/50293846
tags question: http://stackoverflow.com/q/50285820
tags question: http://stackoverflow.com/q/50357852
tags question: http://stackoverflow.com/q/50350986
tags question: http://stackoverflow.com/q/50306029
tags question: http://stackoverflow.com/q/50315002
tags question: http://stackoverflow.com/q/50271016
tags question: http://stackoverflow.com/q/50275846
tags question: http://stackoverflow.com/q/50307071
tags question: http://stackoverflow.com/q/50296824
tags question: http://stackoverflow.com/q/50315792
tags question: http://stackoverflow.com/q/50282505
tags question: http://stackoverflow.com/q/50309815
tags question: http://stackoverflow.com/q/50306012
tags question: http://stackoverflow.com/q/50346498
tags question: http://stackoverflow.com/q/50361422
tags question: http://stackoverflow.com/q/50271807
tags question: http://stackoverflow.com/q/50301229
tags question: http://stackoverflow.com/q/50251570
tags question: http://stackoverflow.com/q/50342300
tags question: http://stackoverflow.com/q/50379132
tags question: http://stackoverflow.com/q/50358662
tags question: http://stackoverflow.com/q/50311704
tags question: http://stackoverflow.com/q/50253008
tags question: http://stackoverflow.com/q/50352157
tags question: http://stackoverflow.com/q/50356711
tags question: http://stackoverflow.com/q/50257509
tags question: http://stackoverflow.com/q/50319925
tags question: http://stackoverflow.com/q/50257320
tags question: http://stackoverflow.com/q/50361118
tags question: http://stackoverflow.com/q/50315148
tags question: http://stackoverflow.com/q/50344802
tag name: matplotlib
tags question: http://stackoverflow.com/q/50264517
tags question: http://stackoverflow.com/q/50237183
tags question: http://stackoverflow.com/q/50361685
tags question: http://stackoverflow.com/q/50308610
tags question: http://stackoverflow.com/q/50271043
tags question: http://stackoverflow.com/q/50335503
tags question: http://stackoverflow.com/q/50235752
tags question: http://stackoverflow.com/q/50320275
tags question: http://stackoverflow.com/q/50322470
tags question: http://stackoverflow.com/q/50317308
tags question: http://stackoverflow.com/q/50356795
tags question: http://stackoverflow.com/q/50341684
tags question: http://stackoverflow.com/q/50247596
tags question: http://stackoverflow.com/q/50338284
tags question: http://stackoverflow.com/q/50311861
tags question: http://stackoverflow.com/q/50232363
tags question: http://stackoverflow.com/q/50368992
tags question: http://stackoverflow.com/q/50371855
tags question: http://stackoverflow.com/q/50315780
tags question: http://stackoverflow.com/q/50346166
tags question: http://stackoverflow.com/q/50350051
tags question: http://stackoverflow.com/q/50330320
tags question: http://stackoverflow.com/q/50355293
tags question: http://stackoverflow.com/q/50333186
tags question: http://stackoverflow.com/q/50331539
tags question: http://stackoverflow.com/q/50254813
tags question: http://stackoverflow.com/q/50359593
tags question: http://stackoverflow.com/q/50350996

http://stackoverflow.com/q/50252156
has answer: http://stackoverflow.com/a/77287795
possible better answer: http://stackoverflow.com/a/77287795
tagged with: flask
linked to: http://stackoverflow.com/q/3759981
favorite count: 0
type: Question
has body: I want to get user's location. When I test the following code on my local computer it returns the correct position. Tried to change location with vpn and everything worked correctly too. app.py: @app.route('/') def index(): url = 'http://freegeoip.net/json' r = requests.get(url) j = json.loads(r.text) city = j['city'] print(city) But when I run my site with the same code on pythonanywhere it returns one incorrect city all the time, doesn't matter wherever I connect from. Does it return the location of the server instead? How can I get the correct location of each user?
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/50252288
accepted answer: http://stackoverflow.com/a/50252288
has title: Get location of user in Flask

http://stackoverflow.com/comment/87583299
type: QuestionComment
comment on: http://stackoverflow.com/q/50282765
score: 0
type: Comment
has text: `plt.plot()` expects numeric or otherwise plottable data. You cannot feed it some plotting object like an AxesSubplot. So the question is, what are trying to achive here?

http://stackoverflow.com/comment/87614419
type: QuestionComment
has text: @GabrielFernandes Yup, was already mentioned in the answer I'd written. Cheers.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50298705

http://stackoverflow.com/comment/87558069
type: QuestionComment
comment on: http://stackoverflow.com/q/50250010
score: 3
has text: I guess the issue is discussed here: https://youtrack.jetbrains.com/issue/PY-14534
type: Comment

http://stackoverflow.com/a/50264667
score: 3
type: Answer
has body: You can use in with a for loop so it work like this s = "I just go on Facebook today" banned_words = ["facebook", "Facebook", "Netflix"] exist = False for word in banned_words: if (word in s): print('banned words "{}" found in str'.format(word)) exist = True break if (not exist): print ('Banned words not found in str') output: banned words "Facebook" found in str
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50264597

exception
tags question: http://stackoverflow.com/q/50293827
tags question: http://stackoverflow.com/q/50262750
tags question: http://stackoverflow.com/q/50327868
tags question: http://stackoverflow.com/q/50233935
tags question: http://stackoverflow.com/q/50361475
tags question: http://stackoverflow.com/q/50320281
tags question: http://stackoverflow.com/q/50275767
tags question: http://stackoverflow.com/q/50274084
tags question: http://stackoverflow.com/q/50238135
tag name: exception
tags question: http://stackoverflow.com/q/50331303
tags question: http://stackoverflow.com/q/50351567
type: Tag
tags question: http://stackoverflow.com/q/50382642
tags question: http://stackoverflow.com/q/50246680

http://stackoverflow.com/comment/87630010
has text: *causing it to potentially have a runtime error constantly* - you can avoid that catching only the required exceptions. For instance, `except (AttributeError, ValueError)`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50304607
type: Comment
score: 2

http://stackoverflow.com/a/56637583
has comment: http://stackoverflow.com/comment/139632451
score: 1
answers question: http://stackoverflow.com/q/50240210
type: Answer
has body: It looks like the way to do this in the API is: from jira import JIRA jira = JIRA(basic_auth=('username', 'password'), options = {'server': 'url'}) # get an example issue that has the field you're interested in issue = jira("PRJ-1") meta = jira.editmeta(issue) # inspect the meta to get the field you want to look at allowed_values = [v['value'] for v in meta['fields']['customfield_99999']['allowedValues']]
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87573156
type: Comment
has text: BTW, this is from experience... I've analyzed data with lots of zeros (which really should have been NaN values). Filtering them out is both correct and also prevents upward bias in the case of 'bad' data.
comment on: http://stackoverflow.com/a/50246196
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87663238
score: 0
comment on: http://stackoverflow.com/q/50322384
has text: update your scipy
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50243108
answers question: http://stackoverflow.com/q/50242968
has body: Main question Is there a duplicate value in a column, True/False? ╔═════════╦═══════════════╗ ║ Student ║ Date ║ ╠═════════╬═══════════════╣ ║ Joe ║ December 2017 ║ ╠═════════╬═══════════════╣ ║ Bob ║ April 2018 ║ ╠═════════╬═══════════════╣ ║ Joe ║ December 2018 ║ ╚═════════╩═══════════════╝ Assuming above dataframe (df), we could do a quick check if duplicated in the Student col by: boolean = not df["Student"].is_unique # True (credit to @Carsten) boolean = df['Student'].duplicated().any() # True Further reading and references Above we are using one of the Pandas Series methods. The pandas DataFrame has several useful methods, two of which are: drop_duplicates(self[, subset, keep, inplace]) - Return DataFrame with duplicate rows removed, optionally only considering certain columns. duplicated(self[, subset, keep]) - Return boolean Series denoting duplicate rows, optionally only considering certain columns. These methods can be applied on the DataFrame as a whole, and not just a Serie (column) as above. The equivalent would be: boolean = df.duplicated(subset=['Student']).any() # True # We were expecting True, as Joe can be seen twice. However, if we are interested in the whole frame we could go ahead and do: boolean = df.duplicated().any() # False boolean = df.duplicated(subset=['Student','Date']).any() # False # We were expecting False here - no duplicates row-wise # ie. Joe Dec 2017, Joe Dec 2018 And a final useful tip. By using the keep paramater we can normally skip a few rows directly accessing what we need: keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. Example to play around with import pandas as pd import io data = '''\ Student,Date Joe,December 2017 Bob,April 2018 Joe,December 2018''' df = pd.read_csv(io.StringIO(data), sep=',') # Approach 1: Simple True/False boolean = df.duplicated(subset=['Student']).any() print(…
downvote count: 0
upvote count: 129
has comment: http://stackoverflow.com/comment/87504814
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87504842
has comment: http://stackoverflow.com/comment/87515864
accepted answer of: http://stackoverflow.com/q/50242968
score: 129
type: Answer

http://stackoverflow.com/comment/87539581
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ one additional question: if the field is a List instead of a Set. How would I alter the `lambda` function to add the Lists together into. For example: `.apply(lambda x: set(values1 + values2))`. What would be the correct code for this?
comment on: http://stackoverflow.com/q/50260261
score: 0

http://stackoverflow.com/a/50306346
accepted answer of: http://stackoverflow.com/q/50306251
type: Answer
answers question: http://stackoverflow.com/q/50306251
has body: You should use an xml parser: soup = BeautifulSoup(content, "xml")
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50633915
score: 3
upvote count: 3
downvote count: 0
has body: If anyone finds this by a search, the easiest solution I've found (I'm OP) is to use use the pandas.melt() function. This concatenates all the columns into a single column, but adds a second column that preserves the column title adjacent to each value. This dataframe can be passed directly to seaborn.
type: Answer
answers question: http://stackoverflow.com/q/50337237

http://stackoverflow.com/a/50319233
has comment: http://stackoverflow.com/comment/87654528
has comment: http://stackoverflow.com/comment/87654442
has comment: http://stackoverflow.com/comment/87654702
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50317308
score: 1
type: AcceptedAnswer
has body: As mentioned in the comments, you don't specify the axis object, so therefore plt.XYZ just takes the last object to perform the function. A way to overcome this problem is to store each axis object in a variable so you can address them separately. Here is an example as close as possible to your code: import numpy as np import matplotlib.pyplot as plt Choice = input('Which figure do you want to run: \n *for Fig.1 , write 1 \n *for Fig.2, write 2 \n *for both , write b \n--&gt; ') Etta_Source={};Etta_Source1={};QKN_Source={} for E_So in [100,200,400,800,600,1000]: for Temp in range(0,110,10): Etta = 0.8 - ((3.41*Temp)+(0.014*(Temp)**2))/E_So if Choice == '1' or Choice == 'b': QKN_Source[Temp] = Etta*2.3*E_So Etta_Source[Temp] = Etta if E_So == 1000 and (Choice == '2' or Choice == 'b'): Etta_Source1[Temp]=Etta if Choice == '1' or Choice == 'b': fig1 = plt.figure(1) #get axis object for this figure ax1 = plt.gca() #now perform all commands with this axis object ax1.plot(QKN_Source.keys(),QKN_Source.values(),label='D = %s'%E_So) QKN_Source.clear() if Choice == '2' or Choice == 'b': fig2 = plt.figure(2) #and create a separate axis object for the second figure ax2 = plt.gca() ax2.plot(Etta_Source.keys(),Etta_Source.values(),label='C= %s'%E_So) Etta_Source.clear() axlist = [] #collect the axes for the choices if Choice == '2' or Choice == 'b': ax2.axhline(0.8,ls='-.',color='skyblue') ax2.fill_between(Etta_Source1.keys(),Etta_Source1.values(),0.8,facecolor='wheat') ax2.axhspan(0.8,1.0,alpha=0.5, color='c') ax2.axis([0,100,0,1]) ax2.text(50, 0.9, r'Area 1',fontsize=14,fontweight='bold') ax2.text(80, 0.6, r'Area 2',fontsize=14,fontweight='bold') ax2.set_yticks(np.arange(0,1.1,0.1)) ax2.set_ylabel('W',fontsize=14) axlist.append(ax2) if Choice == '1' or Choice == 'b': ax1.axis([0,100,0,2000]) ax1.set_ylabel('V',fontsize=14) axlist.append(ax1) #now we have to apply these commands to both axis objects, i.e., both figures for ax in axlist: ax.grid(True) ax.set_title('Results',color…
accepted answer of: http://stackoverflow.com/q/50317308
type: Answer

http://stackoverflow.com/q/50235265
type: Question
has body: Here's the relevant .py code: from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.core.image import Image from kivy.graphics import Color, Rectangle from kivy.core.audio import SoundLoader from kivy.core.text import LabelBase import pygame from pygame.locals import* import random class RootScreen(ScreenManager): pass class LevelOneBedroomScreen(Screen): def __init__(self, **kwargs): super(LevelOneBedroomScreen, self).__init__(**kwargs) def next_text(self): if self.ids.level_one_bedroom_text.text == '*YAWN*': self.ids.level_one_bedroom_image.source = 'placeholder_background2.png' self.ids.level_one_bedroom_text.text = 'Hello' elif self.ids.level_one_bedroom_text.text == 'Hello': self.manager.current = 'level one bedroom choice' class LevelOneBedroomChoiceScreen(Screen): def __init__(self, **kwargs): super(LevelOneBedroomChoiceScreen, self).__init__(**kwargs) def get_image(self): #This part is not working self.ids.level_one_bedroom_choice_image.source = LevelOneBedroomScreen.ids.level_one_bedroom_image.source class screensApp(App): def build(self): return RootScreen() if __name__ == "__main__": screensApp().run() Near the bottom I commented the part of the code that does not work. I have two, nearly identical screens where one LevelOneBedroomScreen has text and LevelOneBedroomChoiceScreen has buttons. I need both background images to be the same, and since the first screen updates images occasionally I wrote something in the .kv file to hopefully pull the image from the first screen but it results in an error. Here is the relevant code from the .kv: #:import FadeTransition kivy.uix.screenmanager.FadeTransition &lt;RootScreen&gt;: transition: FadeTransition() LevelOneBedroomScreen: LevelOneBedroomChoiceScreen: &lt;LevelOneBedroomScreen&gt;: name: 'level one bedroom' id: level_one_bedroom Image: …
has comment: http://stackoverflow.com/comment/87496210
has comment: http://stackoverflow.com/comment/87495521
has comment: http://stackoverflow.com/comment/87495440
tagged with: python
tagged with: kivy
has title: Python Kivy referencing between classes
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50239783
has comment: http://stackoverflow.com/comment/87493460
has answer: http://stackoverflow.com/a/50239783
has comment: http://stackoverflow.com/comment/87495477
answer count: 1
has comment: http://stackoverflow.com/comment/87495451
has comment: http://stackoverflow.com/comment/87493359

http://stackoverflow.com/q/50233954
has answer: http://stackoverflow.com/a/50234176
has comment: http://stackoverflow.com/comment/87485263
favorite count: 0
tagged with: numpy
has body: I want to load more than 10000 images in my 8gb ram in the form of numpy arrays.So far I have tried cv2.imread,keras.preprocessing.image.load_image,pil,imageio,scipy.I want to do it the fastest way possible but I can't figure out which on is it.
has answer: http://stackoverflow.com/a/50234119
type: Question
has title: fastest way to load images in python for processing
possible better answer: http://stackoverflow.com/a/61824499
tagged with: python
tagged with: computer-vision
score: 6
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50234176
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/61824499
tagged with: image-processing
tagged with: machine-learning

http://stackoverflow.com/comment/87765137
score: 1
has text: There's so many things wrong this this post.... 1. if you have a setup.py it's `python setup.py install`, 2. SSL error can occur when pip is installing from the internet, you need to add a trusted host, search your error message in SO there's tons a dupe questions, 3. tkinter is built-in to python, you don't have to install it, (maybe tk/tkl but not the package tkinter) 4. If you're already using anaconda, use conda to install packages.
type: QuestionComment
comment on: http://stackoverflow.com/q/50374292
type: Comment

http://stackoverflow.com/comment/87504512
has text: When you get to a resolution, please remember to up-vote useful things and accept your favourite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.
type: QuestionComment
comment on: http://stackoverflow.com/q/50242564
score: 0
type: Comment

http://stackoverflow.com/q/50231266
has comment: http://stackoverflow.com/comment/87482874
answer count: 0
has comment: http://stackoverflow.com/comment/87482443
linked to: http://stackoverflow.com/q/27261350
type: Question
tagged with: numpy
tagged with: uint8t
has comment: http://stackoverflow.com/comment/87491104
type: UnansweredQuestion
has body: I need to read a file as bytes to use the webrtcvad library. I have done this like in the example from his github: def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width == 2 sample_rate = wf.getframerate() assert sample_rate in (8000, 16000, 32000) pcm_data = wf.readframes(wf.getnframes()) return pcm_data, sample_rate But now I need to convert this array of bytes to something I can work with, and I am doing this like so (like seen on here): wav_r = np.fromstring(wav_bytes, dtype=np.uint8) where wav_bytes it's the pcm_data from read_wav. But when I plot this wav_r I get something like this: and if I read the same file using librosa.load and I plot it I get something like this: which it is how wav_r should look like. So any idea on how can I correctly convert bytes to some array that I can work with? Thanks! PD: I have also tried using int8 instead of uint8 and it gives me this, which still incorrect:
tagged with: python
tagged with: wav
has comment: http://stackoverflow.com/comment/87481371
has title: Raw wav bytes to uint array or some other format
tagged with: bytestream
score: 0

google-api
tags question: http://stackoverflow.com/q/50368883
tags question: http://stackoverflow.com/q/50299537
tag name: google-api
tags question: http://stackoverflow.com/q/50234541
tags question: http://stackoverflow.com/q/50297037
tags question: http://stackoverflow.com/q/50340306
tags question: http://stackoverflow.com/q/50294533
tags question: http://stackoverflow.com/q/50370258
type: Tag

http://stackoverflow.com/comment/87603584
has text: @plalanne It will, but that's not the point. Even if the OP had used `rstrip` (strip from the right), it would have had the same effect, because the whole string is made of the strippable characters.
type: Comment
comment on: http://stackoverflow.com/a/50293460
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87529111
score: 0
type: AnswerComment
has text: Thanks! I got an error due to the last line: ----> 9 globals()[var_name] = pd.DataFrame(data[col_name]) TypeError: list indices must be integers, not str
comment on: http://stackoverflow.com/a/50254155
type: Comment

http://stackoverflow.com/q/50283461
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/87583397
type: UnansweredQuestion
tagged with: pdf-scraping
has comment: http://stackoverflow.com/comment/87583383
downvote count: 0
upvote count: 1
tagged with: python
tagged with: excel
favorite count: 0
has body: I am working with PDF documents containing lab results. The PDFs are identical except for the customer name, along with the respective sample value. Can Python be used to extract the specific values from the given location on the page and export to 1 excel document ? This would ideally be done in a batch format.
has title: Using Python to specific values from multiple PDFs and converting it to 1 excel sheet
score: 1
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/q/50314541
tagged with: printing
tagged with: for-loop
type: UnansweredQuestion
tagged with: addition
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87645315
has title: is it possible to put print strings/floats from a for loop to another text files?
score: 0
has body: for city,number in b: city = '{:^30}'.format(city) number = '{:&lt;5}'.format(number) print(city, number) I used this for loop, after I clicked run, it gave me: AKRON 65.5574 ALTON 69.6722 that's what I want to put into a new text file plus adding [61-70], is there any functions I can use to put them into a new text file? Thank you
tagged with: python
has answer: http://stackoverflow.com/a/50314598
has comment: http://stackoverflow.com/comment/87656231
tagged with: text-files

http://stackoverflow.com/comment/87537863
score: 0
comment on: http://stackoverflow.com/a/50259856
has text: @cᴏʟᴅsᴘᴇᴇᴅ I think it's a copy :( (that's if `df1.select_dtypes(object)._is_view` is anything to go by... I'm sure that's not the right way to do that anyway... brain's tired :) (think it's something like `values.base is... other.values.base` or something
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87543407
has text: @JohnSmith sure see my 2nd example.
type: AnswerComment
comment on: http://stackoverflow.com/a/50262194
score: 0
type: Comment

http://stackoverflow.com/a/50266927
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50265570
has body: A TCP connection consists of 2 almost independent unidirectional streams. The conn.close() closes only the stream from the client to the server. The connection from the server to the client is still open and the server still sends data. I know 2 option how to prevent server send data that are not necessary. Do not use the GET method. Use the OPTIONS method. If server supports the OPTIONS method (and it should) then handled it like a GET request but it sends HTTP response with HTTP headers but without body. Reset the connection instead closing it. You can reset connection when set SO_LINGER socket option - see Sending a reset in TCP/IP Socket connection for example.

http://stackoverflow.com/q/50232539
upvote count: 1
favorite count: 0
tagged with: series
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87482644
possible better answer: http://stackoverflow.com/a/50232697
linked to: http://stackoverflow.com/q/21291259
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50232697
accepted answer: http://stackoverflow.com/a/50232784
has comment: http://stackoverflow.com/comment/87482655
has answer: http://stackoverflow.com/a/50232784
type: AnsweredQuestion
answer count: 2
has title: Why does Python function return 1.0 (float) when `return 1` is specified?
has body: I have a lot of strings, some of which consist of 1 sentence and some consisting of multiple sentences. My goal is to determine which one-sentence strings end with an exclamation mark '!'. My code gives a strange result. Instead of returning '1' if found, it returns 1.0. I have tried: return int(1) but that does not help. I am fairly new to coding and do not understand, why is this and how can I get 1 as an integer? 'Sentences' 0 [This is a string., And a great one!] 1 [It's a wonderful sentence!] 2 [This is yet another string!] 3 [Strange strings have been written.] 4 etc. etc. e = df['Sentences'] def Single(s): if len(s) == 1: # Select the items with only one sentence count = 0 for k in s: # loop over every sentence if (k[-1]=='!'): # check if sentence ends with '!' count = count+1 if count == 1: return 1 else: return '' df['Single'] = e.apply(Single) This returns the the correct result, except that there should be '1' instead of '1.0'. 'Single' 0 NaN 1 1.0 2 1.0 3 4 etc. etc. Why does this happen?
score: 1

http://stackoverflow.com/q/50383845
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50401660
has title: How do I get passed Elasticsearch Updating or Inserting using Python TypeError?
score: 1
has answer: http://stackoverflow.com/a/50385083
tagged with: elasticsearch
tagged with: python
answer count: 2
upvote count: 1
has body: I have a weird issue. If I use curl with the payload I am sending to Elasticsearch I have no issues. When I try to pass JSON to elastic via a web service using Python I get, depending on how I set the payload TypeError: unhashable type: 'dict' elasticsearch.exceptions.RequestError: TransportError(400, 'action_request_validation_exception', 'Validation Failed: 1: script or doc is missing;') To help debug this I took the code out and ran it inline to try to figure it out. To create the record I run the following. edit_author1 = {"name": "Sheldon Sid", "myid": 18} resp = es.index(index="radsearch", doc_type="default", id=18, body={"doc": edit_author1}) This works for the initial creation of the record when using es.create or es.index and it returns the following just as it does if I use curl from the terminal. { "_index": "radsearch", "_type": "default", "_id": "18", "_version": 1, "found": true, "_source": { "doc": { "name": "Sheldon Sid", "myid": 18 } } } It works as expected. When I try to run an update where I have the following resp = es.update(index="radsearch", doc_type="default", id=18, body={'doc': edit_author1}) The above returns { "_index": "radsearch", "_type": "default", "_id": "18", "_version": 2, "found": true, "_source": { "doc": { "name": "Sheldon Sid", "myid": 18 **}, "myid": 18, "name": "Sheldon Sid" }** } But the document repeats itself as a separate entry under doc. If I run it via curl it updates the document and does not create a second entry as above. If I try to run create or update without the doc key I get a TypeError: unhashable type: 'dict' resp = es.update(index="radsearch", doc_type="default", id=18, body={edit_author1}) TypeError: unhashable type: 'dict' If I try to run update as resp = es.update(index="radsearch", doc_type="default", id=18, body=edit_author1) I get elasticsearch.exceptions.RequestError: TransportError(400, 'action_request_validation_exception', 'Validation Failed: 1: script or doc is missing;') Any ideas on how to fix t…
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/50252833
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50250609
downvote count: 0
type: Answer
has body: You can achieve your desired result by setting 'AGE' as your index, followed by pd.DataFrame.transpose: df = pd.DataFrame({'AGE': ['00-04', '05-17', '18-25'], 'GROUP-A': [77, 117, 64], 'GROUP-Q': [133, 106, 110]}) res = df.set_index('AGE')\ .transpose() print(res) AGE 00-04 05-17 18-25 GROUP-A 77 117 64 GROUP-Q 133 106 110
answers question: http://stackoverflow.com/q/50250609
score: 3

http://stackoverflow.com/q/50254171
possible better answer: http://stackoverflow.com/a/50254708
downvote count: 2
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/50254841
linked to: http://stackoverflow.com/q/3310614
type: AnsweredQuestion
score: 0
has title: python script to strip white spaces
has answer: http://stackoverflow.com/a/50255667
has answer: http://stackoverflow.com/a/50254330
has body: I'm fairly new to python looking for an help! on this I have this string which has a xml content. I need to strip white spaces in between different tags. <SIMPLE_RETURN> 2018-05-09T12:47:24Z <CODE>2014 Too many concurrent login(s) </SIMPLE_RETURN> afterwards it looks like: <SIMPLE_RETURN> 2018-05-09T12:47:24Z <CODE>2014 Too many concurrent login(s) </SIMPLE_RETURN> Appreciated if anyone can help!!
favorite count: 0
type: Question
tagged with: python-2.6
has answer: http://stackoverflow.com/a/50254363
accepted answer: http://stackoverflow.com/a/50254330
upvote count: 2
has answer: http://stackoverflow.com/a/50254247
has comment: http://stackoverflow.com/comment/87525830
has answer: http://stackoverflow.com/a/50254708

http://stackoverflow.com/comment/87541813
comment on: http://stackoverflow.com/a/50261778
type: Comment
has text: Well thanks for the response, but for the specific problem that I am solving, I need to apply crossover in the way I explained in the P.S.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87755889
comment on: http://stackoverflow.com/q/50284506
type: Comment
has text: Did the below answer help? If so, feel free to accept, or ask for clarification.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87813897
has text: what is `train_dense`, `train_embed` and `ae_input`?
comment on: http://stackoverflow.com/q/50381504
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87734072
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50358598
score: 1
has text: If it's just those math operations, you probably can avoid calling `apply` and do the calculation in a vectorized way with boolean masks. Can't tell unless you provide a [mcve].

http://stackoverflow.com/comment/87551969
type: Comment
type: QuestionComment
has text: Well then, try `np.exp(y_pred)` to get actual results.
score: 0
comment on: http://stackoverflow.com/q/50243520

http://stackoverflow.com/comment/87804980
has text: `row` holds a list of all values for each row. `row[0]` is the first column value. `row[1]` would be the second column value.
type: AnswerComment
comment on: http://stackoverflow.com/a/50369834
score: 0
type: Comment

http://stackoverflow.com/q/50321057
has answer: http://stackoverflow.com/a/52446643
tagged with: qutip
has body: Code: b=qt.Bloch(axes=a) pnt = [px[:],py[:],pz[:]] b.add_points(pnt) # b.fig = plt.subplot(326) plt.title('Bloch sphere') This code creates small onset figure, but it is empty. See screenshot of the result Showing Bloch sphere as a separate figure works fine.
has title: How to show QuTiP Bloch sphere as onset figure on the bigger plot with other data?
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1
type: Question

pyhive
tags question: http://stackoverflow.com/q/50356542
tag name: pyhive
type: Tag

http://stackoverflow.com/a/50348266
has body: Using pd.to_datetime, pd.TimeDelta and strftime: fmt = '%Y-%m-%d' (pd.to_datetime(&lt;your series or column&gt;, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt) Example df = pd.DataFrame({'date': ['2017-04-02', '2017-04-23']}) fmt = '%Y-%m-%d' &gt;&gt;&gt; (pd.to_datetime(df.date, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt) 0 2017-04-03 1 2017-04-24 Name: date, dtype: object
type: Answer
answers question: http://stackoverflow.com/q/50348141
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/comment/87735861
comment on: http://stackoverflow.com/q/50359563
type: QuestionComment
has text: data ['last_col']=last_col
type: Comment
score: 2

http://stackoverflow.com/q/50379042
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87774665
has comment: http://stackoverflow.com/comment/87779275
tagged with: python
has title: Progress Bar Python
tagged with: progress-bar
has comment: http://stackoverflow.com/comment/87779210
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/50379248
linked to: http://stackoverflow.com/q/34690043
has comment: http://stackoverflow.com/comment/87774368
downvote count: 0
upvote count: 1
has body: I've got the following piece of code: def progressbar(count, total, status=""): bar_len = 40 filled_len = int(round(bar_len * count / float(total))) percents = round(100.1 * count / float(total), 1) bar = "X" * filled_len + "-" * (bar_len - filled_len) print("[{}] {}{} ...{}".format(bar, percents, "%", status), end="\r", flush=True) And for calling the progress bar: total = 100 i = 0 while i &lt; total: i += 1 progressbar(i, total, status="Creating stuff") time.sleep(1) Where total is a number of iterations. When I run this code I get the progress bar running on multiple lines instead of just one. Any advice?
accepted answer: http://stackoverflow.com/a/50381865
score: 1
has comment: http://stackoverflow.com/comment/87774660
has answer: http://stackoverflow.com/a/50379248
has answer: http://stackoverflow.com/a/50381865

http://stackoverflow.com/comment/87558383
score: 0
comment on: http://stackoverflow.com/q/50270434
type: Comment
type: QuestionComment
has text: Double quotes in ```max_time = file.loc["Voltage]==max_vol,"Timestamp"] ``` is not proper

http://stackoverflow.com/comment/87765345
comment on: http://stackoverflow.com/q/50374496
has text: `[i for i in text.split() if i[0] != 't']`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87502903
type: AnswerComment
has text: Great addition @AntonvBR
score: 1
comment on: http://stackoverflow.com/a/50242394
type: Comment

http://stackoverflow.com/comment/118291869
comment on: http://stackoverflow.com/a/50337885
type: Comment
type: AnswerComment
score: 0
has text: the link must be updated to https://pymupdf.readthedocs.io/en/latest/

http://stackoverflow.com/q/50245145
type: UnansweredQuestion
downvote count: 0
answer count: 1
score: 4
favorite count: 0
type: Question
tagged with: buffer
has comment: http://stackoverflow.com/comment/87507695
has title: Slicing assignment in Memoryview throws a ValueError despite having correct syntax
has answer: http://stackoverflow.com/a/50245186
has body: So I have this code buffer_size = 190000000 start_offset = 0 b = bytearray(buffer_size) mv = memoryview(b) end_offset = len(record) mv[start_offset: end_offset] = record.encode(constants.file_encoding) Whenever the last statement is encountered, it throws an error like the following: ValueError: Memoryview assignment: Lvalue has a different structure than RValue
has comment: http://stackoverflow.com/comment/87511651
tagged with: memoryview
tagged with: python
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/87530030
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50256081
has text: it's not a Python error, your script is returning '103' try `out = subprocess.check_output('script_customer_update', shell=True)` then `print(out)`, of course, you need to `import subprocess`
score: 0

http://stackoverflow.com/comment/87538564
type: Comment
score: 0
type: QuestionComment
has text: this is generated url by what i meant 'https://ssl.dotpay.pl/test_payment/?id=123456&amount={}&description={}'.format(123.00, 'Test')
comment on: http://stackoverflow.com/q/50260133

http://stackoverflow.com/comment/87653990
has text: `plt.axis([0,100,0,2000])` applies the scaling to the second figure, since you don't specify the axes. Another sign of this effect is that the y-axis label "V" is now in the second figure, because this command is executed after the generation of the first figure.
score: 0
comment on: http://stackoverflow.com/q/50317308
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87504357
type: QuestionComment
has text: Thank you very much dear Sir you really help me a lot , now everything showing fine
comment on: http://stackoverflow.com/q/50242278
score: 0
type: Comment

http://stackoverflow.com/q/50360583
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: binary-tree
has title: How to switch from using a stack to just using the parent field in a parse tree?
has body: I have a homework assignment about making a parse tree after taking in a fully-parenthesized string and then printing the parse tree. It asks me to modify a couple things and one of those is to change the way we keep track of the parent node. In the original code they use a stack to do so, but my instructor told us to just use the parent node instead. I have all the code running in the same file rather than having to deal with imports for now. These are the rules the algorithm uses to create a parse tree: If the current token is a '(', add a new node as the left child of the current node, and descend to the left child. If the current token is in the list ['+','-', '^', '/','*'], set the root value of the current node to the operator represented by the current token. Add a new node as the right child of the current node and descend to the right child. If the current token is a number, set the root value of the current node to the number and return to the parent. If the current token is a ')', go to the parent of the current node. First is creating a binary tree: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self,newNode): if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): return self.rightChild def getLeftChild(self): return self.leftChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key Next is the Stack class which I want to change: class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(se…
tagged with: parse-tree
tagged with: python

http://stackoverflow.com/comment/87528172
has text: I think perhaps selenium/phantom.js isn't responding to a redirect correctly.. but it's strange that it would work through requests and not selenium... check some of these links https://github.com/ariya/phantomjs/issues/10389 https://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/ https://stackoverflow.com/questions/29358269/handling-redirection-w-phantomjs-selenium
comment on: http://stackoverflow.com/q/50242587
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50279735
answers question: http://stackoverflow.com/q/50279334
type: Answer
has body: You could iterate over the keys of the JSON until you find what you are searching for: data = json_data['data'] for i in data.keys(): if data[i]['order'] == 160: nethash = data[i]['info']['nethash'] Edit: Here is some possible code for searching for multiple values, I tested and it works but not sure how efficient it would be for a large dataset: data = json_data['data'] search_list = [160, 61] nethash_dict = {} for i in data.keys(): if data[i]['order'] in search_list: nethash_dict[data[i]['order']] = data[i]['info']['nethash']
has comment: http://stackoverflow.com/comment/87586347
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50279334
score: 0
has comment: http://stackoverflow.com/comment/87603437

http://stackoverflow.com/q/50314846
has comment: http://stackoverflow.com/comment/87646166
tagged with: django
has comment: http://stackoverflow.com/comment/87646037
tagged with: backend
score: 0
has comment: http://stackoverflow.com/comment/87646128
tagged with: python
has comment: http://stackoverflow.com/comment/87645948
has comment: http://stackoverflow.com/comment/87645980
type: Question
has title: How can I add a model in custom CBV view?
answer count: 0
has comment: http://stackoverflow.com/comment/87645566
has body: My custom CBV is working fine but When I open a page it displays nothing. All I want is when a get() is called it displays a Blog Post and form underneath the post and when form is filled it calls the post() and save it in the database. but when I open a blog post it displays nothing. before moving to Custom CBV I was using the (detailView) everything was fine. class DetailView(View): form_class = CommentForm template_name = "blogs/details.html" model = BLOG def get(self, request, slug): forms = self.form_class(None) blogs = self.model context = {'forms': forms, "blogs":blogs} return render(request, self.template_name, context) def post(self, request): forms = self.form_class(request.POST) if forms.is_valid(): user_comment = forms.save(commit=False) Name = cleaned_data["Name"] Email = cleaned_data["Name"] comment = cleaned_data['comment'] user_comment.save() blogs/details.html {% extends "blogs/main.html" %} {% block dyn_title %}{{blog.blog_title}}{% endblock dyn_title %} {% block body %} &lt;h2&gt;{{blog.blog_title}}&lt;/h3&gt; &lt;p&gt; &lt;/p&gt; &lt;form action="" method="post"&gt; {% csrf_token %} {% include "blogs/form_template.html" %} &lt;/form&gt; {% endblock body %} &lt;!-- form_template.html --&gt; {% for field in form %} &lt;label&gt;{{field.label_tag}}&lt;/label&gt; &lt;div class=""&gt; {{field}} &lt;/div&gt; {% endfor %}
type: UnansweredQuestion

http://stackoverflow.com/comment/98756526
comment on: http://stackoverflow.com/a/50283090
score: 0
has text: Channels 2 doesn't have a Group class and as such Channels_presence doesn't work.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87675582
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50329465
type: AnswerComment
has text: That works great!!! But what if I have a column(similar to address column with commas as it's characters in some lines) next to address column instead of Phone column??I mean if two non numeric columns with same issue are present in the data set next to each other, then It will be difficult to differenciate them using above solution right?

http://stackoverflow.com/comment/87500964
has text: Updated my answer
type: Comment
comment on: http://stackoverflow.com/a/50241482
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87723769
score: 2
comment on: http://stackoverflow.com/q/50353370
has text: What did you actually try? Adding it to your question will help people to answer your specific question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87703992
has text: @BearBrown One last question, how do I translate the value of django model field to its string equivalent. I am assuming I need to override to_representation?
type: Comment
comment on: http://stackoverflow.com/a/50342959
score: 0
type: AnswerComment

http://stackoverflow.com/a/50373841
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50372642
type: Answer
has body: While looping through the images in your text handler function, you can save the filenames in a list, and pass that list as a param to your storyTimeMap function. Something like this: def text(): if request.method == "POST": if 'filename' not in request.files: flash("No Image Uploaded, Try Again") return redirect(request.url) file = request.files['filename'] if file.filename == '': flash("No File Selected, Try Again") return refirect(request.url) if file and allowed_file(file.filename): file_list = [] for f in request.files.getlist("filename"): file_list.append(f.filename) f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename)) print "THIS IS MULIPLE IMAGES?" print f.filename And then you can pass the list when you call your storyTimeMap function: data[request.form["Title"]] = storyTimeMap(request.form, file_list) At the moment, you seem to be passing just the name of the last image to your storyTimeMap function. Which explains why you are getting only one filename in the list. Then instead of doing this: storyTime["filename"] = filename.split() you can just assign the list like this instead: storyTime["filename"] = file_list
answers question: http://stackoverflow.com/q/50372642

database
tags question: http://stackoverflow.com/q/50260803
tags question: http://stackoverflow.com/q/50260418
tags question: http://stackoverflow.com/q/50324996
tags question: http://stackoverflow.com/q/50330119
tags question: http://stackoverflow.com/q/50372057
tags question: http://stackoverflow.com/q/50284750
tags question: http://stackoverflow.com/q/50355697
tags question: http://stackoverflow.com/q/50280523
tags question: http://stackoverflow.com/q/50347536
tags question: http://stackoverflow.com/q/50352178
type: Tag
tags question: http://stackoverflow.com/q/50357383
tags question: http://stackoverflow.com/q/50305181
tags question: http://stackoverflow.com/q/50277438
tags question: http://stackoverflow.com/q/50336747
tags question: http://stackoverflow.com/q/50374151
tags question: http://stackoverflow.com/q/50362013
tags question: http://stackoverflow.com/q/50272309
tags question: http://stackoverflow.com/q/50289882
tags question: http://stackoverflow.com/q/50269153
tag name: database

http://stackoverflow.com/comment/87647396
type: QuestionComment
score: 0
has text: Did you try considering using a `list of lists`? Do you plan to have a `5x3` matrix from the sample you've shown above?
comment on: http://stackoverflow.com/q/50315688
type: Comment

http://stackoverflow.com/q/50321037
answer count: 0
downvote count: 0
tagged with: cbir
upvote count: 1
tagged with: python
type: UnansweredQuestion
has title: Using sift descriptors with a classification algorithm
tagged with: sift
has body: I'm trying to make a simple image search engine using Oxford Buildings Dataset First I used SIFT to extract features. Basically I iterated over every image in dataset and generate key points and descriptors for everyone of them. Then, I choose one random picture as query and used bf.match method and find the matching key points find distance between images in dataset and query.But after that -I guess this is the part that I went really wrong- I count the matching key point. The idea was which picture has the most matching key point is the picture that most similar to the query image. matches = bf.match(query_d, desc) # Sort the matches in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) print matches matches_num.append((len(matches), imageID)) My question is how can I apply any classification methods after I calculate key points?
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87489881
comment on: http://stackoverflow.com/q/50235512
type: Comment
type: QuestionComment
has text: @Chiefir I have included views.py
score: 0

downsampling
tag name: downsampling
tags question: http://stackoverflow.com/q/50301330
type: Tag

http://stackoverflow.com/q/50352178
score: 0
has title: Python-Mysql : ModuleNotFoundError: No module named 'pymysql'
tagged with: database
tagged with: python
tagged with: mysql
has body: I've installed pymysql package using all possible ways. Using : sudo apt-get install python3-pymysql sudo pip3 install pymysql conda install PyMySQL I checked the packages installed in my system using command : sudo apt list --installed I found following lines in result : python3-pymysql/xenial-updates,xenial-updates,now 0.7.2-1ubuntu1 all [installed] python-pymysql/xenial-updates,xenial-updates,now 0.7.2-1ubuntu1 all [installed] And i can clearly see that pymysql is installed. But when i import pymysql in any python program. It give me error "ModuleNotFoundError: No module named 'pymysql' ". I don't know what i'm doing wrong. Please help.
has comment: http://stackoverflow.com/comment/87793467
has comment: http://stackoverflow.com/comment/87749281
answer count: 0
tagged with: sql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87720379
has comment: http://stackoverflow.com/comment/87721404
type: Question

http://stackoverflow.com/a/50282806
downvote count: 0
answers question: http://stackoverflow.com/q/50281510
upvote count: 1
type: Answer
has body: From the SSL error, I suspect that you're running an old version of Canopy. What version are you running? The current version is 2.1.9. To update Canopy, and for a link to release notes, please see "Installing a new Canopy version".
score: 1

http://stackoverflow.com/comment/87536961
comment on: http://stackoverflow.com/a/50239100
type: AnswerComment
has text: @ShAlzoubi, I'd need to see an example as I don't understand your description.
score: 0
type: Comment

http://stackoverflow.com/q/50310505
type: Question
has comment: http://stackoverflow.com/comment/87640008
has comment: http://stackoverflow.com/comment/87638369
has answer: http://stackoverflow.com/a/50312596
has body: I want to run a python script from Qt. I am able to call it with QProcess and get qDebug() to print what the python script prints. But for some reason I can't Qt to read any of the python script's prints after a certain point in the code. Does anyone have any idea how to fix this? Thank you so much in advance. This is my first question here so I'm sorry if I did something wrong. My widget.cpp file and python script are below. (The python script is in the Qt program's directory.) My widget.cpp file: #include "widget.h" #include "ui_widget.h" #include "QDebug" #include &lt;QTimer&gt; #include &lt;QProcess&gt; #include &lt;QDir&gt; Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui-&gt;setupUi(this); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(checkTexts())); timer-&gt;start(5000); } Widget::~Widget() { delete ui; } void Widget::checkTexts() { //QProcess process; //I also tried this way with the same results QProcess *process = new QProcess(this); QStringList arguments { QCoreApplication::applicationDirPath() + "/../../../../../Folder/Qt Desktop Application/ApplicationFiles/PullText.py"}; process-&gt;start("python", arguments); process-&gt;waitForFinished(-1); QString output = process-&gt;readAll(); process-&gt;close(); qDebug() &lt;&lt; output; } My Python script (PullText.py) which is supposed to send one line of a text file to my Qt application: newMessageSplitter = "***\n" #print "1" #this prints in the qDebug() &lt;&lt; output file = open("texts.txt","r") #print “2” #this doesn't print texts = file.read() x = texts.find(newMessageSplitter) + len(newMessageSplitter) singleLine = texts[:x-len(newMessageSplitter)] file.close() file = open("texts.txt","w") file.write(texts[x:]) file.close() #print singleLine #this is what I want to send to the output but it doesn't get sent to Qt
has comment: http://stackoverflow.com/comment/87641304
has title: Python script doesn't fully run from Qt
upvote count: 0
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87639703
downvote count: 1
tagged with: qt
tagged with: c++
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50312596
favorite count: 0

http://stackoverflow.com/comment/92745739
has text: Is there any way to delete users who didn't activate their account after x hours or days ? Actually because is some situations a user can sign up with an email address of someone else. And it gonna be necessary to make the registration available again with the email address within x days..
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50330016
type: AnswerComment

http://stackoverflow.com/a/50614959
score: 0
accepted answer of: http://stackoverflow.com/q/50327439
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/95889690
has body: As per flask-restplus: Flask-RESTPlus provides a way to use almost the same pattern as Flask’s blueprint. The main idea is to split your app into reusable namespaces. from: http://flask-restplus.readthedocs.io/en/stable/scaling.html namespace is from the Flask-RESTPlus and Blueprint is from flask to organize your app. the namespaces modules (specific to Flask-RESTPlus) are reusable namespaces designed like you would do with Flask’s Blueprint.
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50327439
downvote count: 6

http://stackoverflow.com/q/50352614
accepted answer: http://stackoverflow.com/a/50711837
has body: So, I've been using R Markdown extensively lastly, and I'm pretty satisfied with what it can do. However, I'm having a problem with python plots. I have a chunk of python code where I plot multiple figures in python. When I do that with R, RStudio will display all the plots generated in this chunk side by side inline. Unfortunately, when doing the same with a chunk of python code, RStudio opens a new Window where it displays the plot, then the code execution is halted until I close that window, then it plots the next figure, I have to close it again, etc etc. Is there a possibility to force RStudio to put the figures inline, and then continue code execution? Thanks for your help in advance!
has title: R Markdown: How can I make RStudio display Python plots inline instead of in new window?
answer count: 1
has comment: http://stackoverflow.com/comment/88417499
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/28269157
upvote count: 20
score: 20
tagged with: r-markdown
tagged with: rstudio
tagged with: python
has comment: http://stackoverflow.com/comment/87996254
linked to: http://stackoverflow.com/q/458209
has comment: http://stackoverflow.com/comment/88431122
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50711837

http://stackoverflow.com/comment/87521267
comment on: http://stackoverflow.com/q/50248769
type: Comment
type: QuestionComment
score: 0
has text: Is your application running on Linux or Windows?... See [Here](https://stackoverflow.com/questions/1289813/python-multiprocessing-vs-threading-for-cpu-bound-work-on-windows-and-linux?rq=1)...

http://stackoverflow.com/a/50293568
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50293496
has comment: http://stackoverflow.com/comment/87603696
has body: Assuming the relevant column in each DataFrame is called 'user', you can use pd.merge( df1, df2.user.groupby(df2.user).count(), left_on='user', right_index=True, how='left') Explanation: The groupby + count will find the number of occurrences of each user. It will create a DataFrame whose index is the user, and the value is the count. The merge left-merges the resulting DataFrame onto df1.
type: Answer
upvote count: 2

http://stackoverflow.com/q/50322830
has comment: http://stackoverflow.com/comment/87661961
tagged with: pyqt4
downvote count: 0
has comment: http://stackoverflow.com/comment/87661543
tagged with: python
tagged with: sorting
tagged with: qtableview
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50332395
has body: I have trouble with trying create my own sorting function with QAbstractItemModel. It works but not case insensitive. I have tried to use QSortFilterProxyModel, but any success. My sort function: def sort(self, col, order): self.emit(SIGNAL("layoutAboutToBeChanged()")) self.tableData = sorted(self.tableData, key=operator.itemgetter(col)) if order == Qt.AscendingOrder: self.tableData.reverse() self.emit(SIGNAL("layoutChanged()")) I am using QTableView. How I could make it case insensitive? Full example: from PyQt4.QtCore import * from PyQt4.QtGui import * import operator import sys class Window(QWidget): def __init__(self): super(Window, self).__init__() header = ["one", "two"] tableDict = [["abcdef", "tuvwx"], ["aBcde", "TUvWx"], ["acdef","tUvWX"], ["Acdef", "TUVwx"], ["ACdef", "TUVwx"]] self.myTable = newTableModel(header, tableDict) mainLayout = QHBoxLayout() mainLayout.addWidget(self.myTable.tableView) self.setLayout(mainLayout) self.setWindowTitle("Test table") class newTableModel(QAbstractTableModel): def __init__(self, header, data, parent=None, *args): super(newTableModel, self).__init__(parent) self.tableView = QTableView() self.tableData = data self.header = header self.tableView.setShowGrid(True) self.tableView.setFrameStyle( QFrame.NoFrame ) self.tableView.setFocusPolicy( Qt.NoFocus ) self.tableView.setSelectionMode( QAbstractItemView.NoSelection ) vHeader = self.tableView.verticalHeader() vHeader.setVisible(False) vHeader.setStretchLastSection(False) hHeader = self.tableView.horizontalHeader() hHeader.setVisible(True) hHeader.setStretchLastSection(False) self.tableView.setSortingEnabled(True) self.tableView.setModel(self) self.tableView.resizeRowsToContents() self.tableView.resizeColumnsToContents() vHeader.setResizeMode(QHeaderView.ResizeToContents) self.tableView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.tableView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) def rowCount(self, parent): return len(self.tableData) def columnCount(self,…
answer count: 1
has comment: http://stackoverflow.com/comment/87662639
has answer: http://stackoverflow.com/a/50332395
has title: Sorting case insensitively in QAbstractItemModel
tagged with: qabstracttablemodel
favorite count: 0
has comment: http://stackoverflow.com/comment/87663199
type: Question
upvote count: 2
score: 2

http://stackoverflow.com/comment/107290936
has text: Any explanation to your answer ?
comment on: http://stackoverflow.com/a/60643333
score: 3
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87793358
has text: CurrentValues.qml: ``` ```
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50382404

http://stackoverflow.com/comment/87758509
type: QuestionComment
comment on: http://stackoverflow.com/q/50371357
has text: Expressions, not equations.
score: 1
type: Comment

http://stackoverflow.com/a/50368945
answers question: http://stackoverflow.com/q/50368612
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87753823
type: Answer
has body: I think this should fix it (more details on this reference): from PIL import Image, ImageTk image = Image.open("logo.png") logo = ImageTk.PhotoImage(image) lb1 = Label(f0,image=logo) lb1.image = logo #keep a reference to it lb1.pack() EDIT: I think your tkinter version is able to run this directly: logo = ImageTk.PhotoImage("logo.png") lb1 = Label(f0,image=logo) lb1.image = logo #keep a reference to it lb1.pack()

http://stackoverflow.com/q/50368376
has comment: http://stackoverflow.com/comment/87783400
has comment: http://stackoverflow.com/comment/87783254
tagged with: python
answer count: 6
has body: docker swarm throwing an error "swarm already part of swarm" when I am joining the new node to the existing node I am running the docker swarm in my local machine and trying to init the swarm and getting executed very well but when i am trying to add the new worker or node to the existing manager node then it is throwing an error like swarm already part of the node you have to leave the node. $docker swarm init Swarm initialized: current node (fn405d6jtk8mxbpvdrftr0np1) is now a manager. To add a worker to this swarm, run the following command: docker swarm join --token SWMTKN-1-5tyw8ux789wpa7yyt75qbilb669tiw53pxriyxu48niznpmaka-7u63l4hom3h60myvtyw8p1mcj 192.168.2.219:2377 To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions. =>And again am using above token as a worker and join then i gotta error like this.. $ docker swarm join --token SWMTKN-1-5tyw8ux789wpa7yyt75qbilb669tiw53pxriyxu48niznpmaka-7u63l4hom3h60myvtyw8p1mcj 192.168.2.219:2377 Error response from daemon: This node is already part of a swarm. Use "docker swarm leave" to leave this swarm and join another one.
has answer: http://stackoverflow.com/a/50384925
has answer: http://stackoverflow.com/a/52436614
tagged with: docker
has answer: http://stackoverflow.com/a/64282755
has title: docker swarm throwing an error "swarm already part of swarm"
has comment: http://stackoverflow.com/comment/87783448
type: AnsweredQuestion
score: 15
accepted answer: http://stackoverflow.com/a/50384925
has answer: http://stackoverflow.com/a/50612750
downvote count: 0
tagged with: docker-swarm
has comment: http://stackoverflow.com/comment/87784909
possible better answer: http://stackoverflow.com/a/52436614
favorite count: 0
has answer: http://stackoverflow.com/a/73874235
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/87754634
has answer: http://stackoverflow.com/a/52765836

http://stackoverflow.com/comment/87554132
comment on: http://stackoverflow.com/a/50266619
type: Comment
score: 0
type: AnswerComment
has text: It is common to "normalize" your input to a neural network when using a sigmoid activation function. Every column of input data is adjusted so that it has a mean of zero and a standard deviation of 1.

http://stackoverflow.com/comment/87735769
has text: Ok, they finally showed in the `Third party` tab, I don't know why.
score: 0
comment on: http://stackoverflow.com/q/50356723
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50303726
downvote count: 2
has comment: http://stackoverflow.com/comment/87624632
has body: My Stackoverflow senses tell mey you are pasting this in the python shell. You need to put it into a python file, e.g. continents.py , and then execute the interpreter like so python continents.py Or, you can remove the if __name__ == "__main__": and it should work also directly when pasted into the python shell. See it in action here.
answers question: http://stackoverflow.com/q/50303627
has comment: http://stackoverflow.com/comment/87624849
score: -2
type: Answer
has comment: http://stackoverflow.com/comment/87627066
has comment: http://stackoverflow.com/comment/87624831
upvote count: 0

http://stackoverflow.com/q/50358784
has answer: http://stackoverflow.com/a/50358980
type: AnsweredQuestion
score: 0
tagged with: vector
tagged with: matrix
has title: Python: recursive fucntion to compute the sum of the difference of 2 vectors
answer count: 1
has comment: http://stackoverflow.com/comment/87734403
type: Question
tagged with: recursion
has body: I have a matrix M and the initial vector v0. I want to write a recursive function to perform M*v_{i} so that I can find v_{i} and v_{i+1} such that the sum of all the elements of the difference of the vectors is less than 0.45. For example: import numpy as np M = np.array([[0, 0, 0, 0.5, 0, 0], [1, 0, 0, 0, 0.5, 0], [0, 1, 0, 0, 0.5, 1], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0.5, 0, 0]]) M = M.astype(float) v0 = np.array([1/6, 1/6, 1/6, 1/6, 1/6, 1/6]) v1 = np.dot(M, v0) v2 = np.dot(M, v1) v3 = np.dot(M, v2) v4 = np.dot(M, v3) v5 = np.dot(M, v4) x = np.absolute(v4 - v5) print(sum(x)) Here, my desired output is the value of sum(x) = 0.42 and the vectors v4 and v5. I have tried this so far and got stuck. def diff_sum(M, v): v1 = np.dot(M, v) x = np.absolute(v - v1) x = sum(x) if x &lt; 0.45: return (x, v, v1) else: diff_sum(M, np.dot(M, v1)) return (x, v, v1)
tagged with: sum
accepted answer: http://stackoverflow.com/a/50358980
has comment: http://stackoverflow.com/comment/87734225
tagged with: python

http://stackoverflow.com/comment/87688974
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50336251
type: QuestionComment
has text: 00:00 basically datetime.min.time()

http://stackoverflow.com/comment/87696079
comment on: http://stackoverflow.com/q/50339569
type: Comment
has text: I don't see what difference the _editor_ could make, but I'm using CPython 3.6.5 on linux.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87773747
score: 0
comment on: http://stackoverflow.com/q/50378513
has text: @dirn that makes sense, thank you!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87587291
type: Comment
type: QuestionComment
has text: Oh you told working find in tutorial 2.. I didn't see it. What happend when you call `AsyncWebsocketConsuemr` in `python manage.py shell`?
comment on: http://stackoverflow.com/q/50285479
score: 0

http://stackoverflow.com/q/50346166
has comment: http://stackoverflow.com/comment/87712837
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87712429
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50349445
linked to: http://stackoverflow.com/q/46901622
has answer: http://stackoverflow.com/a/50349445
score: 1
tagged with: matplotlib
answer count: 1
has title: Draw an Arc as Polygon using Start, End, Center and Radius using Python Matplotlib
has body: I have used the below code with only inputs start_point and end_point: import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches start_point = (25, 50) end_point = (50, 25) center = (25, 25) radius = (25 # We need to some how automatically calculate this midpoint mid_point = (45, 45) verts = [start_point, mid_point, end_point] codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]#, Path.CLOSEPOLY] path = Path(verts, codes) shape = patches.PathPatch(path, facecolor='none', lw=0.75) plt.gca().add_patch(shape) plt.axis('scaled') I get the following output I need the following output (I created the below output using MS Paint) [Explanation: Converted the arc into set of points joined as straight lines. I need those set of points as list]
favorite count: 0
type: Question

http://stackoverflow.com/q/50295437
tagged with: python
tagged with: boto3
has title: boto3 describe VPC connections - where is the region?
type: AnsweredQuestion
score: 0
answer count: 1
has body: I am looking to create a 'topology' of all my VPC's which are peered. In essence, I have an 'origin' vpc, and from their, I am querying all the peers to see their zones, subnets, peer ids, etc... However, when I query the peered connections, I cannot for the life of me get the region of each 'accepter'! My current method: connections = (self.client.describe_vpc_peering_connections())["VpcPeeringConnections"] How do I get the region for these connections?
tagged with: amazon-web-services
type: Question
has answer: http://stackoverflow.com/a/50295514
accepted answer: http://stackoverflow.com/a/50295514

http://stackoverflow.com/comment/87672520
type: Comment
type: QuestionComment
score: 0
has text: I add some colors, hope that it is clearer, I want to print only values of dataframes
comment on: http://stackoverflow.com/q/50293689

http://stackoverflow.com/q/50350537
answer count: 1
has comment: http://stackoverflow.com/comment/87729567
favorite count: 0
has comment: http://stackoverflow.com/comment/87735306
type: Question
tagged with: argparse
type: UnansweredQuestion
has title: How to stack up multiple subcommands and have an implied default command using argparse?
has answer: http://stackoverflow.com/a/50359403
linked to: http://stackoverflow.com/q/10448200
tagged with: python
has body: In my example below, I am trying to setup the following command line scenarios: $ myapp.py flowers [-h] $ myapp.py flowers plants [-h] $ myapp.py flowers plants add [-h] The actual outcomes are: $ python myapp.py flowers usage: myapp.py flowers [-h] {plants} ... myapp.py flowers: error: too few arguments $ python myapp.py flowers plants usage: myapp.py flowers plants [-h] [--format {plain,json}] {add} ... myapp.py flowers plants: error: too few arguments $ python myapp.py flowers plants add Adding flowers... The input format is expected to be plain The problem is the second scenario. I intend for it to be an implicit "list" operation. How to do this? Here is the source code to my example. import sys import argparse def _flowers_plants_list(args): print('if this were real, the output format would be %s' % (args.format)) print('Here are all the flowers:') print('flower 1: rose') print('flower 2: tulip') print('flower 3: daisy') def _flowers_plants_add(args): print('Adding flowers... The input format is expected to be %s' % (args.format)) def main(): # myapp.py parser_main = argparse.ArgumentParser() subparsers_main = parser_main.add_subparsers() # myapp.py flowers [-h] parser_flowers = subparsers_main.add_parser("flowers") subparsers_flowers = parser_flowers.add_subparsers() # (this is supposed to be an implicit list - NOT WORKING) # myapp.py flowers plants [-h] parser_flowers_plants = subparsers_flowers.add_parser("plants") parser_flowers_plants.add_argument("--format", default='plain', choices=['plain', 'json'], help="what format should the result be in") parser_flowers_plants.set_defaults(func=_flowers_plants_list) subparsers_flowers_plants = parser_flowers_plants.add_subparsers() # myapp.py flowers plants add [-h] parser_flowers_plants_add = subparsers_flowers_plants.add_parser("add") parser_flowers_plants_add.add_argument("--format", default='plain', choices=['plain', 'json'], help="what format will the input be in") parser_flowers_plants_add.set_defaults(func=_f…
score: 2
upvote count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/23349349

http://stackoverflow.com/a/50260132
has body: Add a dictionary before the start of the loop: running_inds = {} for rec in SeqIO.parse("concatenate_0035_0042_dna2.fa", "fasta"): Now when you perform rec.name = rec.description = rec.id = x.iloc[0] + rec.id[rec.id.index("_"):] first do the following: running = running_inds.get(x.iloc[0] + rec.id[rec.id.index("_"):], 1) # Get the running index for this sequence running_inds[x.iloc[0] + rec.id[rec.id.index("_"):]] = running + 1 now simply append this to the name: rec.name = rec.description = rec.id = x.iloc[0] + rec.id[rec.id.index("_"):] + '_' + str(running)
type: Answer
accepted answer of: http://stackoverflow.com/q/50260066
answers question: http://stackoverflow.com/q/50260066
score: 1
has comment: http://stackoverflow.com/comment/87538338
has comment: http://stackoverflow.com/comment/87538526
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87538382
has comment: http://stackoverflow.com/comment/87538581
has comment: http://stackoverflow.com/comment/87540739

http://stackoverflow.com/a/50379051
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87775959
accepted answer of: http://stackoverflow.com/q/50378390
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50378390
has body: DB table partitioning needs a good design and proper queries. There is a python app Architect which works with django. Schemaless DB is another approach for massive data, Uber is known to be using it.

http://stackoverflow.com/a/50338578
has comment: http://stackoverflow.com/comment/87693392
has comment: http://stackoverflow.com/comment/87693551
has comment: http://stackoverflow.com/comment/87693542
has comment: http://stackoverflow.com/comment/87693436
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50338454
downvote count: 1
has body: On way could be using np.roll to shift the number in your array such as: A_1 = np.roll(A,1) # output: array([8, 1, 2, 3, 4, 5, 6, 7]) And then the same thing with rolling by -2, -1 and 2: A_2 = np.roll(A,2) A_m1 = np.roll(A,-1) A_m2 = np.roll(A,-2) Now you just need to sum your 4 arrays, as for each index you have the 4 neighbors in one of them: B = (A_1 + A_2 + A_m1 + A_m2)/4. And as you said you don't care about the edges, I think it works for you! EDIT: I guess I was focus on the rolling idea that I mixed up mean and median, the median can be calculated by B = np.median([A_1,A_2,A_m1,A_m2],axis=0)
score: 1
answers question: http://stackoverflow.com/q/50338454
has comment: http://stackoverflow.com/comment/87693769
type: Answer

http://stackoverflow.com/comment/87618423
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50299075
has text: @LegacyKS can you post a base structure of KsBot.py (ie. definition of the bot + when you run the bot) and the file structure? In general, discord.py has an option to "add_extension" to an external file.

http://stackoverflow.com/q/50321843
duplicate of: http://stackoverflow.com/q/480214
has body: My code to the question "Write a function remove_duplicates that takes in a list and removes elements of the list that are the same (in the form of a new list)" returns an empty list, that is, [], instead of a list with no duplicates. I cannot seem to understand why? def remove_duplicates(sequence): k = [] for x in sequence: for i in k: if x != i: k.append(x) else: k = k return k
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/87659611
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87659493
linked to: http://stackoverflow.com/q/7961363
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/7961363
type: UnansweredQuestion
tagged with: python
has title: I cannot figure out why my code is returning an empty list

http://stackoverflow.com/q/50367332
answer count: 1
tagged with: python
tagged with: notify
has body: I have a written a small python script that uses notifications to alert the user when something happens. The script is run on either a cinnamon or gnome based desktop environment. The nitty-gritty of the script is this: from gi.repository import Notify Notify.init("My Program Name") notification = Notify.Notification.new("Hi") notification.show() Notify.uninit() Notify.init("My New Program Name") notification = Notify.Notification.new("Hi") notification.show() Notify.uninit() from subprocess import call call(['notify-send', 'hello', 'world']) call(['notify-send', 'hello', 'again']) As you can see the script is using Notify to send the first two messages and a subprocess call to send the last two messages. What happens when you run this is you get 4 messages appear as notifications. If I click on either of the "Notify" messages they both get deleted at once. If I click on either of the "subprocess calls" they get deleted separately depending on which one I click. This is the behaviour I would like for the "Notify" messages. As you can see in the code I supplied I have tried to re-init Notify with a new program name in order to try to get the messages appear to be from a different source but the messages still get deleted at the same time no matter which one I click on. How do I get only one message to be deleted at a time when using Notify? (I cannot just use the subprocess calls as I also want to add an action to the notification which I do not believe is possible with notify-send.)
type: AnsweredQuestion
tagged with: libnotify
score: 0
has title: How do I only clear one notification message using Notify and python?
accepted answer: http://stackoverflow.com/a/50385909
type: Question
tagged with: gnome
has answer: http://stackoverflow.com/a/50385909
tagged with: cinnamon

http://stackoverflow.com/comment/87638418
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50311060
has text: thank you for your answer and i have already changed the typos, but another problem appeared, i have output in the stmt_seq function that "hiiio" as s sort of telling me where the error might be , when i run the program the output is "hiiio" after it is false, if you could help me in it it would be extremely nice as i suspect there is an error in the logic of these funcs (simple_seq,factor,term)

http://stackoverflow.com/a/50376946
answers question: http://stackoverflow.com/q/50376556
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has body: JSON encoding is supported for the following native python types out of the box Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ So if you do json.dumps(1) -> it will work because this is supported by default. Now your variable content is a python dictionary; which clearly is something you can JSON Serializer out of the box; if (and this is a big if) all the contents of the dictionary are also native types that can be serialized. However, the contents of content are a Django Queryset, which is not natively JSON Serializeable. You can however convert the queryset into all native python types using django's serializer classes, but that works well if you were only returning one queryset. Since you are returning a dictionary, whose values are themselves querysets, I'd recommend you look at Django Rest Framework or Tastypie. If you want to keep things simple; here's a great workaround, where you define a custom encoder that uses Django's serializer classes for Querysets, and the builtin one for other data types: Django: Serialize to JSON a dictionary with items that can include querysets
has comment: http://stackoverflow.com/comment/87794733
type: Answer
accepted answer of: http://stackoverflow.com/q/50376556
score: 8

http://stackoverflow.com/a/50278481
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50263129
type: Answer
has body: You need to be careful with trailing newlines. As such it is safer to remove the newlines before comparing and then add them back when writing: input_file1 = "A.csv" input_file2 = "B.csv" output_path = "out.csv" with open(input_file1, 'r') as t1: fileone = set(t1.read().splitlines()) with open(input_file2, 'r') as t2, open(output_path, 'w') as outFile: for line in t2: line = line.strip() if line not in fileone: outFile.write(line + '\n')
answers question: http://stackoverflow.com/q/50263129
upvote count: 2

http://stackoverflow.com/q/50284506
has answer: http://stackoverflow.com/a/50291809
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/87755889
downvote count: 4
has body: I am trying to use Python to search keywords in sentences. I found one coding provided by Chris_Rands is really helpful, but I would like to change the output format. Here is the code and its output, followed by what I would like the new output to look like. Can you suggest changes to the code to create the new output? Original code from Chris_Rands: sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".") search_keywords=['mother','sing','song'] for sentence in sentences: print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence))) for word in search_keywords: if word in sentence: print(word) print(sentence + "\n") Chris_Rands's output: 2 key words in sentence: My name is sing song 1 key words in sentence: I am a mother 0 key words in sentence: I am happy 2 key words in sentence: You sing like my mother I am wondering how to print those "keywords" in the outcome, so the outcome will look like this: Desired Output 2 key words in sentence: sing song My name is sing song 1 key words in sentence: mother I am a mother 0 key words in sentence: I am happy 2 key words in sentence: sing mother You sing like my mother
upvote count: 1
has comment: http://stackoverflow.com/comment/87585308
answer count: 1
has comment: http://stackoverflow.com/comment/87585296
has title: Finding keywords in text by sentence
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87583924
type: AnswerComment
comment on: http://stackoverflow.com/a/50272653
has text: That fixed it! Converting the array to bytes and then using the `frombytes` method, like in your second example, processed the image with no errors. Thank you sooooo much!
score: 0
type: Comment

http://stackoverflow.com/a/50237012
score: 2
downvote count: 0
has body: You can create two new events (FIRE_ANIMATION_START, STAR_ANIMATION_START) which you post to the event queue with a delay (with pygame.time.set_timer(eventid, milliseconds)). Then in your event loop you just check for it. FIRE_ANIMATION_START = pygame.USEREVENT + 1 STAR_ANIMATION_START = pygame.USEREVENT + 2 # ... Your code ... for event in pygame.event.get(): if event.key == pygame.K_SPACE and buttonHighlight == 0: pygame.time.set_timer(FIRE_ANIMATION_START, 10) # Post the event every 10 ms. pygame.time.set_timer(STAR_ANIMATION_START, 1000) # Post the event every 1000 ms. elif event.code == FIRE_ANIMATION_START: pygame.time.set_timer(FIRE_ANIMATION_START, 0) # Don't post the event anymore. FireAnimation() #displays a fire image if player[6] == 'Magic': #you deal damage to the enemy enemy[0] = enemy[0]-(((player[1])+((player[1])*1)-enemy[4])) else: enemy[0] = enemy[0]-(((player[1])+((player[1])*1)-enemy[3])) elif event.code == STAR_ANIMATION_START: pygame.time.set_timer(STAR_ANIMATION_START, 0) # Don't post the event anymore. StarAnimation() #displays a star image if enemy[6] == 'Magic': #enemy deals damage to you player[0] = player[0]-(((enemy[1])+((enemy[1])*1)-player[4])) else: player[0] = player[0]-(((enemy[1])+((enemy[1])*1)-player[3])) Documentation for pygame.time.set_timer(eventid, milliseconds). Also, as the code is right now it has bugs in it. The attributes for the events differs between different event types, so always make sure to check whether an event is KEYDOWN or USEREVENT before accessing the attributes event.key or event.code. The different types and attributes can be found here.
answers question: http://stackoverflow.com/q/50232714
type: Answer
upvote count: 2

http://stackoverflow.com/a/50274868
has body: One way of implementing it using a dict: def compressed(word): letters = dict() for c in word: letters[c] = letters.get(c, 0) + 1 for key, value in letters.items(): print(f'{value}{key}', end=' ')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50274685

http://stackoverflow.com/comment/87542538
score: 0
comment on: http://stackoverflow.com/q/50261988
type: Comment
type: QuestionComment
has text: I think that I see your issue. You are changing the value of the variable, but this does not change the text that you are attempting to change. You will have to specifically Change the value of the text on the widget that you want to alter.

http://stackoverflow.com/q/50277848
has answer: http://stackoverflow.com/a/76733763
has comment: http://stackoverflow.com/comment/87572914
downvote count: 0
has answer: http://stackoverflow.com/a/54921831
has comment: http://stackoverflow.com/comment/87573411
has comment: http://stackoverflow.com/comment/87574161
has title: pip3 install tesserocr gives error
has comment: http://stackoverflow.com/comment/87586516
has answer: http://stackoverflow.com/a/50289058
favorite count: 0
has answer: http://stackoverflow.com/a/50434616
has comment: http://stackoverflow.com/comment/87573136
has comment: http://stackoverflow.com/comment/87572951
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87573506
answer count: 4
type: Question
upvote count: 2
has body: I am trying to install tesserocr package for python3.6 on Ubuntu. When I run pip3 install tesserocr, I get this error: Running setup.py bdist_wheel for tesserocr ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-cmhownuf/tesserocr/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/tmpg1f69eahpip-wheel- --python-tag cp36: Supporting tesseract v4.0.0-beta.1 Configs from pkg-config: {'include_dirs': ['/usr/include'], 'libraries': ['lept', 'tesseract'], 'cython_compile_time_env': {'TESSERACT_VERSION': 1024}} running bdist_wheel running build running build_ext building 'tesserocr' extension creating build creating build/temp.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fdebug-prefix-map=/build/python3.6-EKG1lX/python3.6-3.6.5=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include -I/usr/include/python3.6m -c tesserocr.cpp -o build/temp.linux-x86_64-3.6/tesserocr.o cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ tesserocr.cpp: In function ‘tesseract::TessResultRenderer* __pyx_f_9tesserocr_13PyTessBaseAPI__get_renderer(__pyx_obj_9tesserocr_PyTessBaseAPI*, __pyx_t_9tesseract_cchar_t*)’: tesserocr.cpp:21180:106: error: no matching function for call to ‘tesseract::TessPDFRenderer::TessPDFRenderer(__pyx_t_9tesseract_cchar_t*&amp;, const char*)’ __pyx_t_3 = new tesseract::TessPDFRenderer(__pyx_v_outputbase, __pyx_v_self-&gt;_baseapi.GetDatapath()); ^ In file included from tesserocr.cpp:625:0: /usr/include/tesseract/renderer.h:190:3: note: candidate: tesseract::TessPDFRenderer::TessPDFRenderer(const char*, const char*, bool) TessPDFRenderer(const char* outputbase, const char* datadir, bool textonly); ^~~~~…
has comment: http://stackoverflow.com/comment/87573424
has comment: http://stackoverflow.com/comment/87573277
tagged with: pip
tagged with: python
type: UnansweredQuestion
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87573142
score: 2

http://stackoverflow.com/a/52241919
answers question: http://stackoverflow.com/q/50366014
has comment: http://stackoverflow.com/comment/91432362
has body: As you can see in your error message you are missing the module 'gdbm' as it says here: sudo apt-get install python3.5-gdbm
type: Answer
score: 0

http://stackoverflow.com/comment/87482644
comment on: http://stackoverflow.com/q/50232539
has text: Possible duplicate of [Convert floats to ints in Pandas?](https://stackoverflow.com/questions/21291259/convert-floats-to-ints-in-pandas)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87503515
has text: dear sir i found that now I can add course to student , Please give a complete example from profile html to display student and his course
comment on: http://stackoverflow.com/a/50242498
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87539801
has text: You can check this https://stackoverflow.com/questions/8984287/execute-php-code-in-python
score: 0
comment on: http://stackoverflow.com/q/50260825
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50277238
has comment: http://stackoverflow.com/comment/91255812
type: UnansweredQuestion
has body: I am using the simple-salesforce python package with python 3. According to the documentation, I should be able to bulk update records using this syntax: data = [{'Id': '0000000000AAAAA', 'Email': 'examplenew@example.com'}, {'Id':'0000000000BBBBB', 'Email': 'testnew@test.com'}] sf.bulk.Contact.update(data) However the instance of simple-salesforce that I implemented does not recognize sf.bulk.Custom_Object__c When I try to execute: sf.bulk.Custom_Object__c.update(data) I get this error: AttributeError Traceback (most recent call last) &lt;ipython-input-126-b287358940fc&gt; in &lt;module&gt;() ----&gt; 1 sf.bulk.Custom__bject__c.update(data) AttributeError: 'SFType' object has no attribute 'Custom_Object__c' Has anyone else worked with the simple-salesforce python package and run into this issue before?
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/71532582
answer count: 2
downvote count: 0
tagged with: simple-salesforce
has answer: http://stackoverflow.com/a/54952201
tagged with: salesforce
has title: Salesforce bulk api using the python simplesalesforce package
favorite count: 0
has comment: http://stackoverflow.com/comment/103426184
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50304880
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50305408
has title: Filtering or of multiple between in sqlalchemy
tagged with: python
has body: I have a list of tuples like this: l = [ (100, 230), (10, 12), (7,1320), ... ] I want to generate a query in SQLAlchemy that the value field of my table are between 100 , 230 or 10, 12or 7, 1320 and so on. my table looks like this: id | value ----|------ 1 | 120 2 | 2 3 | 9 4 | 1245 5 | 4512 in this case I want these ids: 1,3,4. I did something like this but I cant do the or part so it just filter the rows that matches all criteria q = session.query(Table.value) for f in l: q = q.filter((Table.value.between(f[0], f[1]))) I'm using Python3.6.
type: AnsweredQuestion
score: 7
answer count: 1
downvote count: 0
upvote count: 7
tagged with: sqlalchemy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50305408

http://stackoverflow.com/comment/87778816
type: AnswerComment
comment on: http://stackoverflow.com/a/50379814
score: 0
type: Comment
has text: Yeah, they (the white spaces) show up when using Excel to open the file also.

http://stackoverflow.com/comment/87716661
type: QuestionComment
comment on: http://stackoverflow.com/q/50350404
score: 1
type: Comment
has text: Can you [edit](https://stackoverflow.com/posts/50350404/edit) to include **what you expect** from the output?

http://stackoverflow.com/q/50337332
tagged with: python
type: Question
answer count: 1
tagged with: neural-network
accepted answer: http://stackoverflow.com/a/50338238
type: AnsweredQuestion
score: 0
has title: Backpropagation for sigmoid activation and softmax output
has body: I am trying to build a L layer neural network for multi-class classification with softmax activation in the output layer and sigmoid activation in other layers. The function used for training looks like this: def L_layer_model(X, Y, layers_dims, learning_rate=0.01, num_iterations=5000, print_cost=True): """ Implements a L-layer neural network: [LINEAR-&gt;SIGMOID]*(L-1)-&gt;LINEAR-&gt;SOFTMAX. Arguments: X -- data, numpy array of shape (number of features, number of examples) Y -- true "label" vector of shape (number of classes, number of examples) layers_dims -- list containing the input size and each layer size, of length (number of layers + 1). learning_rate -- learning rate of the gradient descent update rule num_iterations -- number of iterations of the optimization loop print_cost -- if True, it prints the cost every 100 steps Returns: parameters -- parameters learnt by the model. They can then be used to predict. """ np.random.seed(1) costs = [] # keep track of cost # Parameters initialization. parameters = initialize_parameters_deep(layers_dims) L = len(parameters) // 2 # number of layers in the neural network forward_calculated = {} m = Y.shape[1] # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: [LINEAR -&gt; SIGMOID]*(L-1) -&gt; LINEAR -&gt; SOFTMAX. A = X forward_calculated["A0"] = X for l in range(1, L+1): A_prev = A #print(A_prev) W = parameters['W' + str(l)] b = parameters['b' + str(l)] #print("W.shape: "+str(W.shape)) #print("A_prev.shape: "+str(A_prev.shape)) #print("b.shape: "+str(b.shape)) Z = np.dot(W, A_prev) + b #Z = np.matmul(W, A_prev) + b assert(Z.shape == (W.shape[0], A.shape[1])) forward_calculated["Z" + str(l)] = Z # store for future use if l != L: # except the last layer A = sigmoid(Z) else: A = softmax(Z) #print("A is a tuple: ", end='') #print(isinstance(A, tuple)) forward_calculated["A" + str(l)] = A # store for future use assert(forward_calculated["A" + str(L)].shape == (NUMBER_OF_CLASSES, X.shape[1]…
tagged with: backpropagation
has answer: http://stackoverflow.com/a/50338238

http://stackoverflow.com/comment/87483905
comment on: http://stackoverflow.com/q/50233259
type: Comment
score: 4
type: QuestionComment
has text: It is exactly the same, 'a b' in 'a b c' will return True.

http://stackoverflow.com/q/50370798
accepted answer: http://stackoverflow.com/a/50371257
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87758043
type: Question
upvote count: 2
score: 2
has title: Hashable abstract class from abc module
downvote count: 0
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50371257
type: AnsweredQuestion
has body: I read about the abc module by reading chapter two of "Fluent Python". So I started writing some code just to play with it. Why is an empty class an instance of the abstract base class Hashable? from collections import abc class foo: pass print(isinstance(foo,abc.Hashable)) # True

http://stackoverflow.com/q/50380692
favorite count: 0
has body: I am trying to accelerate my code and this part of it is giving me problems, I tried to use Cython and then followed the advise given here but my pure python function performs better than both the cython and cython_optimized ones The cython code is the following: import numpy as np cimport numpy as np DTYPE = np.float ctypedef np.float_t DTYPE_t cimport cython @cython.boundscheck(False) @cython.wraparound(False) def compute_cython(u, PorosityProfile, DensityIceProfile, DensityDustProfile, DensityProfile): DustJ, DustF, DustG, DustH, DustI = 250.0, 633.0, 2.513, -2.2e-3, -2.8e-6 IceI, IceC, IceD, IceE, IceF, IceG, IceH = 273.16, 1.843e5, 1.6357e8, 3.5519e9, 1.6670e2, 6.4650e4, 1.6935e6 delta = u-DustJ result_dust = DustF+DustG*delta+DustH*delta**2+DustI*(delta**3); x= u/IceI; result_ice = (x**3)*(IceC+IceD*(x**2)+IceE*(x**6))/(1+IceF*(x**2)+IceG*(x**4)+IceH*(x**8)) return (DensityIceProfile*result_ice+DensityDustProfile*result_dust)/DensityProfile def compute_cythonOptimized(np.ndarray[DTYPE_t, ndim=1] u, np.ndarray[DTYPE_t, ndim=1] PorosityProfile, np.ndarray[DTYPE_t, ndim=1] DensityIceProfile, np.ndarray[DTYPE_t, ndim=1] DensityDustProfile, np.ndarray DensityProfile): assert u.dtype == DTYPE assert PorosityProfile.dtype == DTYPE assert DensityIceProfile.dtype == DTYPE assert DensityDustProfile.dtype == DTYPE assert DensityProfile.dtype == DTYPE cdef float DustJ = 250.0 cdef float DustF = 633.0 cdef float DustG = 2.513 cdef float DustH = -2.2e-3 cdef float DustI = -2.8e-6 cdef float IceI = 273.16 cdef float IceC = 1.843e5 cdef float IceD = 1.6357e8 cdef float IceE = 3.5519e9 cdef float IceF = 1.6670e2 cdef float IceG = 6.4650e4 cdef float IceH = 1.6935e6 cdef np.ndarray[DTYPE_t, ndim=1] delta = u-DustJ cdef np.ndarray[DTYPE_t, ndim=1] result_dust = DustF+DustG*delta+DustH*delta**2+DustI*(delta**3); cdef np.ndarray[DTYPE_t, ndim=1] x= u/IceI; cdef np.ndarray[DTYPE_t, ndim=1] result_ice = (x**3)*(IceC+IceD*(x**2)+IceE*(x**6))/(1+IceF*(x**2)+IceG*(x**4)+IceH*(x**8)) re…
type: Question
has comment: http://stackoverflow.com/comment/87787607
possible better answer: http://stackoverflow.com/a/50383529
has title: Cython function taking more time than pure python
tagged with: python
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87778056
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87778547
downvote count: 0
linked to: http://stackoverflow.com/q/49058949
has answer: http://stackoverflow.com/a/50387858
has answer: http://stackoverflow.com/a/50383529
tagged with: cython
linked to: http://stackoverflow.com/q/49803899
accepted answer: http://stackoverflow.com/a/50387858

http://stackoverflow.com/comment/135272682
comment on: http://stackoverflow.com/a/50259405
score: 0
type: AnswerComment
has text: I have now added a simplified solution which should be easier to work with.
type: Comment

http://stackoverflow.com/comment/87584393
has text: @JohnSmith ya but I keep running into problems with my attempts. I have some code that will remove the zero if it is by itself but its not tracking properly with the `.` or other numbers. I am sure there is a better way then what I am trying to do.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50262194

http://stackoverflow.com/comment/87783561
has text: Consider also looking at [heapq.merge()](https://docs.python.org/3/library/heapq.html#heapq.merge) standard library function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50383929

http://stackoverflow.com/a/50325234
has comment: http://stackoverflow.com/comment/87666735
upvote count: 2
has body: You are right, you are just using it wrongly. See the error: TypeError: unsupported operand type(s) for %: 'Timestamp' and 'datetime.timedelta'. This error means you cannot simply write x % timedelta(minutes=15) and hope it can work. It cannot. x, which is an instance of Timestamp, doesn't know how to % a datetime.timedelta. If you want it to work, you at least need to convert x to datetime_modulo.datetime.
answers question: http://stackoverflow.com/q/50324848
has comment: http://stackoverflow.com/comment/87674318
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87703100

http://stackoverflow.com/q/50342680
tagged with: subclass
has title: Keras Sub classing api style
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/52837830
has comment: http://stackoverflow.com/comment/103460205
tagged with: api
score: 0
has body: I'm stuck to make a model with a subclass method.The question is that in this subclass method where is our input shape method and where is our compilation step? Kindly help I have to do my assignments. import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) def call(self, inputs): x = self.dense1(inputs) return self.dense2(x) model = MyModel() Here is the link
upvote count: 1
tagged with: keras
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/87617931
score: 0
type: Comment
type: AnswerComment
has text: Oha, `win.document.write(data);` indeed shows the alert (instead of `win.document.body.innerHTML = data;`)! That looks promising, thanks!
comment on: http://stackoverflow.com/a/50300536

http://stackoverflow.com/q/50350975
has comment: http://stackoverflow.com/comment/87717844
has title: Indexing specific values in a list to be changed based off a corresponding index
has comment: http://stackoverflow.com/comment/87718870
has comment: http://stackoverflow.com/comment/87718568
tagged with: indexing
has comment: http://stackoverflow.com/comment/87717924
has comment: http://stackoverflow.com/comment/87718367
tagged with: python
type: Question
score: 0
has body: I have two arrays from previous functions ALPt = (90, -70, 90) N = [1, 2, 1] I've defined a new function to do operations with each element in N but I want to set a condition based on the sign of the corresponding element in ALPt I've tried a few different methods, this is the closest I have def ALPe(): ALPe = [] for i in N: ALPe0 = math.degrees(math.acos((i * Bt) / (math.pi * Dk))) ALPe.append(ALPe0) for n, j in enumerate(ALPe): for m, k in enumerate(ALPt): if k &lt; 0: ALPe[n] = j * -1 return ALPe ALPe = ALPe() print(ALPe) Output: [-80.8421504880813, -71.43925528310385, -80.8421504880813] I am missing something that changes the sign of the n element in ALPe based on m element in ALPt, which would make the output look like this: [80.8421504880813, -71.43925528310385, 80.8421504880813] any suggestions?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87717921
tagged with: function
answer count: 1
has answer: http://stackoverflow.com/a/50353093

http://stackoverflow.com/q/50334389
type: Question
has body: I ran an asynchronous task with celery; I use redis as Backend and MessageQueue. I try to get the stored result through a new AsyncResult object, but it hangs.. My run : &gt;&gt;&gt; from test_celery.tasks import add &gt;&gt;&gt; from celery.result import AsyncResult &gt;&gt;&gt; r = add.delay(1,1) &gt;&gt;&gt; r.id '71bfc569-5752-4535-8a9e-108a80157a1d' &gt;&gt;&gt; r.backend &lt;celery.backends.redis.RedisBackend object at 0x7f4242feb0d0&gt; &gt;&gt;&gt; r.get() 2 &gt;&gt;&gt; r.get() 2 &gt;&gt;&gt; x = AsyncResult(r.id) &gt;&gt;&gt; x.get() --&gt; hangs What am I doing wrong?
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Celery AsyncResult with Redis BackendResult Strange behaviour
has answer: http://stackoverflow.com/a/50336097
score: 0
tagged with: celery

http://stackoverflow.com/comment/87624491
type: Comment
has text: I am trying to avoid the use of sets, as I'm wanting to write it as an algorithm. So while sets would work it's not my preferred solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/50304061
score: 0

http://stackoverflow.com/a/50361613
score: 0
accepted answer of: http://stackoverflow.com/q/50359384
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87770398
answers question: http://stackoverflow.com/q/50359384
has body: The problem is that you are concating tuples together, the countReducer will not give you a list of tuples. In Python: (1,2) + (3,4) = (1,2,3,4) What you can do is to convert the tuple to an list of tuples (with a single element). It can be done by using a map: .map(lambda x: (x[0], [ x[1] ])) But in this case it would be better to change the convertTuple function to return what you want: def convertTuple(*data): for k,v in data: return k[0], [(k[1],v)] As a side note, it look like you are using RDDs and not dataframes. If you don't use an old Spark version I would recommend looking into changing to dataframes instead since they are a bit easier to work with.
type: Answer

http://stackoverflow.com/comment/87777875
type: AnswerComment
has text: see if update works but I think something with apply will do better.
comment on: http://stackoverflow.com/a/50379148
type: Comment
score: 0

http://stackoverflow.com/comment/87640968
score: 0
comment on: http://stackoverflow.com/q/50312307
type: QuestionComment
has text: Forgot how toxic StackOverflow can be. I'm guessing people think this is more Ubuntu related question than programming. Will move question.
type: Comment

http://stackoverflow.com/a/50244412
has comment: http://stackoverflow.com/comment/87659540
has body: With DNF, it would look something like this (untested because writing quickly): base = dnf.Base() base.read_all_repos() base.fill_sack() for pkg in base.sack.query().filter(name='xterm'): print(pkg.remote_location()) You probably want to do a little more processing, like only using one of the locations if multiple exist, and maybe some error handling.
answers question: http://stackoverflow.com/q/50244085
type: Answer
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87517560
has comment: http://stackoverflow.com/comment/87547113

http://stackoverflow.com/comment/87778747
score: 0
type: AnswerComment
has text: For clarity, you should also consider looping and calling writerow.
type: Comment
comment on: http://stackoverflow.com/a/50381259

http://stackoverflow.com/a/50263843
answers question: http://stackoverflow.com/q/50261024
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50261024
score: 1
type: Answer
has body: You could check which mouse button is pressed in the elif event.type == pg.MOUSEMOTION: block, e.g. if event.buttons[0]:, and then either move or scale the rect depending on the button. To move the rect, just add the event.rel to the rect.x and rect.y attributes. import pygame as pg pg.init() screen = pg.display.set_mode((640, 480)) clock = pg.time.Clock() rect1 = pg.Rect(100, 100, 161, 100) rect2 = pg.Rect(300, 200, 161, 100) selected_rect = None done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.MOUSEBUTTONDOWN: for rect in (rect1, rect2): if rect.collidepoint(event.pos): selected_rect = rect # Select the colliding rect. elif event.type == pg.MOUSEBUTTONUP: selected_rect = None # De-select the rect. elif event.type == pg.MOUSEMOTION: if selected_rect is not None: # If a rect is selected. if event.buttons[0]: # Left mouse button is down. # Move the rect. selected_rect.x += event.rel[0] selected_rect.y += event.rel[1] else: # Right or middle mouse button. # Scale the rect. selected_rect.w += event.rel[0] selected_rect.h += event.rel[1] selected_rect.w = max(selected_rect.w, 10) selected_rect.h = max(selected_rect.h, 10) screen.fill((30, 30, 30)) pg.draw.rect(screen, (0, 100, 250), rect1) pg.draw.rect(screen, (0, 200, 120), rect2) pg.display.flip() clock.tick(30)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87769493
type: AnswerComment
comment on: http://stackoverflow.com/a/50374921
score: 0
type: Comment
has text: Thanks .Actually match=re.findall(r'\b(?!t)\w+',text) worked. It was looking for raw string

http://stackoverflow.com/a/50339258
score: 1
type: Answer
has body: The problem is here: def another_rec(): second_rec = "" second_rec = (input("Would you like another recommendation Y/N: ")) while second_rec == str("Y"): show_rec_output(age) You don't have age here, but you're trying to use it anyway. To fix it, you want to do the exact same thing you do with show_rec_output. First, add an age parameter to the another_rec function: def another_rec(age): … and then, pass the value in from main_module: show_rec_output(age) another_rec(age)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50339216

http://stackoverflow.com/q/50249514
tagged with: web-scraping
tagged with: python
score: 0
has body: I've written a web-scraping program using scrapy which extracts the header and body from the search results and while running the spider using the command scrapy crawl reddit it shows DEBUG: Crawled (200) <GET https://www.reddit.com/r/help/search?q=hydrochlorothiazide/> (referer: None) ERROR: Spider error processing <GET https://www.reddit.com/r/help/search?q=hydrochlorothiazide/> (referer: None) But if I run these commands one by one in a scrapy shell it gets scraped correctly. Can someone help me out with this issue? import scrapy class RedditSpider(scrapy.Spider): name = 'reddit' allowed_domains = ['www.reddit.com'] start_urls = ['https://www.reddit.com/r/help/search?q=hydrochlorothiazide/'] def parse(self, response): #view(self.response) posts = response.xpath('//*[@class="search-result-group"]') for post in posts: header = post.xpath('//*[@class="search-result-header"]/a/text()').extract_first() text = post.xpath('//*[@class="md"]/p/text()').extract_first() yield{'Header':header,'Text':text}
tagged with: scrapy
has title: ERROR: Spider error processing in Scrapy Module
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50250480

http://stackoverflow.com/comment/87695314
type: AnswerComment
has text: tf.sparse_matmul() is between two matrices, not a matrix and a vector. I tried saving the vector as another sparse matrix and doing this but this gives "TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: SparseTensor(indices=Tensor("SparseTensor_6/indices:0", shape=(2, 2), dtype=int64), values=Tensor("SparseTensor_6/values:0", shape=(2,), dtype=float32), dense_shape=Tensor("SparseTensor_6/dense_shape:0", shape=(2,), dtype=int64)). Consider casting elements to a supported type."
score: 0
comment on: http://stackoverflow.com/a/50339164
type: Comment

http://stackoverflow.com/a/50385057
answers question: http://stackoverflow.com/q/50384614
downvote count: 0
upvote count: 1
has body: There are few mistakes in your code. First of all, you've got the indexes messed up. Indexing in this starts at 0. So just substract 1 from all of your indexes. You can't read from file repeatedly, because the reader will hit it's end and then it won't read anything anymore, because it's at the end. So for the second loop, you need to reset it's reader back to start. That can be easily done by setting the seek. import csv with open('File1', 'r') as ranges, open('File2', 'r') as timeStamp: range_reader = csv.reader(ranges, quotechar='"') timeStamp_reader = csv.reader(timeStamp, quotechar='"') rangeArray = {} for range_row in range_reader: print("%s / %s" % ( range_row[1], range_row[2])) # This looks better, and gives more info than just printing both timestamps on each line timeStamp.seek(0) # This will set position of cursor in timeStamp back to start, so it can iterate repeatedly rangeArray[range_row[0]] = [] for timeStamp_row in timeStamp_reader: if range_row[1] &lt;= timeStamp_row[1] and range_row[2] &gt;= timeStamp_row[1]: rangeArray[range_row[0]].append(timeStamp_row[0]) print (" %s falls within %s " % (timeStamp_row[0], range_row[0])) print("\n\n") # Desired Output: for key in rangeArray: print("%s falls within %s" % (', '.join([str(x) for x in rangeArray[key]]), key)) This gives output like this: 2018-05-17 01:50:17+0000 / 2018-05-17 02:00:17+0000 TimeStamp1 falls within Range1 2018-05-17 01:50:17+0000 / 2018-05-17 04:00:17+0000 TimeStamp1 falls within Range2 TimeStamp2 falls within Range2 2018-05-17 01:50:17+0000 / 2018-05-17 08:00:17+0000 TimeStamp1 falls within Range3 TimeStamp2 falls within Range3 TimeStamp3 falls within Range3 TimeStamp1 falls within Range1 TimeStamp1, TimeStamp2 falls within Range2 TimeStamp1, TimeStamp2, TimeStamp3 falls within Range3
type: Answer
score: 1

http://stackoverflow.com/a/50335524
type: Answer
answers question: http://stackoverflow.com/q/50335474
has comment: http://stackoverflow.com/comment/87687403
has comment: http://stackoverflow.com/comment/87687389
has comment: http://stackoverflow.com/comment/121809304
has comment: http://stackoverflow.com/comment/87687332
has comment: http://stackoverflow.com/comment/87687342
has comment: http://stackoverflow.com/comment/87687373
has comment: http://stackoverflow.com/comment/87687430
upvote count: 2
score: 2
has body: You can flatten the first list using itertools.chain.from_iterable and use set intersection: &gt;&gt;&gt; set(itertools.chain.from_iterable(a)) &amp; set(b) set(['Afghanistan', 'Albania', 'Angola', 'Algeria']) If you don't want the itertools import (at the cost of a bit of performance): &gt;&gt;&gt; set([i for j in a for i in j]) &amp; set(b) set(['Afghanistan', 'Albania', 'Angola', 'Algeria'])
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50335474
has comment: http://stackoverflow.com/comment/87687398
has comment: http://stackoverflow.com/comment/121809257

http://stackoverflow.com/comment/87497359
comment on: http://stackoverflow.com/q/50239611
has text: it's because some of your `msgs` don't have the attribute `user` so, `msg.user` is None for them in your loop. Django will always raise `Reverse for 'home' with keyword arguments '{'pk': ''}' not found.`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87728918
score: 0
type: Comment
type: QuestionComment
has text: @CharlesDuffy yes I have shown that I *can* do that, but I can't pass the decorator an argument. The pattern for passing extra arguments to decorators works when the decorator returns a callable, not when it's a non-callable object -- such as `property`.
comment on: http://stackoverflow.com/q/50354039

http://stackoverflow.com/comment/87611049
type: Comment
comment on: http://stackoverflow.com/a/50245509
has text: @AndréSousa: I have no idea what you mean with your last comment.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87517373
has text: Great. Thanks. I guess this q deserves an answer instead of deletion since I am sure sb else will wonder the same thing.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50249979

http://stackoverflow.com/comment/87690491
score: 0
comment on: http://stackoverflow.com/q/50262291
type: Comment
type: QuestionComment
has text: I have used inner join on one paramater. Also i have tried using a sample of the whole data. It then worked fine. But when am dealing with the whole df, it's giving memory error. I have reduced the size of df by converting into suitable data type also. I have used dask in the end. But still that's taking way more time.

http://stackoverflow.com/comment/128119018
comment on: http://stackoverflow.com/a/50263930
type: Comment
has text: Yes, it took me 2 weeks of swapping out computers and upgrading memory to figure out that Windows is poorly reporting this error. In my case linux was not reporting this mismatch between the requested size and the file size on disk and was running without a problem. Once I switched to Windows for deployment I got this cryptic and completely misleading message.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50293427
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50294599
favorite count: 0
type: Question
tagged with: anaconda
has title: Import custom .py files in Jupyter Notebook for Anaconda3
tagged with: python
tagged with: jupyter-notebook
score: 2
upvote count: 2
has body: Where do I store custom .py files for Anaconda3 on Mac, so that I can import them as packages in Jupyter Notebook?
type: UnansweredQuestion

http://stackoverflow.com/q/50317384
favorite count: 0
type: Question
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has title: Using select to match a class and an element beautifulSoup error
has body: So i am using 'beautifulsoup at python to try to take some html info from a page. from bs4 import BeautifulSoup page = requests.get('http://www.meteo.gr/cf.cfm?city_id=14') #sending the request to take the html file. soup = BeautifulSoup(page.content, 'html.parser') #creating beautifulSoup object of the html code. four_days = soup.find("div", {"class": "content"})#PINPOINTING to the section that i want to focus (the outer). #Selecting specific elements , having as my base the seven_day. periods_times = [p.get_text(strip=True) for p in four_days.select(".perhour .fulltime")] anemos = [sd.get_text("|", strip=True) for sd in four_days.select(".anemosfull")] temps = [t.get_text("|", strip=True) for t in four_days.select(".temperature .tempcolorcell") ] prognosi_ouranou =[pk.get_text("|", strip=True) for pk in four_days.select(".phenomenafull .phenomeno-name") ] drastiriotita_kounoupion =[po.get_text("|", strip=True) for po in four_days.select(".someclass .tr &gt; title") ] #creating a Data Frame via pandas to print it TABLE-like. import pandas as pd weather = pd.DataFrame({ "drastiriotita_kounoupion": drastiriotita_kounoupion}) print weather I get an error when i try something like this. I know how to use 2 classes in a selector but the info i want to take from the site is inside one class and this class contains the info in a element. Any suggestion. Thanks i tried to find simmilar examples in the documentation but none of them really covers my question. [simmilar example] css_soup.select("p.strikeout.body")

http://stackoverflow.com/q/50354039
has answer: http://stackoverflow.com/a/50356352
answer count: 1
has comment: http://stackoverflow.com/comment/87728918
linked to: http://stackoverflow.com/q/5929107
has comment: http://stackoverflow.com/comment/87726219
has comment: http://stackoverflow.com/comment/87730606
type: Question
has body: I have subclassed the built-in property class (call it SpecialProperty) in order to add more fields to it: class SpecialProperty(property): extra_field_1 = None extra_field_2 = None def __init__(self, fget=None, fset=None, fdel=None, doc=None): super().__init__(fget, fset, fdel, doc) def make_special_property(func): prop = SerialisableProperty(fget=func) return prop and I am able to use it in the same fashion as the built-in property() decorator: @my_module.make_special_property def get_my_property(self): return self._my_property I now want to further specialise my SpecialProperty instances populating one of the extra fields I have added to the class with an arbitrary value. Is it possible, in Python, to write a decorator that will return a property with also accepting extra parameters? I'd like to do it via the decorator because this is where and when the information is most relevant, however I'm finding myself stuck. I suspect this falls under the domain of decorators with arguments that have been well documented (Decorators with arguments? (Stack Overflow), or Python Decorators II: Decorator Arguments (artima.com) to only cite a couple sources), however I find myself unable to apply the same pattern to my case. Here's how I'm trying to write it: @my_module.make_special_property("example string") def get_my_property(self): return self._my_property And on the class declaring get_my_property: &gt;&gt;&gt; DeclaringClass.my_property &lt;SpecialProperty object at 0x...&gt; &gt;&gt;&gt; DeclaringClass.my_property.extra_field_1 'example string' Since I am making properties, the decorated class member should be swapped with an instance of SpecialProperty, and hence should not be a callable anymore -- thus, I am unable to apply the "nested wrapper" pattern for allowing a decorator with arguments. Non working example: def make_special_property(custom_arg_1): def wrapper(func): prop = SerialisableProperty(fget=func) prop.extra_field_1 = custom_arg_1 return prop return wrapp…
has comment: http://stackoverflow.com/comment/87732535
has comment: http://stackoverflow.com/comment/88347613
tagged with: python
has comment: http://stackoverflow.com/comment/87728861
has title: Can a decorator returning a non-callable take additional arguments?
tagged with: python-decorators
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50356352

http://stackoverflow.com/comment/87652371
has text: Why do you believe that `weight` is going to be defined?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50318278
score: 0

http://stackoverflow.com/a/52934163
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50237887
upvote count: 0
downvote count: 1
has body: Even I am facing the same trouble but that is not the case when we use google colaboratory !! You can perform all your experiment in the cloud within an environment alreay setup : [Colaboratory][1] https://colab.research.google.com/notebooks/welcome.ipynb#scrollTo=-Rh3-Vt9Nev9

http://stackoverflow.com/comment/87633013
has text: @SalA. - Unfortunately it was answered before, so if you can upvote [this](https://stackoverflow.com/questions/47311266/update-pandas-dataframe-based-on-matching-columns-of-a-second-dataframe) answer. Thanks.
comment on: http://stackoverflow.com/q/50308340
type: Comment
score: 0
type: QuestionComment

terminal
tags question: http://stackoverflow.com/q/50308757
type: Tag
tag name: terminal
tags question: http://stackoverflow.com/q/50326090
tags question: http://stackoverflow.com/q/50243373
tags question: http://stackoverflow.com/q/50281510

http://stackoverflow.com/comment/87588732
type: Comment
has text: @jezrael I need one more help, is there any way to do the same thing if the header (ID,var_name,var_value) is not present in my file only other rows are present, but in the file it should be in the same sequence as the header.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50285324

http://stackoverflow.com/a/50321284
has body: re.split() is good choice for complex spliting: import re [re.split('([\d\/\.\-\:\s]+)\s+([A-Z\s\,]+)', x[0])[1:3] for x in a]
answers question: http://stackoverflow.com/q/50321160
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/50281108
has title: Scrapy not writing all outputs to CSV
score: 1
has comment: http://stackoverflow.com/comment/87584834
answer count: 0
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
favorite count: 0
has comment: http://stackoverflow.com/comment/87596865
has body: I am using Scrapy to ping a bunch of webpages and determine which of the homepages are no longer live. The full code of my spider is very simple, and reproduced below: class BrokenLinksSpider(scrapy.Spider): name = 'broken-link-spider' def __init__(self, id_homepage_mapping, *args, **kwargs): self.org_homepages = id_homepage_mapping self.download_timeout = 10 def start_requests(self): for qId, url in self.org_homepages.items(): if url.endswith("/"): url = url[0:-1] yield scrapy.Request(url, callback=self.complete_callback, errback=self.error_callback, dont_filter=True, meta={ 'handle_httpstatus_all': True, 'id': id }) def complete_callback(self, response): if str(response.status)[0] in ("4", "5"): yield BrokenLinkCheckerItem( url=response.request.url, status=response.status, qId=response.meta['id']) def error_callback(self, failure): yield BrokenLinkCheckerItem( url=failure.request.url, status=repr(failure), qId=failure.request.meta['id']) In the logs of my app, I can see in the scrapy stats collector that there were exceptions with fetching about 40,000 links. However, the csv output file that I'm writing to only contains about 8k rows. Furthermore, the CSV file seems to contain all of the different types of exceptions reported by the StatsCollector, just less instances of each. So my question is, why is there such a discrepancy between what the statsCollector reports and what's actually written to the CSV? Given my understanding of the errback callback function, shouldn't all those exceptions end up being written to the CSV? Thanks!
type: Question
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/87775778
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50379574
has text: OK. As @ZiyadEdher said, you need to print a newline character at the end of each `highGreen` call.
type: Comment

http://stackoverflow.com/a/50302320
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87642320
has body: The builtin csv module will handle this, with the only wrinkle being that that library is really designed to consume files, so the documentation may be a little unhelpful for your case, where you have a string. But the reader object can consume lists, so instead of a file, you can just pass in a list of CSV-formatted strings: import csv print(list(csv.reader(["""14,Amazing,Mark of the Ninja,PC,9.0,"Action, Adventure",Y,2012,9,7"""]))) # '14', 'Amazing', 'Mark of the Ninja', 'PC', '9.0', 'Action, Adventure', 'Y', '2012', '9', '7'
has comment: http://stackoverflow.com/comment/87621556
accepted answer of: http://stackoverflow.com/q/50302291
has comment: http://stackoverflow.com/comment/87621476
type: Answer
answers question: http://stackoverflow.com/q/50302291

http://stackoverflow.com/comment/87650427
comment on: http://stackoverflow.com/q/50317305
type: QuestionComment
score: 0
has text: Do you want all the combinations consisting of any number of rows that matches your criteria? If so, this problem seems computationally rather hard to me at first glance.
type: Comment

http://stackoverflow.com/comment/126657081
has text: The `if/else` is really redundant here (as comparation already returns a boolean). This can just be `is_retired = is_retired == 'on'`
comment on: http://stackoverflow.com/a/58500141
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/50275747
has body: I finally solved the problem using the following link: On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error I have downgraded my tensorflow version from 1.7 to 1.5. Apparently, the newer version needs AVX instruction set which is not supported by my CPU. I hope this is going to be helpful for other users.
score: 0
answers question: http://stackoverflow.com/q/50257840
type: Answer

http://stackoverflow.com/q/50278746
downvote count: 0
tagged with: url
tagged with: python
accepted answer: http://stackoverflow.com/a/50278847
has answer: http://stackoverflow.com/a/50278847
type: AnsweredQuestion
score: 2
has title: python take out portion of URL and keep original formatting
favorite count: 0
type: Question
tagged with: split
possible better answer: http://stackoverflow.com/a/50278860
answer count: 2
upvote count: 2
has body: Lets say i have the following URL: https://espn.com/1234/44/222/mlb/standings And i wanted to extract the /1234/44/222 as is. I understand that split('/')[3:5] would extract that , but it would lose the / formatting.
has answer: http://stackoverflow.com/a/50278860

http://stackoverflow.com/comment/115776346
has text: Suppose you do this and you end up with two images in that array. How do you get the ith item of that array, meaning a specific image (e.g. the second)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50280844
type: AnswerComment

http://stackoverflow.com/comment/87719271
score: 0
type: Comment
type: QuestionComment
has text: when posting an error message, please post the **full** stacktrace so one can see where the error happens. Also, it would help if you would provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). In you case, that would be code that does not rely on receiving data through the serial port
comment on: http://stackoverflow.com/q/50342300

http://stackoverflow.com/comment/87715249
score: 0
type: Comment
has text: And I did not think about the consequences that it could have to add my entire code. I assure you that my intention was not to hurt you, besides the code does not work. By the way, you can check yourself to or point this server: it is local. But now, I doubt that people will take my motivations seriously. It is difficult to convey one's sincerity on such an area.
comment on: http://stackoverflow.com/q/50347502
type: QuestionComment

http://stackoverflow.com/q/50252558
linked to: http://stackoverflow.com/q/46486078
has body: I have an image, that a result of scanning a hardcopy file like this : as you can see, there is a whitespace and also four rectangles on every corners. i need to find coordinates of every edge of rectangles, so i can crop it. I use opencv, how to do that with opencv? How to get edge coordinates of scanned image with opencv? this is result i want achieve if i have that coordinates, so i can crop it with this code i got from internet : # USAGE # python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]" # python transform_example.py --image images/example_02.png --coords "[(101, 185), (393, 151), (479, 323), (187, 441)]" # python transform_example.py --image images/example_03.png --coords "[(63, 242), (291, 110), (361, 252), (78, 386)]" # import the necessary packages from pyimagesearch.transform import four_point_transform import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", help = "path to the image file") ap.add_argument("-c", "--coords", help = "comma seperated list of source points") args = vars(ap.parse_args()) # load the image and grab the source coordinates (i.e. the list of # of (x, y) points) # NOTE: using the 'eval' function is bad form, but for this example # let's just roll with it -- in future posts I'll show you how to # automatically determine the coordinates without pre-supplying them image = cv2.imread(args["image"]) pts = np.array(eval(args["coords"]), dtype = "float32") # apply the four point tranform to obtain a "birds eye view" of # the image warped = four_point_transform(image, pts) # show the original and warped images cv2.imshow("Original", image) cv2.imshow("Warped", warped) cv2.waitKey(0)
has comment: http://stackoverflow.com/comment/87524277
type: Question
has answer: http://stackoverflow.com/a/50252871
has title: How to get edge coordinates of scanned image with opencv?
tagged with: python
tagged with: opencv
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50252871
has comment: http://stackoverflow.com/comment/87522453
answer count: 1

http://stackoverflow.com/comment/87692619
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50336458
score: 0
has text: Thanks @arieljannai. That was a screen paste error on my part. I get the same message whether I try root or the user I created, paul. I've also tried both "password" and "passwd".

http://stackoverflow.com/comment/87770979
score: 0
type: AnswerComment
has text: Are you accidentally using axis twice in the set_axis call? : no i copied and pasted your exact code
type: Comment
comment on: http://stackoverflow.com/a/50377342

http://stackoverflow.com/q/50231968
score: 1
linked to: http://stackoverflow.com/q/26690932
has answer: http://stackoverflow.com/a/50232212
favorite count: 0
tagged with: draw
type: Question
tagged with: polygon
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: computer-vision
has title: opencv polygon with dotted or dashed lines
has body: I have a line of code here that uses the python binding for opencv: cv2.polylines(mask, [pts],True, ignore_mask_color) This draws a blue polygon on image mask. But is there a way the lines of the polygon can be stylized? Not too much. Just dotted, or dashed, that's it really.
tagged with: opencv

http://stackoverflow.com/q/50266975
linked to: http://stackoverflow.com/q/33919948
has answer: http://stackoverflow.com/a/55734389
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
has body: Keras has a callback that reduces the learning rate upon a plateauing of a specified metric, called ReduceLROnPlateau. How do you create such a feature in native Tensorflow? In a Tensorflow model, is it possible to call on Keras callbacks? Or does it need to be written in native Tensorflow? If so, how would you set the learning rate in the middle of a training session?
tagged with: neural-network
tagged with: machine-learning
tagged with: python
possible better answer: http://stackoverflow.com/a/55734389
tagged with: keras
has answer: http://stackoverflow.com/a/50268296
accepted answer: http://stackoverflow.com/a/50268296
type: AnsweredQuestion
has title: How would you do ReduceLROnPlateau in Tensorflow?
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87691727
type: AnswerComment
score: 0
has text: just pass the -e argument with system run. os.system('gradle run -e')
type: Comment
comment on: http://stackoverflow.com/a/50337648

http://stackoverflow.com/a/50334807
type: Answer
answers question: http://stackoverflow.com/q/50334685
score: 1
has comment: http://stackoverflow.com/comment/87686575
downvote count: 0
upvote count: 1
has body: You could do this in similar way without any module: lst = [] for line in f: if not line.startswith('#') and line: lst.append([int(i) if i.isdigit() else i for i in line.split(',')]) print(lst) # [[1, 'foo', 'bar', 1], [1, 'foo', 'bar', 2], [21, 'foo', 'bar', 8]]

http://stackoverflow.com/comment/87532894
score: 0
type: Comment
has text: @bloo People are probably downvoting the question because you haven’t explained why you’re calling `strptime` to turn the value back into the very same `datetime` object you started with, or what you expected that to do. Also, it seems like you want to know how to fix the zero padding on `Date`, but that’s not what you asked about—instead you showed us the string representation of `x`, and asked how to get the format you already have in `Date`
type: QuestionComment
comment on: http://stackoverflow.com/q/50256825

http://stackoverflow.com/q/50319579
tagged with: classname
tagged with: python
has body: I'm new to Scrapy and working on a scrapy project. I want to scrape a div with more than one class name as below: &lt;div class="col-xs-12 available-columns inner-available trans-fade-in"&gt;&lt;div&gt; Here is my scripy (the def parse) : def parse(self, response): for flight in response.css('div.col-xs-12 available-columns inner-available trans-fade-in'): yield { 'price': flight.css('span.w-bold::text').extract_first(), } And the output is empty. So what should I do?
accepted answer: http://stackoverflow.com/a/50319600
type: AnsweredQuestion
score: 0
has title: python scrape a div with more than one class name using response.css
has answer: http://stackoverflow.com/a/50319600
tagged with: web-scraping
tagged with: scrapy
type: Question
answer count: 1

http://stackoverflow.com/a/50310152
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87768962
score: 5
has comment: http://stackoverflow.com/comment/87665910
upvote count: 5
has body: I'm going to start by pointing out ctypes official documentation: [Python 3.5]: ctypes - A foreign function library for Python. I defined a bit more complex structure tree (2 nesting levels). data_types.py: import ctypes PRAGMA_PACK = 0 class Struct2(ctypes.Structure): if PRAGMA_PACK: _pack_ = PRAGMA_PACK _fields_ = [ ("c_0", ctypes.c_char), # 1B ("s_0", ctypes.c_short), # 2B ("wanted", ctypes.c_int), # 4B ] class Struct1(ctypes.Structure): if PRAGMA_PACK: _pack_ = PRAGMA_PACK _fields_ = [ ("d_0", ctypes.c_double), # 8B ("c_0", ctypes.c_char), # 1B ("struct2_0", Struct2), ] class Struct0(ctypes.Structure): if PRAGMA_PACK: _pack_ = PRAGMA_PACK _fields_ = [ ("i_0", ctypes.c_int), # 4B ("s_0", ctypes.c_short), # 2B ("struct1_0", Struct1), ] Notes: I named the member of interest wanted (part of Struct2 which is the deepest one) One important thing when dealing with structs, it's alignment. Check [MSDN]: #pragma pack for more details. In order to illustrate the 2nd bullet (above), I prepared a small example (which has nothing to do with the question). test_addressof.py: import sys import ctypes import data_types OFFSET_TEXT = "Offset of '{:s}' member in '{:s}' instance: {:3d} (0x{:08X})" def offset_addressof(child_structure_instance, parent_structure_instance): return ctypes.addressof(child_structure_instance) - ctypes.addressof(parent_structure_instance) def print_offset_addressof_data(child_structure_instance, parent_structure_instance): offset = offset_addressof(child_structure_instance, parent_structure_instance) print(OFFSET_TEXT.format(child_structure_instance.__class__.__name__, parent_structure_instance.__class__.__name__, offset, offset)) def main(): s0 = data_types.Struct0() s1 = s0.struct1_0 s2 = s1.struct2_0 print("PRAGMA_PACK: {:d} {:s}\n".format(data_types.PRAGMA_PACK, "" if data_types.PRAGMA_PACK else "(default)")) print_offset_addressof_data(s1, s0) print_offset_addressof_data(s2, s1) print_offset_addressof_data(s2, s0) print("\nAlignments and sizes:\n\t'…
type: Answer
has comment: http://stackoverflow.com/comment/87653730
has comment: http://stackoverflow.com/comment/87653598
answers question: http://stackoverflow.com/q/50304516
has comment: http://stackoverflow.com/comment/87667204
accepted answer of: http://stackoverflow.com/q/50304516

http://stackoverflow.com/comment/87663419
score: 1
type: Comment
type: QuestionComment
has text: @PatrickArtner `(x, y)`, which is why `(52, 6), (114, 6)` before `(193, 3)`
comment on: http://stackoverflow.com/q/50323276

http://stackoverflow.com/q/50316235
favorite count: 0
type: Question
has title: Not able to import pandas in R
upvote count: 2
has comment: http://stackoverflow.com/comment/87648482
has comment: http://stackoverflow.com/comment/87648562
tagged with: python
accepted answer: http://stackoverflow.com/a/50316729
has body: I am calling a python script from R/shiny as: system("python /Users/Downloads/Untitled3.py EMEA regulatory '10% productivity saves SOW'") It is not able to import pandas. But when I straight call the script from the terminal as: python /Users/Downloads/Untitled3.py EMEA regulatory '10% productivity saves SOW' It is able to import pandas. I guess some version issue in python.I have anaconda installed. Can anyone of you please help me in rectifying the issue. Although not required as, script starts as: import pandas as pd import numpy as np import sys from difflib import SequenceMatcher ##### More code#########
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/50316729
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/a/50262648
downvote count: 0
answers question: http://stackoverflow.com/q/50262612
upvote count: 1
has comment: http://stackoverflow.com/comment/87543554
has comment: http://stackoverflow.com/comment/87568510
has comment: http://stackoverflow.com/comment/87543479
accepted answer of: http://stackoverflow.com/q/50262612
type: Answer
has comment: http://stackoverflow.com/comment/87567859
has comment: http://stackoverflow.com/comment/87567726
has comment: http://stackoverflow.com/comment/87568884
has comment: http://stackoverflow.com/comment/87568832
score: 1
has comment: http://stackoverflow.com/comment/87568104
has body: You can use vectorized method: Series.replace(lst1, lst2, regex=True) In [90]: (text_df.Text .replace(replace_terms_df.Text.tolist(), replace_terms_df.Replace_item.tolist(), regex=True)) Out[90]: 0 &lt;HERE_REPLACED&gt; is &lt;SOME_REPLACED&gt; &lt;RANDOM_REP... 1 &lt;RANDOM_REPLACED&gt; text &lt;HERE_REPLACED&gt; 2 more &lt;RANDOM_REPLACED&gt; text Name: Text, dtype: object
type: AcceptedAnswer

http://stackoverflow.com/comment/87554515
score: 1
type: Comment
type: QuestionComment
has text: @Watty62 IMO it's not, see the edit.
comment on: http://stackoverflow.com/q/50268284

http://stackoverflow.com/q/50309668
upvote count: 8
accepted answer: http://stackoverflow.com/a/50309835
has comment: http://stackoverflow.com/comment/87635356
has body: I have csv dataset of size 5.2GB (Taken from here). It has about 7M rows of dimension = 29. The values are of type float64. I want to convert this dataset into a binary file. To do so, I do the following simple lines: import numpy as np import pandas as pd df = pd.read_csv('data.csv', sep=',') np.asarray(df.values).tofile('data_binary.dat') A snapshot of the data looks like this: 0.000000000000000000e+00,9.439358860254287720e-02,1.275558676570653915e-02,9.119330644607543945e-01,-9.083136916160583496e-02,-2.335745543241500854e-01,-1.054220795631408691e+00,-9.759366512298583984e-01,-1.067278265953063965e+00,-6.138502955436706543e-01,7.542607188224792480e-01,-9.256605505943298340e-01,-5.289512276649475098e-01,1.235263347625732422e+00,8.606486320495605469e-01,-2.320102453231811523e-01,-4.043335020542144775e-01,-1.559396624565124512e+00,-8.154401183128356934e-01,-1.376865267753601074e+00,6.759096682071685791e-02,1.372575879096984863e+00,-5.736824870109558105e-01,-1.368692040443420410e+00,-4.793794453144073486e-01,1.529256343841552734e+00,-5.757816433906555176e-01,-1.290232419967651367e+00,4.999999694824218750e+02 1.000000000000000000e+00,3.272003531455993652e-01,-2.395536154508590698e-01,-1.592038273811340332e+00,-2.324983835220336914e+00,-5.070934891700744629e-01,1.574625492095947266e+00,-1.050106048583984375e+00,9.686639308929443359e-01,1.312386870384216309e+00,7.542607188224792480e-01,-9.113077521324157715e-01,-1.718587398529052734e+00,3.751282095909118652e-01,8.606486320495605469e-01,-3.711451292037963867e-01,-5.625200271606445312e-01,-2.721544206142425537e-01,-8.154401183128356934e-01,-3.339428007602691650e-01,1.058411240577697754e+00,4.364815354347229004e-01,-5.736824870109558105e-01,-2.172690257430076599e-02,-5.791836977005004883e-01,-3.260441124439239502e-01,-2.024624943733215332e-01,-4.585579931735992432e-01,7.500000000000000000e+02 The new binary file data_binary.dat is reduced to 1.5GB. This is a huge reduction which made me wonder if something went wrong with…
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50309835
type: AnsweredQuestion
has title: The conversion from csv to binary format reduces the file size abnormally
has comment: http://stackoverflow.com/comment/87635359
tagged with: pandas
has comment: http://stackoverflow.com/comment/87635316
tagged with: python
favorite count: 0
score: 8
type: Question
tagged with: numpy
tagged with: python-3.x

http://stackoverflow.com/q/50341426
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: In Python, a thread to call a function called check_values is created as follows: checking_thread = threading.Thread(target=check_values) My question is why are the parentheses omitted for check_values? What happens if they're included?
has comment: http://stackoverflow.com/comment/87698953
tagged with: python
has title: Omitted parentheses from target function
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87699029
has answer: http://stackoverflow.com/a/50341542
accepted answer: http://stackoverflow.com/a/50341542

http://stackoverflow.com/q/50248804
has comment: http://stackoverflow.com/comment/87546864
has comment: http://stackoverflow.com/comment/87529279
tagged with: python
has comment: http://stackoverflow.com/comment/87522023
has comment: http://stackoverflow.com/comment/87548122
has title: Numpy keep dimensions globally
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87524531
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87528930
has comment: http://stackoverflow.com/comment/87533520
has body: Currently, most numpy functions drop singleton dimensions automatically, and to keep them, one needs to memorize various arguments such as keepdims=True or np.newaxis. I was wondering if there has been (or will be) a global setting for that because I am writing a program that needs to keep dimensions all the time. My ideal code would be like import numpy as np np.setparams(keepdims=True) # anything like this? x = np.random.randint(10, size=(5, 10)) np.sum(x, axis=0).shape # prints (1, 10) x[:, 0].shape # prints (5, 1) Thank you!
has answer: http://stackoverflow.com/a/77249058
type: UnansweredQuestion

http://stackoverflow.com/q/50346498
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87734953
tagged with: console
favorite count: 0
type: Question
answer count: 0
downvote count: 0
tagged with: python
type: UnansweredQuestion
has body: I am trying to plot my data with matplotlib in pycharm but if I execute the script in the console the plt.show() doesn't work. It only shows a white figure window with the hourglass coursor and when I close it it says 'program has stop working' Also the first time I execute the code import matplotlib.pyplot as plt, the error message Matplotlib support failed appears. The second time it works fine and if I run it in run or debug mode it does show the plot. I don't understand what's going on here. I am using python 3.6
tagged with: plot
tagged with: pycharm
has title: matplotlib.show does not show figure in console mode
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/87745989

http://stackoverflow.com/comment/115788798
type: AnswerComment
score: 1
type: Comment
has text: Ah yes! Of course! I have this piece of code `for level in args.levels.split(","): if level == 'm': img = fimage.associated_images["macro"] else: level = int(level) img = fimage.read_region((0, 0), level, fimage.level_dimensions[level]) img = np.asarray(img)[:,:, 0:3]` but I was totally not realising the for-loop. So for each item it will produce an image and put it in an array. Weirdly enough you helped me a lot @user2357112-supports-monica!
comment on: http://stackoverflow.com/a/50280844

http://stackoverflow.com/a/50261971
score: 0
answers question: http://stackoverflow.com/q/50260488
type: Answer
has body: This is possibly an escaping issue. It would be safer if you passed the values as a list of parameters to execute() rather than manually building a string. This will ensure that they are correctly escaped. insert = 'INSERT INTO {} ('.format(table) + ', '.join(headers) + ') VALUES ({})' \ .format(', '.join(len(headers) * '?')) # Add parameter placeholders as ? for row in csvFile: values = map((lambda x: x.strip()), row) # No need for the quotes cursor.execute(insert, values) # Pass the list of values as 2nd argument conn.commit()

http://stackoverflow.com/a/50295928
accepted answer of: http://stackoverflow.com/q/50295689
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50295689
score: 5
has body: Answers to your questions: I don't know whether your approach works, but there is an easier solution. You can pass multiple arguments by defining a partial function. The output of a loss function is a scalar. Here is an example that demonstrates how to pass multiple arguments to a loss function: from keras.layers import Input, Dense from keras.models import Model import keras.backend as K def custom_loss(arg1, arg2): def loss(y_true, y_pred): # Use arg1 and arg2 here as you wish and return loss # For example: return K.mean(y_true - y_pred) + arg1 + arg2 return loss x = Input(shape=(1,)) arg1 = Input(shape=(1,)) arg2 = Input(shape=(1,)) out = Dense(1)(x) model = Model([x, arg1, arg2], out) model.compile('sgd', custom_loss(arg1, arg2))
upvote count: 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87664860
type: QuestionComment
score: 2
has text: @Hadaka Kubo delete your database and migrations and create db and makemigrations and apply it.
comment on: http://stackoverflow.com/q/50324561
type: Comment

http://stackoverflow.com/a/50282844
downvote count: 0
has comment: http://stackoverflow.com/comment/87582595
has body: This is a simple linear directed-graph problem. Make a set from all the s elements, another from all the e elements. Your starting location here is the one element in here = s_set - e_set. Find the edge path with here as its first element. Now, simply traverse the edge: here = edge[1]. As you've already done in your answer, you can pop that edge from the available list, as this should speed up successive searches. Repeat this paragraph until you have no more edges to traverse.
answers question: http://stackoverflow.com/q/50282633
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/87754712
score: 3
has text: `datetime.strptime(tm, '%I:%M')`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50369338

http://stackoverflow.com/q/50307185
type: AnsweredQuestion
tagged with: bash
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Google Compute Engine start up python script doesn't run at boot
accepted answer: http://stackoverflow.com/a/50338897
has answer: http://stackoverflow.com/a/50338897
tagged with: google-compute-engine
tagged with: python
has body: I'm trying to set up a short list of start-up commands for my Google Compute engine instance, but no matter what I do it doesn't execute. The script is supposed to start a daemon screen session and run a python script inside the screen session. This works fine from the command prompt but does not execute at all as a start-up script: #! /bin/bash screen -dmS mhsession &amp;&amp; screen -S mhsession -X stuff 'cd stream python3 streamer.py 'ABCD' ' UPDATE, output from /var/log/syslog: May 16 08:25:27 netherlands startup-script: INFO startup-script: No screen session found. May 16 08:25:27 netherlands startup-script: INFO startup-script: No screen session found. May 16 08:25:27 netherlands startup-script: INFO startup-script: Return code 1. May 16 08:25:27 netherlands startup-script: INFO Finished running startup scripts.

canny-operator
tags question: http://stackoverflow.com/q/50284122
type: Tag
tag name: canny-operator

http://stackoverflow.com/a/52432229
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50302219
has body: The important part on your error stack is: Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns iter(patterns) TypeError: 'module' object is not iterable It shows that the url resolver is trying to iterate but it is getting an object. So some of your urls.py is not returning a list or tuple as urlpatterns. A possible situation is some urlpatterns with just one pattern where you have forgot to put a comma at the end of the pattern: urlpatterns = ( url(r'^foo/$', my_view_func, name='bar'), ) If you forget the comma, urlpatterns will be a RegexURLPattern object and not a list of RegexURLPattern, getting a error just like on your stack.
type: Answer
downvote count: 0

http://stackoverflow.com/q/50353143
tagged with: python
has title: Django: Clearing request.session between forms causes csrf token error?
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has body: I am facing a very specific problem that I've narrowed down to a particular reason, and I am afraid I may simply be misunderstanding or wrongly applying my logic here. Django users will know that CSRF protection is handled by a django middleware and that each form used in the project should be followed by a {% csrf_token %} tag. My project contains an app that serves users data based on their OAuth2-authenticated sessions, for which I then save/retain some session-specific REST data. As you can probably guess, I have to clear the session cache quite often in cases of new users, or some particular parameters changing in terms of the current user's session. In order to do this, I retain some of the values from the request.session dictionary and then clear the session like so remember_dictionary = { '''some values that I wish to remember''' } request.session.clear() for key, value in remember_dictionary.items(): if value: request.session[key] = value If this function has been called in the event of the user having two forms up on the website concurrently, the older form will throw a Forbidden Error/csrf token missing. I understand that the request.session.clear() probably has something to do with this, but I was under the impression that the csrf token would remain the same for the same request.session? As far as I am aware, request.session.flush() is what would be deleting request.session and creating a new one? Furthermore, I tried saving the csrf_token in request.session using the following line in my settings.py CSRF_USE_SESSIONS = True and then including the current csrf token value in my remember dictionary before I clear the session like so, remember_dictionary = { '''some values that I wish to remember''', '_csrf_token': request.session.get('_csrf_token', False) } request.session.clear() for key, value in remember_dictionary.items(): if value: request.session[key] = value I've verified that the csrf_token gets remembered in the second method, but submission of …
favorite count: 0
type: Question
tagged with: token
type: UnansweredQuestion
tagged with: session
tagged with: csrf
tagged with: django

http://stackoverflow.com/comment/91798556
type: QuestionComment
has text: nop never... you can DM me on twitter if needed @lucky_simFR
type: Comment
comment on: http://stackoverflow.com/q/50381369
score: 0

http://stackoverflow.com/q/50310616
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/87637236
has comment: http://stackoverflow.com/comment/87637217
has comment: http://stackoverflow.com/comment/87691562
downvote count: 7
has answer: http://stackoverflow.com/a/50310636
favorite count: 0
has body: I have a code as below: items = [] for item in json.loads(json_result): items.append((item['pk'])) Is there a more elegant way to write it? From multiple lines to a flatter structure, these 3 lines are in [.......] one line. what I want is to short three lines to only one line, actually, is to use a flat structure instead of insert structure. This problem have been sloved, thanks!
possible better answer: http://stackoverflow.com/a/50310632
has title: How to short python for loop, from insert structure to flat structure?
has answer: http://stackoverflow.com/a/50310632
type: Question
upvote count: 2
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50310636
has comment: http://stackoverflow.com/comment/87637279

http://stackoverflow.com/a/50321019
score: 0
answers question: http://stackoverflow.com/q/50319942
has comment: http://stackoverflow.com/comment/87660972
has body: I recommend not using global state and instead use functions that return values directly.
has comment: http://stackoverflow.com/comment/87658800
type: Answer
has comment: http://stackoverflow.com/comment/87659723

http://stackoverflow.com/comment/87494780
type: Comment
has text: I do have multiple source roots, but the roots of the project don't contain `__init__.py` (the project spans multiple languages), therefore you can't import from the project root, which pycharm is attempting to do. It used to work fine before the reinstall though, so it must be a configuration error somewhere.
score: 0
comment on: http://stackoverflow.com/a/50238494
type: AnswerComment

http://stackoverflow.com/comment/87701802
has text: User input does not need to be validated for my purposes
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50342348

http://stackoverflow.com/comment/87485081
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50233819
score: 0
has text: Perhaps within your loop you can first check the values for `row[0]` and `row[1]` and only if they both exist, then you can update your `res` variable.

http://stackoverflow.com/a/50301798
score: 0
has body: To understand what's going on here, compare what happens in a similar example, where I want to set any numbers bigger than 20 to -1: numbers = [1, 10, 30, 40, 50] for number in numbers: if number &gt; 20: number = -1 print(numbers) # same as before! Why does this not set the last three numbers to -1? Because number here is a value—it's location in memory is totally unrelated to the contents of the numbers array. word in your example is exactly the same. Inside your loop, word is bound to a new piece of memory whose contents happen to be the same as the current entry of the words array. By the time word is defined in your first snippet, you have lost any way to manipulate the array location it came from. By iterating over the indexes like in your second snippet, you keep a back door into the array. These two references, http://foobarnbaz.com/2012/07/08/understanding-python-variables/ and https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ might help understand the following tricky business: instead of a list of strings, what happens if we have a list of lists? listOfLists = [[1], [2, 3], [9, 10, 11], [40, 50, 60, 70]] for l in listOfLists: if len(l) &gt;= 3: l[:] = l[::-1] # note that `[:]`!!! print(listOfLists) This actually will reverse any sub-list that has more than 2 elements. Can you understand why? If so, take this gold star: !
type: Answer
answers question: http://stackoverflow.com/q/50301666

http://stackoverflow.com/comment/87723387
has text: Is this the same BMP file as in your other question, because that doesn't look like a valid BMP file as I already said... https://stackoverflow.com/q/50333239/2836621
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50352528
type: QuestionComment

conv-neural-network
tags question: http://stackoverflow.com/q/50306702
tags question: http://stackoverflow.com/q/50376463
tags question: http://stackoverflow.com/q/50249658
tags question: http://stackoverflow.com/q/50232685
tags question: http://stackoverflow.com/q/50289204
tags question: http://stackoverflow.com/q/50240354
tags question: http://stackoverflow.com/q/50369331
tags question: http://stackoverflow.com/q/50364706
tags question: http://stackoverflow.com/q/50314634
tags question: http://stackoverflow.com/q/50330549
tags question: http://stackoverflow.com/q/50255438
tags question: http://stackoverflow.com/q/50291346
tags question: http://stackoverflow.com/q/50308951
type: Tag
tags question: http://stackoverflow.com/q/50282413
tags question: http://stackoverflow.com/q/50250332
tags question: http://stackoverflow.com/q/50351457
tags question: http://stackoverflow.com/q/50323756
tags question: http://stackoverflow.com/q/50383888
tags question: http://stackoverflow.com/q/50240752
tags question: http://stackoverflow.com/q/50281723
tags question: http://stackoverflow.com/q/50283057
tags question: http://stackoverflow.com/q/50291549
tags question: http://stackoverflow.com/q/50239641
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/50307105
tags question: http://stackoverflow.com/q/50248736
tags question: http://stackoverflow.com/q/50382382
tags question: http://stackoverflow.com/q/50363681

http://stackoverflow.com/comment/87754731
has text: Sure, happy to help! I don't know if there is a detailed description anywhere. I couldn't find one. That's why I used (and suggested) simply printing the result to see what's there.
comment on: http://stackoverflow.com/a/50334867
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/50339260
upvote count: 41
downvote count: 2
type: AcceptedAnswer
type: Answer
has body: One solution is to use numpy.vectorize. This may be more efficient than pandas-based solutions. You can use pd.DataFrame.select_dtypes to select object columns. import pandas as pd import numpy as np df = pd.DataFrame({'A': ['abc', 'de', 'abcd'], 'B': ['a', 'abcde', 'abc'], 'C': [1, 2.5, 1.5]}) measurer = np.vectorize(len) Max length for all columns res1 = measurer(df.values.astype(str)).max(axis=0) array([4, 5, 3]) Max length for object columns res2 = measurer(df.select_dtypes(include=[object]).values.astype(str)).max(axis=0) array([4, 5]) Or if you need output as a dictionary: res1 = dict(zip(df, measurer(df.values.astype(str)).max(axis=0))) {'A': 4, 'B': 5, 'C': 3} df_object = df.select_dtypes(include=[object]) res2 = dict(zip(df_object, measurer(df_object.values.astype(str)).max(axis=0))) {'A': 4, 'B': 5}
has comment: http://stackoverflow.com/comment/118830871
answers question: http://stackoverflow.com/q/50339065
accepted answer of: http://stackoverflow.com/q/50339065
score: 39
has comment: http://stackoverflow.com/comment/116973574

http://stackoverflow.com/comment/87538865
score: 0
has text: @Code-Apprentice either is fine. My issue is mine seems a bit complicated **and** it is very slow -- it's using `deepcopy` two times.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50260261

http://stackoverflow.com/comment/87627618
comment on: http://stackoverflow.com/a/50305444
type: Comment
score: 0
has text: UPDATE: each "TX_DROP..." occurs 8 rows later after last data of the previous TX_DROP
type: AnswerComment

http://stackoverflow.com/a/50293235
answers question: http://stackoverflow.com/q/50284390
type: Answer
has body: Rearranging equations needs symbolic math. You need SymPy for that. For example, define the symbols (usually these are single characters, not words): &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import sympy &gt;&gt;&gt; v, p = sympy.symbols('v p') Now you can make an expression for v: &gt;&gt;&gt; vexpr = -100 + p / 10 And you can define an equation to solve: &gt;&gt;&gt; veq = sympy.Eq(v, vexpr) &gt;&gt;&gt; sympy.pprint(veq) p v = ── - 100 10 &gt;&gt;&gt; pexpr, = sympy.solve(veq, p) &gt;&gt;&gt; pexpr 10*v + 1000 And you can turn your expression into a Python function, which will work on your position array: &gt;&gt;&gt; f = sympy.lambdify(p, vexpr) &gt;&gt;&gt; position = np.arange(-10000, 10001) &gt;&gt;&gt; f(position) array([-1100. , -1099.9, -1099.8, ..., 899.8, 899.9, 900. ]) You can change your expression for v and re-solve or re-compute these other things.
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/q/50309146
has body: I want to sum the sizes of files that match a particular extension (and do so for several extensions). Below is partially working code to do so, but I need help applying this to all extensions found in a Directory. import glob import os path = '/tmp' files = glob.glob(path + "/**/*.txt") total_size = 0 for file in files: total_size += os.path.getsize(os.path.join(path, file)) print len(files), total_size So, I want to end up with variables containing the values of how much total .txt or .mp3 file data there is. Something like: Data1[] = { .mp3, 1209879834 bytes); Data2[] = { .txt, 134213443 bytes); DataX[] = { .X, X bytes);
has answer: http://stackoverflow.com/a/50309328
tagged with: python
has answer: http://stackoverflow.com/a/50309305
has comment: http://stackoverflow.com/comment/87634235
score: 0
has title: Find summed size of files with specific extensions within a directory?
has comment: http://stackoverflow.com/comment/87634340
has comment: http://stackoverflow.com/comment/87637408
type: Question
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/50317635
favorite count: 0
accepted answer: http://stackoverflow.com/a/50318059
type: Question
has body: could you please help me to understand what i'm doing wrong. I have two lists below and i need if x will be !=' ' in board => continue to input x until it will be ' '. Thank you in advance. board = [' ', ' ', 'X', ' ', ' ', ' '] testlist_1 = ['x','y', 'z'] x = int(input('&gt;')) while True: if board[x] == ' ': for i in range (len (testlist_1)): board[x] = testlist_1[i] x += 1 if board[x] !=' ': break else: x = int (input ('&gt;')) continue #I need: #input:x = 2 #board = [' ', ' ', 'X', ' ', ' ', ' '] #ask x #input:x =0 #board = ['x', 'y', 'X', ' ', ' ', ' ']
has comment: http://stackoverflow.com/comment/87651683
tagged with: python
score: -1
tagged with: continue
has title: While and continue issue
has comment: http://stackoverflow.com/comment/87650989
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87651052
downvote count: 2
has comment: http://stackoverflow.com/comment/87651263
tagged with: while-loop
upvote count: 1
has comment: http://stackoverflow.com/comment/87651070
answer count: 1
has comment: http://stackoverflow.com/comment/87651652
has answer: http://stackoverflow.com/a/50318059
has comment: http://stackoverflow.com/comment/88081424

http://stackoverflow.com/a/50360670
has comment: http://stackoverflow.com/comment/87738868
downvote count: 0
has comment: http://stackoverflow.com/comment/87738905
has comment: http://stackoverflow.com/comment/87737956
answers question: http://stackoverflow.com/q/50360643
has comment: http://stackoverflow.com/comment/87737937
type: Answer
has comment: http://stackoverflow.com/comment/87737941
has comment: http://stackoverflow.com/comment/87737929
has comment: http://stackoverflow.com/comment/87738667
has comment: http://stackoverflow.com/comment/87738008
has body: You can use re: import re s = 'MULTILINESTRING((10 10,10 40),(40 40,30 30,40 20,30 10))' final_result = list(filter(None, [list(map(int, i.split())) for i in re.findall('[\d\s]+', s)])) Output: [[10, 10], [10, 40], [40, 40], [30, 30], [40, 20], [30, 10]]
has comment: http://stackoverflow.com/comment/87737982
has comment: http://stackoverflow.com/comment/87737992
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87738808

http://stackoverflow.com/q/50282961
type: Question
has comment: http://stackoverflow.com/comment/87610398
has answer: http://stackoverflow.com/a/54580359
has comment: http://stackoverflow.com/comment/87582826
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87610182
downvote count: 0
has title: openpyxl loaded workbooks are empty
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/100417126
has comment: http://stackoverflow.com/comment/87582669
score: 1
tagged with: openpyxl
answer count: 1
upvote count: 1
has body: When I create my own workbook using openpyxl, I am able to save the active sheet, create new sheets, and then print out a list of all sheets in the workbook. When I load a pre-existing workbook, load_workbook appears to execute fine, but when I attempt to print out a list of sheets in the file or access the active sheet, the loaded workbook appears to be empty. The list of sheets in the workbook prints as an empty list, and saving the active sheet produces a None type object. My code: from openpyxl import Workbook from openpyxl import load_workbook existing_book = load_workbook('existing_book.xlsx') print(existing_book.sheetnames) This workbook is not empty. It has several sheets. Yet, this prints an empty list. [] While this: new_workbook = Workbook() dest_name = "New_Workbook.xlsx" main_sheet = new_workbook.active main_sheet.title = "Main" second_sheet = new_workbook.create_sheet("Sheet_2") print(new_workbook.sheetnames) prints the expected list of sheets. Why are my loaded workbooks... empty? Furthermore, if I try to save one of my loaded workbooks, I get the error: IndexError: At least one sheet must be visible :-(
favorite count: 0

http://stackoverflow.com/comment/88475724
type: Comment
type: AnswerComment
score: 0
has text: Wonderful. This is exactly what I need. Cheers @ImportanceOfBeingErnest
comment on: http://stackoverflow.com/a/50349445

http://stackoverflow.com/comment/117142627
has text: @asmaier, noted. It makes it easier by being shorter.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/61472212

http://stackoverflow.com/comment/87947071
type: AnswerComment
has text: First of all I would like to thank you, especially for your second last comment, which is actually the solution I was looking for. Since I am new to Python I was not aware of the globals() method. I agree with you. It is generally not a good idea, but in the special case where you use only a few methods extensively it can be helpful though. I guess it is not possible to mark a comment as "accepted answer"?
score: 0
comment on: http://stackoverflow.com/a/50407236
type: Comment

http://stackoverflow.com/q/50302910
has title: Regex [A-Z] Do Not Recognize Local Characters
score: 0
has body: I've checked other problems and I've read their solutions, they do not work. I've tested the regular expression it works on non-locale characters. Code is simply to find any capital letters in a string and doing some procedure on them. Such as minikŞeker bir kedi would return kŞe however my code do not recognize Ş as a letter within [A-Z]. When I try re.LOCALE as some people request I get error ValueError: cannot use LOCALE flag with a str pattern when I use re.UNICODE import re corp = "minikŞeker bir kedi" pattern = re.compile(r"([\w]{1})()([A-Z]{1})", re.U) corp = re.sub(pattern, r"\1 \3", corp) print(corp) Works for minikSeker bir kedi doesn't work for minikŞeker bir kedi and throws error for re.L. The Error I'm getting is ValueError: cannot use LOCALE flag with a str pattern Searching for it yielded some git discussions but nothing useful.
has comment: http://stackoverflow.com/comment/87622179
has answer: http://stackoverflow.com/a/50303123
has comment: http://stackoverflow.com/comment/87622412
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/150033
has comment: http://stackoverflow.com/comment/87622460
has comment: http://stackoverflow.com/comment/87622315
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87622241
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50303332
tagged with: nlp

http://stackoverflow.com/q/50246070
tagged with: django-extensions
tagged with: ipython
has answer: http://stackoverflow.com/a/50246437
type: Question
has body: When I run python manage.py shell_plus there are many pre and post imports there. How can I hide them(I want to use it but not to see it). I use python 3.4.3 and ipython 6.2.1
tagged with: django
possible better answer: http://stackoverflow.com/a/50246437
tagged with: python
has title: django extensions hide pre and post imports
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51351323
has answer: http://stackoverflow.com/a/51351323

http://stackoverflow.com/comment/87581504
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50282476
has text: could you use a regex to check?

http://stackoverflow.com/a/50306375
answers question: http://stackoverflow.com/q/50306359
upvote count: 3
has comment: http://stackoverflow.com/comment/87629249
downvote count: 0
has comment: http://stackoverflow.com/comment/87629206
has comment: http://stackoverflow.com/comment/87629000
has comment: http://stackoverflow.com/comment/87631281
has body: can you try this? import sys sys.path.append('C:/Users/hchopra/Desktop/Python-Folder') import myModule as m m.fish()
has comment: http://stackoverflow.com/comment/87631420
has comment: http://stackoverflow.com/comment/87629133
has comment: http://stackoverflow.com/comment/87629228
has comment: http://stackoverflow.com/comment/87628964
has comment: http://stackoverflow.com/comment/87629176
score: 3
has comment: http://stackoverflow.com/comment/87628992
type: Answer
has comment: http://stackoverflow.com/comment/87629131
has comment: http://stackoverflow.com/comment/87628980

http://stackoverflow.com/comment/115289924
comment on: http://stackoverflow.com/a/50339224
score: 0
type: AnswerComment
has text: I've changed ´O´ to ´object´ - it should select object columns now.
type: Comment

http://stackoverflow.com/a/50366700
has comment: http://stackoverflow.com/comment/87749599
has comment: http://stackoverflow.com/comment/87750333
has comment: http://stackoverflow.com/comment/87749925
has comment: http://stackoverflow.com/comment/87749912
score: 2
has comment: http://stackoverflow.com/comment/87750146
answers question: http://stackoverflow.com/q/50366607
type: Answer
has comment: http://stackoverflow.com/comment/87751607
has comment: http://stackoverflow.com/comment/87749801
has comment: http://stackoverflow.com/comment/87750253
has comment: http://stackoverflow.com/comment/87749875
upvote count: 2
has body: You can join function like this on the base list_A, itself, no need to split it for probable int values: list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)] ["_".join(map(str, i)) for i in list_A] Output: ['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52'] Update: For you requirement, where you want to ignore last element for last tuple in your list_A, need to add if-else condition inside the list-comprehension as below: ["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A ] Updated Output: ['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']
has comment: http://stackoverflow.com/comment/87750079
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50366607

http://stackoverflow.com/q/50358409
tagged with: python
has body: I am in a Discrete Math course and am trying to replicate De Morgan's law of Complement(B union C) = Complement(B) intersect Complement(C). I tried searching for Python's ability to perform a complement on a set, but I didn't see much if anything. So I just tried this in IDLE. Does this appear correct? U = {'pink', 'purple', 'red', 'blue', 'gray', 'orange', 'green', 'yellow', 'indigo', 'violet'} A = {'purple', 'red', 'orange', 'yellow', 'violet'} B = {'blue', 'gray', 'orange', 'green'} C = {'pink', 'red','blue','violet'} Comp_B = U - B Comp_C = U - C Comp_Union_BC = Comp_B.intersection(Comp_C) print(Comp_Union_BC)
has title: Python set operations - complement union of set
has answer: http://stackoverflow.com/a/55546360
downvote count: 0
has answer: http://stackoverflow.com/a/50358447
has comment: http://stackoverflow.com/comment/87736613
score: 8
favorite count: 0
type: Question
tagged with: discrete-mathematics
has comment: http://stackoverflow.com/comment/87733381
answer count: 2
upvote count: 8
has comment: http://stackoverflow.com/comment/87737323
type: UnansweredQuestion

http://stackoverflow.com/q/50336008
has body: I am doing scientific calculations with both very small and large numbers, so obviously if I'm using python the decimal.Decimal() representation is key. The problem is the tedium. Having to type Decimal() around every relevant operation is cumbersome. Is there a way to set the default numeric representation as Decimal somewhere, anywhere?
tagged with: decimal
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50337609
downvote count: 0
favorite count: 0
type: Question
has title: Set Python's default numerical representation to "Decimal"
has comment: http://stackoverflow.com/comment/87692283
has answer: http://stackoverflow.com/a/50336051
has comment: http://stackoverflow.com/comment/87688275
tagged with: python
score: 4
upvote count: 4

http://stackoverflow.com/q/50350986
has comment: http://stackoverflow.com/comment/87793918
has title: Can I use axes.lines.remove(line) of matplot axes method from other thread?
has comment: http://stackoverflow.com/comment/87717951
tagged with: python-multithreading
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/87742995
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88057096
type: Question
has comment: http://stackoverflow.com/comment/87769345
score: 0
tagged with: matplotlib
has body: I am using matplotlib to plot graph as below. for adding plot lines to figure I am using main GUI thread(with pyplot.plot method) and to worker/other thread to update plot axis data as there is more number of plots. update function is run by thread, I used to remove some unwanted plot lines. does removing plot lines from worker/other thread allowed? As shown in code I am remove line as below : if len(self.plot_lines) > 5: # remove last line untill total line = 5 self.axes_plot.lines.remove(self.plot_lines.pop()) please go through below code import os import sys import random import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt from PyQt4 import QtCore, QtGui class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() vbox = QtGui.QVBoxLayout() vbox.addStretch(1) self.setLayout(vbox) self.setWindowTitle('Update Plot with Qthread.....') self.threadpool = QtCore.QThreadPool() self.threadpool.setMaxThreadCount(2) self.timer = QtCore.QTimer() # to update plot on some time interval self.timer.timeout.connect(self.timerEventOccued) # Add figure object using figurecanvas self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) vbox.addWidget(self.canvas) vbox.addWidget(self.toolbar) self.canvas.draw() # draw plot using main thread self.draw_plot() def timerEventOccued(self): worker = Worker(self.updatePlot) self.threadpool.start(worker) # Execute using Qthread def draw_plot(self): rect = [0.07, 0.065, 1, 1] self.axes_plot = self.figure.add_axes(rect, xlabel='Xaxis (deg)', ylabel='Yaxis (deg)') self.figure.gca().xaxis.labelpad = 0 self.figure.gca().yaxis.labelpad = 0 self.figure.gca().tick_params(axis='both', which='major', labelsize=7) self.figure.gca().tick_params(axis='both', which='minor', labelsize=12) self.axes_plot.margin…

http://stackoverflow.com/comment/87965742
has text: Did run a test on it and it did the job. So thanks for that. Joining them in a single file is now my mission
score: 0
comment on: http://stackoverflow.com/q/50368569
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/116628997
score: 0
type: Comment
type: AnswerComment
has text: I also can't `!cd` directly to the correct directory even if I give the full path: `! cd "C:\Users\rabbott\Google Drive\Colab Notebooks"`
comment on: http://stackoverflow.com/a/65933710

http://stackoverflow.com/q/50287916
answer count: 1
has body: I got a class with arrays of classes as properties class classToJson(): def __init__(self, name, image, objects1, objects2): self.name = name self.image = image self.boolean = True self.objects1 = objects1 self.objects2 = objects2 def __repr__(self): return json.dumps(self.__dict__) object1 and object2 class looks like this: class object1(): value1 = 1 value2 = 0 class objects2: def __init__(self, name, value): self.name = name self.value = value This is how I create my json of the class. obj2 = [...] parsedObject = classToJson(name, image, [object1], obj2) file = open("{}.json".format(name),"w") file.write("[{}]".format(parsedObject.__repr__())) file.close() This works if I only use name, image and boolean in the class but when I include objects1 or objects2 I get the TypeError: Object of type 'type' is not JSON serializable. Why? The json schema I want to accomplish: [ { "name": "name", "image": "image", "boolean": true, "objects1": [ { "value1": 1, "value2": 0 } ], "objetcs2": [ { "name": "name", "value": "value" } ] } ]
accepted answer: http://stackoverflow.com/a/50289063
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50289063
type: Question
has title: How to parse class with arrays of properties to json
tagged with: python

http://stackoverflow.com/q/50375436
tagged with: list
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87767417
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87767228
accepted answer: http://stackoverflow.com/a/50375538
has comment: http://stackoverflow.com/comment/87767269
has answer: http://stackoverflow.com/a/50375538
tagged with: python
tagged with: list-comprehension
has title: Improving Python List Comprehension to Eliminate Nested Arrays
has body: I am trying to create a list comprehension, that improves upon one I already have. I have a list of numbers representing the lengths of a month. months = [35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28] I want to expand this array into an array with a length of the full year, and every value in that array representing which week that day (index) falls into. Currently I am doing this with two list comprehensions. weeks = [w for w in range(sum(months)) if w % 7 == 0] weeks_expanded = [day for week in [[d + 1] * 7 for d in range(len(weeks))] for day in week] I wanted to know how I could add something to the new list 7 times without making it an array of length 7. I'm trying to get rid of the added step of flattening my inner list comprehension in weeks_expanded. [[d + 1] * 7 for d in range(len(weeks))] Thanks for the help.
type: AnsweredQuestion

http://stackoverflow.com/comment/87760368
comment on: http://stackoverflow.com/q/50372220
has text: I believe you need to call `set_random_seed` inside the graph init code on a per-graph basis based on [this question](https://stackoverflow.com/questions/36096386/tensorflow-set-random-seed-not-working)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50303560
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50303579
type: AnsweredQuestion
has body: I need to obtain three complex numbers from a set of three equations which is part of an error correction procedure for a set of S-parameters. import numpy as np G_A1 = -1 + 0j G_A2 = 0 + 0j G_A3 = 1 + 0j G_M1 = -0.5323 - 0.0163j G_M2 = -11.1951 - 37.7373j G_M3 = 0.5528 + 0.1621j a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]]) b = np.array([G_M1,G_M2,G_M3]) x = np.linalg.solve(a, b) print(x) This gives me the error a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]]) TypeError: a float is required I thought I might as well try to convert the complex values to float but then I get this error. G_M1 = float(-0.5323 - 0.0163j) TypeError: can't convert complex to float If complex values cannot be converted to float, what alternative method should I be using here?
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/50303579
tagged with: numpy
score: 0
upvote count: 1
has title: How to calculate complex simultaneous equations in python?
answer count: 1

ms-word
tag name: ms-word
tags question: http://stackoverflow.com/q/50376081
type: Tag

http://stackoverflow.com/a/50352388
has comment: http://stackoverflow.com/comment/87721019
has body: I think need set_index with unstack: df['COUNT'] = df.groupby(['ID','col']).cumcount()+1 df = df.set_index(['ID','col', 'COUNT'])['col2'].unstack().add_prefix('col').reset_index() print (df) COUNT ID col col1 col2 0 1 A 50.0 52.0 1 1 B 45.0 NaN 2 1 C 18.0 NaN Or: c = df.groupby(['ID','col']).cumcount()+1 df = df.set_index(['ID','col', c])['col2'].unstack().add_prefix('col').reset_index() print (df) ID col col1 col2 0 1 A 50.0 52.0 1 1 B 45.0 NaN 2 1 C 18.0 NaN EDIT: For multiple columns is solution a bit changed, because working with MultiIndex in columns: df['COUNT'] = (df.groupby(['ID','col']).cumcount()+1).astype(str) #remove col2 df = df.set_index(['ID','col', 'COUNT']).unstack() #flatten Multiindex df.columns = df.columns.map('_'.join) df = df.reset_index() print (df) ID col col2_1 col2_2 col3_1 col3_2 col4_1 col4_2 0 1 A 50.0 52.0 S M 1.0 4.0 1 1 B 45.0 NaN N None 8.0 NaN 2 1 C 18.0 NaN S None 7.0 NaN
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/50352271
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50352271
has comment: http://stackoverflow.com/comment/87722633
has comment: http://stackoverflow.com/comment/87722528

http://stackoverflow.com/q/50276202
tagged with: python
type: UnansweredQuestion
has body: I know this will seem like a silly question, but I have read all the related/similar questions I could find, and I am pretty sure I am experiencing a different issue. See the end of this question for a list of similar problems which I have avoided. I am trying to use a Tkinter Checkbutton. I have used the example code from the documentation (here) almost verbatim. from tkinter import Tk, Checkbutton, IntVar class MyGUI: def __init__(self, window): self.var = IntVar() self.c = Checkbutton(window, text="Enable Tab", variable=self.var, command=self.cb) self.c.pack() def cb(self): print("self.var is", self.var.get()) root = Tk() gui = MyGUI(root) root.mainloop() root.destroy() The only thing I changed was to remove the event argument from the cb method, because as far as I could tell it wasn't being used for anything, and the checkbutton doesn't pass any event to cb. My problem is that the variable storing the checkbutton's value always reads 0, even when the checkbutton is checked: I don't know what I am doing wrong. I know I have avoided the following pitfalls: Using the wrong variable -- I have used Tk's IntVar, not a python int Using daft colours Using the same attribute name for the button and its variable -- I have saved the button and the variable as separate attributes to my class. Chaining the Checkbox creation with the place method and accidentally storing None Also, when I run code from a question with a similar issue, I get the same behaviour -- checkbox always returns False/0 -- even though that question is marked as resolved. I am using Anaconda python with the following versions: Python 3.5.4 |Anaconda custom (64-bit)| (default, Nov 8 2017, 14:34:30) [MSC v.1900 64 bit (AMD64)] IPython 6.2.1 -- An enhanced Interactive Python.
has comment: http://stackoverflow.com/comment/87569236
upvote count: 6
linked to: http://stackoverflow.com/q/44791347
has title: Tkinter Checkbutton not working
has comment: http://stackoverflow.com/comment/87569580
tagged with: tkinter
answer count: 4
has answer: http://stackoverflow.com/a/66050283
has answer: http://stackoverflow.com/a/67288949
linked to: http://stackoverflow.com/q/35770471
tagged with: user-interface
tagged with: button
has comment: http://stackoverflow.com/comment/87569039
has comment: http://stackoverflow.com/comment/87569130
has answer: http://stackoverflow.com/a/50276987
linked to: http://stackoverflow.com/q/47617902
has comment: http://stackoverflow.com/comment/87576540
has comment: http://stackoverflow.com/comment/87569077
has comment: http://stackoverflow.com/comment/87569332
has comment: http://stackoverflow.com/comment/87570085
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87569177
has comment: http://stackoverflow.com/comment/87569308
has comment: http://stackoverflow.com/comment/87576747
has comment: http://stackoverflow.com/comment/87569257
has answer: http://stackoverflow.com/a/50276953
has comment: http://stackoverflow.com/comment/87569292
has comment: http://stackoverflow.com/comment/87569436
type: Question
linked to: http://stackoverflow.com/q/47178646
score: 5
linked to: http://stackoverflow.com/q/34177007

http://stackoverflow.com/comment/87545101
type: Comment
has text: I thought I did explain it. That's the optional `start` argument, which tells `find` where to start looking for `AGAG`. So it starts looking after the `GUGU`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50263277

http://stackoverflow.com/comment/87742699
score: 0
comment on: http://stackoverflow.com/q/50363078
type: QuestionComment
has text: @CharlesDuffy, sounds fair. :) I am still new here and also learning from other's experience. So, if you want to flag this, what point would you flag it under? I do not see any relevant option to flag it for closing.
type: Comment

http://stackoverflow.com/comment/87609861
has text: @d2718nis meant that you have equipment with `s`, it should be without `s`, {{ equipment.get_absolute_url } in this templates `equipment_list.html`
score: 1
comment on: http://stackoverflow.com/a/50281747
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50297996
type: Answer
has comment: http://stackoverflow.com/comment/87613235
has comment: http://stackoverflow.com/comment/87612996
has comment: http://stackoverflow.com/comment/87613370
accepted answer of: http://stackoverflow.com/q/50297923
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87613138
downvote count: 0
has comment: http://stackoverflow.com/comment/87613473
has comment: http://stackoverflow.com/comment/87613027
has body: You'll need two loops. One per key, and another one for each list value per key. Append to a new dictionary per iteration. data = {'RDBMS' : [...]} new_data = {} for k in data: for l in data[k]: new_data.setdefault(l["driverKey"].split()[0], []).append(l) Alternatively, use a defaultdict: from collections import defaultdict new_data = defaultdict(list) for k in data: for l in data[k]: new_data[l["driverKey"].split()[0]].append(l) The defaultdict is slightly more efficient for a lot of data (the dict.setdefault unnecessarily creates and returns lists regardless of whether or not it has to at each turn). Based on your comments, the outer loop isn't necessary, but it's always good to write code that won't easily break when your input changes. print(new_data) { 'PostgreSQL': [{ 'userName': 'a', 'entityName': 'entity1', 'connectionString': 'DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;', 'databaseName': 'database1', 'driverKey': 'PostgreSQL Unicode' }, { 'userName': 'b', 'entityName': 'entity2', 'connectionString': 'DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;', 'databaseName': 'database1', 'driverKey': 'PostgreSQL Unicode' }], 'SQL': [{ 'userName': 'a', 'entityName': 'entity3', 'connectionString': 'DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;', 'databaseName': 'database1', 'driverKey': 'SQL Server' }] }
answers question: http://stackoverflow.com/q/50297923
upvote count: 3
score: 3

http://stackoverflow.com/a/53698659
answers question: http://stackoverflow.com/q/50335503
type: Answer
has comment: http://stackoverflow.com/comment/123518908
upvote count: 31
has comment: http://stackoverflow.com/comment/135674028
downvote count: 0
has comment: http://stackoverflow.com/comment/123524374
has comment: http://stackoverflow.com/comment/115189087
has body: If you compiling python yourself, you need to install libbz2 headers and .so files first, so that python will be compiled with bz2 support. On ubuntu, apt-get install libbz2-dev then compile python.
score: 31
has comment: http://stackoverflow.com/comment/134943210

http://stackoverflow.com/comment/87537804
type: Comment
type: QuestionComment
has text: So, I don't know what your problem is unless you can reproduce it for me.
comment on: http://stackoverflow.com/q/50259780
score: 1

http://stackoverflow.com/comment/87777281
type: QuestionComment
has text: what i mean with a 4-scale list is like a matrix 4scaleListe=[[["word1","word2",None...],[None,"word1","word2",...]...],...]
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50380479

http://stackoverflow.com/comment/87553163
score: 0
has text: use `pip freeze` to check which packages are installed
type: QuestionComment
comment on: http://stackoverflow.com/q/50267732
type: Comment

http://stackoverflow.com/q/50339117
downvote count: 0
answer count: 1
has body: Other than declaring the variable as a new object, is there a way I could apply extra information to a python variable that I could later refer back to? someVar = ... # any variable type someVar.timeCreated = "dd/mm/yy" # or someVar.highestValue = someValue # then later if someVar.timeCreated == x: ... # or if someVar == someVar.highestValue: ... I see that this is essentially just an object, but is there a neat way I could do this without declaring an object separate to the python variable object itself?
favorite count: 0
type: Question
tagged with: python-3.x
has title: How might I give a variable custom metadata?
tagged with: metadata
has comment: http://stackoverflow.com/comment/87694585
accepted answer: http://stackoverflow.com/a/50339460
has comment: http://stackoverflow.com/comment/87694535
has comment: http://stackoverflow.com/comment/87694825
has comment: http://stackoverflow.com/comment/87694731
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50339460

http://stackoverflow.com/comment/87729102
type: Comment
has text: @MrUpsidown - When working with Chinese, be sure to use `utf8mb4`, not just `utf8`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50280199
score: 1

string
tags question: http://stackoverflow.com/q/50375941
tags question: http://stackoverflow.com/q/50301044
tags question: http://stackoverflow.com/q/50240332
tags question: http://stackoverflow.com/q/50263902
tags question: http://stackoverflow.com/q/50337594
tags question: http://stackoverflow.com/q/50230233
tags question: http://stackoverflow.com/q/50290009
type: Tag
tags question: http://stackoverflow.com/q/50305682
tags question: http://stackoverflow.com/q/50293172
tags question: http://stackoverflow.com/q/50357767
tags question: http://stackoverflow.com/q/50326886
tags question: http://stackoverflow.com/q/50248042
tags question: http://stackoverflow.com/q/50307325
tags question: http://stackoverflow.com/q/50258067
tags question: http://stackoverflow.com/q/50277108
tags question: http://stackoverflow.com/q/50252207
tags question: http://stackoverflow.com/q/50289743
tags question: http://stackoverflow.com/q/50349995
tags question: http://stackoverflow.com/q/50259791
tags question: http://stackoverflow.com/q/50298705
tags question: http://stackoverflow.com/q/50258257
tags question: http://stackoverflow.com/q/50284098
tags question: http://stackoverflow.com/q/50348303
tags question: http://stackoverflow.com/q/50344118
tags question: http://stackoverflow.com/q/50306386
tags question: http://stackoverflow.com/q/50241548
tags question: http://stackoverflow.com/q/50363046
tags question: http://stackoverflow.com/q/50304647
tags question: http://stackoverflow.com/q/50376532
tags question: http://stackoverflow.com/q/50276843
tags question: http://stackoverflow.com/q/50319824
tags question: http://stackoverflow.com/q/50233259
tags question: http://stackoverflow.com/q/50282532
tags question: http://stackoverflow.com/q/50272334
tags question: http://stackoverflow.com/q/50310699
tags question: http://stackoverflow.com/q/50241048
tags question: http://stackoverflow.com/q/50335159
tags question: http://stackoverflow.com/q/50293977
tags question: http://stackoverflow.com/q/50327590
tags question: http://stackoverflow.com/q/50239582
tags question: http://stackoverflow.com/q/50302207
tags question: http://stackoverflow.com/q/50260409
tags question: http://stackoverflow.com/q/50356802
tags question: http://stackoverflow.com/q/50266513
tags question: http://stackoverflow.com/q/50274685
tags question: http://stackoverflow.com/q/50252761
tags question: http://stackoverflow.com/q/50259043
tags question: http://stackoverflow.com/q/50271208
tags question: http://stackoverflow.com/q/50308634
tags question: http://stackoverflow.com/q/50324894
tags question: http://stackoverflow.com/q/50340761
tags question: http://stackoverflow.com/q/50264150
tags question: http://stackoverflow.com/q/50383022
tags question: http://stackoverflow.com/q/50372558
tags question: http://stackoverflow.com/q/50255556
tags question: http://stackoverflow.com/q/50273860
tags question: http://stackoverflow.com/q/50312305
tags question: http://stackoverflow.com/q/50342462
tags question: http://stackoverflow.com/q/50256698
tags question: http://stackoverflow.com/q/50308612
tag name: string
tags question: http://stackoverflow.com/q/50343561
tags question: http://stackoverflow.com/q/50251515
tags question: http://stackoverflow.com/q/50277510
tags question: http://stackoverflow.com/q/50358785
tags question: http://stackoverflow.com/q/50253985
tags question: http://stackoverflow.com/q/50319311
tags question: http://stackoverflow.com/q/50352104
tags question: http://stackoverflow.com/q/50323809
tags question: http://stackoverflow.com/q/50253753
tags question: http://stackoverflow.com/q/50365138
tags question: http://stackoverflow.com/q/50337843
tags question: http://stackoverflow.com/q/50304607
tags question: http://stackoverflow.com/q/50376649
tags question: http://stackoverflow.com/q/50284554
tags question: http://stackoverflow.com/q/50278300
tags question: http://stackoverflow.com/q/50310358
tags question: http://stackoverflow.com/q/50360643

http://stackoverflow.com/comment/87746602
score: 0
has text: in your responses is absent `_links` and some other fields that means your changed standart configuration. Compare with `curl http://eve-demo.herokuapp.com/people | json_pp`
comment on: http://stackoverflow.com/q/50360058
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50353362
has answer: http://stackoverflow.com/a/50353790
downvote count: 0
has body: I would like to be able to retrieve the vertex_index of a currently selected vertex (the vertex currently having the mouse over it). I have not found this question asked in StackOverflow, nor this information mentioned in the official graph-tool documentation. For example, I would like to retrieve the value "56" from this graph :
has title: How can I retrieve a selected vertex in graph-tool?
accepted answer: http://stackoverflow.com/a/50369840
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50353790
tagged with: graph-tool
tagged with: python
type: Question
score: 2
has answer: http://stackoverflow.com/a/50369840
answer count: 2
upvote count: 2

http://stackoverflow.com/a/50277027
type: Answer
has body: For most applications, your groupby object returned by df.groupby('CLASS') is your collection of separate datasets, and there are lots of ways to do complex manipulations on a groupby object within pandas (see the two links at the bottom of this post). However, if you want to do it explicitely and have access to each dataset individually, one way to do it would be splitting your groupby into a dictionary of datasets by iterating through your groupby: datasets = {} by_class = df.groupby('CLASS') for groups, data in by_class: datasets[groups] = data You can then access each individual dataset like you would access any value in a dictionary: &gt;&gt;&gt; datasets['A'] CLASS value1 0 A 1 1 A 2 2 A 3 3 A 5 &gt;&gt;&gt; datasets['B'] CLASS value1 4 B 4 5 B 1 6 B 2 &gt;&gt;&gt; datasets['C'] CLASS value1 7 C 1 8 C 5 Or, you can use the GroupBy.get_group() method: by_class = df.groupby('CLASS') &gt;&gt;&gt; by_class.get_group('A') CLASS value1 0 A 1 1 A 2 2 A 3 3 A 5 In any case, it's definitely worth reading this and this in order to understand what groupby is and how you can apply it to your task
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50276911

http://stackoverflow.com/comment/87546217
comment on: http://stackoverflow.com/q/50263808
has text: It is using an undocumented property of QuerySet class. See [this question](https://stackoverflow.com/questions/21487291/check-if-django-queryset-is-read-or-write).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87774545
type: Comment
type: QuestionComment
has text: `from pathlib import Path` then `for p in Path(r'C:\Main\Division\Reports').glob('*/Data.xls'): do_stuff(p)`
score: 0
comment on: http://stackoverflow.com/q/50379088

http://stackoverflow.com/comment/87691074
score: 0
type: Comment
has text: Thank you. It now throws: __NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@aria-label="Email" and @placeholder="Email *"]"}__
comment on: http://stackoverflow.com/a/50337280
type: AnswerComment

http://stackoverflow.com/q/50373229
accepted answer: http://stackoverflow.com/a/50373321
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50373305
possible better answer: http://stackoverflow.com/a/50373305
has comment: http://stackoverflow.com/comment/87764093
has title: Django: Form object has no attribute 'user' despite passing user as kwarg?
has answer: http://stackoverflow.com/a/50373321
type: Question
has body: I'm getting this error when I instantiate the TransactionForm in my view. The traceback is below. I would expect this to work because I'm passing "user" as a keyword argument when I call the Form instance, so I'm not sure what the problem is here? File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\py\portfolio-project\myportfolio\views.py" in add_transaction 122. form = TransactionForm(user = request.user) File "C:\py\portfolio-project\myportfolio\forms.py" in __init__ 36. qs_coin = Coin.objects.get(user = self.user) Exception Type: AttributeError at /myportfolio/add_transaction/ Exception Value: 'TransactionForm' object has no attribute 'user' Views.py def add_transaction(request): print(request.method) print("test1") if request.method == "GET": if request.is_ajax(): print("ajax test") data = { 'test': "test1" } form = TransactionForm(request.GET, user = request.user, coin_price = GetCoin(str(coin.coin)).price) return JsonResponse(data) form = TransactionForm(user = request.user) if request.method == "POST": print("test2") form = TransactionForm(request.POST, user = request.user) if form.is_valid(): print("test3") obj = form.save(commit = False) obj.user = request.user obj.save() return HttpResponseRedirect('/myportfolio/') else: print(form.errors) return render(request, 'myportfolio/add_transaction.html', {'form': form}) Forms.py class TransactionForm(forms.ModelForm): CHOICES = ((1, 'Buy'), (2, 'Sell'),) coin = forms.ModelChoiceField(queryset = Coin.objects.all()) buysell = forms.ChoiceField(choices = CHOICES) field_order = ['buysell', 'coin', 'a…
tagged with: django
tagged with: python

http://stackoverflow.com/comment/87549312
type: QuestionComment
score: 0
has text: @tdelaney I'm on linux, checking pexpect. thanks!
comment on: http://stackoverflow.com/q/50265439
type: Comment

http://stackoverflow.com/comment/87731519
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50357318
score: 0
has text: If your code is identical to what you have posted above you need to indent the class members of DirTrav

http://stackoverflow.com/comment/87698584
type: Comment
score: 0
has text: Euclidian distance calculation is what I wanted. Thank you. The result is indeed arbitrary.
type: AnswerComment
comment on: http://stackoverflow.com/a/50323391

http://stackoverflow.com/comment/87725192
comment on: http://stackoverflow.com/q/50354360
score: 0
type: Comment
type: QuestionComment
has text: well you are not creating json in the first place @Shankar, you have to use `json.dumps(colDataDict)` to get the json object that you need

http://stackoverflow.com/comment/87684945
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50333866
has text: Yes @Wen `[x.isoformat() if isinstance(x, pd.Timestamp) else x for x in s]` seems to be a good workaround. With `s.map...` it returns the wrong result for which I have no explanation.

http://stackoverflow.com/comment/87549956
comment on: http://stackoverflow.com/a/50265954
has text: Before using `pd.to_datetime` command, there was 38310 rows. After your suggestion, it appears to be converting. But after filtering May, I get 35389 rows.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50322454
downvote count: 0
has comment: http://stackoverflow.com/comment/87669031
linked to: http://stackoverflow.com/q/12179271
upvote count: 1
has answer: http://stackoverflow.com/a/50322491
favorite count: 0
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/87660709
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50327658
has comment: http://stackoverflow.com/comment/87671409
tagged with: python
has body: I am trying to create multiple instances of a Soda object using information from a file. The file is formatted like this Name,price,number Mtn. Dew,1.00,10 Coke,1.50,8 Sprite,2.00,3 My code I have is this (this is a function within main()): from Sodas import Soda def fillMachine(filename) : # Create an empty list that will store pop machine data popMachine = [] # Open the file specified by filename for reading infile = open(filename, "r") # Loop to read each line from the file and append a new Soda object # based upon information from the line into the pop machine list. for line in infile : popMachine.append(Soda(str(line.strip()))) # Close the file infile.close() # Return the pop machine list return popMachine If I got this right, popMachine should be a list of 3 different Soda objects, each with one line of the input file. Within my class, I then need to be able to get just the name or price or quantity for use in calculations later. My class Sodas code looks like this: #Constructor def __init__(self, _name = "", _price = 0.0, _quantity = 0) : self._name = self.getName() self._price = _price self._quantity = _quantity def getName(self) : tempList = self.split(",") self._name = tempList[0] return self._name This is where I run into problems. IIRC self stands in place of line in the main code, so self should be a string such as "Mtn. Dew,1.00,10" and the expected outcome of the split(",") method should form a list like ["Mtn. Dew", "1.00", "10"] where I can then use the index of that list to return just the name. However, I get this error "AttributeError: Soda instance has no attribute 'split'" And I'm not sure why. Also, all the comments in this code came from my instructor as part of the assignment, so even if there are quicker/better methods for doing this whole thing, this is the way I have to do it :/
has answer: http://stackoverflow.com/a/50322639
tagged with: factory
tagged with: class
tagged with: static-methods
has answer: http://stackoverflow.com/a/50322655
has comment: http://stackoverflow.com/comment/87671128
has title: How to to split() a string and pass it into an object's __init__() method?
score: 1
has answer: http://stackoverflow.com/a/50322497

http://stackoverflow.com/comment/87534767
has text: Might be a a `zorder` issue. What happens if you place a text object with high zorder explicitly, e.g. by adding the following before `plt.show()`: `t = ax.text(55, 10, 'Node 1'); t.set_zorder(1000)`?
type: QuestionComment
comment on: http://stackoverflow.com/q/50239182
score: 0
type: Comment

http://stackoverflow.com/comment/87491454
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50233978
type: Comment
has text: @NienkeLuirink, That is strange. You should provide an input exactly in the format I have in my answer. Then we should be able to see the problem.

http://stackoverflow.com/q/50356091
upvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
has body: If I have a binary classification problem that I want to build a model from using sklearn or matlab. Should the label files contain 0 and 1 or it can instead contain the name for classes for example "R" (for rainy) and "S"(for sunny)? should I convert it to 0 and 1?
type: Question
has comment: http://stackoverflow.com/comment/87732654
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/87738575
has comment: http://stackoverflow.com/comment/87741516
tagged with: python
has title: binary classification label names
has comment: http://stackoverflow.com/comment/87728958
tagged with: matlab
has comment: http://stackoverflow.com/comment/87738887
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50358976
accepted answer: http://stackoverflow.com/a/50358976
tagged with: classification

http://stackoverflow.com/comment/87731326
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50357222
has text: What is that `dir` in your `DirTrav(dir)`? Also, can you include the whole traceback in your question, rather than just a description of the error, so we can tell exactly where the error occurred?

http://stackoverflow.com/comment/87628775
type: QuestionComment
has text: Yes in python 2.7 just use `with open(filepath, "w")`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50306051

apache2
tags question: http://stackoverflow.com/q/50232079
type: Tag
tags question: http://stackoverflow.com/q/50379323
tag name: apache2

http://stackoverflow.com/q/50232744
score: 0
has answer: http://stackoverflow.com/a/50235435
answer count: 1
tagged with: opencv
type: Question
has title: how to copy a part of image to another with OpenCV?
tagged with: python
type: UnansweredQuestion
tagged with: numpy
has body: I have a model that predicts the human face segmentation. But unfortunately the model is not trained to predict the hair with the face. So now I have the above images as numpy arrays. Is it possible to add the hair from the original photo (The one on the left) to the prediction mask (in the middle) or directly to the result prediction (the one on the right) ? Basically I just need to deal with the original image to get a little bit from the head above the prediction mask and add it to the prediction so that way at least I'll have a part of the hair in the result. The code used to create the previous figure: fn = "images/beard.jpg" im = cv2.cvtColor(cv2.imread(fn), cv2.COLOR_BGR2RGB) im = auto_downscaling(im) # vgg_preprocess: output BGR channel w/ mean substracted. inp_im = vgg_preprocess(im) # Predicting the face segmentation out = model.predict([inp_im]) out_resized = cv2.resize(np.squeeze(out), (im.shape[1],im.shape[0])) out_resized_clipped = np.clip(out_resized.argmax(axis=2), 0, 1).astype(np.float64) mask = cv2.GaussianBlur(out_resized_clipped, (7,7), 6) plt.figure(figsize=(12,6)) plt.subplot("131") plt.axis('off') plt.imshow(im) plt.subplot("132") plt.axis('off') plt.imshow(out_resized_clipped, cmap='gray') plt.subplot("133") plt.axis('off') plt.imshow((mask[:,:,np.newaxis]*im.astype(np.float64)).astype(np.uint8)) plt.show()

http://stackoverflow.com/comment/87613075
comment on: http://stackoverflow.com/q/50296390
has text: This code is just small portion of a script where df1 & df2 are dataframes defined earlier. You can use any dataframes in place of df1 and df2
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50352542
tagged with: python
has comment: http://stackoverflow.com/comment/87724901
has title: Apply function to 3D tensor while ignoring zero rows and padding
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50354824
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50354824
has comment: http://stackoverflow.com/comment/87724774
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am currently trying to improve the running time of the most expensive operation of my tensorflow pipeline. I am trying to accomplish the following: I am given a 3D tensor containing multiple samples of some patient data, for example the data could look like this n_hidden = 3 #number of elements per 1D tensor batch_size = 3 #number of patients n_mc_samples = 2 #number of samples per patient rnn_grid_times = [2,3,1] #number of non zero 1D tensors per patient all_outputs = tf.constant([[[0.15, 0.874, 0.2], [0.1,0.00878,0.58],[0.0,0.0,0.0]], #beginning of patient 1 [[0.456,0.454,0.003],[0.4564,0.4984,0.21], [0.0,0.0,0.0]], [[0.121,0.22,0.45],[0.15,0.488,0.222], [0.11,0.849,0.45]], #beginning of patient 2 [[0.15, 0.5646, 0.15], [0.45,0.48949,0.56465], [0.4489,0.456,0.9]], [[0.121, 0.22, 0.01], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], #beginning of patient 3 [[0.15, 0.89, 0.42], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]]) This data corresponds to 3 patients, and each patient is sampled twice. As you can see the data of patient 1 and 3 is padded to have the same size as that of patient 2. My goal is to feed each non zero 1D tensor to a single output neural network with one hidden layer, and then add extra pedding at the location of the zero tensors in order to keep an uniform dimension across patients. So here a valid result could be [[-0.11379365, -0.11188659, 0. ], [-0.11379365, -0.11379365, 0. ], [-0.1135166 , -0.11379365, -0.11379365], [-0.11379365, -0.11359671, -0.11270589], [-0.11379365, 0. , 0. ], [-0.11379365, 0. , 0. ]] Just to reiterate because I realize that this is a bit convoluted, the outpout associated to [0.15, 0.874, 0.2]in the first block of code is -0.11379365 in the second block of code. Here is the isolated code, with the toy data presented above. This should be runnable without problem if you have a working tensorflow environnment import tensorflow as tf RANDOM_SEED = 42 tf.set_random_seed(RANDOM_SEED) def code(): n_hidden = 3 batch_size = 3 n_mc_samples = 2 num_…

http://stackoverflow.com/a/50320544
answers question: http://stackoverflow.com/q/50320531
type: Answer
has body: you print my_file variable, which is of type _io.TextIOWrapper. What you actually need is print(my_file.read())
upvote count: 3
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50320531
type: AcceptedAnswer

pyqt5
tags question: http://stackoverflow.com/q/50263545
tags question: http://stackoverflow.com/q/50283851
tags question: http://stackoverflow.com/q/50282786
tags question: http://stackoverflow.com/q/50256606
type: Tag
tags question: http://stackoverflow.com/q/50309334
tags question: http://stackoverflow.com/q/50232639
tags question: http://stackoverflow.com/q/50381025
tags question: http://stackoverflow.com/q/50309257
tags question: http://stackoverflow.com/q/50252980
tags question: http://stackoverflow.com/q/50237093
tags question: http://stackoverflow.com/q/50370722
tags question: http://stackoverflow.com/q/50355919
tags question: http://stackoverflow.com/q/50248769
tags question: http://stackoverflow.com/q/50372753
tags question: http://stackoverflow.com/q/50313410
tags question: http://stackoverflow.com/q/50380475
tags question: http://stackoverflow.com/q/50379530
tags question: http://stackoverflow.com/q/50263858
tags question: http://stackoverflow.com/q/50344551
tags question: http://stackoverflow.com/q/50311879
tags question: http://stackoverflow.com/q/50357948
tags question: http://stackoverflow.com/q/50312307
tags question: http://stackoverflow.com/q/50278123
tag name: pyqt5
tags question: http://stackoverflow.com/q/50282156
tags question: http://stackoverflow.com/q/50288068
tags question: http://stackoverflow.com/q/50272397
tags question: http://stackoverflow.com/q/50372055
tags question: http://stackoverflow.com/q/50353239
tags question: http://stackoverflow.com/q/50384846
tags question: http://stackoverflow.com/q/50252587
tags question: http://stackoverflow.com/q/50270311
tags question: http://stackoverflow.com/q/50233156
tags question: http://stackoverflow.com/q/50367837

http://stackoverflow.com/q/50316993
downvote count: 0
tagged with: python
tagged with: php
has title: Output returns from long running python script called by php not displayed on web-page
tagged with: ajax
answer count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I am simply calling python script from my php program and I need to display the output return from python script to webpage. I am new to this, so I tried many ways to get the output return, 1. $command = escapeshellcmd('python script.py "ab" "cd" '); $output = shell_exec($command); 2. $output = shell_exec('python script.py "ab" "cd" '); print $output; 3. $command = system('python script.py "ab" "cd" ',$output); echo "output is ".$output; echo "command is".$command; 4. $command = passthru ('python script.py "ab" "cd" '); $output = shell_exec($command); echo $output; 5. exec('python script.py "ab" "cd" ', $output, $return_var); echo $output; echo $return_var; If time taken taken by python script is less, then I able to get the output return to my php program and able to display on my web page. print "Hello" print "world" But when my python program is calling any background process, which taking more time and giving output after few seconds, then that parts are not returning to the php program. print "Hello" returned_value=subprocess.check_output('ssh -p 29418 xyz.com --format=JSON', shell=True) print returned_value I tried to include sleep in php program but it is not helping as output is already returned. Some posts suggested to use Ajax Whether that is the only and correct way to solve this question? Thanks in advance for your help or suggestion.
type: UnansweredQuestion

naivebayes
tags question: http://stackoverflow.com/q/50381760
type: Tag
tag name: naivebayes

http://stackoverflow.com/q/50330935
type: Question
tagged with: postgresql
type: AnsweredQuestion
tagged with: python
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/50344204
score: 2
has title: Query with JSON array in WHERE in Postgresql
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50344204
tagged with: jsonb
has body: I have a user model with a payment_info JSONB column that contains the following json example: { "customer_id": "cst_K5gCsCkKAU", "subscriptions": [ { "status": "active", "external_id": "sub_3Q9Q4bP2zW" } ] } I am a newbie with JSON queries, but created the following against the Postgres (PG) db that seem to work, that is: I search for all users that has a certain external_id value: SELECT payment_info-&gt;'subscriptions' as Subscriptions FROM public."user" , jsonb_array_elements(payment_info-&gt;'subscriptions') as subs where (subs-&gt;&gt;'external_id')::text = 'sub_3Q9Q4bP2zW' How do I do the same in SQLAlchemy? I tried several thinks that I found on the web (SO) but it does't work. I tried: JSONB Comparator query = misc.setup_query(db_session, User).filter( User.payment_info.comparator.contains( ('subscriptions', 'external_id') == payment_subscription_id)) That results in following error: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: jsonb @&gt; boolean LINE 3: WHERE "user".payment_info @&gt; false ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. json_contains function: from sqlalchemy import func query = misc.setup_query(db_session, User).filter( func.json_contains(User.payment_info, payment_subscription_id, ['subscriptions', 'external_id'])) That results in: LINE 3: WHERE json_contains("user".payment_info, 'sub_QxyMEmU', ARRA... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Path to the key: query = misc.setup_query(db_session, User).filter( User.payment_info['subscriptions', 'external_id'].astext == payment_subscription_id) That results in empty result, with the following query: SELECT * FROM "user" WHERE ("user".payment_info #&gt;&gt; %(payment_info_1)s) = %(param_1)s What am I doing wrong, and how can I make it work? BTW: Do I need to put an index on the external_id? (not present yet)
favorite count: 0

http://stackoverflow.com/comment/87661475
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50322936
has text: Yeah... I thought about this, but the scope for errors is just too large (quoting issues, etc etc).

http://stackoverflow.com/a/50348569
has comment: http://stackoverflow.com/comment/87714599
answers question: http://stackoverflow.com/q/50348504
upvote count: 2
downvote count: 0
type: Answer
has body: You should create your array with list; a = np.array([{'a':1}])
score: 2

http://stackoverflow.com/comment/87762930
score: 0
has text: Possible duplicate of [Convert string to Python class object?](https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50373189

http://stackoverflow.com/a/50333653
score: 0
has body: This should work: max = [0] * N for i in range(N): for j in range(N): if n[i, j] &gt; max[i]: max[i] = n[i, j]
has comment: http://stackoverflow.com/comment/87686632
answers question: http://stackoverflow.com/q/50333247
type: Answer

http://stackoverflow.com/a/50272285
type: Answer
accepted answer of: http://stackoverflow.com/q/50272134
has comment: http://stackoverflow.com/comment/87564957
answers question: http://stackoverflow.com/q/50272134
has body: Demo: import pandas as pd from scipy.spatial.distance import pdist, squareform In [101]: np.random.seed(123) In [102]: coords = np.random.rand(20, 2) In [103]: r = 0.3 In [104]: d = pd.DataFrame(squareform(pdist(coords))) In [105]: d Out[105]: 0 1 2 3 4 5 6 7 8 9 10 11 12 \ 0 0.000000 0.539313 0.138885 0.489671 0.240183 0.566555 0.343214 0.541508 0.525761 0.295906 0.566702 0.326087 0.045059 1 0.539313 0.000000 0.509028 0.765644 0.299834 0.212418 0.535287 0.253292 0.378472 0.305322 0.504946 0.501173 0.545672 2 0.138885 0.509028 0.000000 0.369830 0.240542 0.484970 0.459329 0.449965 0.591335 0.217102 0.434730 0.187983 0.100192 3 0.489671 0.765644 0.369830 0.000000 0.579235 0.639118 0.827519 0.585140 0.946945 0.474554 0.383486 0.266724 0.444612 4 0.240183 0.299834 0.240542 0.579235 0.000000 0.364005 0.335128 0.355671 0.368796 0.148598 0.482379 0.327450 0.251218 5 0.566555 0.212418 0.484970 0.639118 0.364005 0.000000 0.676135 0.055591 0.576447 0.272729 0.315123 0.399127 0.555655 6 0.343214 0.535287 0.459329 0.827519 0.335128 0.676135 0.000000 0.679527 0.281035 0.481218 0.813671 0.621056 0.387169 7 0.541508 0.253292 0.449965 0.585140 0.355671 0.055591 0.679527 0.000000 0.602427 0.245620 0.261309 0.350237 0.526773 8 0.525761 0.378472 0.591335 0.946945 0.368796 0.576447 0.281035 0.602427 0.000000 0.498845 0.811462 0.695304 0.559738 9 0.295906 0.305322 0.217102 0.474554 0.148598 0.272729 0.481218 0.245620 0.498845 0.000000 0.333842 0.208528 0.282959 10 0.566702 0.504946 0.434730 0.383486 0.482379 0.315123 0.813671 0.261309 0.811462 0.333842 0.000000 0.254850 0.533784 11 0.326087 0.501173 0.187983 0.266724 0.327450 0.399127 0.621056 0.350237 0.695304 0.208528 0.254850 0.000000 0.288072 12 0.045059 0.545672 0.100192 0.444612 0.251218 0.555655 0.387169 0.526773 0.559738 0.282959 0.533784 0.288072 0.000000 13 0.339648 0.350100 0.407307 0.769145 0.202592 0.501132 0.185248 0.511020 0.186913 0.347808 0.678357 0.527288 0.372879 14 0.530211 0.104003 0.473790 0.689158 0.303486 0.10984…
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87566385
downvote count: 0

http://stackoverflow.com/q/50272801
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50272881
accepted answer: http://stackoverflow.com/a/50272881
tagged with: python
has title: convert an image to value (hex code for example) with opencv and python
has comment: http://stackoverflow.com/comment/87562463
tagged with: image
type: Question
score: 0
tagged with: encoding
upvote count: 1
has body: I'm currently working on image processing, and I want to convert some images to a code (hexadecimal for example). I'm using opencv with python. Here is the code I'm using, but it's not working. import cv2 import base64 image = cv2.imread('image.jpg') buffer = cv2.imencode('.jpg', image) imcode = base64.b64encode(buffer) print(imcode) and the response is "must be string or buffer, not tuple"
answer count: 1
downvote count: 1
tagged with: image-processing
favorite count: 0
tagged with: opencv

http://stackoverflow.com/a/50236730
has comment: http://stackoverflow.com/comment/87490817
has comment: http://stackoverflow.com/comment/87490822
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50236703
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50236703
upvote count: 5
has body: You're looking for functools.partial. You can supply all the arguments, so you can do something like: obj = functools.partial(test_for_active_server, server_address="http://localhost/") # ...do other things... obj()
type: Answer

http://stackoverflow.com/comment/87618122
type: QuestionComment
score: 2
has text: This sounds like an XY problem, especially if you can't provide the necessary `__eq__` method for `MyClass`.
comment on: http://stackoverflow.com/q/50300510
type: Comment

http://stackoverflow.com/q/50304867
type: Question
has answer: http://stackoverflow.com/a/50305553
has comment: http://stackoverflow.com/comment/87627429
type: UnansweredQuestion
score: -2
tagged with: python
has title: Finding a repeated values in Excel with different locations in an Excel using python
answer count: 2
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/50305444
has comment: http://stackoverflow.com/comment/87626039
has body: I have an Excel sheet with a value called "TX_DROP" which is a title with 80 to 90 row below it (let's call these rows X). This title repeats again in the file after these 80-90 rows in a different column but with a different number of columns and rows, so I cannot predict the column and row where "TX_Drop" appears in each repeat. I want to write a Python script to read all TX_Drops from this file. Example of a file: Granularity ETH_RX RX_DROP TX_DROP 15 Min 2 8 3 15 Min 0 6 12 15 Min 11 5 0 15 Min 1 5 4 Granularity ETH_RX TX_DROP RX_DROP 15 Min 0 1 0 15 Min 0 0 4 15 Min 12 11 8 15 Min 90 23 9 Granularity TX_DROP ETH_RX RX_DROP ETH_TX 15 Min 30 0 0 10 15 Min 4 0 0 11 15 Min 7 0 0 5 15 Min 8 0 0 3 I want to read all TX_DROPs with python in this file, as follows: TX_DROP 3 12 0 4 1 0 11 23 30 4 7 8 Thanks
tagged with: excel
favorite count: 0

http://stackoverflow.com/comment/89136913
has text: Maybe you could benefit from using `cache()`, transformations will be recomputed if you perform multiple actions on the dataframe.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50339462

http://stackoverflow.com/q/50326706
score: 0
has answer: http://stackoverflow.com/a/50326863
answer count: 1
has title: Show data in subsequent lines are increasing in size
type: Question
tagged with: python
type: UnansweredQuestion
has body: My query is concerned with showing data in each line is larger than the previous line, i.e. Line 2 > Line 1, Line 3 > Line 2, where this would only occur up to the point where the data would have words, before restarting the 'iteration'. The data set is as below 853764622753 1055334825425 927168311000 1142876772659 1390557034408 1538194473087 1567178619062 1459597906913 1345383143356 1204616439828 Australia 33050343783 48852482960 44291490421 52902703376 65951627200 69684317719 74164435946 75244166773 53074370486 37847715736 Azerbaijan I have no clue what to do with the code. I understand that you would need to initialise a boolean to set as True. My end code should be able to process lines and give indication if it is True or False that the code has increased. increased = True for x in open("dataset"): y = x.rstrip("\n") if y.isnumeric(): floated = float(y) if increased = increased and (floated &gt; floated ) ???CONFUSED print("GDP increased every year:",increased) else: print("GDP increased every year:",increased) else: str(y)

http://stackoverflow.com/comment/87635489
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50309217
has text: Works as expected. Thanks!

http://stackoverflow.com/comment/87696071
type: Comment
type: QuestionComment
has text: Maybe describe your computation more precisely, as it's quite informal, arr_two is not part of it and the C-code is not that much helping with magic-constants.
comment on: http://stackoverflow.com/q/50339688
score: 0

http://stackoverflow.com/comment/87753938
type: QuestionComment
comment on: http://stackoverflow.com/q/50368612
score: 0
has text: I read `Photoimage` doesn't support `PNG` but when i use it displays on label and button i think it will the version of `Tkinter`
type: Comment

http://stackoverflow.com/comment/87627151
comment on: http://stackoverflow.com/a/50296705
type: Comment
type: AnswerComment
has text: You write standard serializer solution, but it makes a lot of queries to collect all data. I try to optimize collecting.
score: 0

http://stackoverflow.com/q/50298005
upvote count: 4
type: AnsweredQuestion
has body: The interface of the id() function in Python is clear to me: "An object’s identity never changes once it has been created" [1], and "This is an integer which is guaranteed to be unique and constant for this object during its lifetime." [2] But this statement in [1] confuses me: "you may think of it as the object’s address in memory". The issue is it's not clear what object's address in memory is and how it changes. I would think this is really an implementation detail. This question seems to suggest for this statement in the Language Reference to hold true, the virtual address of an object must never change in the implementation. My questions are then: Is this address being referred to the virtual memory address or the physical memory address? The physical address of any process is determined at run-time by the OS so I don't see how it can be physical. How does the implementation keep the virtual object address the same, and still avoid internal fragmentation? By contrast, in Java, the JVM routines moves objects during GC.
downvote count: 0
answer count: 1
tagged with: memory
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50298309
accepted answer: http://stackoverflow.com/a/50298309
linked to: http://stackoverflow.com/q/10795682
tagged with: python
has title: The nuances of "object’s address in memory" in Python documentation and implementation
score: 4

http://stackoverflow.com/q/50304669
upvote count: 1
score: 1
answer count: 1
has body: I have the following function: def func(x, y, z): d = -5.9 T = 230.0 f = x - y * T + z + d return f From this, I want to make a single list of f-values extracted from func(x, y, z). The values x, y, and z are three different lists of values. My question is, how do I make the list of f-values? I have tried the following, but it did not work properly: f_list = [func(x, y, z) for x in x_list for y in y_list for z in z_list]
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50304685
accepted answer: http://stackoverflow.com/a/50304685
has title: Defining list from a function with multiple arguments
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0

http://stackoverflow.com/a/50343732
has comment: http://stackoverflow.com/comment/87704644
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: cumsum + iloc df.iloc[1] += '-' + (df.iloc[1].eq('JAN').cumsum() + 2017).astype(str) df 0 1 2 3 4 5 6 \ 0 2017-18 1 APR-2017 MAY-2017 JUN-2017 JULY-2017 AUG-2017 SEP-2017 OCT-2017 7 8 9 10 11 0 1 NOV-2017 DEC-2017 JAN-2018 FEB-2018 MAR-2018
answers question: http://stackoverflow.com/q/50343650
accepted answer of: http://stackoverflow.com/q/50343650
has comment: http://stackoverflow.com/comment/87704688
has comment: http://stackoverflow.com/comment/87703768
type: Answer
has comment: http://stackoverflow.com/comment/87705405

http://stackoverflow.com/q/50344778
score: 3
tagged with: pandas
upvote count: 3
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87705699
accepted answer: http://stackoverflow.com/a/50348713
has body: I have a data set in a csv file. I have imported it using pandas as a dataframe. I then order my data from smallest to largest based on the column which I have named Vf. From here what my code is trying to do: Group the sorted dataframe (DF) into groups of 11. Calculate the difference between the corresponding min and max values in each group. Iterate through each group and check to see if the difference between the min and max value of any of the groups is greater than 0.2. If this condition is met for any of the groups, I want the code to remove the row of data containing the minimum value of that group from the orginal dataframe. Then sort and group the dataframe again, minus that row. Iterate through each group again, checking the differences between the min and max values. It should continue to do this until it has gone through each group and found that none of them have a difference between the min and max values greater than 0.2. Right now my code does this as far as I can tell. But it does not stop when I want it to, ie when all of the groups have a difference between the min and max values of less than 0.2, it does not stop. Also, at this point it actually seems to add rows back into the original dataframe. Here is the code. Note that I have set it to only go through the first 2 groups in my data. Also note that the lines in my for loop asking it to print statements and the shape of the sorted dataframe. This is all to provide info for debugging purposes. def celling(): import numpy as np import pandas as pd Data = input("Name of File: ") DF = pd.read_csv("Y:\CHRIS\{}.csv".format(Data), skiprows = 20, names = ["Serial","Bin","Ir","Vf"]) def sort(Data): SortedDF = Data.sort_values(by='Vf') GroupedDF = SortedDF.groupby(np.arange(len(SortedDF))//11) GroupMax = GroupedDF["Vf"].max() GroupMin = GroupedDF["Vf"].min() GroupDiff = GroupMax - GroupMin GroupMinIndices = GroupedDF["Vf"].idxmin() #sort(DF) for i in range(2): if GroupDiff[i] &gt; 0.2: DF = Data[Data.ind…
has title: Removing rows from groups in a dataframe that have a minimum value in a certain column
favorite count: 0
has answer: http://stackoverflow.com/a/50348713
type: Question
has comment: http://stackoverflow.com/comment/87707727
downvote count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/50302547
has comment: http://stackoverflow.com/comment/87659543
has body: What you could do if you wanted is have a tkinter file selection window come up for the user. Here is the code: import tkinter import tkinter.filedialog #You might not need this line, sometimes I run into an error if I don't have it tkinter.Tk().withdraw() file = tkinter.filedialog.askopenfilename() The "file" variable will have the full path with the file name.
has comment: http://stackoverflow.com/comment/87660022
answers question: http://stackoverflow.com/q/50302205
score: 0
type: Answer

http://stackoverflow.com/comment/87577876
has text: Are you sure _every_ image has the tag? Your output would be compatible with some having it, some not.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50280590
type: QuestionComment

http://stackoverflow.com/comment/87546319
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50264164
has text: Don't need the `[]` in the join.

http://stackoverflow.com/q/50272214
downvote count: 0
upvote count: 1
has title: python : I want to avoid using 'copy' module
favorite count: 0
type: Question
has body: (The code below is not a working code. It's just to convey ideas) My intention is to recursively call sumsubset(arr.remove(el),num,org), parsing updated arr. However, this will cause unwanted removal to original arr which will cause error. So, I often depend on copy module, feeling somewhat awkward. Is there any better way parsing updated arr without using copy module? Thanks for answering my first question. arr=[1, 1, 2, 4, 4, 4, 7, 9, 9, 13, 13, 13, 15, 15, 16, 16, 16, 19, 19, 20] num=36 import copy def sumsubset(arr,num,org): for el in arr: if el==org: return [el] tmp=copy.copy(arr) tmp.remove(el) result=[el]+sumsubset(tmp,num-el,org) return result a=sumsubset(arr,36,36)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50272473
tagged with: arrays
tagged with: python
tagged with: copy
tagged with: recursion
score: 1
answer count: 1

http://stackoverflow.com/a/50341645
answers question: http://stackoverflow.com/q/50337544
has comment: http://stackoverflow.com/comment/88038682
has comment: http://stackoverflow.com/comment/87776355
has comment: http://stackoverflow.com/comment/87779293
has body: Short answer: You did not include the column you want to query into your table. Long answer: SQLAlchemy helps you convert models that reside in a database to move them into classes in your python code so both can interact pretty magically. You can use python to extend the models generated with SQLAlchemy, just like you did when declaring mealprice and json. You can also overload existing attributes, just like you did with repr. To be able to query an attribute, you have to make it an attribute in the SQLAlchemy sense of the word, and that is a column. When you do: category_id = db.Column(db.Integer, db.ForeignKey('category.id')) You create a category_id attribute in python, based on a db.Column, which is an SQLAlchemy attribute, therefore you can put queries to it. In other words, if you do: mealprice = db.Column(db.Numeric, default=calc_mealprice, onupdate=calc_mealprice) And you define your function however you like, http://docs.sqlalchemy.org/en/latest/core/defaults.html That would make your mealprice queryable, since it is now a column. However, you will have problems making your function in your current database state, because your mealprice is the sum of colums inside the results of a query. The error you recieve, TypeError, is because you're mixing queries with numbers, and they are evaluated after the object has been constructed. So recipe.ingredients.price is a query when you define mealprice (during construction), but becomes a list during json. EDIT: Personally, I would keep concerns separate and avoid hybrid attributes for now, because they may blur the limits between the database and python for you. If your ingredients may change, I would do something like: def calc_price_by_minamount(context): price = context.get_current_parameters()['price'] minamount = context.get_current_parameters()['minamount'] return price / ingredient.minamount class IngredientModel(db.Model): ... price_by_minamount = db.Column(db.Numeric, default=calc_price_by_minamount, onupda…
has comment: http://stackoverflow.com/comment/88188358
score: 0
has comment: http://stackoverflow.com/comment/87774270
type: Answer
has comment: http://stackoverflow.com/comment/87707605
has comment: http://stackoverflow.com/comment/87707691

http://stackoverflow.com/comment/87771358
comment on: http://stackoverflow.com/a/50377446
score: 0
has text: uh completely missed `sort_index`!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87684827
type: Comment
has text: Hi, really is boo language, it is based on Python language,
type: QuestionComment
comment on: http://stackoverflow.com/q/50332735
score: 0

http://stackoverflow.com/comment/87522049
has text: I tried to do so but the problem is that request.remote_addr returns private ip address and the output of the request for such ip is empty
comment on: http://stackoverflow.com/a/50252288
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87648830
type: Comment
type: QuestionComment
score: 0
has text: @KtZr I have edited the question. you may like to help someone:)
comment on: http://stackoverflow.com/q/50316383

http://stackoverflow.com/comment/87763345
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50373530
has text: how do you call `recusion` first time?

http://stackoverflow.com/comment/87584198
type: Comment
type: QuestionComment
score: 0
has text: In this case, `Mark:)))` is a username a user gave himself, so I didn't think about splitting it up. I don't know how else to explain myself. @TimBiegeleisen
comment on: http://stackoverflow.com/q/50283784

http://stackoverflow.com/q/50288315
upvote count: 1
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87592996
tagged with: multi-index
has answer: http://stackoverflow.com/a/50288470
has title: Pandas slicing data with MultiIndex
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50288960
has body: I have some features that I want to write to some csv files. I want to use pandas for this approach if possible. I am following the instruction in here and have created some dummy data to check it out. Basically there are some activities with a random number of features belonging to them. import io data = io.StringIO('''Activity,id,value,value,value,value,value,value,value,value,value Run,1,1,2,2,5,6,4,3,2,1 Run,1,2,4,4,10,12,8,6,4,2 Stand,2,1.5,3.,3.,7.5,9.,6.,4.5,3.,1.5 Sit,3,0.5,1.,1.,2.5,3.,2.,1.5,1.,0.5 Sit,3,0.6,1.2,1.2,3.,3.6,2.4,1.8,1.2,0.6 Run, 2, 0.8, 1.6, 1.6, 4. , 4.8, 3.2, 2.4, 1.6, 0.8 ''') df_unindexed = pd.read_csv(data) df = df_unindexed.set_index(['Activity', 'id']) When I run: df.xs('Run') I get value value.1 value.2 value.3 value.4 value.5 value.6 value.7 \ id 1 1.0 2.0 2.0 5.0 6.0 4.0 3.0 2.0 1 2.0 4.0 4.0 10.0 12.0 8.0 6.0 4.0 2 0.8 1.6 1.6 4.0 4.8 3.2 2.4 1.6 value.8 id 1 1.0 1 2.0 2 0.8 which almost what I want, that is all run activities. I want to remove the 1st row and 1st column, i.e. the header and the id column. How do I achieve this? Also a second question is when I want only one activity, how do I get it. When using idx = pd.IndexSlice df.loc[idx['Run', 1], :] gives value value.1 value.2 value.3 value.4 value.5 value.6 \ Activity id Run 1 1.0 2.0 2.0 5.0 6.0 4.0 3.0 1 2.0 4.0 4.0 10.0 12.0 8.0 6.0 value.7 value.8 Activity id Run 1 2.0 1.0 1 4.0 2.0 but slicing does not work as I would expect. For example trying df.loc[idx['Run', 1], 2:11] instead produces an error: TypeError: cannot do slice indexing on with these indexers [2] of 'int'> So, how do I get my features in this place? P.S. If not clear I am new to Pandas so be gentle. Also the column id is editable to be unique to each activity or to whole dataset if this makes things easier etc
has answer: http://stackoverflow.com/a/50288508
tagged with: python
tagged with: slice
has comment: http://stackoverflow.com/comment/87592792
has comment: http://stackoverflow.com/comment/87592718
answer count: 3
downvote count: 0
tagged with: pandas

http://stackoverflow.com/comment/87487480
type: Comment
comment on: http://stackoverflow.com/q/50234265
type: QuestionComment
has text: This seems like an awfully broad question. Are you asking for someone to show you how to validate moves for every type of chess piece? A narrowed scope will probably give you a better chance of getting quality answers.
score: 1

http://stackoverflow.com/q/50234355
type: AnsweredQuestion
tagged with: multidimensional-array
downvote count: 3
has body: There are a large number of questions on iterating over nested lists, however I would like to iterate over a nested list and apply another list. Here is my scenario: def operation(a, b): return a + b def magic_function(func, list, nested_list): """iterate over nested_list and apply the next element of list""" ... magic_function(operation, [0, 0, 0, 10, 10, 10], [[1, 2, 3], [1, 2, 3]]) Desired output: [[1, 2, 3], [11, 12, 13]] The urge might be strong to answer this with numpy, but in the real scenario, these are objects, not numbers. The standard itertools.chain.from_iterable does not work here, since it does not preserve the nesting of the list.
tagged with: python
has answer: http://stackoverflow.com/a/50234525
score: -1
possible better answer: http://stackoverflow.com/a/50234525
upvote count: 2
tagged with: list
tagged with: iterator
answer count: 2
tagged with: functional-programming
has title: Apply operation and list to nested list
has comment: http://stackoverflow.com/comment/87486058
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50234615
accepted answer: http://stackoverflow.com/a/50234615

http://stackoverflow.com/comment/87578663
score: 0
comment on: http://stackoverflow.com/q/50275174
type: Comment
has text: Is there anything you have done so far with respect to solving this by your own? I mean there so many questions about animations, I can't believe none of them even helps a little bit.
type: QuestionComment

http://stackoverflow.com/a/50275259
type: Answer
has comment: http://stackoverflow.com/comment/87567557
has comment: http://stackoverflow.com/comment/87567336
accepted answer of: http://stackoverflow.com/q/50275129
score: 0
has comment: http://stackoverflow.com/comment/87568255
answers question: http://stackoverflow.com/q/50275129
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87567967
has comment: http://stackoverflow.com/comment/87567129
has comment: http://stackoverflow.com/comment/87571204
has comment: http://stackoverflow.com/comment/87567432
has body: In your final print statement, you need to make sure that everything is a string: print ("The Student with the higgest average is: ", winner, "With the highest average of: ", str(highest), "gpa is: " + determine_score(grade) ) Also your functions should return the value and not a hardcoded string: return firsttermScore ... return midtermScore ... return finalScore You also need to operate on double (or float) if you want a precise score: firsttermScore = (fst_sub1+fst_sub2+fst_sub3+fst_sub4+fst_sub5)/5.0 finalScore = (fnl_sub1+fnl_sub2+fnl_sub3+fnl_sub4+fnl_sub5)/5.0 midtermScore = (mid_sub1+mid_sub2+mid_sub3+mid_sub4+mid_sub5)/5.0 student_avg = (firstterm + midterm + final) / 3.0 If you divide by an int, and your input data are int. The result will be an int, and you will lose your precision. And a last print statement that would fail because list_marks is a list and not a string: print ("exam result: ", str(list_marks), "grade is: ", determine_score(grade)) There is also a last error: finalGrade = final() You need to echange the name of your variable to something different from your function.

http://stackoverflow.com/q/50311057
tagged with: python
has title: Class variables, difference between instance.var and instance.__class__.var
has body: I see this was flagged as a duplicate of "What is the difference between class and instance variables?" However I don't believe I'm using any instance variables in my example, neither of my classes has a __init__ I'm editing class variables in two different ways and trying to understand the difference between them, not the difference between a class and instance variable. I'm trying to understand the difference between calling a class variable just with .var and with .__class__.var. I thought it was to do with subclassing so I wrote the following code. class Foo: foo = 0 class Bar(Foo): bar = 1 def print_class_vals(f, b): """ prints both instant.var and instant.__class__.var for foo and bar""" print("f.foo: {}, {} " "b.foo: {}, {} " "b.bar: {}, {} " "".format(f.foo, f.__class__.foo, b.foo, b.__class__.foo, b.bar, b.__class__.bar)) f = Foo() b = Bar() print_class_vals(f, b) Foo.foo += 1 print_class_vals(f, b) Bar.foo += 1 print_class_vals(f, b) Bar.bar += 1 print_class_vals(f, b) This outputs the following: f.foo: 0, 0, b.foo: 0, 0, b.bar: 1, 1 f.foo: 1, 1, b.foo: 1, 1, b.bar: 1, 1 f.foo: 1, 1, b.foo: 2, 2, b.bar: 1, 1 f.foo: 1, 1, b.foo: 2, 2, b.bar: 2, 2 I can't seem to find any difference between calling inst.var and inst.__class__.var. How are they different and when should I use one over the other?
tagged with: class
possible better answer: http://stackoverflow.com/a/50311137
type: AnsweredQuestion
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/87638405
linked to: http://stackoverflow.com/q/8959097
downvote count: 0
has comment: http://stackoverflow.com/comment/87638515
upvote count: 1
accepted answer: http://stackoverflow.com/a/50311191
has answer: http://stackoverflow.com/a/50311191
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50311137
has comment: http://stackoverflow.com/comment/87638489
has comment: http://stackoverflow.com/comment/87638541

http://stackoverflow.com/q/50359593
score: 0
has answer: http://stackoverflow.com/a/50359744
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87736017
tagged with: matplotlib
tagged with: python
has body: I need to change the size of the delimiters of a scatter plot. I need to compare plots and they should all be at the same size, i.e., starting in the same point and ending at same size. plt.scatter(x, y) plt.show() Another plot is plt.scatter(x, y) plt.show() And I wish the they be at the same ratio
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50359864
answer count: 2
possible better answer: http://stackoverflow.com/a/50359744
has answer: http://stackoverflow.com/a/50359864
has title: How to change the size of a pyplot scatterplot?

http://stackoverflow.com/comment/87759361
score: 0
type: Comment
type: QuestionComment
has text: Also you may want to use `logging.DictConfig` which is much more friendly than manual config.
comment on: http://stackoverflow.com/q/50370495

http://stackoverflow.com/a/50287717
has body: Barcode scanners often (always?) act as a keyboard. Scanning a barcode with a barcode scanner appears to the computer exactly the same as if you had a keyboard plugged in, typed the number and pressed enter. If you have a command prompt or a text editor open and scan something, do you see the number appear as if you had typed it? Usually you don't need to use a low level interface to interact with it - just use the built in input()
answers question: http://stackoverflow.com/q/50287470
type: Answer
has comment: http://stackoverflow.com/comment/87595814
has comment: http://stackoverflow.com/comment/87598910
score: 0
has comment: http://stackoverflow.com/comment/87595668

http://stackoverflow.com/a/50311636
downvote count: 0
answers question: http://stackoverflow.com/q/50311585
type: Answer
score: 3
has body: You should render your template with a context: https://docs.djangoproject.com/en/2.0/ref/templates/api/#rendering-a-context The method of passing the context to the template depends on how your views are written. Function-based views Pass the context dictionary to the render() function: https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#optional-arguments from django.shortcuts import render def my_view(request): # View code here... context = {'foo': 'bar'} return render(request, 'myapp/index.html', context=context) Class-based views Write your own implementation of the add_context_data() method: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#adding-extra-context from django.views.generic import DetailView from books.models import Book, Publisher class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context Once you passed key: value context to the template, you should use it in the template like this: {{ key }}. https://docs.djangoproject.com/en/2.0/topics/templates/#variables &lt;script type="text/javascript"&gt; var a = ""; &lt;/script&gt; escapejs template filter is required to prevent possible XSS vulnerabilities. If you need to pass JSON, you could check out Django ticket #17419
accepted answer of: http://stackoverflow.com/q/50311585
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/50348505
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50348426
type: Answer
has comment: http://stackoverflow.com/comment/87713348
accepted answer of: http://stackoverflow.com/q/50348426
has body: You can use literal_eval to remove all escape sequences. In [29]: x = {"{\"rid\":\"PHMJ3BD77P81B225A0GM\",\"sid\":\"259-2748551-5638001\",\"mid\":\"A1PA6795UKMFR9\",\"sn\":\"www.amazon.de\",\"reqs\":[{\"cap-ciba\":{\"k\":\"fwcim\",\"t\ ...: ":1522150437949,\"md\":\" +I42uPPjwZf0N \",\"p\":\"https://www.amazon.de/ap/signin?clientContext":"257-0866472-4844452","openid.return_to":"https%3A%2F%2Fwww.amazon.de%2 ...: Fkindle-dbs%2Fku%2Fku-central%3Fref_%3Dnav_youraccount_ku%26_encoding%3DUTF8","openid.identity":"http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select","openid. ...: assoc_handle":"amzn_kplp_desktop_de","openid.mode":"checkid_setup","marketPlaceId":"A1PA6795UKMFR9","openid.claimed_id":"http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fide ...: ntifier_select","pageId":"amzn_aui_light","openid.ns":"http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0","openid.pape.max_auth_age":"3600","siteState":"clientContext%3D259-274 ...: 8551-5638001%2CsourceUrl%3Dhttps%253A%252F%252Fwww.amazon.de%252Fkindle-dbs%252Fku%252Fku-central%253Fref_%253Dnav_youraccount_ku%2526_encoding%253DUTF8%2Csignature%3Dik ...: QPbHmIyj2F3VCmlAXOMRBtpWIRAj3D\"}}]}"} In [30]: from ast import literal_eval In [31]: literal_eval(str(x)) Out[31]: {'marketPlaceId': 'A1PA6795UKMFR9', 'openid.assoc_handle': 'amzn_kplp_desktop_de', 'openid.claimed_id': 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select', 'openid.identity': 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select', 'openid.mode': 'checkid_setup', 'openid.ns': 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0', 'openid.pape.max_auth_age': '3600', 'openid.return_to': 'https%3A%2F%2Fwww.amazon.de%2Fkindle-dbs%2Fku%2Fku-central%3Fref_%3Dnav_youraccount_ku%26_encoding%3DUTF8', 'pageId': 'amzn_aui_light', 'siteState': 'clientContext%3D259-2748551-5638001%2CsourceUrl%3Dhttps%253A%252F%252Fwww.amazon.de%252Fkindle-dbs%252Fku%252Fku-central%253Fref_%253Dnav_youraccount_ku%2526_encoding%253DUTF8%2Csignature%3DikQPbHmIyj2F3VCmlAXOMRBtp…
score: 0

http://stackoverflow.com/comment/87481759
type: Comment
score: 0
has text: added it, test it out to see what i ment - the objects do a little hop upon new objects being generated
type: QuestionComment
comment on: http://stackoverflow.com/q/50232002

http://stackoverflow.com/a/50309210
has comment: http://stackoverflow.com/comment/87664008
type: Answer
has body: There are couple of things to mention in your code: Firstly, when you want to find contours the shape must be in white. The image provided by you has shapes that are dark. So I had to invert your image and then find the contours. Secondly, you were storing coordinates of only one contour. I have modified your code to store coordinates for each contour in a separate file. Code: import numpy as np import cv2 THRESHOLD = 55 path = 'C:/Users/Desktop/' im = cv2.imread(path + 'date.jpg') imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) cv2.imshow("imgray", imgray) ret, thresh = cv2.threshold(imgray, THRESHOLD, 255, 0) cv2.imshow('thresh', thresh) _th, contours, hierarchy = cv2.findContours(cv2.bitwise_not(thresh), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) print "Number of contours detected = %d" % len(contours) cv2.drawContours(im, contours, -1, (1, 70, 255), 2) cv2.imshow("Contours", im) contour_num = 0 for i in range(0, len(contours)): coords = np.array2string(contours[i]) contour_num+=1 open(path + 'contour_%d.txt' %contour_num, "w").write(coords) cv2.waitKey(0) cv2.destroyAllWindows() Run the code as it is and see the saved files.
has comment: http://stackoverflow.com/comment/87663340
answers question: http://stackoverflow.com/q/50246672
score: 0

http://stackoverflow.com/comment/87644131
score: 0
type: Comment
has text: Hello @jezrael.. it hogs upto 60% memory now with group by .. With pivot it was upto 70%.. Though there is 10% reduction, I still need to optimize more. :) Thanks a lot!
comment on: http://stackoverflow.com/q/50308352
type: QuestionComment

http://stackoverflow.com/q/50338108
has answer: http://stackoverflow.com/a/50338305
tagged with: python
has body: I'm currently working on a crawling-script in Python where I want to map the following HTML-response into a multilist or a dictionary (it does not matter). My current code is: from bs4 import BeautifulSoup from urllib.request import Request, urlopen req = Request("https://my.site.com/crawl", headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req) soup = BeautifulSoup(webpage, 'html.parser') ul = soup.find('ul', {'class': ''}) After running this I get the following result stored in ul: Data1 Data2 Data3 Data4 Data5 Data6 . . . Data7 Data8 Data9 . . . Data10 Data11 Data12 As this is an external site I cannot control the id or class of the elements in the list. It seems that I can not get my head around this, is there a simple way to arrange the data into a list or dict?: dict = {'Data1': {'href': 'ref1'}, 'Data2': {'href': 'ref2', { 'Data3': {'href': 'ref3'}, 'Data4': {'href': 'ref4', { 'Data5': {'href': 'ref5'}, 'Data6': {'href': 'ref6'}, . . . } } } } } I do feel like this is a cumbersome process, however I do not see any other way of doing it. Any help to get me going in the right direction is much appreciated! Cheers!
tagged with: html-lists
has comment: http://stackoverflow.com/comment/87692669
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87692627
answer count: 3
has answer: http://stackoverflow.com/a/61963812
has comment: http://stackoverflow.com/comment/87692871
score: 2
accepted answer: http://stackoverflow.com/a/50338305
has comment: http://stackoverflow.com/comment/87692633
downvote count: 0
has answer: http://stackoverflow.com/a/50338308
favorite count: 0
tagged with: beautifulsoup
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/50338308
has title: Using BeautifulSoup in order to find all "ul" and "li" elements

http://stackoverflow.com/q/50356723
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55963298
has title: Can't see my project's strings in Django Rosetta
answer count: 1
downvote count: 0
tagged with: django
tagged with: python
tagged with: django-rosetta
has comment: http://stackoverflow.com/comment/87733401
has body: I have installed and configured rosetta on my Django project and I can say it is working because I can see multi-language features with Django admin and I can see strings to translate in third party and django tabs, but when a chose project tab I get this message: Nothing to translate! You haven't specified any languages in your settings file, or haven't yet generated a batch of translation catalogs. Please refer to Django's I18N documentation for a guide on how to set up internationalization for your project. I have already used gettext() in my code but I can't see those strings in rosetta. This is an example of the use of gettext() in my models.py: from django.utils.translation import gettext as _ class Hotel(models.Model): ONE_STAR = '*' TWO_STARS = '**' THREE_STARS = '***' FOUR_STARS = '****' FIVE_STARS = '****' GRAND_TOURISM = 'GRAND_TOURISM' NA = 'NA' SPECIAL = 'SPECIAL' ECO = 'ECO' BOUTIQUE = 'BOUTIQUE' HOTEL_CATEGORY_CHOICES = ( (ONE_STAR, _('*')), (TWO_STARS, _('**')), (THREE_STARS, _('***')), (FOUR_STARS, _('****')), (FIVE_STARS, _('*****')), (GRAND_TOURISM, _('Grand Tourism')), (NA, _('NA')), (SPECIAL, _('Special')), (ECO, _('Eco-Hotel')), (BOUTIQUE, _('Boutique-Hotel')) ) This is the configuration of languages in settings.py: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('de', gettext('German')), ('es', gettext('Spanish')), ) USE_I18N = True I don't know what I am missing.
has comment: http://stackoverflow.com/comment/87735769
favorite count: 0
type: Question
score: 2
upvote count: 2

http://stackoverflow.com/q/50372010
has comment: http://stackoverflow.com/comment/87762099
has comment: http://stackoverflow.com/comment/87800705
tagged with: video-processing
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87765899
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has title: -to value smaller than -ss error while clipping videos with ffmpeg
has comment: http://stackoverflow.com/comment/87761873
score: 1
has body: I am trying to clip videos using frame information, I first convert the frame to time since ffmpeg uses this notion to clip videos. The problem is for shorter videos, it gives the error: -to; value smaller than -ss; aborting. But in reality, this is false. For example, I get an error even with these values: 0:0:47.4 -to 0:0:47.21 (format -&gt; hh:mm:ss.frame) Can anyone tell me how I can fix this? The video frame rate is 25 fps and the command structure I use is: os.system('ffmpeg -i ' + inputvideo + '.mp4' + ' -qscale:v 2 -vf scale=427:240 ' + ' -ss '+ str(fhours) + ':' + str(fminutes) + ':' + str(fseconds) + '.' + str(fframes) + ' -to ' + str(lhours) + ':' + str(lminutes) + ':' + str(lseconds) + '.' + str(lframes) + ' ' + outputvideo + '.avi')
type: Question

http://stackoverflow.com/comment/87553287
type: QuestionComment
has text: `numexpr` works better on large arrays and with numeric data. Just keep that in mind.
comment on: http://stackoverflow.com/q/50267780
score: 0
type: Comment

http://stackoverflow.com/q/50260368
answer count: 1
tagged with: celery
has title: Cassandra Celery python timeout happens on raw query execution using django db connection execute
tagged with: cqlengine
tagged with: cassandra
type: Question
has body: My celery is configured for the Cassandra session like this: def cassandra_init(*args, **kwargs): """ Initialize a clean Cassandra connection. """ if cql_cluster is not None: cql_cluster.shutdown() if cql_session is not None: cql_session.shutdown() connection.setup([settings.DATABASES["default"]["HOST"],], settings.DATABASES["default"]["NAME"]) # Initialize worker context (only standard tasks) worker_process_init.connect(cassandra_init) When I am executing a raw cassandra query, timeout happens, from django.db import connection cursor = connection.cursor() total_ap = cursor.execute( "SELECT cpu_info FROM ap_live_stats;") It works well all over in my django project but not inside the celery tasks. Error: [2018-05-09 18:50:21,576: ERROR/ForkPoolWorker-5] Task apps.statistic.tasks.ap_hourly_data_migrator[77a596d4-61a2-43f4-8580-6abc6e9b5866] raised unexpected: OperationTimedOut("errors={'192.168.98.65': 'Client request timeout. See Session.execute[_async](timeout)'}, last_host=192.168.98.65",) Traceback (most recent call last): File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/vkchlt0079/projects/wlcd/src/web_gui/backend/django/wlcd/apps/statistic/tasks.py", line 59, in ap_hourly_data_migrator "SELECT cpu_info FROM ap_live_stats;") File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/utils.py", line 47, in execute return self.cursor.execute(sql) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/connection.py", line 12, in execute return self.connection.execute(*args, **kwargs) File "/home/vkchlt0079/virtuals/wlc-env/lib/python3.5/site-packages/django_cassandra_engine/connection.py", line 86, in execute self.session.set_keyspace(s…
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50485501
score: 0
tagged with: django
has answer: http://stackoverflow.com/a/50485501

http://stackoverflow.com/comment/87576546
has text: @HonzaNijaký We need more code, just that single line has nothing wrong with it so we need more code to diagnose the problem. We should see the connect (minus sensitive info) through the closing of the cursor.
comment on: http://stackoverflow.com/q/50279896
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50267783
has comment: http://stackoverflow.com/comment/87556162
answer count: 1
has title: Time a single execution of a function using timeit
upvote count: 1
accepted answer: http://stackoverflow.com/a/50267841
has body: print function is called many times.I want to calculate function's time.I wrote codes, import timeit class UserClass: def callname(self): print("HiTom") if __name__ == '__main__': def test(): user = UserClass() user.callname() test() mtime = timeit.timeit(lambda: test()) print(mtime) When I run the codes,"Hi Tom" is called many times. I really cannot understand why such a thing happens. I rewrote mtime = timeit.timeit(test(), number=1) but ValueError: stmt is neither a string nor callable error happens.How can I make my ideal system?What is wrong in my codes?
favorite count: 0
has answer: http://stackoverflow.com/a/50267841
type: Question
downvote count: 2
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87553280
tagged with: timeit
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87553309

http://stackoverflow.com/comment/87598674
score: 0
type: Comment
type: QuestionComment
has text: If you click edit under your question you can put the code there, properly formatted.
comment on: http://stackoverflow.com/q/50291028

http://stackoverflow.com/comment/87679359
has text: thanks! i want to plot the sinc function while it is computed (plot it point by point: as in it is re-drawn after each newly computed sinc value) to show it during a presentation.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50328277

http://stackoverflow.com/comment/87687767
has text: You can use Flask and set a Restful API to call those functions, take a look at this [guide](https://medium.com/python-pandemonium/build-simple-restful-api-with-python-and-flask-part-1-fae9ff66a706)
comment on: http://stackoverflow.com/q/50335761
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87766851
score: 0
comment on: http://stackoverflow.com/a/50374398
has text: Well this code does it, you can maybe propose another question with more details and I'll be glad to help you
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87552753
has text: Why is this tagged both [tag:python-2.7] and [tag:python-3.x]? If you need a solution which is portable to Python 2 you should be more explicit about this requirement; and if not, please refrain from tag spam.
score: 0
comment on: http://stackoverflow.com/q/50266568
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50347502
type: Question
has comment: http://stackoverflow.com/comment/87716269
has comment: http://stackoverflow.com/comment/87712057
has comment: http://stackoverflow.com/comment/87711113
has body: I have to project to learn to realize a runPE under python (for educational purposes). However, as I do not know much about the domain, I try to modify sources in order to make them functional (because indeed, all runPE projects under python published on github do not currently work). So I decided to train under the project: https: //github.com/oueldz4/runpe First of all, to be clear with you, I need to talk to you about what it is. RunPE is the generic name of a technique used by many malware. This technique consists in launching a new process in pause, then replacing the memory contents of the executable in pause and finally to release the process. This allows you to run a complete executable without having to put it on the disk. This avoids detection by the antivirus. https://www.root-me.org/fr/Documentation/Applicatif/RunPE So, as you can read, this method is used to infect a computer without being detected by Anti-Virus. However, for my part, I wish to realize this educational project. The world of security interests me a lot, and it is true that understanding these mechanisms is useful not to be infected yourself by downloading files on the internet. Let's go back to the problem I'm having. The crypter finally outputs this code: #!/usr/bin/env python # This script uses the runpe technique to bypass AV detection # The payload it contains, is encrypted each time with a random key # INSTALL pefile and ctypes packages from itertools import cycle, izip import sys, pefile import ctypes BYTE = ctypes.c_ubyte WORD = ctypes.c_ushort DWORD = ctypes.c_ulong LPSTR = ctypes.c_char_p HANDLE = ctypes.c_void_p CREATE_SUSPENDED = 0x0004 MEM_COMMIT = 0x1000 MEM_RESERVE = 0x2000 PAGE_EXECUTE_READWRITE = 0x40 class PROCESS_INFORMATION(ctypes.Structure): _fields_ = [ ('hProcess', HANDLE), ('hThread', HANDLE), ('dwProcessId', DWORD), ('dwThreadId', DWORD), ] class STARTUPINFO(ctypes.Structure): _fields_ = [ ('cb', DWORD), ('lpReserved', LPSTR), ('lpDesktop', LPSTR), ('lpTitle', LPS…
tagged with: api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87715507
has comment: http://stackoverflow.com/comment/87715097
has title: 0xC0000005 error in my RunPE with python
tagged with: encryption
has comment: http://stackoverflow.com/comment/87713341
downvote count: 0
tagged with: runtime
tagged with: python
has comment: http://stackoverflow.com/comment/87713458
has comment: http://stackoverflow.com/comment/87714487
has comment: http://stackoverflow.com/comment/87715726
has comment: http://stackoverflow.com/comment/87711791
has comment: http://stackoverflow.com/comment/87712615
answer count: 0
linked to: http://stackoverflow.com/q/48788549
score: 1
tagged with: windows
has comment: http://stackoverflow.com/comment/87715249
has comment: http://stackoverflow.com/comment/87712987
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/50291224
downvote count: 0
type: AcceptedAnswer
has body: So i found thanks to the comment that i needed to sudo apt install python3.5-dev This question is resolved.
accepted answer of: http://stackoverflow.com/q/50289691
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/106972799
answers question: http://stackoverflow.com/q/50289691
type: Answer

http://stackoverflow.com/a/50323093
score: 2
answers question: http://stackoverflow.com/q/50323054
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50323054
has body: You're missing two major things. First, your version doesn't pass along the keyword arguments. To do that, you need to splat them as well: lambda *args, **kwargs: func(*args, **kwargs) But let's ignore that for the moment. The bigger problem is that you're missing the partial arguments, which is the entire point of partial. For example: &gt;&gt;&gt; def f(a, b): ... return a + b &gt;&gt;&gt; add2 = partial(f, 2) &gt;&gt;&gt; add2(3) 5 &gt;&gt;&gt; add2 = lambda *args: f(*args) &gt;&gt;&gt; add2(3) f() missing 1 required positional argument: 'b' To do the same thing, you'd need to do this: &gt;&gt;&gt; add2 = lambda *args: f(2, *args) &gt;&gt;&gt; add2(3) 5 … or, equivalently: &gt;&gt;&gt; add2 = lambda *args: f(*((2,) + args)) &gt;&gt;&gt; add2(3) 5 Also, there's no good reason to use lambda here. The point of lambda is that (a) you don't have to come up with a name, and (b) you can use it in an expression. If you're just going to use it in an assignment statement to give it a name, better to use def: def add2(*args): return f(*((2,) + args))
upvote count: 2
type: Answer

http://stackoverflow.com/comment/87771321
type: AnswerComment
score: 0
type: Comment
has text: for example it would be 'number of tests_x' and 'number of tests_y', 'count number_x' and 'count number_y', etc.
comment on: http://stackoverflow.com/a/50377342

http://stackoverflow.com/comment/87626233
has text: The gene1 is present just once, so I only want to add _number for this specific gene yep.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50304937
score: 0

http://stackoverflow.com/comment/87642290
comment on: http://stackoverflow.com/q/50313119
type: QuestionComment
has text: That is a csv file with csv content!
score: 0
type: Comment

http://stackoverflow.com/a/50313717
type: Answer
score: 0
has body: If, for each matrice, you have a tuple (offrow, offcol), you could create your output directly by iterating over all your matrices: output = np.zeros((5,5)) matrices = [mat1, mat2, mat3] offsets = [(0, 0), (2, 2), (1, 0)] for m, o in zip(matrices, offsets): for i in range(3): for j in range(3): output[i + o[0], j + o[1]] += m[i,j] This avoids to create temporary 5x5 matrices, created from the 3x3 matrices. This will consume less memory but it might not be faster.
answers question: http://stackoverflow.com/q/50313616

http://stackoverflow.com/q/50366484
accepted answer: http://stackoverflow.com/a/50386374
downvote count: 0
has comment: http://stackoverflow.com/comment/87753537
has comment: http://stackoverflow.com/comment/87749309
tagged with: python
has answer: http://stackoverflow.com/a/50366567
tagged with: sorting
has answer: http://stackoverflow.com/a/50386374
favorite count: 0
has answer: http://stackoverflow.com/a/50519473
has answer: http://stackoverflow.com/a/62226240
type: Question
tagged with: algorithm
has title: Longest alphabetical substring - where to begin
answer count: 5
has body: I am working on the "longest alphabetical substring" problem from the popular MIT course. I have read a lot of the information on SO about how to code it but I'm really struggling to make the leap conceptually. The finger exercises preceding it were not too hard. I was wondering if anyone knows of any material out there that would really break down the problem solving being employed in this problem. I've tried getting out a pen and paper and I just get lost. I see people employing "counters" of sorts, or strings that contain the "longest substring so far" and when I'm looking at someone else's solution I can understand what they've done with their code, but if I'm trying to synthesize something of my own it's just not clicking. I even took a break from the course and tried learning via some other books, but I keep coming back to this problem and feel like I need to break through it. I guess what I'm struggling with is making the leap from knowing some Python syntax and tools to actually employing those tools organically for problem solving or "computing". Before anyone points me towards it, I'm aware of the course materials that are aimed at helping out. I've seen some videos that one of the TAs made that are somewhat helpful but he doesn't really break this down. I feel like I need to pair program it with someone or like... sit in front of a whiteboard and have someone walk me step by step and answer every stupid question I would have. For reference, the problem is as follows: Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc I know that it's helpful to post code but I don't have anything that…
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/50373820
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50366567

http://stackoverflow.com/comment/87750253
score: 0
type: Comment
has text: it works for me, but no need if `A[:]`. just adding `[:-1]` at the end should work, like `["_".join(map(str, i)) for i in list_A[:-1]]`
type: AnswerComment
comment on: http://stackoverflow.com/a/50366700

http://stackoverflow.com/q/50286363
upvote count: 2
has answer: http://stackoverflow.com/a/50286469
downvote count: 0
tagged with: flask
has title: Why does localhost:5000 not work in Flask Python?
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50286471
has body: I'm using flask app factory pattern like and have this helloworld.py file from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'This is the home page' if __name__=="__name__": app.run(debug=True) Then I run the app in Terminal : python helloworld.py (venv) C:\Users\Jayalakshmi.S1\myproject>python helloworld.py (venv) C:\Users\Jayalakshmi.S1\myproject> But when I go to http://localhost:5000 it doesn't work. It says: Can’t reach this page Make sure the web address http://127.0.0.1:5000 is correct What could be wrong?
tagged with: python
score: 2
answer count: 2

http://stackoverflow.com/q/50338607
score: 0
has comment: http://stackoverflow.com/comment/87734871
has answer: http://stackoverflow.com/a/50350791
has body: I am using seaborn and trying to create and then edit plots. I'm somewhat new to Python and what I'd like to do is something like this: 1) Create plot: g = sns.lmplot(x, y, df, hue=z); #with seaborn imported as sns 2) g.style = "whitegrid" #I know this cannot be done as written, but how? 3) g.Font = "times new roman" #Same comment... Anyway, I hope this makes sense. I appreciate the help.
tagged with: python
has title: Set axis properties after plot is created
type: Question
answer count: 2
tagged with: seaborn
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50354611
has comment: http://stackoverflow.com/comment/87694319
has comment: http://stackoverflow.com/comment/87711143

http://stackoverflow.com/comment/87656282
type: Comment
comment on: http://stackoverflow.com/q/50318247
type: QuestionComment
has text: @zindarod, cv2 returns a numpy array, matplotlib is a perfectly good image display and avoids some of the problems with imshow
score: 0

http://stackoverflow.com/comment/87529928
type: AnswerComment
score: 1
has text: I need to extract the tables in those links, so if you have another suggestion pelase tell me
comment on: http://stackoverflow.com/a/50255630
type: Comment

http://stackoverflow.com/comment/87523508
has text: your `re.findall` in `get_contents` returns nothing and therefore the `content` is empty and you cannot loop over it hence you get nothing
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50253011

http://stackoverflow.com/q/50368882
possible better answer: http://stackoverflow.com/a/50370499
has comment: http://stackoverflow.com/comment/87754431
score: 0
has comment: http://stackoverflow.com/comment/87755166
has answer: http://stackoverflow.com/a/50370499
type: Question
has body: I am creating a save/load system that uses CSV files. An average CSV save file would look like this: name1a,RGB,1,|[0, 0, 1]| name2a,RGB,1,|[0, 1, 0]| name3a,RGB,1,|[0, 1, 1]| name1b,RGB,2,|[0, 0, 1]| Head2b,RGB,2,|[0, 1, 0]| Head3b,RGB,2,|[0, 1, 1]| The last item between the |s refers to a code, and is stored as one item (the |s make a string literal rather than 3 items). I'm saving the files like this: writer.writerow(name, type, slaveNumber, '|' + str(fix.code) + '|']) where code is a list such as [0, 1, 1]. I expected to get something like this: Head3b,RGB,2,|[0, 1, 1]| but instead I get: Head3b,RGB,2,|"[0, 1, 1]"| How can I solve this?
has comment: http://stackoverflow.com/comment/87756399
answer count: 2
has title: Python: Prevent quotes being written to CSV
has answer: http://stackoverflow.com/a/50369759
tagged with: python
accepted answer: http://stackoverflow.com/a/50369759
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/50286215
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50285820
score: 2
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50285820
downvote count: 1
type: Answer
has body: If you look at the source code for plot , it goes something like this: def plot(*args, **kwargs): ... The documentation does it make it clear that x,y arrays are mandatory , but if you pass x=[],y=[] , the plot function would recognise them as parts of kwargs and not the args. Plot expects two arrays as direct arguments without which it returns an empty object set. These links would tell you more about them: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ https://www.geeksforgeeks.org/args-kwargs-python/

http://stackoverflow.com/comment/87585635
has text: I recommend you to change the regex to: re.split('(?<!,),(?!,)', text) , it's more general ..
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50282531

http://stackoverflow.com/comment/87572634
has text: Apparently i don't have permission to edit your answer. Anyways, your code doesn't compile for noobs since you need to change your 2nd last line to `output.append(tmp_arr)`
type: AnswerComment
comment on: http://stackoverflow.com/a/50277906
score: 0
type: Comment

http://stackoverflow.com/q/50242565
has answer: http://stackoverflow.com/a/50242715
tagged with: python
has body: I've got some Python code that needs to call an .sh script that lives in a different directory and pass a couple variables to it. It's in a .py file that's part of a Flask path for an API. subprocess.call(shlex.split('script_name.sh {} {}'.format(var1,var2))) It works if I copy the code to a separate .py file and run it directly from a venv when I'm in the directory where the .py file lives AND I include an os.chdir line in that file: os.chdir('/path/to/sh_script_dir') OR if I cd into the directory where the .sh script lives and call it directly using &gt;&gt; python /path/to/py_file.py In the latter case, the os.chdir is not needed. However, when I call it from Flask (by hitting the API path for it, like a "real" user) I get: Exception class: builtins.FileNotFoundError Exception message: [Errno 2] No such file or directory: 'script_name.sh' This error happens whether I define the absolute path to the script in that line or not. I think it's because it's ultimatley being called from the main Flask api.py, which is in whatever working directory it's in, and it's ignoring the os.chdir command. I know there's another way to do this, with "cwd" but I couldn't get it to work. I've tried many variations on the following but nothing works: subprocess.call(shlex.split('script_name.sh {} {}'.format(var1,var2), cwd = '/path/to/sh_script_dir')) subprocess.call(shlex.split('script_name.sh {} {}'.format(var1,var2)), cwd = '/path/to/sh_script_dir') subprocess.call([shlex.split('script_name.sh {} {}'.format(var1,var2))], cwd = '/path/to/sh_script_dir') subprocess.call([shlex.split('script_name.sh {} {}'.format(var1,var2)], cwd = '/path/to/sh_script_dir')) Do I need to define the change in working dir one level up, in the Flask route? Side note is that I'm not entirely sure the shlex.split is needed here but it didn't work without it, then it did, so I left it. I can provide more code/info but the problem seems to be very specific to getting this function to run as if the current w…
has comment: http://stackoverflow.com/comment/87502933
tagged with: flask
has comment: http://stackoverflow.com/comment/87502907
has comment: http://stackoverflow.com/comment/87502919
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87503003
tagged with: subprocess
has comment: http://stackoverflow.com/comment/87502954
upvote count: 3
has comment: http://stackoverflow.com/comment/87503179
has comment: http://stackoverflow.com/comment/87502989
favorite count: 0
type: Question
has title: Python - Change working directory in subprocess.call syntax
accepted answer: http://stackoverflow.com/a/50242715
has comment: http://stackoverflow.com/comment/87503239
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50271308
tagged with: video-streaming
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87559810
linked to: http://stackoverflow.com/q/47037987
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/87578853
linked to: http://stackoverflow.com/q/46219454
has title: Streaming my camera's output to another PC in the same network Python
tagged with: opencv
score: 0
answer count: 0
has body: I'm looking for a method to stream my PC's camera to another PC in the same network using Python. I thought about using OpenCV module to capture my camera's output and then to serialize the 3 dimensional array to bytes and sending it using sockets but the thing is that this is a lot of bytes to send. For example if I reduce the camera's output to 480* 640 every frame is 480*640*3 bytes( The 3 is for RGB) . I can optimize this if I use a gray scale video. Any other ideas that are not sockets ?
type: Question

http://stackoverflow.com/comment/87786155
type: AnswerComment
comment on: http://stackoverflow.com/a/50380962
score: 0
has text: This is a good alternative but then it would print `Choose 0: ` twice. Once when `input()` gets called and the second time when `print()` gets called.
type: Comment

http://stackoverflow.com/a/50369309
score: 0
answers question: http://stackoverflow.com/q/50369108
type: AcceptedAnswer
has body: Add at the top of your class: def __init__(self): self.data_list = None # initialises to None at class instantiation Then further down check whether it has been assigned before using it: ... if self.data_list: do_something()
type: Answer
accepted answer of: http://stackoverflow.com/q/50369108

http://stackoverflow.com/a/50797726
type: AcceptedAnswer
has body: I declared the variables as Decimal in MySQL, that leads python to accept the right value. Unfortunately I cant explain why it doesnt work if I declare them as Float
score: 0
accepted answer of: http://stackoverflow.com/q/50384795
type: Answer
answers question: http://stackoverflow.com/q/50384795

http://stackoverflow.com/comment/87619160
comment on: http://stackoverflow.com/q/50300496
type: Comment
has text: Then read one line at a time in the file, replace each string in that line, and write the new line to a new file. Now your problem is broken into subproblems which all have standard, easily searchable solutions.
type: QuestionComment
score: 0

encryption
tags question: http://stackoverflow.com/q/50347502
tags question: http://stackoverflow.com/q/50321667
tag name: encryption
tags question: http://stackoverflow.com/q/50271956
tags question: http://stackoverflow.com/q/50319454
tags question: http://stackoverflow.com/q/50265299
type: Tag

computer-vision
tags question: http://stackoverflow.com/q/50239066
tags question: http://stackoverflow.com/q/50231968
tags question: http://stackoverflow.com/q/50355859
tags question: http://stackoverflow.com/q/50277397
tags question: http://stackoverflow.com/q/50268092
tags question: http://stackoverflow.com/q/50295442
tags question: http://stackoverflow.com/q/50351248
tags question: http://stackoverflow.com/q/50297176
tags question: http://stackoverflow.com/q/50233954
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/50273650
tags question: http://stackoverflow.com/q/50364235

http://stackoverflow.com/a/50312449
has body: By default the exec command is used to execute the commands in build systems, and the exec command doesn't buffer output at all. There is more information in this answer (which also provides a version of exec that does line buffering) but in short exec launches one thread to handle stdout and one to handle stderr, and both forward whatever data they get to the panel as soon as they get it. As such, a problem like the one you're describing here is generally caused by the program doing it's own buffering. Depending on the language and platform that you're using, buffering may change from what you expect in unexpected ways: For example, see this text in the man page for stdout under Linux: The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed. This can produce unexpected results, especially with debugging output. In the general case, the solution to this problem would be to modify the program itself to ensure that it's not buffering, and how you would do that depends on the language you're using and the platform that you're on. It could be something as simple as setting an environment variable or as complex as startup code that ensures that regardless of circumstance buffering is set as you expect it to be. In the specific case of Python, the -u command line argument to the interpreter tells Python to keep things unbuffered: -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u' The Python.sublime-build that ships with Sublime uses this argument to the python command to ensure that the output is unbuffered, and using that build system works as expected for your sample program. I don't use the Anaconda package so I'm not sure if it provides it's own build systems or not, but you may want to check the build command that you're using to ensure that it uses -u.
answers question: http://stackoverflow.com/q/50296736
type: Answer
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50296736

http://stackoverflow.com/comment/87777101
score: 0
type: Comment
type: QuestionComment
has text: `u'Hello world こんにちは世界'` — this is not "UTF-16". It's just Unicode.
comment on: http://stackoverflow.com/q/50380017

http://stackoverflow.com/comment/87733802
comment on: http://stackoverflow.com/q/50358113
has text: When I try: pip install --upgrade setuptools pip , I get this: Can't roll back setuptools; was not uninstalled
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87766901
has text: What does `x[0]` represent? The first data point or a list of data points?
comment on: http://stackoverflow.com/q/50375207
score: 0
type: Comment
type: QuestionComment

virtualenv
tags question: http://stackoverflow.com/q/50232207
tags question: http://stackoverflow.com/q/50252090
tags question: http://stackoverflow.com/q/50274273
tag name: virtualenv
tags question: http://stackoverflow.com/q/50363356
tags question: http://stackoverflow.com/q/50238800
tags question: http://stackoverflow.com/q/50301939
tags question: http://stackoverflow.com/q/50335676
tags question: http://stackoverflow.com/q/50238512
tags question: http://stackoverflow.com/q/50355080
tags question: http://stackoverflow.com/q/50346369
tags question: http://stackoverflow.com/q/50241308
tags question: http://stackoverflow.com/q/50337837
tags question: http://stackoverflow.com/q/50374464
tags question: http://stackoverflow.com/q/50245041
tags question: http://stackoverflow.com/q/50264229
tags question: http://stackoverflow.com/q/50232728
type: Tag
tags question: http://stackoverflow.com/q/50264760
tags question: http://stackoverflow.com/q/50235010
tags question: http://stackoverflow.com/q/50295727

http://stackoverflow.com/comment/87551719
type: QuestionComment
comment on: http://stackoverflow.com/q/50262913
score: 0
has text: They are similar but not the same. That's why it may cause problems. As for now, I'd say try either one and see if that solves your problem first.
type: Comment

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

http://stackoverflow.com/q/50289650
has comment: http://stackoverflow.com/comment/87595309
score: 0
tagged with: jmeter
tagged with: performance-testing
answer count: 1
has comment: http://stackoverflow.com/comment/87595600
type: Question
type: UnansweredQuestion
has title: Module ImportError in running Python Script in JMeter
has answer: http://stackoverflow.com/a/50325487
tagged with: python
has body: I would like to use python scripts in Jmeter, so I can check the Load and the performance of an application...for that I've created a Thread with JSR223 Sampler, and I put the content of python script, and after the run, Jmeter throws error like : File "", line 8, in ImportError: No module named opcua, ModuleNotFoundError: No module named 'dateutil' see snapshot: I don't know how to install this modules (package)in Jmeter, with PyCharm, I installed the package in the Project Interpreter under the setting see the snapshot...

http://stackoverflow.com/comment/87833449
type: Comment
type: AnswerComment
has text: Why do i need the dependencies installed, in order to approach a running app via a CLI? doesn't it work the same as a restful API would? approach via a port?
score: 0
comment on: http://stackoverflow.com/a/50291559

http://stackoverflow.com/comment/87663310
score: 0
type: Comment
has text: Hi, I not try to sort by area.
comment on: http://stackoverflow.com/a/50323391
type: AnswerComment

http://stackoverflow.com/q/50302222
has comment: http://stackoverflow.com/comment/87631363
has comment: http://stackoverflow.com/comment/87631672
has comment: http://stackoverflow.com/comment/87632266
has comment: http://stackoverflow.com/comment/87633515
type: Question
has comment: http://stackoverflow.com/comment/87620939
has comment: http://stackoverflow.com/comment/87633740
has comment: http://stackoverflow.com/comment/87633914
type: UnansweredQuestion
tagged with: google-text-to-speech
tagged with: python
has body: I have been working on trying to code a AI assistant in python. But when i try to install gTTs or basically anything, it would say, Could not find a version that satisfies the requirement gTTs (from versions: ) No matching distribution found for gTTs. I have tried pip install, sudo pip install, and other things i cannot remember. If somone could help me with this issue, that would be great. Thanks
tagged with: artificial-intelligence
has title: Could not find a version that satisfies the requirement gTTs (from versions: ) No matching distribution found for gTTs
score: 0
has comment: http://stackoverflow.com/comment/87635627
has comment: http://stackoverflow.com/comment/87633775
has answer: http://stackoverflow.com/a/73002272
has comment: http://stackoverflow.com/comment/87633382
answer count: 1
has comment: http://stackoverflow.com/comment/87631962

http://stackoverflow.com/q/50313785
downvote count: 0
has answer: http://stackoverflow.com/a/50313811
has comment: http://stackoverflow.com/comment/87643573
accepted answer: http://stackoverflow.com/a/50313811
score: 1
upvote count: 1
favorite count: 0
has body: I am trying to insert "\n" when ever I am finding Google. Google(12,AB12,XYZ,A2) Note: the Parameters inside Google is dynamic. What I have tried: Str=re.sub(r"Google(.*)",r"Google(.*)\n",str) Currently I am getting as: Google(.*) followed by newline What I want is: Google(12,AB12,XYZ,A2) followed by newline
type: Question
has answer: http://stackoverflow.com/a/50313828
has title: Any reason why this substitution is not working- python
has answer: http://stackoverflow.com/a/50313812
possible better answer: http://stackoverflow.com/a/50313812
tagged with: python
has comment: http://stackoverflow.com/comment/87643587
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/50232762
downvote count: 0
has comment: http://stackoverflow.com/comment/87483119
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50232902
tagged with: scheduler
has answer: http://stackoverflow.com/a/50233059
has answer: http://stackoverflow.com/a/50232902
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1186789
answer count: 3
has answer: http://stackoverflow.com/a/50232913
score: 1
has title: Python schedule with commandline
favorite count: 0
tagged with: command-line
type: Question
accepted answer: http://stackoverflow.com/a/50232913
has body: I have this problem that I want to automate a script. And in passed projects I've used python scheduler for this. But for this project I'm unsure how to handle this. The problem is that the code works with login details that are outside the code and entered in the commandline when launching the script. ex. python scriptname.py email@youremail.com password How can I automate this with python scheduler? The code that is in 'scriptname.py' is: //LinkedBot.py import argparse, os, time import urlparse, random from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup def getPeopleLinks(page): links = [] for link in page.find_all('a'): url = link.get('href') if url: if 'profile/view?id=' in url: links.append(url) return links def getJobLinks(page): links = [] for link in page.find_all('a'): url = link.get('href') if url: if '/jobs' in url: links.append(url) return links def getID(url): pUrl = urlparse.urlparse(url) return urlparse.parse_qs(pUrl.query)['id'][0] def ViewBot(browser): visited = {} pList = [] count = 0 while True: #sleep to make sure everything loads, add random to make us look human. time.sleep(random.uniform(3.5,6.9)) page = BeautifulSoup(browser.page_source) people = getPeopleLinks(page) if people: for person in people: ID = getID(person) if ID not in visited: pList.append(person) visited[ID] = 1 if pList: #if there is people to look at look at them person = pList.pop() browser.get(person) count += 1 else: #otherwise find people via the job pages jobs = getJobLinks(page) if jobs: job = random.choice(jobs) root = 'http://www.linkedin.com' roots = 'https://www.linkedin.com' if root not in job or roots not in job: job = 'https://www.linkedin.com'+job browser.get(job) else: print "I'm Lost Exiting" break #Output (Make option for this) print "[+] "+browser.title+" Visited! \n("\ +str(count)+"/"+str(len(pList))+") Visited/Queue)" def Main(): parser = argparse.ArgumentParser() parser.add_argument("email", help="li…

http://stackoverflow.com/q/50365289
tagged with: django-rest-framework
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87746853
has comment: http://stackoverflow.com/comment/87749250
score: 5
tagged with: django-views
has comment: http://stackoverflow.com/comment/87754050
type: UnansweredQuestion
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87751600
has answer: http://stackoverflow.com/a/50369693
has title: Update Nested Serializers Correctly in Django Rest Framework
answer count: 1
downvote count: 0
tagged with: django
has body: I am using django rest framework I am trying to implement an update method to a nested serializer. How do I implement an update method to nested serializer correctly? I'm trying to update an existing employee but I get the following response: { "user": { "username": [ "A user with that username already exists." ] } } I have implemented an update method on the serializers just to update the user fields. class EmployeeUpdateSerializer(serializers.ModelSerializer): user = UserSerializer() contract_type = ContractSerializer(read_only=True) company = CompanySerializer(read_only=True) job_title = JobSerializer(read_only=True) department = DepartmentSerializer(read_only=True) skill = SkillSerializer(read_only=True) unit = UnitSerializer(read_only=True) class Meta: model = Employee fields = ['id', 'user', 'hr_number', 'nssf_no', 'nhif_no', 'induction_date', 'induction_date', 'contract_type', 'company', 'tax_id_number', 'joining_date', 'job_title', 'skill', 'unit', 'department', 'identification_number', 'is_manager', 'active'] def update(self, instance, validated_data): user = validated_data.get('user') instance.user.first_name = user.get('first_name') instance.user.save() return instance Then in the views I have implemented the following: class EmployeeDetailView(APIView): permission_classes = [AllowAny] # queryset = Employee.objects.all() serializer_class = EmployeeUpdateSerializer """ Retrieve, update or delete a employee instance. """ def get(self, request, pk, format=None): try: employee = Employee.objects.get(pk=pk) except Employee.DoesNotExist: raise Http404 serializer = EmployeeUpdateSerializer(employee) return Response(serializer.data, status=status.HTTP_200_OK) def put(self, request, pk, format=None): try: employee = Employee.objects.get(pk=pk) serializer = EmployeeUpdateSerializer( employee, data=request.data) except Employee.DoesNotExist: raise Http404 # serializer = EmployeeUpdateSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) seri…

http://stackoverflow.com/q/50319454
score: 0
tagged with: encryption
tagged with: powershell
has body: I am working on a project where I will be encrypting a string of data using the AES module from PyCrypto and then decrypting it using Powershell. I've written a simple encryption function to do what I need here: import base64 from Crypto import Random from Crypto.Cipher import AES key = "SuperSecret" #Insecure and just for testing plaintext = "Secret message please don't look" BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) def padKey(s): #Pad key to 32 bytes for AES256 return (s * (int(32/len(s))+1))[:32] class AESCipher: def __init__(self, key): self.key = key def encrypt(self, raw): raw = pad(raw) iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key, AES.MODE_CBC, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ) paddedKey = padKey(key) cipher = AESCipher(paddedKey) encrypted = str(cipher.encrypt(plaintext)) encrypted = encrypted[2:-1] print("Key:", paddedKey) print("Plaintext:",plaintext) print("Encrypted and B64:",encrypted) I am having some issues with decrypting and decoding the output with Powershell and could use some help. I was able to find a simple decryption script that I've been working with online, but the output is all garbage: function Create-AesManagedObject($key, $IV) { $aesManaged = New-Object "System.Security.Cryptography.AesManaged" $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros $aesManaged.BlockSize = 128 $aesManaged.KeySize = 256 if ($IV) { if ($IV.getType().Name -eq "String") { $aesManaged.IV = [System.Convert]::FromBase64String($IV) } else { $aesManaged.IV = $IV } } if ($key) { if ($key.getType().Name -eq "String") { $aesManaged.Key = [System.Convert]::FromBase64String($key) } else { $aesManaged.Key = $key } } $aesManaged } function Decrypt-String($key, $encryptedStringWithIV) { $bytes = [System.Convert]::FromBase64String($encryptedStringWithIV) $IV = $bytes[0..15] $aesManaged = Create-AesManagedObject $k…
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50340315
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50340315
linked to: http://stackoverflow.com/q/48292315
has comment: http://stackoverflow.com/comment/87693396
has comment: http://stackoverflow.com/comment/87696708
has title: Decrypting AES CBC data from PyCrypto with Powershell
has comment: http://stackoverflow.com/comment/87693849
has answer: http://stackoverflow.com/a/50323051
tagged with: python
tagged with: pycrypto
favorite count: 0
has comment: http://stackoverflow.com/comment/87682804
tagged with: aes
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50323051

http://stackoverflow.com/comment/87764955
type: Comment
has text: @Benjamin - i test it by `df1 = pd.read_csv('Best_blast_candidate_hit_0042.csv') print (df1.head())` and `df2 = pd.read_csv('Dataframe_HGT_candidates_filtered.csv', sep='\t')` and `a = df1[df1['#qseqid'].isin(df2['seq2_id'])]`
type: AnswerComment
comment on: http://stackoverflow.com/a/50370450
score: 0

http://stackoverflow.com/comment/87537884
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50259184
has text: im aware of this but i ll like to tell pandas to ignore everything in between "

http://stackoverflow.com/comment/88054708
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50284020
type: AnswerComment
has text: Yes - my apologies - I am new to this site!

http://stackoverflow.com/a/50305544
has body: This list comprehension does the same as these two nested for loops: nonprime=[] for i in range(2,8): for j in range(i*2, 50,i): nonprime.append(j) So in the outer loop, i is just increased by one in every iteration, and takes on the values i=2,3,4,5,6,7. The inner for loop over j depends on the outer loop. It starts at 2*i and j is increased by i in each iteration. So for ì=2, the inner loop starts at j=4 and j takes on the values j=4,6,8,...,48. Then ì is increased to 3 in the outer loop and j takes on the values 6,9,12,...48 Notice that the nonprime list does not create unique elements, since for example the 6 appears more than once. As Bakuriu rightfully points out, this method makes use of the Sieve of Eratosthenes
score: 3
downvote count: 1
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/50305446

http://stackoverflow.com/a/50335517
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50265801
has body: I finally solved the problem by including a hidden filter_form in the search_form. So in _search.html, within the &lt;form&gt; tags, I added {% for field in filter_form %} {{ field.as_hidden }} {% endfor %} This makes use of the as_hidden property of the field.
score: 2
upvote count: 2

http://stackoverflow.com/comment/87723872
score: 0
has text: Yeah it printed 2.7.4...
comment on: http://stackoverflow.com/q/50351830
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87711682
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50346402
score: 0
has text: [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)

http://stackoverflow.com/a/50376586
has body: Your regex need to allow an and or end of string with a lazy quantifier. In your regex .* is greedy and would attempt to match longest string till end of string. Following regex should work for you: r'^.*foo=(.*?)(?:\sand|$)' Here is full code: &gt;&gt;&gt; s1 = 'quz=1, 2, 3 and foo=4, 5, 6 and bar=7, 8, 9' &gt;&gt;&gt; s2 = 'quz=1, 2, 3 and foo=4, 5, 6' &gt;&gt;&gt; p = r'^.*foo=(.*?)(?:\sand|$)' &gt;&gt;&gt; print re.findall(p, s1) ['4, 5, 6'] &gt;&gt;&gt; print re.findall(p, s2) ['4, 5, 6']
type: Answer
answers question: http://stackoverflow.com/q/50373123
score: 0

http://stackoverflow.com/a/50356976
has comment: http://stackoverflow.com/comment/87752959
has comment: http://stackoverflow.com/comment/87753185
has comment: http://stackoverflow.com/comment/87730533
type: Answer
has comment: http://stackoverflow.com/comment/87731747
score: 1
downvote count: 0
upvote count: 1
has body: The following should work: python -m venv --without-pip my_venv_name The options are documented here
has comment: http://stackoverflow.com/comment/87800159
has comment: http://stackoverflow.com/comment/87750364
has comment: http://stackoverflow.com/comment/87730795
answers question: http://stackoverflow.com/q/50356887

http://stackoverflow.com/q/50325786
score: 18
tagged with: confusion-matrix
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50329263
has answer: http://stackoverflow.com/a/50326051
has answer: http://stackoverflow.com/a/50325898
tagged with: machine-learning
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50329263
has answer: http://stackoverflow.com/a/60540583
has title: Sci-kit learn how to print labels for confusion matrix?
favorite count: 0
has body: So I'm using sci-kit learn to classify some data. I have 13 different class values/categorizes to classify the data to. Now I have been able to use cross validation and print the confusion matrix. However, it only shows the TP and FP etc without the classlabels, so I don't know which class is what. Below is my code and my output: def classify_data(df, feature_cols, file): nbr_folds = 5 RANDOM_STATE = 0 attributes = df.loc[:, feature_cols] # Also known as x class_label = df['task'] # Class label, also known as y. file.write("\nFeatures used: ") for feature in feature_cols: file.write(feature + ",") print("Features used", feature_cols) sampler = RandomOverSampler(random_state=RANDOM_STATE) print("RandomForest") file.write("\nRandomForest") rfc = RandomForestClassifier(max_depth=2, random_state=RANDOM_STATE) pipeline = make_pipeline(sampler, rfc) class_label_predicted = cross_val_predict(pipeline, attributes, class_label, cv=nbr_folds) conf_mat = confusion_matrix(class_label, class_label_predicted) print(conf_mat) accuracy = accuracy_score(class_label, class_label_predicted) print("Rows classified: " + str(len(class_label_predicted))) print("Accuracy: {0:.3f}%\n".format(accuracy * 100)) file.write("\nClassifier settings:" + str(pipeline) + "\n") file.write("\nRows classified: " + str(len(class_label_predicted))) file.write("\nAccuracy: {0:.3f}%\n".format(accuracy * 100)) file.writelines('\t'.join(str(j) for j in i) + '\n' for i in conf_mat) #Output Rows classified: 23504 Accuracy: 17.925% 0 372 46 88 5 73 0 536 44 317 0 200 127 0 501 29 85 0 136 0 655 9 154 0 172 67 0 97 141 78 1 56 0 336 37 429 0 435 198 0 135 74 416 5 37 0 507 19 323 0 128 164 0 247 72 145 12 64 0 424 21 296 0 304 223 0 190 41 36 0 178 0 984 29 196 0 111 43 0 218 13 71 7 52 0 917 139 177 0 111 103 0 215 30 84 3 71 0 1175 11 55 0 102 62 0 257 55 156 1 13 0 322 184 463 0 197 160 0 188 36 104 2 34 0 313 99 827 0 69 136 0 281 80 111 22 16 0 494 19 261 0 313 211 0 207 66 87 18 58 0 489 23 157 0 464 239 0 …
accepted answer: http://stackoverflow.com/a/50326049
type: Question
has answer: http://stackoverflow.com/a/50326049
downvote count: 0
tagged with: python
answer count: 5
upvote count: 18

http://stackoverflow.com/q/50361361
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87739819
has answer: http://stackoverflow.com/a/50361655
tagged with: python
has comment: http://stackoverflow.com/comment/108899557
upvote count: 3
score: 3
tagged with: python-2.7
linked to: http://stackoverflow.com/q/49656725
downvote count: 0
has title: tensorflow-gpu 1.8.0 ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory
has body: I've just installed Ubuntu 18.04 NVIDIA GPU driver 390 CUDA Toolkit version 9.0 (with all the patches) CUDNN 7.0.5 followed this link https://github.com/markjay4k/Install-Tensorflow-on-Ubuntu-17.10-/blob/master/Tensorflow%20Install%20instructions.ipynb and instead of conda for tensorflow installation I've used Virtualenv and after installation, I couldn't import tensorflow module in python due to this error Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/home/kai/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory but I think I correctly put those at the right place like below show $ cd /usr/…
answer count: 1

linux
tags question: http://stackoverflow.com/q/50283776
tags question: http://stackoverflow.com/q/50366257
tags question: http://stackoverflow.com/q/50235516
tags question: http://stackoverflow.com/q/50235375
tags question: http://stackoverflow.com/q/50243536
tag name: linux
tags question: http://stackoverflow.com/q/50301570
tags question: http://stackoverflow.com/q/50287470
tags question: http://stackoverflow.com/q/50300745
tags question: http://stackoverflow.com/q/50356224
tags question: http://stackoverflow.com/q/50241308
tags question: http://stackoverflow.com/q/50372075
tags question: http://stackoverflow.com/q/50252213
tags question: http://stackoverflow.com/q/50297563
tags question: http://stackoverflow.com/q/50343886
tags question: http://stackoverflow.com/q/50284343
tags question: http://stackoverflow.com/q/50270685
tags question: http://stackoverflow.com/q/50362727
tags question: http://stackoverflow.com/q/50258986
tags question: http://stackoverflow.com/q/50365268
tags question: http://stackoverflow.com/q/50347675
tags question: http://stackoverflow.com/q/50354231
tags question: http://stackoverflow.com/q/50283958
type: Tag
tags question: http://stackoverflow.com/q/50241937
tags question: http://stackoverflow.com/q/50384771
tags question: http://stackoverflow.com/q/50334443
tags question: http://stackoverflow.com/q/50337172
tags question: http://stackoverflow.com/q/50325752

http://stackoverflow.com/q/50284174
has body: I want a dictionary with default to None. I have two ways to implement: 1) use collections.defaultdict and set default value to None. https://docs.python.org/2/library/collections.html 2) use an ordinary dictionary but use .get() to get the value. When the key does not exist, by default it returns None. Which way is better?
possible better answer: http://stackoverflow.com/a/50284256
has title: using python default dictionary vs .get()
linked to: http://stackoverflow.com/q/7423428
tagged with: python
tagged with: dictionary
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/50284256
downvote count: 1
has answer: http://stackoverflow.com/a/50289178
accepted answer: http://stackoverflow.com/a/50289178
has comment: http://stackoverflow.com/comment/87584678
favorite count: 0
has comment: http://stackoverflow.com/comment/87584646
type: Question

http://stackoverflow.com/q/50259649
has comment: http://stackoverflow.com/comment/87537197
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87537401
tagged with: decode
score: 0
has answer: http://stackoverflow.com/a/50259920
has title: b64decode on json import reading data incorrectly
answer count: 1
tagged with: python-3.x
linked to: http://stackoverflow.com/q/31658115
has body: I am importing json data from github for a class, and when I try to convert to a dictionary the values are not staying in key-value pairs. Here is the import: from pprint import pprint as pp import base64 response = requests.get('https://api.github.com/repos/bsullins/data/contents/MonthlySales.csv') response_json = json.loads(response.text) csv_val = base64.b64decode(response_json['content']) pp(csv_val) The result of this has the original data, although I'm not sure what the "\r\n" delimiters are. Clearly it did not import correctly, as the strings cut off at different points than they should. (b'month,sales\r\n2013-01-01,14236.9\r\n2013-02-01,4519.89\r\n2013-03-01,5569' b'1.01\r\n2013-04-01,28295.35\r\n2013-05-01,23648.29\r\n2013-06-01,34595.13\r' b'\n2013-07-01,33946.39\r\n2013-08-01,27909.47\r\n2013-09-01,81777.35\r\n2013' b'-10-01,31453.39\r\n2013-11-01,78628.72\r\n2013-12-01,69545.62\r\n2014-01-0' b'1,18174.08\r\n2014-02-01,11951.41\r\n2014-03-01,38726.25\r\n2014-04-01,341' b'95.21\r\n2014-05-01,30131.69\r\n2014-06-01,24797.29\r\n2014-07-01,28765.33' When I later try to read the data with DictReader, it parses everything letter by letter: import csv csv_dict = csv.DictReader(str(csv_val)) dict_list = [] for a in csv_dict: dict_list.append(a): for a in dict_list: print(a) Here is the result: OrderedDict([('b', "'")]) OrderedDict([('b', 'm')]) OrderedDict([('b', 'o')]) OrderedDict([('b', 'n')]) OrderedDict([('b', 't')]) OrderedDict([('b', 'h')]) OrderedDict([('b', ''), (None, [''])]) OrderedDict([('b', 's')]) OrderedDict([('b', 'a')]) OrderedDict([('b', 'l')]) OrderedDict([('b', 'e')]) OrderedDict([('b', 's')]) OrderedDict([('b', '\\')]) OrderedDict([('b', 'r')]) OrderedDict([('b', '\\')]) OrderedDict([('b', 'n')]) OrderedDict([('b', '2')]) OrderedDict([('b', '0')]) OrderedDict([('b', '1')]) OrderedDict([('b', '3')]) OrderedDict([('b', '-')]) OrderedDict([('b', '0')]) OrderedDict([('b', '1')]) OrderedDict([('b', '-')]) OrderedDict([('b', '0')]) OrderedDict([('b'…
type: Question
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/50366626
tagged with: tensorflow
type: Question
has title: CNN model on Rapberry Pi
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/87749684
has body: I am working on a project that involves glaucoma detection on the Raspberry pi 3B. The model was trained on my laptop and is around 400mb ".h5" file. I am trying to load the model onto the pi using keras The pi seems to load other smaller models but is showing up this error with mine: 2018-05-15 18:07:04.117054: W tensorflow/core/framework/allocator.cc:101] Allocation of 134217728 exceeds 10% of system memory. 2018-05-15 18:07:05.052281: W tensorflow/core/framework/allocator.cc:101] Allocation of 134217728 exceeds 10% of system memory. 2018-05-15 18:07:05.513437: W tensorflow/core/framework/allocator.cc:101] Allocation of 134217728 exceeds 10% of system memory. 2018-05-15 18:07:06.191609: W tensorflow/core/framework/allocator.cc:101] Allocation of 134217728 exceeds 10% of system memory. Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1322, in _do_call return fn(*args) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1307, in _run_fn options, feed_dict, fetch_list, target_list, run_metadata) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1409, in _call_tf_sessionrun run_metadata) tensorflow.python.framework.errors_impl.InternalError: Could not allocate ndarray 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 "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 273, in load_model topology.load_weights_from_hdf5_group(f['model_weights'], model.layers) File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 3393, in load_weights_from_hdf5_group K.batch_set_value(weight_value_tuples) File "/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py", line 2377, in batch_set_value get_session().run(assign_ops, feed_dict=feed_dict) File "/usr/local/lib/python3.5/dist-pac…
tagged with: machine-learning
tagged with: python
tagged with: keras
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50377239
has answer: http://stackoverflow.com/a/50377239

http://stackoverflow.com/q/50305423
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50309978
accepted answer: http://stackoverflow.com/a/50309978
has answer: http://stackoverflow.com/a/70881279
possible better answer: http://stackoverflow.com/a/70881279
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Shortest Time Remaining Next (STRN) Scheduling
score: 3
tagged with: job-scheduling
tagged with: algorithm
tagged with: operating-system
tagged with: python
linked to: http://stackoverflow.com/q/5440128
has body: Another user posted this question on Shortest Job First (SJF). Here's the example: How would this be solved for Shortest Remaining Time Next? The preemptive version of Shortest Job First. I understand that the process with smallest amount of time remaining until completion is selected to execute. However, what happens if a new process arrives that has a burst time that is exactly the same as the remaining completion time of the currently executing process? In the instance that a new process arrives that has a burst time that is the same as the current executing process (as evident in this example), then does the process currently executing continue? Gantt chart showing how I understand the processes would be scheduled: Am I correct in my understanding? Thank you in advance.
answer count: 2
tagged with: scheduling

http://stackoverflow.com/comment/87735305
has text: This is indeed the case with feature_importances_. The problem is that the Tree object itself has a few read-only properties that are populated when the model is trained. I haven't figured out yet how to establish the Tree object persistence without using pickle or joblib. Populating the non read-only attributes and then calling the getters produced incorrect values.
score: 0
comment on: http://stackoverflow.com/q/50312012
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87729660
comment on: http://stackoverflow.com/a/50343011
type: Comment
has text: You are doing unnecessary conditional checks then, and if branch prediction can't catch that then you might unnecessarily slow down a project if number of conditionals is scaled up
type: AnswerComment
score: 0

http://stackoverflow.com/q/50356711
has answer: http://stackoverflow.com/a/50357266
tagged with: python
has title: matplotlib barplot not working with logarithmic scale
has body: I am trying to do a barplot in Matplotlib in logarithmic scale. If I do this manually (figure 3 below) I get the correct answer, but if I use matplotlib's set_yscale('log') or use the log attribute of the barplot, I get the wrong plot. So as you can see in figs 1 and 2, the plot is wrong, since log10(y2) = ([ 5.7363965 , 5.77815125]) Below is a MWE: from __future__ import division import numpy as np from matplotlib import pyplot as plt ind = np.array(['US', 'EU']) y2 = [545000, 600000] fig = plt.figure(1) ax = fig.add_subplot(1, 1, 1) plt.bar(ind, y2) ax.set_yscale('log') plt.title('example 1') #plt.savefig('../../Desktop/ex1.jpg') fig = plt.figure(2) ax2 = fig.add_subplot(1, 1, 1) plt.bar(ind, y2, log=True) plt.title('example2') #plt.savefig('../../Desktop/ex2.jpg') fig2 = plt.figure(3) ax1 = fig2.add_subplot(1, 1, 1) plt.bar(ind, np.log10(y2)) plt.title('example 3') #plt.savefig('../../Desktop/ex3.jpg') plt.show() and here are the figures:
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/50357266
favorite count: 0
type: Question

http://stackoverflow.com/comment/87497053
score: 0
comment on: http://stackoverflow.com/q/50239611
has text: But why can I retrieve pk outside the url but not inside?
type: QuestionComment
type: Comment

inheritance
tags question: http://stackoverflow.com/q/50358462
tags question: http://stackoverflow.com/q/50259824
tags question: http://stackoverflow.com/q/50336227
tags question: http://stackoverflow.com/q/50349653
tags question: http://stackoverflow.com/q/50288766
tag name: inheritance
tags question: http://stackoverflow.com/q/50260632
tags question: http://stackoverflow.com/q/50366434
tags question: http://stackoverflow.com/q/50276731
tags question: http://stackoverflow.com/q/50378906
type: Tag
tags question: http://stackoverflow.com/q/50297337

http://stackoverflow.com/q/50274268
tagged with: dataframe
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87565954
has comment: http://stackoverflow.com/comment/87566331
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50274601
score: 2
has comment: http://stackoverflow.com/comment/87565282
tagged with: pandas-groupby
tagged with: pandas
has title: Split data into continuous groups
has body: I am fairly new to coding so please bear with me. I have a pandas df with either a continuous sequence of positive or negative values or 0. df = x y 0 -5 25 1 -7 32 2 -3 33 3 0 22 4 1 16 5 6 10 6 3 36 7 0 22 8 0 55 9 -10 24 10 -9 32 11 -8 5 12 11 4 13 17 9 14 13 88 15 0 14 16 0 12 17 0 0 18 0 10 19 0 96 20 -1 492 21 -9 -440 22 -3 34 I want to break up this data like so: data1 = [-5 -7 -3 0] data2 = [1 6 3 0 0] data3 = [-10 -9 -8] data4 = [11 17 13 0 0 0 0 0] data5 = [-1 -9 -3] Where value 0 or any number of 0's together are placed with the values that preceded it and into sets that are negative or positive only. Any help or pointer in the right direction would be much appreciated.
has answer: http://stackoverflow.com/a/50274618

http://stackoverflow.com/q/50317827
tagged with: row
tagged with: textinput
tagged with: python
tagged with: bokeh
has body: I am looking for a workaround to an issue in Bokeh. When you put a button and a text input in a row- they will be un-alighned. This effect happens because the text input has a label and is described here: https://github.com/bokeh/bokeh/issues/4817 screenshot of messed up alignment Example code: # hello.py from bokeh.io import curdoc from bokeh.layouts import column, row from bokeh.models.widgets import TextInput, Button, Paragraph # create some widgets button = Button(label="Say HI") input = TextInput(value="Bokeh") output = Paragraph() # add a callback to a widget def update(): output.text = "Hello, " + input.value button.on_click(update) # create a layout for everything #layout = VBox(children=[HBox(children=[button, input]), output]) layout = column(row(button, input), output) # add the layout to curdoc curdoc().add_root(layout)
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50324196
answer count: 1
tagged with: button
has title: bokeh layout vertical alignment with buttons
score: 0

http://stackoverflow.com/comment/87486738
type: AnswerComment
comment on: http://stackoverflow.com/a/50234555
score: 1
type: Comment
has text: You can even remove the braces and collect only the words between the braces by using parentheses `re.findall('\{(.*?)\}', string1)`

http://stackoverflow.com/q/50266753
score: 0
tagged with: tensorflow-lite
has title: How and when does quantization work in a TFLite Graph?
tagged with: python
has answer: http://stackoverflow.com/a/52787541
has body: I have a TF model which was trained with quantization, frozen, converted to tflite with TOCO, and now I have the TFLite HTML Graph Model and json. I can see that, for each of the tensors in my graph, each have quantization attributes (min, max, scale, zero-pt), and I'm trying to determine how each of these attributes applies to each tensor. For instance, I understand the representation of quantized data, and I can understand that taking the quantized weights/biases, multiplying by scale and adding the minimum value returns the original weights/biases (almost). What I don't understand: Why do some tensors have quantization attributes (eg Relu, Sigmoid) but no intrinsic parameters (like weights and biases do)? Is it because they are output tensors and the quantization is applied before the data is input into the next operation? At what points (if any) are the quantization applied during the dataflow through the model? For example, say there is an image tensor of floats passed a conv2d operation - where and how are the quantization attributes of weights/bias/relu used to get the output of the conv2d operation? Essentially, If I parsed the TFLite models data to a numpy array, what are all the things I'd need to know about the flow of the data through the network (with respect to quantization) in order to recreate the model for inference from scratch. I can't seem to find any documentation regarding this. Any help would be appreciated.
accepted answer: http://stackoverflow.com/a/52787541
type: AnsweredQuestion
answer count: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/88635496
has text: ValueError: Unsupported type <class 'NoneType'> for value None on elem <Element 'm:ParentFolderId' at 0x000000000C03CEF8>, I've already upgraded exchangelib to 1.11.4
type: Comment
comment on: http://stackoverflow.com/a/50407053
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87774635
type: Comment
has text: I am running all within the same environment, I think. Both are in the same folder and in each terminal, I am starting a virtual environment before running main_test.py and stest.py . If this is actually starting two different environments I see the problem, but then how do I make sure they are running in the same env?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50377986

http://stackoverflow.com/q/50281987
has comment: http://stackoverflow.com/comment/87588752
has comment: http://stackoverflow.com/comment/115790475
has comment: http://stackoverflow.com/comment/87733643
linked to: http://stackoverflow.com/q/36002296
tagged with: pygobject
has comment: http://stackoverflow.com/comment/87596941
has comment: http://stackoverflow.com/comment/87606837
has comment: http://stackoverflow.com/comment/87617084
score: 1
type: Question
has comment: http://stackoverflow.com/comment/87606322
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/87593660
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/40761906
has title: Different color for odd and even rows in a PyGObject TreeView
tagged with: treeview
tagged with: python
has body: I want two row colors in a Gtk.TreeView each for the odd and even rows. This minimal example run without errors but has no effect on the colors. #!/usr/bin/env python3 import datetime import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk class TreeView(Gtk.TreeView): def __init__(self): # model self.model = Gtk.ListStore.new([int]) for i in range(5): self.model.append([i]) # view Gtk.TreeView.__init__(self, self.model) # style css_provider = Gtk.CssProvider() css_provider.load_from_data(''' Gtk.TreeView row:nth-child(even) { background-color: #d0e4f7 } Gtk.TreeView row:nth-child(odd) { background-color: #fdffff } '''.encode('utf-8')) Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self.set_rules_hint(True) col = Gtk.TreeViewColumn('int', Gtk.CellRendererText(), text=0) self.append_column(col) class Window(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title='Mein Gtk-Fenster') self.set_default_size(100, 120) self.view = TreeView() self.add(self.view) self.connect('destroy', Gtk.main_quit) self.show_all() if __name__ == '__main__': win = Window() Gtk.main()
downvote count: 1
tagged with: gtk
favorite count: 0
duplicate of: http://stackoverflow.com/q/40761906

http://stackoverflow.com/comment/87671181
type: Comment
comment on: http://stackoverflow.com/q/50327432
type: QuestionComment
score: 0
has text: try with javascript executor

http://stackoverflow.com/comment/87736406
has text: the version appears in the log file `geckodriver INFO geckodriver 0.19.1`, maybe there is something to find from here ?
comment on: http://stackoverflow.com/a/50359621
type: AnswerComment
score: 1
type: Comment

doc2vec
tags question: http://stackoverflow.com/q/50264369
type: Tag
tags question: http://stackoverflow.com/q/50352777
tag name: doc2vec
tags question: http://stackoverflow.com/q/50362506
tags question: http://stackoverflow.com/q/50361783

http://stackoverflow.com/q/50372342
tagged with: class
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50372503
accepted answer: http://stackoverflow.com/a/50372383
has body: I have a class that has several methods which each have certain properties (in the sense of quality). I'd like these methods to be available in a list inside the class so they can be executed at once. Note that the properties can be interchangeable so this can't be solved by using further classes that would inherit from the original one. In an ideal world it would look something like this: class MyClass: def __init__(): red_rules = set() blue_rules = set() hard_rules = set() soft_rules = set() @red def rule_one(self): return 1 @blue @hard def rule_two(self): return 2 @hard def rule_three(self): return 3 @blue @soft def rule_four(self): return 4 When the class is instantiated, it should be easy to simply execute all red and soft rules by combining the sets and executing the methods. The decorators for this are tricky though since a regular registering decorator can fill out a global object but not the class attribute: def red(fn): red_rules.add(fn) return fn How do I go about implementing something like this?
has answer: http://stackoverflow.com/a/50372383
tagged with: python
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/50372503
has title: Class with a registry of methods based on decorators
downvote count: 0
upvote count: 1
tagged with: decorator
favorite count: 0

http://stackoverflow.com/a/50377342
has comment: http://stackoverflow.com/comment/87771321
has comment: http://stackoverflow.com/comment/87770979
has body: Use df.columns.str.split to generate a new MultiIndex Use prod with axis and level arguments Use sum with axis argument Use assign to create new column df.assign( Total=df.set_axis( df.columns.str.split('_', expand=True), axis=1, inplace=False ).prod(axis=1, level=0).sum(1) ) measure1_x measure2_x measure3_x measure1_y measure2_y measure3_y Total 0 10 11 10 1 1 1 31 1 12 12 0 2 1 0 36 2 20 10 12 2 1 2 74 3 30 3 1 3 3 1 100 4 21 3 1 1 3 1 31 Restrict dataframe to just columns that look like 'meausre[i]_[j]' df.assign( Total=df.filter(regex='^measure\d+_\w+$').pipe( lambda d: d.set_axis( d.columns.str.split('_', expand=True), axis=1, inplace=False ) ).prod(axis=1, level=0).sum(1) ) Debugging See if this gets you the correct Totals d_ = df.copy() d_.columns = d_.columns.str.split('_', expand=True) d_.prod(axis=1, level=0).sum(1) 0 31 1 36 2 74 3 100 4 31 dtype: int64
has comment: http://stackoverflow.com/comment/87771337
has comment: http://stackoverflow.com/comment/87770941
has comment: http://stackoverflow.com/comment/87770890
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87771086
has comment: http://stackoverflow.com/comment/87771277
downvote count: 0
has comment: http://stackoverflow.com/comment/87771494
answers question: http://stackoverflow.com/q/50377228
type: Answer
has comment: http://stackoverflow.com/comment/87770953
has comment: http://stackoverflow.com/comment/87772296

http://stackoverflow.com/comment/87660982
has text: @Code-Apprentice The OP said "I want to argument interface to be explict. That is explict write argument names as `ff(a,b,c)` when making function definition", and even edited the question to put that in bold after you made your comments on the answer, so… I think, even if maybe that's what the OP _should_ want, it's not what the OP _does_ want.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50322592
type: Comment

http://stackoverflow.com/q/50244109
tagged with: django
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
type: Question
has body: I have two models related through a one to one field, and I want to create a REST services that manages them both as they where one. The post works perfectly so far, and new instances are created in both models as they where one, but the put method just does nothing. It raises no error or anything, it just leaves the data unchanged. These are my models: class Company(models.Model): name = models.CharField(max_length=40) legal_name = models.CharField(max_length=100) url = models.URLField() address = models.TextField(max_length=400) def __str__(self): return "[{}]{}".format(self.id, self.name) class Hotel(models.Model): company = models.OneToOneField('Company', on_delete=models.CASCADE, primary_key=True) code = models.CharField(max_length=10) city = models.ForeignKey('City', on_delete=models.PROTECT, related_name='city_hotels') category = models.ForeignKey('HotelCategory', on_delete=models.PROTECT, related_name='category_hotels') capacity = models.IntegerField() position = models.DecimalField(max_digits=11, decimal_places=2, default=0.00) in_pickup = models.BooleanField(default=False) def __str__(self): return self.company.name This is my ViewSet: class HotelViewSet(viewsets.ModelViewSet): queryset = models.Hotel.objects.all() serializer_class = serializers.HotelSerializer These are my serializers: class CompanySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Company fields = ('id', 'name', 'legal_name', 'url', 'address') class HotelSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer() class Meta: model = models.Hotel fields = ('company', 'code', 'city', 'category', 'capacity', 'position', 'in_pickup') def create(self, validated_data): company_data = validated_data.pop('company') new_company=models.Company.objects.create(**company_data) hotel = models.Hotel.objects.create(company=new_company, **validated_data) return hotel def update(self, instance, validated_data): company = models.Company( id=instance.company…
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50245814
answer count: 2
has title: Django Rest Framework update don't save changes
has answer: http://stackoverflow.com/a/50244275
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/50310157
score: -1
has body: I was able to get the correct result with show_counts = df[df['no_Show'] == 0].groupby('age_bracket').count(). ['no_Show'] noshow_counts=df[df['no_Show'] == 1].groupby('age_bracket').count(). ['no_Show']
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/50309899
type: Answer

http://stackoverflow.com/q/50237911
has body: This certainly makes the width of the bars wider, but would be better to set them to "1 day" wide: source = ColumnDataSource(df) p = figure(x_axis_type="datetime", height=200, ...) ... c.vbar('dt', top='pct_change', width=100000000, source=source)
possible better answer: http://stackoverflow.com/a/50238144
type: AnsweredQuestion
answer count: 2
score: 5
downvote count: 1
favorite count: 0
has title: when plotting with vbar on an xaxis that's a datetime axis, how can I set the width of the bars to be "one day"?
type: Question
has answer: http://stackoverflow.com/a/50238241
accepted answer: http://stackoverflow.com/a/50238241
tagged with: python
tagged with: bokeh
upvote count: 6
has answer: http://stackoverflow.com/a/50238144

http://stackoverflow.com/q/50239200
has title: Pygame how to get previous song
answer count: 2
has comment: http://stackoverflow.com/comment/87496591
has answer: http://stackoverflow.com/a/50239889
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/50239944
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87495753
has body: I want to make the program to go to the previous song if the user decides to press the button (mind you I'm doing this on a raspberry pi). The problem is I cannot figure out how to make the program to get to the previous song. I got to the point where I can go to next song, I also tried 'pygame.mixer.music.rewind()' but that only goes to the beginning of the current song. def prevSong(): print("musiclist is ",musiclist) print('Playing previous song') pygame.mixer.music.rewind() def nextSong(): pygame.mixer.init() print("musiclist is ",musiclist) print(' ') random_song = random.choice(musiclist) randSong = pygame.mixer.music.load(random_song) print('Playing next song: {}'.format(random_song)) pygame.mixer.music.play() musiclist.remove(random_song) I want the changes to be made to prevSong(). The function nextSong() is an example to go on. Any suggestions? Thanks Edit 1:Ok so I created a new list called 'prevSongList', but I can't get my head around as how am I supposed to get the song appended def playMusic(): pygame.mixer.init() print("musiclist is ",musiclist) print(' ') random_song = random.choice(musiclist) randSong = pygame.mixer.music.load(random_song) prev = prevSongList.append(randSong) print('Playing song: {}'.format(random_song)) pygame.mixer.music.play()
downvote count: 0
tagged with: raspberry-pi3
accepted answer: http://stackoverflow.com/a/50239944
has comment: http://stackoverflow.com/comment/87496373
favorite count: 0
tagged with: python-3.x
tagged with: raspberry-pi
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/50239889

http://stackoverflow.com/comment/87577230
comment on: http://stackoverflow.com/q/50280247
has text: In general, you should not expect a garbage collector to release memory unless it has to. As you see in your 80 user test, memory is not leaked but available for reuse. You should only be worried if memory consumption increases without workload increasing as well.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50355330
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87727064
has comment: http://stackoverflow.com/comment/87727827
has comment: http://stackoverflow.com/comment/87727289
has comment: http://stackoverflow.com/comment/87727349
score: 1
has comment: http://stackoverflow.com/comment/87727080
downvote count: 1
has comment: http://stackoverflow.com/comment/87727117
tagged with: python
has comment: http://stackoverflow.com/comment/87727303
has body: I occasionally find myself appending numbers to the end of each variable when I have a couple of arguments, but I don't do it consistently and I would like to establish just one pattern going forward. Let's say I have a function which takes in two numbers and the name of a mathematical operation and then it returns the result of that operation. def do_math(input1, input2, operation): # perform the operation and return result Edit: please don't get hung up on this example. My question applies to variable names, not just functions, and not just operands I generally end up with something like this input1 and input2 style, but it feels odd since Python uses zero-based indexing. But input0 and input1 also doesn't seem right. Sometimes (like in a Jupyter Notebook) I start with one variable like var (just an example, I'm usually more descriptive) and then later end up adding another one and call it something like var1 or possibly var2. When I'm prototyping things in a Notebook, I don't usually think it's important enough to then go back and add the 0 or 1 to the first variable name, but then I end up with really inconsistent names. Edit 2: Adding a more typical/realistic example, as requested: bits0 = hash_to_binary(hash0) bits1 = hash_to_binary(hash1) distance = hamming_distance(bits0, bits1) I've checked all over this site as well as various style guides, including https://www.python.org/dev/peps/pep-0008/#function-and-variable-names and can't seem to find an answer to this question. It's very possible there is no preferred way to do this, but I'd love to hear your suggestions for what makes sense. I know it can depend on the exact scenario, but I'm hoping there's some consistent naming convention I can use to avoid confusion and re-factoring down the line. Other ways I've considered but don't love: var_0, var_1 List, tuple, or custom data structure: vars[0] and vars[1] (This is obviously preferred when using lots of values, but seems like overkill for 2) first_var, seco…
upvote count: 2
has comment: http://stackoverflow.com/comment/87727135
type: UnansweredQuestion
answer count: 1
has title: What's the preferred way to name two or more related Python variables?
has comment: http://stackoverflow.com/comment/87727813
has comment: http://stackoverflow.com/comment/87727156
has comment: http://stackoverflow.com/comment/87727016
has answer: http://stackoverflow.com/a/50355431

gist
tags question: http://stackoverflow.com/q/50258835
tag name: gist
type: Tag

http://stackoverflow.com/comment/118936353
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/67288154
has text: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.

cyrillic
tags question: http://stackoverflow.com/q/50231447
tag name: cyrillic
type: Tag

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/50338778
tag name: decision-tree
tags question: http://stackoverflow.com/q/50261604

http://stackoverflow.com/comment/87757243
score: 0
has text: OP was asking for an alternative over using three loops so it looks like he is looking for something that performs better. Using permutations doesn't seem very efficient.
type: Comment
comment on: http://stackoverflow.com/a/50370365
type: AnswerComment

http://stackoverflow.com/q/50276799
has title: Can't append a set of values from a Class
has comment: http://stackoverflow.com/comment/87570781
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87570499
has comment: http://stackoverflow.com/comment/87570921
tagged with: python
has comment: http://stackoverflow.com/comment/87570581
has comment: http://stackoverflow.com/comment/87570597
has comment: http://stackoverflow.com/comment/87570396
has comment: http://stackoverflow.com/comment/87570332
has comment: http://stackoverflow.com/comment/87570355
has comment: http://stackoverflow.com/comment/87570560
answer count: 0
has body: I am doing a card game. The class is called Card: It can give a random value with the deal() method to display a random card from the numbers 1-13 The other file will import the file name that contains the Class Card. It will call the class 5 times and be able to store it by appending it on a list and displaying it in another def called display_hand Here is the class file: import random class Card: def __init__(self): self.__value = 0 def deal(self): self.__value = random.randint(1, 13) def set_value(self, value): self.__value = value def get_value(self): return self.__value def find_face_value(self): faces = ['Joker','Ace','Two','Three','Four','Five','Six', 'Seven','Eight','Nine','Ten','Jack','Queen','King'] return faces[self.__value] def __str__(self): return self.find_face_value() The program is too big so this is the def for calling the function 5 times: def deal_hand(): # Create an empty list to append the cards. hand = [] deal_hand = classcard3.Card() for i in range(1, 6): deal_hand = classcard3.Card() deal_hand.deal() # Create a new object in memory and assign it to the # hand variable w = classcard3.Card(deal_hand) # add it to the list hand.append(w) return hand Here is the display function: def display_hand(hand): print ("The 5-card hand is: ") for item in hand: print(hand) This is not showing anything except for the print inside the loop. How can I pass it to the display hand to show the cards? This is the only thing that shows whenever I use the print function inside the loop. I'm trying to use it outside and I have no idea what I'm doing wrong. My apologies if I'm not explaining this too well. I'm a beginner at python and new to this website. Thanks deal Four deal Three deal Five deal Six deal Queen The only error that I'm getting from this is: line 274, in deal_hand w = classcard3.Card(deal_hand) TypeError: __init__() takes 1 positional argument but 2 were given This doesn't make sense, because I'm doing it just as the book says and is not willing to di…
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87571307
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87570235

http://stackoverflow.com/q/50238432
has comment: http://stackoverflow.com/comment/87769867
linked to: http://stackoverflow.com/q/50258621
downvote count: 0
tagged with: unit-testing
favorite count: 0
type: Question
has title: Pycharm looks to project root rather than sources root when running unit tests
answer count: 2
has body: I reinstalled PyCharm recently and encountering an import error with the unittests: AttributeError: 'module' object has no attribute 'src'. I'm running a unit test from within PyCharm using the defaults (just clicking on the run icon next to the unit test). The unittest command line displayed in the console tells me that the --target argument is being passed the full path from the project root. It should be a path from the sources root. The project root contains directories that are not packages. I've confirmed in the debugger, where the exception occurs, that I can import from the sources root but not from the project root used by PyCharm. /path_omitted/_jb_unittest_runner.py --target path.from.project.root.myunittest.MyClass.test_function ... Details: When I edit configurations for the unittest in PyCharm the working directory is the correct sources root for the unit test.
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50238890
tagged with: python
duplicate of: http://stackoverflow.com/q/50258621
score: 2
tagged with: python-2.7
tagged with: pycharm
has answer: http://stackoverflow.com/a/50238494

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

http://stackoverflow.com/q/50374631
tagged with: kivy
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50376447
has answer: http://stackoverflow.com/a/50376380
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/50376447
has title: Change variable via selected item in Kivy
possible better answer: http://stackoverflow.com/a/50376380
has body: So I learning Kivy but I am stuck with the ListView or, as the ListView seems to be deprecated, the RecycleView. My problem is that I want the label with species_text as ID to change based on the item I click on, once in the label is in view. The documentation helped me as far as making the SelectableLabel and being able to click / color it, but I do not know how to change the text of species_text via the data list of the RecycleView or how to save the data list in the ScreenTest class. Here is my code: from kivy.app import App from kivy.uix.button import Label, Button from kivy.lang import Builder from kivy.properties import BooleanProperty from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.screenmanager import ScreenManager, Screen Builder.load_string(""" &lt;ScreenTest&gt;: Label: pos_hint: {"x": .45, "top": 1} text: "Headline" size_hint: .1, .1 BoxLayout: pos_hint: {"x": 0.02, "top": .8} RecycleView: id: species_list_view data: [{'name': "Species1", "text": "S1"}, {'name': "Species2", "text": "S2"}] viewclass: 'SelectableLabel' SelectableRecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None orientation: 'vertical' multiselect: False touch_multiselect: False Label: id: species_text text: "Speciestext" BoxLayout: size_hint_y: None height: 30 spacing: 10 canvas: Color: rgba: .5, .2, .1, 1 Rectangle: pos: self.pos size: self.size Button: text: "Go Back" Button: text: "Next" &lt;SelectableLabel&gt;: # Draw a background to indicate selection canvas.before: Color: rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1) Rectangle: pos: self.pos size: self.size """) class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): pass class SelectableLabel(RecycleDataViewBehavior, Label): ''' Add selection support to th…
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/q/50312887
score: 1
has body: I have a list of valid dates in Python myList =['05-06-2015', '01-07-2015', '01-07-2015 01-07-2016', '26-08-2015', '26-08-2016', '23-06-2015 26-08-2016 01-07-2015', '06-07-2015'] As you can see, some elements have a single value, some have two and some have three dates. My problem is to reduce all of these into a flattened list, which looks like this: flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015'] I tried to do this: flatList = list(itertools.chain.from_iterable(myList)) But, this is not behaving as I expected and it is splitting each character as a list. Can you please let me know how I can accomplish this? Expected output: flatList =['05-06-2015', '01-07-2015', '01-07-2015', '01-07-2016', '26-08-2015', '26-08-2016', '23-06-2015', '26-08-2016', '01-07-2015', '06-07-2015']
tagged with: python
type: Question
has title: How to flatten a list of lists containing dates in Python
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50312902
possible better answer: http://stackoverflow.com/a/50312905
has answer: http://stackoverflow.com/a/54682723
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50312902
answer count: 3
has answer: http://stackoverflow.com/a/50312905

sfml
tag name: sfml
type: Tag
tags question: http://stackoverflow.com/q/50307018

http://stackoverflow.com/comment/87783347
has text: I have jumped to page 2 and use 'r=browser.page_source' to get the current source code. But it seems that I got the souce code of page 1 rather page 2. I am not curious about why r1≠r2. They should be different of course bexause of dynamic content. I don't why i got the source code of page 1. I have already jumped to page 2！
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50383690
score: 0

http://stackoverflow.com/a/50307531
score: 5
downvote count: 0
type: AcceptedAnswer
has body: If the first argument to pd.read_excel is a str, it is interpreted as the path to a file (or a URL). If we wish to pass the content of the file directly to read_excel, then we need to wrap the content in a BytesIO to make it a file-like object: Therefore, use BytesIO = pd.io.common.BytesIO df = pd.read_excel(BytesIO(page.content), engine='xlrd')
has comment: http://stackoverflow.com/comment/87635833
accepted answer of: http://stackoverflow.com/q/50307145
upvote count: 5
has comment: http://stackoverflow.com/comment/87635543
has comment: http://stackoverflow.com/comment/87635932
type: Answer
answers question: http://stackoverflow.com/q/50307145
has comment: http://stackoverflow.com/comment/87636137
has comment: http://stackoverflow.com/comment/87635881

http://stackoverflow.com/q/50273023
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
score: 0
has body: I m trying to itterate through images in a folder for further processing. I tried to read just one image in the folder using this code import cv2 import os img=cv2.imread('/home/hch/Desktop/Database/sample.jpg') print (img.shape) for filename in os.listdir('Database') : if filename.endswith(".jpg") : img=cv2.imread(filename) print (img.shape) As you can see the fist part reads the image directly while the second tries to read it through os.listdir. The problem is that the second part doesn't work it. it gives me this message : Traceback (most recent call last): File "resize.py", line 10, in &lt;module&gt; print (img.shape) AttributeError: 'NoneType' object has no attribute 'shape' And when I print filename it prints the name of the image " sample.jpg". Can you help me understand why it doesn't work ? Thank you
tagged with: python
has answer: http://stackoverflow.com/a/50273165
type: Question
has comment: http://stackoverflow.com/comment/87562775
upvote count: 1
has title: cv2.imread and os.listdir don't work
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50273165

http://stackoverflow.com/comment/87502666
comment on: http://stackoverflow.com/q/50239184
type: Comment
score: 0
type: QuestionComment
has text: That's just for the linux terminal, it does not work for idle.

http://stackoverflow.com/a/50281667
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50281510
has comment: http://stackoverflow.com/comment/87580139
has body: Seems like this package is on PyPy, so you can just install it like this pip install orbitalpy If you want to install the latest version from github, you can install it like this pip install -e git+https://github.com/RazerM/orbital.git#egg=orbital
has comment: http://stackoverflow.com/comment/87580173
type: Answer
has comment: http://stackoverflow.com/comment/87691633
accepted answer of: http://stackoverflow.com/q/50281510
downvote count: 0

http://stackoverflow.com/comment/87780030
comment on: http://stackoverflow.com/q/50381981
score: 0
has text: not sure what you mean by "contours from all the values of x and y", could you clarify?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87751270
type: AnswerComment
comment on: http://stackoverflow.com/a/50351619
has text: Thanks! I understand it now.
score: 1
type: Comment

http://stackoverflow.com/comment/87778541
has text: I'd recommend pandas, if you have it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50381203
score: 1

http://stackoverflow.com/comment/87629228
type: AnswerComment
type: Comment
has text: can you try deleting import statement and %run 'myModule.ipynb'?
comment on: http://stackoverflow.com/a/50306375
score: 0

http://stackoverflow.com/q/50282464
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: anaconda
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87581450
type: Question
accepted answer: http://stackoverflow.com/a/50518451
linked to: http://stackoverflow.com/q/46131620
tagged with: visual-studio-code
upvote count: 2
has title: Anaconda/Python/VSCode: vscode editor doesn't recognize installed packages
has answer: http://stackoverflow.com/a/50518451
has body: I'm trying to use VS Code for python in an Anaconda environment. I have (after some googling and travail) gotten it using my custom environment. However, pylint and the editor don't recognize the installed netifaces in the environment. The environment (billh) is being loaded: The errors from python are shown here: Oddly, importing from ipython running in the built-in terminal does work: This was newly installed today, via Anaconda. Here's the version info

http://stackoverflow.com/q/50280523
possible better answer: http://stackoverflow.com/a/50281215
has answer: http://stackoverflow.com/a/50281215
accepted answer: http://stackoverflow.com/a/50280642
has comment: http://stackoverflow.com/comment/87577623
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87577698
tagged with: django
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Django database migration error
has comment: http://stackoverflow.com/comment/87578222
has answer: http://stackoverflow.com/a/50280642
score: 1
tagged with: database
tagged with: migration
tagged with: sqlite
tagged with: python
has body: I have a Django project connected to Gmail API. When I try to do database migration it returns this: C:\Users\Peter\Desktop\FastProject&gt;python manage.py migrate FastProject Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", l ine 371, in execute_from_command_line utility.execute() File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", l ine 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 332, in execute self.check() File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrat e.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Peter\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolv…

http://stackoverflow.com/q/50251423
has answer: http://stackoverflow.com/a/50251574
type: Question
has comment: http://stackoverflow.com/comment/87520052
has comment: http://stackoverflow.com/comment/87520123
tagged with: python
has body: I can't indentify resume label and upload resume for this label url:https://www.roberthalf.com/job/toms-river-nj/marketing-assistant/02760-9501226436/apply?referUrl=aHR0cHM6Ly93d3cucm9iZXJ0aGFsZi5jb20vam9icy9RQQ== Thanks
type: AnsweredQuestion
score: 0
has title: I can't indentify resume label and upload resume
accepted answer: http://stackoverflow.com/a/50251574
answer count: 1
tagged with: selenium

http://stackoverflow.com/a/50297390
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50297337
has body: Define a class method instead: class Class1: def __init__(self): self.foo = 1 self.foo = 2 @classmethod def new(cls): return cls() class Class2(Class1): pass Now when you call c2.new(), the runtime will see that Class2 has no method named new, but Class1 does. Further, Class2 will be passed as the implicit argument to new, not Class1. The class method is more appropriate than an instance method because you don't have any other interest in the object invoking the method beyond what class it is.
score: 3
type: Answer

http://stackoverflow.com/q/50314708
has title: How can i print '\' in python?
linked to: http://stackoverflow.com/q/19095796
favorite count: 0
has answer: http://stackoverflow.com/a/50314732
type: Question
duplicate of: http://stackoverflow.com/q/19095796
tagged with: python
score: -2
has body: Is there any way to print back slash in python? we can write a string in three format. 1. ASCII 2. Unicode 3. Raw String I have tried with all 3 formats but not able to get expected result. Thanks in Advance
has comment: http://stackoverflow.com/comment/87645266
downvote count: 4
tagged with: printing
has answer: http://stackoverflow.com/a/50314715
upvote count: 2
answer count: 2
tagged with: backslash
type: UnansweredQuestion

http://stackoverflow.com/comment/88272795
comment on: http://stackoverflow.com/a/50398910
has text: This is what I'm looking for - ways to condense my code. Really helpful, thanks!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87607242
comment on: http://stackoverflow.com/a/50290868
type: AnswerComment
score: 0
has text: Thanks this helped a lot. Not exactly the answer I wanted mostly because the formula I posted is wrong. I need the value to be scaled based on the values in the current 30 min interval. So `(merged.util + merged.util.shift(-1))` is not correct. Instead I had to resample **B** to 30 minutes and take the sum. This worked out fine.
type: Comment

http://stackoverflow.com/comment/87548951
comment on: http://stackoverflow.com/a/50263930
has text: This message is coming from [ERROR_NOT_ENOUGH_MEMORY](https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx#ERROR_NOT_ENOUGH_MEMORY), which is presumably just what windows returns when an mmap fails.
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50354157
score: 0
linked to: http://stackoverflow.com/q/50311145
has comment: http://stackoverflow.com/comment/87724657
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/87724737
tagged with: selenium
tagged with: drop-down-menu
has comment: http://stackoverflow.com/comment/87725231
type: Question
has title: Select from a dropdown box without using the Select or Option tags: selenium python
type: UnansweredQuestion
has body: I'm trying to select a value from a dropdown list on the web, but the HTML doesn't have any Select or Option tags. The values of the list are in a table and not embedded in the code. I do have the ability to enter text into this box so I figured an easy solution would be just to use .sendkeys (on the webpage if the entered text matches a dropdown option it works), but I guess Python won't let you do that to a combobox because I just get an element is not visible error. I found the below link with a full breakdown of how to interact with dropdown lists, but the "Without Select Option" section only has examples for Java and Ruby. Below is the inspected code of the dropdown box. What are my options? https://sqa.stackexchange.com/questions/12029/how-do-i-work-with-dropdowns-in-selenium-webdriver?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
tagged with: python
has answer: http://stackoverflow.com/a/65321320
tagged with: selenium-webdriver

http://stackoverflow.com/comment/115446917
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65302071
type: Comment
has text: to convert string to datetime object, I used this reference https://www.journaldev.com/23365/python-string-to-datetime-strptime#:~:text=We%20can%20convert%20a%20string,datetime%20and%20time%20objects%20respectively.

http://stackoverflow.com/a/50295224
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50294428
has comment: http://stackoverflow.com/comment/92277368
score: 3
type: Answer
has body: While I too couldn't find anything in the current emcee docs, the latest versions seems to have added a tutorial which happens to show the exact thing you are trying to do: link In case the link breaks or things change, here is the example: import emcee import numpy as np np.random.seed(42) # The definition of the log probability function # We'll also use the "blobs" feature to track the "log prior" for each step def log_prob(theta): log_prior = -0.5 * np.sum((theta-1.0)**2 / 100.0) log_prob = -0.5 * np.sum(theta**2) + log_prior return log_prob, log_prior # Initialize the walkers coords = np.random.randn(32, 5) nwalkers, ndim = coords.shape # Set up the backend # Don't forget to clear it in case the file already exists filename = "tutorial.h5" backend = emcee.backends.HDFBackend(filename) backend.reset(nwalkers, ndim) # Initialize the sampler sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, backend=backend) max_n = 100000 # We'll track how the average autocorrelation time estimate changes index = 0 autocorr = np.empty(max_n) # This will be useful to testing convergence old_tau = np.inf # Now we'll sample for up to max_n steps for sample in sampler.sample(coords, iterations=max_n, progress=True): # Only check convergence every 100 steps if sampler.iteration % 100: continue # Compute the autocorrelation time so far # Using tol=0 means that we'll always get an estimate even # if it isn't trustworthy tau = sampler.get_autocorr_time(tol=0) autocorr[index] = np.mean(tau) index += 1 # Check convergence converged = np.all(tau * 100 &lt; sampler.iteration) converged &amp;= np.all(np.abs(old_tau - tau) / tau &lt; 0.01) if converged: break old_tau = tau

http://stackoverflow.com/comment/119834848
score: 1
has text: `os.environ["KIVY_NO_CONSOLELOG"] = "1"` stop errors from being logged as well.
type: Comment
comment on: http://stackoverflow.com/a/50308896
type: AnswerComment

http://stackoverflow.com/q/50316363
type: Question
upvote count: 2
has body: So I have a Product and ProductImage models. Each Product can have multiple ProductImage models. In the Django admin page, I want the product images to display the name of the product it's related to. class Product(models.Model): name = models.CharField(max_length=150) price = models.DecimalField(max_digits=9, decimal_places=2) product_count = models.IntegerField(blank=True, default=0) description = models.TextField() class ProductImage(models.Model): image_addr = models.FileField(upload_to='products/') product_id = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): q = &lt;*name of the product with the product_id*&gt; If a product image is that of a phone, say iPhone X, the image should display so. Now, the product images column only shows ProductImage objects. How do I solve this?
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50316792
has comment: http://stackoverflow.com/comment/87648621
has comment: http://stackoverflow.com/comment/87648664
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87648786
answer count: 2
accepted answer: http://stackoverflow.com/a/50316388
score: 1
has title: Django Models: __str__ with Foreign object's name
has answer: http://stackoverflow.com/a/50316388
tagged with: web
downvote count: 1
has comment: http://stackoverflow.com/comment/87648579
favorite count: 0
has answer: http://stackoverflow.com/a/50316792

http://stackoverflow.com/a/50351608
has comment: http://stackoverflow.com/comment/87721272
has comment: http://stackoverflow.com/comment/87721181
has comment: http://stackoverflow.com/comment/87720888
has comment: http://stackoverflow.com/comment/87720440
has comment: http://stackoverflow.com/comment/87721736
has comment: http://stackoverflow.com/comment/87720945
type: Answer
accepted answer of: http://stackoverflow.com/q/50351530
upvote count: 11
has comment: http://stackoverflow.com/comment/87720427
answers question: http://stackoverflow.com/q/50351530
has comment: http://stackoverflow.com/comment/87721561
has comment: http://stackoverflow.com/comment/87720522
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87721521
downvote count: 0
has comment: http://stackoverflow.com/comment/87721388
has comment: http://stackoverflow.com/comment/87721701
has body: There is problem NaNs, which convert all values to floats so possible solution is add parameter fill_value=0 if input data are integers: dummy=dummy.pivot_table(index=['hour','new_id'],columns='name', values='values', fill_value=0) print (dummy) name ale alex alf andrew arthur mark matt peter roger tom hour new_id 0 0 0 3 0 0 0 5 4 0 0 0 1 0 0 0 0 7 0 0 0 2 0 1 1 0 0 8 0 0 0 0 0 0 0 2 6 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 5 0 0 2 3 0 0 0 0 0 0 0 0 0 2 4 0 0 0 7 0 0 0 0 0 0 Default aggregate function in pivot_table is mean, so is expected at least one float value in output, so it convert all values to floats. So if change aggregate function to sum all working nice: dummy = dummy.pivot_table(index=['hour','new_id'], columns='name', values='values', fill_value=0, aggfunc='sum')
score: 11
has comment: http://stackoverflow.com/comment/87721744
has comment: http://stackoverflow.com/comment/87720851

http://stackoverflow.com/a/50463785
has body: I never did this kind of things, but I think that you can make this process through this way : Method : unique_together() You can use Options.unique_together and set your university_A and university_B as a unique pair. unique_together = ("university_A", "university_B") In your models.py file, you should have something like this (with maybe some issues, but the idea is there) : class University(models.Model): ... university = models.ForeignKey('self', on_delete=models.CASCADE) sister_university = models.ForeignKey('self', on_delete=models.CASCADE) class Meta: unique_together = (('university','sister_university'),) You should find precious details there : https://docs.djangoproject.com/en/2.0/ref/models/options/ I never tried this command, but it seems to solve your issue according to your context.
answers question: http://stackoverflow.com/q/50355697
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87941225
has comment: http://stackoverflow.com/comment/87941087
score: 2
has comment: http://stackoverflow.com/comment/87940928
has comment: http://stackoverflow.com/comment/87941014
type: Answer

http://stackoverflow.com/a/50345079
has comment: http://stackoverflow.com/comment/87705921
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87706166
has comment: http://stackoverflow.com/comment/87706311
answers question: http://stackoverflow.com/q/50344999
downvote count: 0
has body: import pandas as pd d = [{0:{'city':'newyork', 'name':'John', 'age':'30'}},{0:{'city':'newyork', 'name':'John', 'age':'30'}},] df = pd.DataFrame([list(i.values())[0] for i in d]) print(df) Output: age city name 0 30 newyork John 1 30 newyork John

http://stackoverflow.com/comment/87741220
type: Comment
type: QuestionComment
has text: Try using `if fitur[0] in ...`, it makes for a far more readable code.
score: 0
comment on: http://stackoverflow.com/q/50362253

http://stackoverflow.com/q/50324600
has title: Pandas: replace values in dataframe with another dataframes values based on condition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50325414
answer count: 2
tagged with: pandas
upvote count: 3
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/50324864
favorite count: 0
possible better answer: http://stackoverflow.com/a/50325414
type: Question
has answer: http://stackoverflow.com/a/50324864
has body: I have the following dataframes: df1: +-----+------+------+------+------+------+ | No. | col1 | col2 | col3 | Type | ... | +-----+------+------+------+------+------+ | 123 | 2 | 5 | 2 | MN | ... | | 453 | 4 | 3 | 1 | MN | ... | | 146 | 7 | 9 | 4 | AA | ... | | 175 | 2 | 4 | 3 | MN | ... | | 643 | 0 | 0 | 0 | NAN | ... | +-----+------+------+------+------+------+ df2: +-----+------+------+------+------+ | No. | col1 | col2 | col3 | Type | +-----+------+------+------+------+ | 123 | 24 | 57 | 22 | MN | | 453 | 41 | 39 | 15 | MN | | 175 | 21 | 43 | 37 | MN | +-----+------+------+------+------+ I want to replace col1, col2 and col3 in df1 with corresponding values in df2 if Type equals MN Desired output: df1: +-----+------+------+------+------+-----+ | No. | col1 | col2 | col3 | Type | ... | +-----+------+------+------+------+-----+ | 123 | 24 | 57 | 22 | MN | ... | | 453 | 41 | 39 | 15 | MN | ... | | 146 | 7 | 9 | 4 | AA | ... | | 175 | 21 | 43 | 37 | MN | ... | | 643 | 0 | 0 | 0 | NAN | ... | +-----+------+------+------+------+-----+ EDIT I tried: df1[df1.Type == 'MN'] = df2.values but I get this error: ValueError: Must have equal len keys and value when setting with an ndarray Guess the reason is, that df2 does not have equal number of columns. So how do I make sure, that only the specific columns (col1 - col3) are replaced in df1?
tagged with: python

http://stackoverflow.com/q/50264558
type: Question
has body: I'm trying to extract the pixel coordinates from a given cv::KeyPoint. This class has a variable named pt of type cv::Point2f which is simply a tuple containing two floats. I'm not sure casting the cv::Point2f to cv::Point2i works since I cannot find in the docs what are these float numbers representing. I'm trying to do this in python, but I can't find a proper OpenCV 3 documentation for python neither. My code: import cv2 feature_detector = cv2.xfeatures2d.SURF_create() key_points = feature_detector.detect(img, None) # this is a list of float tuples e.g. (100.3224, 451.2334) float_coordinates = list(map(lambda key_point: key_point.pt)) # pixel_coordinates = ?
tagged with: python
has answer: http://stackoverflow.com/a/50275954
accepted answer: http://stackoverflow.com/a/50275954
has title: OpenCV transform key points into pixel coordinates
type: AnsweredQuestion
tagged with: opencv3.0
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50288004
accepted answer: http://stackoverflow.com/a/50288103
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50288142
has comment: http://stackoverflow.com/comment/87592436
tagged with: python
has body: I have a function foo that takes a parameter stuff Stuff can be something in a database and I'd like to create a function that takes a stuff_id, get the stuff from the db, execute foo. Here's my attempt to solve it: 1/ Create a second function with suffix from_stuff_id def foo(stuff): do something def foo_from_stuff_id(stuff_id): stuff = get_stuff(stuff_id) foo(stuff) 2/ Modify the first function def foo(stuff=None, stuff_id=None): if stuff_id: stuff = get_stuff(stuff_id) do something I don't like both ways. What's the most pythonic way to do it ?
score: 2
answer count: 3
has answer: http://stackoverflow.com/a/50288141
possible better answer: http://stackoverflow.com/a/50288141
upvote count: 2
tagged with: function
downvote count: 0
has title: How to avoid parameter type in function's name?
tagged with: design-patterns
favorite count: 0
has answer: http://stackoverflow.com/a/50288103
type: Question
has comment: http://stackoverflow.com/comment/87592326

http://stackoverflow.com/q/50360129
has answer: http://stackoverflow.com/a/50379097
linked to: http://stackoverflow.com/q/625083
has comment: http://stackoverflow.com/comment/87737410
answer count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87738063
has comment: http://stackoverflow.com/comment/87738118
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87737988
has body: I'm a former c++ coder and have made the plunge into python for several months, which has been great. I'm doing a bit of code porting and have come across a problem of which i'm not sure the best path. There are many ways to skin a cat - but i'm looking for advice on what would be the 'best' and/or most pythonic way to do something similar to the section of c++ code below. I've cut the code to a trivial 'reproducer' just to highlight what was happening. Essentially there is a well-defined interface of callbacks the server will call when certain events happen. When a server is created, it is provided a callback interface as an argument. In the below case, the client has implemented these callbacks on itself, and thus when it is creating the server, it provides the *this pointer. Is this something similar in python? Any suggestions would get greatly appreciated. #include &lt;iostream&gt; // Client Feed Handler function Interface class ClientFeedHandlersI { public: virtual void HandlerFeed1() = 0; virtual void HandlerFeed2() = 0; }; // A very basic server class Server { public: Server(ClientFeedHandlersI&amp; handlers) : mHandlers(handlers) {} void Start() { // Create some random events to illustrate for (int i = 0; i &lt; 10; ++i) EventLoopHandler(); } private: void EventLoopHandler() { if (rand() % 10 &gt; 5) mHandlers.HandlerFeed1(); else mHandlers.HandlerFeed2(); } ClientFeedHandlersI&amp; mHandlers; }; // A really simple client class Client : private ClientFeedHandlersI { public: Client() : mMyServer(*this) { mMyServer.Start(); } private: void HandlerFeed1() override { std::cout &lt;&lt; "HandlerFeed1 called\n"; } void HandlerFeed2() override { std::cout &lt;&lt; "HandlerFeed2 called\n"; } Server mMyServer; }; int main() { auto c = Client(); } So here's an attempt at porting to python. Note that in the real world example, there are 20+ client feed handler functions, hence why i want to force the interface using the @abstractmethod. # python 3.6 from abc import ABC…
has comment: http://stackoverflow.com/comment/87736903
accepted answer: http://stackoverflow.com/a/50379097
upvote count: 1
has comment: http://stackoverflow.com/comment/87737840
tagged with: this
has comment: http://stackoverflow.com/comment/87737903
favorite count: 0
has comment: http://stackoverflow.com/comment/87755146
has title: C++ pure virtual functions and this pointer in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87738011
score: 0
has comment: http://stackoverflow.com/comment/87737950

http://stackoverflow.com/a/50264458
type: Answer
accepted answer of: http://stackoverflow.com/q/50260242
has comment: http://stackoverflow.com/comment/87551359
upvote count: 2
answers question: http://stackoverflow.com/q/50260242
downvote count: 0
has comment: http://stackoverflow.com/comment/87561074
type: AcceptedAnswer
has body: In your TodoCreateSerializer you need to add PrimaryKeyRelatedField with a custom queryset that has the filtered tags of a user. First, you will need to create a custom PrimaryKeyRelatedField that filter any objects to get only those who owned by the user. class UserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): request = self.context.get('request', None) queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset() if not request or not queryset: return None return queryset.filter(user=request.user) (This is a generic one and can be used when filtering in objects by user) Then you should use this one in you TodoCreateSerializer: class TodoCreateSerializer(serializers.ModelSerializer): tags = UserFilteredPrimaryKeyRelatedField(queryset= Tag.objects, many=True) class Meta: model = models.Todo fields = ('title', 'description', 'due_at', 'tags')
score: 2

http://stackoverflow.com/a/50338768
has comment: http://stackoverflow.com/comment/87694052
has comment: http://stackoverflow.com/comment/87693825
type: Answer
score: 0
has body: The problem is that the send call actually runs an iteration and returns a value and you aren't doing anything with it. Try this: print(myGen.send(20)) https://repl.it/repls/RuddyConcretePrinters
answers question: http://stackoverflow.com/q/50338713

http://stackoverflow.com/comment/87661621
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50307758
has text: thanks @snakecharmerb it works, but it prints the below line :: OrderedDict([('Case Number', 'CAS-100828-Q5Z8'), ('Closed Date', '04-09-2018'), ('Yearmonth Closed', '201804'), ('Owner', 'Singh, Rupinder 2. (EXT - IN/Noida)'), ('Case Status', 'Resolved'), ('Priority', 'Major'), ('Customer Name', 'KDDI Corporation'), ('Country Name', 'Japan'), ('Created On', '02-05-2018'), ('Created Yearmonth', '201802'), ('Resolution time', '62.97109954')]) ----- at strat of every line it prints" OrderedDict([('" before the line contents.
type: QuestionComment

http://stackoverflow.com/comment/87758939
score: 0
has text: @pault, you are totally right. I needed to update my Spark-Notebook, because I removed the name of that object 'col' afterwards. Thanks a lot!
comment on: http://stackoverflow.com/q/50366396
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87533544
score: 0
has text: @MegaIng While `perm[:] =` doesn’t create a new list, the comprehension _does_ create a new list. So the OP is right—the old list and the new one are alive simultaneously for the duration of the `__setitem__` call, meaning there is linear temporary space.
comment on: http://stackoverflow.com/q/50256238
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50351357
has comment: http://stackoverflow.com/comment/87723597
has comment: http://stackoverflow.com/comment/87725698
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87721946
downvote count: 0
score: 6
has body: You can set the minor ticks so that only 1 minor tick appears inbetween your major ticks. This is done using matplotlib.ticker.AutoMinorLocator. Then, set the gridlines to only appear at the minor ticks. You also need to shift your xtick positions by 0.5: from matplotlib.ticker import AutoMinorLocator np.random.seed(10) x = range(10) y = np.random.random(10) plt.plot(x,y) plt.xticks(np.arange(0.5,10.5,1), x) plt.xlim(0,9.5) plt.ylim(0,1) minor_locator = AutoMinorLocator(2) plt.gca().xaxis.set_minor_locator(minor_locator) plt.grid(which='minor') plt.show() Edit: I'm having trouble getting two AutoMinorLocators to work on the same axis. When trying to add in another one for the y axis, the minor ticks get messed up. A work around I have found is to manually set the locations of the minor ticks using a matplotlib.ticker.FixedLocator and passing in the locations of the minor ticks. from matplotlib.ticker import AutoMinorLocator from matplotlib.ticker import FixedLocator np.random.seed(10) x = range(10) y = np.random.random(10) plt.plot(x,y) plt.xticks(np.arange(0.5,10.5,1), x) plt.yticks([0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95,1.05], [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]) plt.xlim(0,9.5) plt.ylim(0,1.05) minor_locator1 = AutoMinorLocator(2) minor_locator2 = FixedLocator([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]) plt.gca().xaxis.set_minor_locator(minor_locator1) plt.gca().yaxis.set_minor_locator(minor_locator2) plt.grid(which='minor') plt.show()
has comment: http://stackoverflow.com/comment/87719406
accepted answer of: http://stackoverflow.com/q/50350996
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50350996

http://stackoverflow.com/q/50375660
has comment: http://stackoverflow.com/comment/87767974
has title: Python import from different directory
has comment: http://stackoverflow.com/comment/87767766
has comment: http://stackoverflow.com/comment/87775140
tagged with: import
has comment: http://stackoverflow.com/comment/87768082
type: Question
has comment: http://stackoverflow.com/comment/87768340
has comment: http://stackoverflow.com/comment/87768059
has comment: http://stackoverflow.com/comment/87768867
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87768139
tagged with: python
has comment: http://stackoverflow.com/comment/87768138
has comment: http://stackoverflow.com/comment/87768110
has comment: http://stackoverflow.com/comment/87768516
has comment: http://stackoverflow.com/comment/87767864
has body: This has been discussed to eternity here and I've tried the recommended solutions but I'm still running into a wall. I'm playing around with the OpenBMP package and while attempting to run the main program I get the error ImportError: No module named mrt.logger. I'm running the program src/bin/openbmp-mrt while the file to be imported is located at src/site-packages/openbmp/mrt/logger. The import statement is: from openbmp.mrt.logger import LoggerThread Here is the tree of the src directory: `-- src |-- bin | `-- openbmp-mrt |-- etc | `-- openbmp-mrt.yml `-- site-packages `-- openbmp |-- __init__.py `-- mrt |-- bgp.py |-- bmp_bgp4mp.py |-- bmp_consumer.py |-- bmp.py |-- db_mysql.py |-- __init__.py |-- logger.py |-- mrt_bgp4mp_object.py |-- mrt_table_dump.py `-- RawTimedRotatingFileHandler.py So far I've tried: Appending the fully qualified path of src/site-packages/ to sys.path Adding a __init__.py file to src/site-packages/ But I'm still getting the same error. What am I doing wrong?
has comment: http://stackoverflow.com/comment/87768176
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87768236
has comment: http://stackoverflow.com/comment/87767961

http://stackoverflow.com/q/50252720
downvote count: 0
has body: Tensorflow 1.8 has introduced tf.contrib.data.prefetch_to_device, which can be used with tf.data.Dataset.apply, according to the official documentation. I have written some custom data loading, for which I would like to utilize this to prefetch to GPU. The problem is that this operation needs to be the last one in all transformations of the dataset. I am using tf.data.Iterator.make_initializer and tf.data.Iterator.from_structure as follows. This is a minimal example that raises the error. import tensorflow as tf class MyData(object): def __call__(self): return range(100) expected_shapes = [] expected_types = tf.int32 iterator = tf.data.Iterator.from_structure(output_types=expected_types, output_shapes=expected_shapes) dataset = tf.data.Dataset.from_generator(MyData(), output_types=expected_types, output_shapes=expected_shapes) prefetch_op = tf.contrib.data.prefetch_to_device(device="/gpu:0") dataset = dataset.apply(prefetch_op) # This raises NotImplementedError: `prefetch_to_device()` must be the last transformation in a dataset pipeline. initializer = iterator.make_initializer(dataset) Of course, this does not happen when I turn the order around, but then the prefetching transformation is not taken into account for the initializer. initializer = iterator.make_initializer(dataset) dataset = dataset.apply(prefetch_op) How can I get this to work to create the initializer after telling it to prefetch? Or is that simply not possible (currently)? I would like to avoid having to create a new Iterator, unlike this test case from tensorflow.
tagged with: python
favorite count: 0
tagged with: prefetch
has title: How to combine prefetch_to_device with make_initializer
score: 2
has comment: http://stackoverflow.com/comment/88518920
tagged with: tensorflow
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/50278344
has body: You must first get rid of NaN values: df2=df.dropna() Or replace them by mean: df2 = df.fillna(df.mean()) Or use an algorithm like EM (expectation maximization) for imputation. Then you check for correlations df2.corr() Note: if the missing values rate of a given variable are bigger than 15%, you should consider dropping it from analysis
type: Answer
answers question: http://stackoverflow.com/q/50277490
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/50351524
type: Question
score: 0
has body: The error I am receiving is : TypeError: 'NoneType' object is not subscriptable In this Method I am trying to do string matching along two files (test&amp;master). The master file contains correctly spelled product names, while the test file contains misspelling or simply differently spelled versions of those products. I am trying to match those together with the extractBests function to include a cutoff at a certain score. Also if I am printing earlier steps of my output, for example the fhp_new variable it still works. I think the error is somehow caused by the fact, that some rows to not give any matches that are within the score_cutoff limit, because I don't get the error when I put the limit on say 20. So in theory those rows should just stay empty, but this causes the error I think. This line of code is causing the error: for x in range (1, num_match + 1): d["Match{0}".format(x)] = [y[0] for y in aggregated_matches["Match" + str(x)]] This is the full Code until the line of error def StringMatch (master, testfile, num_match=3, score_cutoff=95, limit=3): master_names = master.iloc[:,3] test_names = testfile.iloc[:,0] fhp_new = [process.extractBests(x, master_names, score_cutoff=score_cutoff,limit=limit) for x in test_names] lab=" " i=1 while i&lt;=num_match: lab = lab + " " + "Match" + str(i) i = i+1 aggregated_matches = pd.DataFrame(fhp_new, columns = lab.split()) d={} for x in range (1, num_match + 1): d["Match{0}".format(x)] = [y[0] for y in aggregated_matches["Match" + str(x)]] print(d)
has comment: http://stackoverflow.com/comment/87722899
accepted answer: http://stackoverflow.com/a/50353448
has comment: http://stackoverflow.com/comment/87719610
has answer: http://stackoverflow.com/a/50353448
tagged with: python
has comment: http://stackoverflow.com/comment/87719675
type: AnsweredQuestion
tagged with: python-3.x
answer count: 1
has comment: http://stackoverflow.com/comment/87721634
has title: TypeError: 'NoneType' object is not subscriptable when creating a pd.Dataframe dictionary
tagged with: fuzzywuzzy

http://stackoverflow.com/q/50259411
answer count: 2
possible better answer: http://stackoverflow.com/a/50259617
tagged with: jinja2
type: AnsweredQuestion
score: 0
has title: Python nested Dictionary: Count the maximum number of keys for a parent key
has answer: http://stackoverflow.com/a/50259479
tagged with: python
tagged with: dictionary
type: Question
has answer: http://stackoverflow.com/a/50259617
has body: Probably my question wordings are not quite correct. Here is the question: Code: import jinja2 import pprint dict = {'PRI_KEY_1': {'SEC_KEY_1': {'KEY_1': 'abcd', 'KEY_2': 'wef'}}, 'PRI_KEY_2': {'SEC_KEY_2': {'KEY_3': 'cwc API', 'KEY_4': 'r34f', 'KEY_5': 'f4f-ef', 'KEY_6': 'dse', 'KEY_7': '78ik', 'KEY_8': 'k9k'}, 'SEC_KEY_1': {'KEY_9': 'kk7 API', 'KEY_10': '9u', 'KEY_11': 'gtgr-45gr', 'KEY_12': 'ggrer', 'KEY_13': 'nmb', 'KEY_14': 'ekj', 'KEY_15': 'das3', 'KEY_16': '5lusf', 'KEY_17': '3rt5hf', 'KEY_18': 'f4gth', 'KEY_19': 'dfghtgr', 'KEY_20': 'chy', 'KEY_21': 'xdvgrw'}}} temp_list = [] for key in dict['PRI_KEY_2']: temp_list.append(len(dict['PRI_KEY_2'][key])) print('Rowspan needed for PRI_KEY_2:',max(temp_list)) Output: Rowspan needed for PRI_KEY_2: 13 Question: Above code works. However, is there a better way to achieve this? The reason being, I am creating an html table using jinja2 where I need to define the rowspan for PRI_KEY_2 considering the maximum keys its child keys has so that the table will look like a table. BTW, My Dict has 100+ PRI_KEY_* and many more under their child, grand child keys.
accepted answer: http://stackoverflow.com/a/50259479

http://stackoverflow.com/comment/87511712
comment on: http://stackoverflow.com/a/50246948
score: 0
type: AnswerComment
has text: @WoJ Yes, but you can't do any better without tweaking the python interpreter.
type: Comment

http://stackoverflow.com/comment/87559510
comment on: http://stackoverflow.com/q/50270199
type: QuestionComment
score: 0
has text: @Andersson: I am not aware on what object i need to click.
type: Comment

http://stackoverflow.com/comment/87664915
score: 0
type: AnswerComment
has text: Sure, I'm adding the comments to my code, just gimme a minute. The keyword of the solution is `in`.
comment on: http://stackoverflow.com/a/50324319
type: Comment

http://stackoverflow.com/comment/87637582
type: QuestionComment
score: 0
has text: @o11c Another thing to note is *why* Java and C++ provided a built-in LinkedList?
comment on: http://stackoverflow.com/q/50310731
type: Comment

points
tag name: points
type: Tag
tags question: http://stackoverflow.com/q/50377031

http://stackoverflow.com/q/50267780
has comment: http://stackoverflow.com/comment/87553561
has answer: http://stackoverflow.com/a/50277513
has comment: http://stackoverflow.com/comment/87553862
has title: Python 3.X: Why numexpr.evaluate() slower than eval()?
has comment: http://stackoverflow.com/comment/87553287
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: eval
tagged with: numexpr
answer count: 1
has body: The purpose of using the numexpr.evaluate() is to speed up the compute. But im my case it wokrs even slower than numpy und eval(). I would like to know why? code as example: import datetime import numpy as np import numexpr as ne expr = '11808000.0*1j*x**2*exp(2.5e-10*1j*x) + 1512000.0*1j*x**2*exp(5.0e-10*1j*x)' # use eval start_eval = datetime.datetime.now() namespace = dict(x=np.array([m+3j for m in range(1, 1001)]), exp=np.exp) result_eval = eval(expr, namespace) end_eval = datetime.datetime.now() # print(result) print("time by using eval : %s" % (end_eval- start_eval)) # use numexpr # ne.set_num_threads(8) start_ne = datetime.datetime.now() x = np.array([n+3j for n in range(1, 1001)]) result_ne = ne.evaluate(expr) end_ne = datetime.datetime.now() # print(result_ne) print("time by using numexpr: %s" % (end_ne- start_ne)) return: time by using eval : 0:00:00.002998 time by using numexpr: __ 0:00:00.052969
tagged with: scipy
has comment: http://stackoverflow.com/comment/87553555
type: Question
accepted answer: http://stackoverflow.com/a/50277513
tagged with: numpy

http://stackoverflow.com/comment/87846627
type: Comment
type: AnswerComment
has text: For the moment I have solved my issue using `etree.register_namespace('xlink','http://www.w3.org/1999/xlink')`. As some of my issues might be related to `pip` vs `yum` on centos (potentialy the dynamic library might have the wrong version) I think there is not much point in diving deeper into this. If you however are still interested, have a look at this [question](https://graphicdesign.stackexchange.com/q/109242/121183) and [answer](https://graphicdesign.stackexchange.com/a/109264/121183). It contains a minimal example svg, and is the reason for looking into etree, the answer is the result
score: 0
comment on: http://stackoverflow.com/a/50300501

http://stackoverflow.com/q/50331920
answer count: 0
has comment: http://stackoverflow.com/comment/87679890
has comment: http://stackoverflow.com/comment/87681309
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87680350
has comment: http://stackoverflow.com/comment/87680718
has comment: http://stackoverflow.com/comment/87680382
has body: I am trying to save ~4 million websites (EDGAR SEC filings) to .txt format. To this end I have a for loop that using selenium in python opens a website, sends crtl+a and crtl+c and copys the text from clipboard into a python string element. This works fine. However, afer - what seem arbirtary intervals - the for loop breaks down, when I try to write the python string into a txt file. Essentially I am looping such that each loop creates new "text" object (which is str in python). driver = webdriver.Firefox(executable_path=path + '/codes_ml/geckodriver/geckodriver.exe') # initialize driver for row in range(1,num_urls): ticker = fund_reports_table.loc[row,"Ticker"] perioddate = fund_reports_table.loc[row,"Perioddater"] part = fund_reports_table.loc[row,"Part"] report_url = fund_reports_table.loc[row,"URL"] nbrparts= fund_reports_table.loc[row,"NbrParts"] filingdate = fund_reports_table.loc[row,"Filingdate"] driver.get(report_url) element = driver.find_element_by_css_selector("body") element.send_keys(Keys.CONTROL+'a') element.send_keys(Keys.CONTROL+'c') text = clipboard.paste() filename = ticker + "_" + filingdate + "_" + perioddate + "_" + str(part) + "of" + str(nbrparts) + ".txt" os.chdir("E:\\EDGAR_reports") output = open(filename, "wb") output.write(text.encode('utf-8', errors="ignore")) output.close() del output, text, perioddate, part, report_url, nbrparts, filingdate where fund_reports_table is a dataframe with columns as indicated in the first few lines of code. After some thousands files (strange enough it seems to vary with where they are saved to), the following error occurs: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\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-4-915577cbb167&gt;", line 21, in &lt;module&gt; output = open(filename, "wb") PermissionError: [Errno 13] Permission denied: 'QILGX_2009-07-29_2009-05-31_1of1.txt' The stran…
has comment: http://stackoverflow.com/comment/87723033
has comment: http://stackoverflow.com/comment/87680771
has comment: http://stackoverflow.com/comment/87679885
type: Question
has comment: http://stackoverflow.com/comment/87683136
has comment: http://stackoverflow.com/comment/87680643
has comment: http://stackoverflow.com/comment/87680070
has title: "open()" fails in large for loops
tagged with: python
has comment: http://stackoverflow.com/comment/87680740
has comment: http://stackoverflow.com/comment/87680232
has comment: http://stackoverflow.com/comment/87680154
has comment: http://stackoverflow.com/comment/87680822
has comment: http://stackoverflow.com/comment/87680857
score: 0

http://stackoverflow.com/q/50261024
has answer: http://stackoverflow.com/a/50263843
score: 2
type: AnsweredQuestion
tagged with: pygame
has title: Moving scalable rectangle with mouse in pygame
has body: I'm trying to move a rectangle inside of pygame, and making it scalable. The scalable rectangle code is something like this then I tried to add an event like this: from pygame imports * init() rect1 = (rect1x, rect1y, 300,300) rect1x = 0 rect1y = 0 while running: x,y = mouse.get_pos() if rect1Pressed == True: rect1x = x rect1y = y for evnt in event.get(): if evnt.type == QUIT: running = False if evnt.type == MOUSEBUTTONDOWN: if evnt.button == 1: if rect1.collidepoint(mouse.get_pos()): rect1Pressed == True How would i incorporate the scalable rectangle and being able to make it move with the mouse? So that the window will follow the mouse motion. So it kinda is like a on your laptop where your able to scale the window and also move it around.
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/50242597
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50263843
tagged with: python

http://stackoverflow.com/comment/87707305
has text: @Kopytok Do you mean defining the function in a seperate file and importing it into the main file? If you mean that, I'll give that a go !
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50345303

http://stackoverflow.com/comment/87658796
comment on: http://stackoverflow.com/q/50303437
type: Comment
has text: I found the issue. it should have been `campaign = Campaign(parent_id=account.get_id_assured())`.
type: QuestionComment
score: 1

http://stackoverflow.com/q/50266736
has answer: http://stackoverflow.com/a/50268437
downvote count: 0
has title: How to get the cross contract matrix from two 2-dim tensors in tensorflow?
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
has body: import tensorflow as tf with tf.Session() as sess: with tf.variable_scope('masssdsms'): a = tf.get_variable('a', [1000,24,128], dtype=tf.float32, initializer=tf.random_normal_initializer(stddev=0.1) ) b = tf.get_variable('b', [1000,15,128], dtype=tf.float32, initializer=tf.random_normal_initializer(stddev=0.1) ) I want to get a new tensor named c from a and b. 1000 is the batch size, and c's shape should be (1000,20, 10, 1). For every instance from a and b: ai and bi, they are both two dimensional tensors. The new instance ci is the result of ai and bi and it has 20 * 10 = 200 elements, that every element is the dot product of ai and bi with 128 dimension respectively. So there are 200 dot products results in sum. The ci is more like a 2-D image. How can I initialize this operation? Modified: When I take the codes in usage, the operation of dot product should be replaced with some other function like guassian distance, or cosine distance etc, which is contact notation in the graph. So I need to a common method to do this. Here is what I design, but I am not sure whether it is a efficient way to do this: with tf.Session() as sess: with tf.variable_scope('masssdsms'): a = tf.get_variable('a', [1000,24,128], dtype=tf.float32, initializer=tf.random_normal_initializer(stddev=0.1) ) b = tf.get_variable('b', [1000,15,128], dtype=tf.float32, initializer=tf.random_normal_initializer(stddev=0.1) ) i = 999 # for i in range(1000): ai = tf.slice(a,[i,0,0],[1,-1,-1]) # (1,24,128) bi = tf.slice(b,[i,0,0],[1,-1,-1]) # (1,15,128) ci = contact_func(ai,bi) # (1,24,15)
has answer: http://stackoverflow.com/a/50268455
tagged with: vectorization
score: 2
answer count: 2
upvote count: 2
tagged with: matrix

http://stackoverflow.com/comment/87784936
type: Comment
type: QuestionComment
has text: @cdarke `index()` works a little differently between strings and other sequences though. A string can be thought of a list of characters while `index()` will also search for multiple characters and not only one. It is not possible to search for a sublist using `index()`, for example.
score: 0
comment on: http://stackoverflow.com/q/50384147

http://stackoverflow.com/comment/87696530
type: QuestionComment
type: Comment
score: 0
has text: In the second one, you are dealing with only one variable. It starts out as one object and is then reassigned to another. When you print it, it shows the second value. If in the first, you had said `print(x)`, like Daniele's answer, it would be directly equivalent to the second.
comment on: http://stackoverflow.com/q/50339997

python-import
tags question: http://stackoverflow.com/q/50358742
tags question: http://stackoverflow.com/q/50301209
tag name: python-import
type: Tag
tags question: http://stackoverflow.com/q/50318309
tags question: http://stackoverflow.com/q/50359402
tags question: http://stackoverflow.com/q/50268137
tags question: http://stackoverflow.com/q/50370581
tags question: http://stackoverflow.com/q/50299075
tags question: http://stackoverflow.com/q/50299143
tags question: http://stackoverflow.com/q/50312470
tags question: http://stackoverflow.com/q/50384348
tags question: http://stackoverflow.com/q/50343062
tags question: http://stackoverflow.com/q/50262722
tags question: http://stackoverflow.com/q/50299676
tags question: http://stackoverflow.com/q/50293850
tags question: http://stackoverflow.com/q/50264247

http://stackoverflow.com/comment/87596564
comment on: http://stackoverflow.com/q/50289220
score: 1
type: Comment
type: QuestionComment
has text: @Mr.T No it is not an assumption, just updated with an example

http://stackoverflow.com/a/50279055
has comment: http://stackoverflow.com/comment/96887652
has comment: http://stackoverflow.com/comment/87583839
has comment: http://stackoverflow.com/comment/87632545
score: 1
answers question: http://stackoverflow.com/q/50263558
has comment: http://stackoverflow.com/comment/87613311
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87613531
has body: Quart requires a specific Gunicorn worker class1. I think if your procfile was web: gunicorn --worker-class quart.worker.GunicornWorker main_loop:app it would work. (I don't have a heroku dyno available to test though). (I am the Quart author)
type: Answer
has comment: http://stackoverflow.com/comment/87582640
has comment: http://stackoverflow.com/comment/96885779

http://stackoverflow.com/a/50766633
upvote count: 1
has body: Cubic splines are known to be prone to oscillations due to the requirement of the continuous second derivative. To avoid that, one way wound be to use instead C1 continuous splines. In the scipy land, look at PchpIntetpolator and/or Akima1DInterpolator
answers question: http://stackoverflow.com/q/50360809
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/comment/87573329
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50277845
has text: Pedantly `range()` is not an iterator, but an immutable sequence. You can iterate over a range multiple times.

http://stackoverflow.com/comment/87619374
has text: can you elaborate? what is causing the error? what is the desired output?
score: 0
comment on: http://stackoverflow.com/q/50301360
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50312896
has comment: http://stackoverflow.com/comment/87642366
has body: In the TensorFlow programmer guide the Flow Control/FizzBuzz example shows: num = tf.constant(num) if num % 3 == 0 and num % 5 == 0: However, that doesn't work for me. fiver % 5 == 0 False The only way I have gotten this to work successfully is by using: (num % 5).numpy() == 0 Are python comparisons supposed to work with the EagerTensor type? tf.equal() works, of course, but the example shows direct comparisons like == 0.
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50313196
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
has title: TensorFlow 1.8.0, eager execution and comparison don't behave as expected
has comment: http://stackoverflow.com/comment/87856632
type: Question
has comment: http://stackoverflow.com/comment/87661338
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50313196
tagged with: python

http://stackoverflow.com/a/50341395
score: 1
has body: Try following data_cleaner = [data_train, data_val] for i,df in enumerate(data_cleaner): data_cleaner[i] = pd.get_dummies(df, columns = categorical_fields) data_train,data_val=data_cleaner
type: Answer
has comment: http://stackoverflow.com/comment/107604374
answers question: http://stackoverflow.com/q/50341356
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87631095
comment on: http://stackoverflow.com/q/50307582
score: 0
has text: by the way the values in the text document are:84.5 62 23 89.9 92 82 78 76.5 99 83 88 78.2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50331744
has title: Non-ASCII characters in python 2 shebang
answer count: 1
has body: As PEP 263 says, Python 2 (specifically 2.7 in my case) requires a magic comment line to specify a file encoding: # -*- coding: utf-8 -*- Without that it is not possible to include non-ASCII characters in the file. A notorious error would be raised: SyntaxError: Non-ASCII character '[…]' in file […] on line […], but no encoding declared; see http://python.org/dev/peps/pep-0263/ However if the non-ASCII character is in the shebang interpreter path, the magic comment does not work: #!/Users/naïve/project/python2.7 # -*- coding: utf-8 -*- print 'Hello.' This happens for example if you create a virtualenv in a folder with a non-ASCII path: Many scripts with a shebang that breaks the script are created. The only workaround I could come up with is to symlink the folder into some ASCII-only path. Then it is possible to change the shebang path to the ASCII one. Or in the case of virtualenv to initialize it from the symlinked path. However this cannot be done if the non-ASCII part of the path is the user’s home path and the user does not have administration access. So I’d like to ask: Is there any other workaround for this situation, hopefully more clean? E.g. some default file encoding setting or environment variable that would Python use if it does’t find a magic comment?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: non-ascii-characters
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50331846
score: 3
tagged with: python-2.7
upvote count: 3

http://stackoverflow.com/a/54353458
type: Answer
has body: You are not activating the scrapy environment $source activate ScrapyEnvironment
answers question: http://stackoverflow.com/q/50324329
score: 0

http://stackoverflow.com/comment/87691921
score: 0
type: AnswerComment
has text: I would recommend editing the `.*?` to a `[^\]]*` to make the regex as safe as possible. Although the OP dodn't explicately mention it, they're editing wikilinks, which shouldn't have brackets within the content (unless it's recursive, which is unlikely, but the above regex does not check for matching recursive brackets anyway.)
type: Comment
comment on: http://stackoverflow.com/a/50337657

http://stackoverflow.com/comment/87717772
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50350890
has text: I think what you need here is a singleton .
score: 0

http://stackoverflow.com/a/50283305
has body: lines = [None, None, None] with open(filename, 'r') as f: for line in f: lines[0] = lines[1] lines[1] = lines[2] lines[2] = line.strip() if lines[1] and lines[2]: print(', '.join([str(l) for l in lines]))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50283152

http://stackoverflow.com/comment/87659541
comment on: http://stackoverflow.com/q/50321856
score: 1
has text: As a separate (related?) issue, it's a good idea to [compose](https://stackoverflow.com/questions/16739290/composing-functions-in-python) your functions into one rather than apply them sequentially in a `for` loop.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87732642
type: AnswerComment
comment on: http://stackoverflow.com/a/50356073
has text: When reading files, each read moves the file pointer which you do in a loop. After the loop, the pointer will stay at the end, so next time you enter the loop it will do nothing as there is nothing to read. My approach uses a Python dictionary to very quickly look up a kmer. This completely avoids needing to keep rereading the same file.
score: 0
type: Comment

http://stackoverflow.com/q/50367837
has answer: http://stackoverflow.com/a/76184457
has body: Dear Stackoverflow community, I am struggling with running a python script that executes a PyQt5 GUI on desktop startup of Raspberry Pi 3B with Raspbian Jessie. What do I have so far? Python script with shebang #!/usr/bin/env python3 in first line (python3 --version is 3.4.2) running the GUI without any problems Shell script (.sh) that is able to execute the GUI with the following lines: #!/bin/bash python3 GUI.py Information that may help: If I place both files in the same directory somewhere, the Shell script starts the GUI, but if they are on the desktop, it doesn't. Automatic login to desktop is enabled. Thank you in advance for any help. RaspiManu UPDATE: I solved my Problem with a lot of testing and posted an answer for other users.
downvote count: 0
tagged with: pyqt5
upvote count: 1
score: 1
has title: PyQt: How to run GUI on Raspberry Pi desktop startup?
possible better answer: http://stackoverflow.com/a/50369111
has answer: http://stackoverflow.com/a/50369111
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/50509384
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50509384
tagged with: raspberry-pi
type: Question
tagged with: pyqt
answer count: 3

mysql
tags question: http://stackoverflow.com/q/50303654
tags question: http://stackoverflow.com/q/50280199
tags question: http://stackoverflow.com/q/50326052
tags question: http://stackoverflow.com/q/50280579
tags question: http://stackoverflow.com/q/50319337
tags question: http://stackoverflow.com/q/50248434
tags question: http://stackoverflow.com/q/50366333
tags question: http://stackoverflow.com/q/50302418
tags question: http://stackoverflow.com/q/50352178
tags question: http://stackoverflow.com/q/50336458
tags question: http://stackoverflow.com/q/50237534
type: Tag
tags question: http://stackoverflow.com/q/50351922
tags question: http://stackoverflow.com/q/50378357
tags question: http://stackoverflow.com/q/50384795
tags question: http://stackoverflow.com/q/50349562
tags question: http://stackoverflow.com/q/50322015
tags question: http://stackoverflow.com/q/50318086
tag name: mysql
tags question: http://stackoverflow.com/q/50274139
tags question: http://stackoverflow.com/q/50383580
tags question: http://stackoverflow.com/q/50327160
tags question: http://stackoverflow.com/q/50348570
tags question: http://stackoverflow.com/q/50283716
tags question: http://stackoverflow.com/q/50323740
tags question: http://stackoverflow.com/q/50298281
tags question: http://stackoverflow.com/q/50286057
tags question: http://stackoverflow.com/q/50283520
tags question: http://stackoverflow.com/q/50313767
tags question: http://stackoverflow.com/q/50320424
tags question: http://stackoverflow.com/q/50243506
tags question: http://stackoverflow.com/q/50359807
tags question: http://stackoverflow.com/q/50260418
tags question: http://stackoverflow.com/q/50314106
tags question: http://stackoverflow.com/q/50261847
tags question: http://stackoverflow.com/q/50279131
tags question: http://stackoverflow.com/q/50256456
tags question: http://stackoverflow.com/q/50359291
tags question: http://stackoverflow.com/q/50321315
tags question: http://stackoverflow.com/q/50270618
tags question: http://stackoverflow.com/q/50381839
tags question: http://stackoverflow.com/q/50270617
tags question: http://stackoverflow.com/q/50379764
tags question: http://stackoverflow.com/q/50359668
tags question: http://stackoverflow.com/q/50244737
tags question: http://stackoverflow.com/q/50289226
tags question: http://stackoverflow.com/q/50362013
tags question: http://stackoverflow.com/q/50316965
tags question: http://stackoverflow.com/q/50232239

http://stackoverflow.com/a/50276898
has comment: http://stackoverflow.com/comment/87570521
downvote count: 0
has body: Solution without numpy: data = [[1,2,3,4,5,6],[3,2,1,4,5,6],[4,3,2,1,5,6],[1,1,1,1,1,1]] list(map(max, *data)) The list is not needed in Python 2 (or even in Python 3, depending on what you're going to do with the result)
score: 9
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/50276851
has comment: http://stackoverflow.com/comment/87572957

http://stackoverflow.com/comment/87558358
comment on: http://stackoverflow.com/q/50270521
score: 0
has text: Alright, let me just remember everything I know about `tvalues` and `ttest_1samp` and so on.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50296680
answers question: http://stackoverflow.com/q/50296546
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50296546
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87610418
score: 6
has body: Comprehensions don't work that way. Conceptually, they allow you to set and filter the individual elements of a list, not accumulate into a single variable. There is a standard idiom for getting around that though. You basically make an iterable of booleans for your condition, or just retain ones for all the elements you want and discard the others, then sum over that. As a further improvement, I would recommend using a generator expression rather than a list comprehension. It looks almost the same, but supports lazy evaluation. This means that you get all the benefits of the one-liner, without having to store the list of flag values in memory. Here is how the first option would look: L = [1,2,4,5,7,8,10] count = sum((x + d in L and x + 2 * d in L) for x in L) The second option would look like this: L = [1,2,4,5,7,8,10] count = sum(1 for x in L if (x + d in L and x + 2 * d in L)) Notice that I renamed your variable list to L so it wouldn't shadow the builtin function.
upvote count: 6
type: Answer

http://stackoverflow.com/a/50367776
type: Answer
score: 2
has body: You can have your function return a tuple with the necessary meta and unpack via sequence unpacking: def check_val(value): if value &lt; 10: previous = value return previous, 'previous' else: current = value + 10 return current, 'current' a, b = check_val(3) print(a, b) 3 previous
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50367702
accepted answer of: http://stackoverflow.com/q/50367702

http://stackoverflow.com/q/50314646
has answer: http://stackoverflow.com/a/50316326
accepted answer: http://stackoverflow.com/a/50332093
tagged with: always-on-top
tagged with: python
tagged with: kivy
has title: "Always on top" window in Kivy
score: 2
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/65745308
has body: Is there some possible way of setting kivy.Window to be always on the top of other windows. I mean something similar to tkinter.Tk().attributes('-topmost', True). I have tried to set Window.on_hide = Window.raise_window but with no success. I need to do this really badly so please write any even complicated solution Any help will be highly appreciated. EDIT: I am on Windows 10, python 3.6.5
has answer: http://stackoverflow.com/a/50332093
tagged with: window
possible better answer: http://stackoverflow.com/a/65745308
downvote count: 0
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/88198357
has text: I am getting similar performance. A code I run a lot will run just fine in the morning say but not run in the afternoon, the first line in my code is 'import numpy as np'. The error message says 'no module numpy'. I'll keep trying to run it and eventually it will run.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50287490
type: QuestionComment

http://stackoverflow.com/a/65098935
downvote count: 1
answers question: http://stackoverflow.com/q/50239507
score: 1
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/138391686
has body: An alternative approach is to set the TTY to raw mode. I wanted to time the duration of a keypress and needed this so that I didn't have to hit the enter key: #!/usr/bin/env python3 import datetime import sys import tty import termios # read a single character on a unix system # https://exceptionshub.com/python-read-a-single-character-from-the-user.html def read_unix(count: int): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(count) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch while True: start = datetime.datetime.now() char = read_unix(1) end = datetime.datetime.now() delta = end - start print(f'char={char}, delta={delta}')

http://stackoverflow.com/q/50279264
type: AnsweredQuestion
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/87575152
has title: Generating Padovan Sequence
answer count: 1
has comment: http://stackoverflow.com/comment/87577740
favorite count: 0
type: Question
has body: The Padovan sequence is governed by the relationship P(n+1) = P(n-1) + P(n-2), for n is a non-negative integer, where P(0) = P(1) = P(2) = 1. So, for instance, P(3) = 2, P(4) = 2, and P (5) = 3, and so on. I want to write a Python program Pad(n) that generates the sequence P(0), P(1), ..., P(n - 1). This is what I have this far, but it only produces a list with the ith number replicated up to the largest number in the sequence: def ith(n): first, sec, third, fourth = 1, 1, 1, 1 for i in range(3, n+1): fourth = first + sec first = sec sec = third third = fourth return fourth def pad(n): pad = ith(n) lst = [] for i in range(n): lst.append(pad) return lst I want it to produce this as an output: &gt;&gt;&gt; Pad(6) &gt;&gt;&gt;[1,1,1,2,2,3] Currently my code only produces: &gt;&gt;&gt;[4,4,4,4,4,4] I now that I append the ith value ith number of times to the list, but I dont know how to append each number in series up to and including the value for the last number. Pad(6) yields 4 since this is all the previous relationships put together. Sorry for my bad description and formulating of the problem.
has answer: http://stackoverflow.com/a/50281658
accepted answer: http://stackoverflow.com/a/50281658
has comment: http://stackoverflow.com/comment/87575710
tagged with: python
upvote count: 2

http://stackoverflow.com/a/50305388
has body: Are you trying to send some form of representation of albums via a socket? Then you need a binary representation of that object first. Using .encode() suggests that you want the string-representation of albumns, which you can get using msg = repr(albums).encode().
type: Answer
answers question: http://stackoverflow.com/q/50305321
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/50332573
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87681466
has body: I need to prepare test which will be comparing content of .json file with expected result (we want to check if values in .json are correctly generated by our dev tool). For test I will use robot framework or unittests but I don't know yet how to parse correctly json file. Json example: { "Customer": [{ "Information": [{ "Country": "", "Form": "" } ], "Id": "110", "Res": "", "Role": "Test", "Limit": ["100"] }] } So after I execute this: with open('test_json.json') as f: hd = json.load(f) I get dict 'hd' where key is: dict_keys(['Customer']) and values: dict_values([[{'Information': [{'Form': '', 'Country': ''}], 'Role': 'Test', 'Id': '110', 'Res': '', 'Limit': ['100']}]]) My problem is that I don't know how to get to only one value from Dict(e.g: Role: Test), because I can get only extract whole value. I can prepare a long string to compare with but it is not best solution for tests. Any ideas how I can get to only one row from .json file?
has comment: http://stackoverflow.com/comment/87681398
has comment: http://stackoverflow.com/comment/87681607
type: Question
has comment: http://stackoverflow.com/comment/87681834
tagged with: python-3.x
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/87682412
has title: How to compare json file with expected result in Python 3?
has comment: http://stackoverflow.com/comment/87681823
has comment: http://stackoverflow.com/comment/87681411
tagged with: python
has answer: http://stackoverflow.com/a/50332707
possible better answer: http://stackoverflow.com/a/50332707
has comment: http://stackoverflow.com/comment/87681750
favorite count: 0
has comment: http://stackoverflow.com/comment/87681526
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87681699
has comment: http://stackoverflow.com/comment/87681904
has answer: http://stackoverflow.com/a/50333044
has comment: http://stackoverflow.com/comment/87681850
accepted answer: http://stackoverflow.com/a/50333044
score: -2

http://stackoverflow.com/comment/87618208
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50300681
has text: I think so but then i am very new to pygame

http://stackoverflow.com/comment/87727884
score: 0
has text: yes, as long as those words are found in the list in the same order, it is considered a match
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50355412

http://stackoverflow.com/comment/87573379
comment on: http://stackoverflow.com/q/50278029
has text: Do you have `__init__.py` file in the directory? This is a empty file that is needed to import .py files that aren't in the default libraries.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50232026
has title: Why nested dictionary slows down numpy save?
has answer: http://stackoverflow.com/a/50234013
has comment: http://stackoverflow.com/comment/87493440
answer count: 1
has comment: http://stackoverflow.com/comment/87482150
has comment: http://stackoverflow.com/comment/87481513
has body: Suppose we have the following code import numpy as np D = [] for _ in range(200): d = [] for _ in range(300): d.append({'a': np.random.randn(64, 64, 3), 'b': np.random.randn(64, 64, 3)}) D.append(d) np.save('data', D) It takes really long time to save this data. Is there something wrong with the code, or is it because of dictionary object ? -----------------------Update---------------------------- By taking the dictionary outside, even though with same data size, it is dramatically faster. So it seems it is the dictionary which slows down the process. Is there some potential reason for that ? i.e. import numpy as np D1 = [] D2 = [] for _ in range(200): d1 = [] d2 = [] for _ in range(300): d1.append(np.random.randn(64, 64, 3)) d2.append(np.random.randn(64, 64, 3)) D1.append(d1) D2.append(d2) np.save('d1', D1) np.save('d2', D2)
type: Question
accepted answer: http://stackoverflow.com/a/50234013
has comment: http://stackoverflow.com/comment/87492564
tagged with: python
has comment: http://stackoverflow.com/comment/87482230
tagged with: numpy
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50253014
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has title: Keras LSTM Continue training after save
tagged with: python
has answer: http://stackoverflow.com/a/50253540
has body: i'm working on a LSTM model and i'd like to save it and continue later with extra data as it accumulates. My problem is that after save the model and load it again next time i run the script, the prediction is completely wrong, it just mimics the data i entered into it. Here's the model initialization: # create and fit the LSTM network if retrain == 1: print "Creating a newly retrained network." model = Sequential() model.add(LSTM(inputDimension, input_shape=(1, inputDimension))) model.add(Dense(inputDimension, activation='relu')) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2) model.save("model.{}.h5".format(interval)) else: print "Using an existing network." model = load_model("model.{}.h5".format(interval)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(trainX, trainY, epochs=epochs, batch_size=batch_size, verbose=2) model.save("model.{}.h5".format(interval)) del model model = load_model("model.{}.h5".format(interval)) model.compile(loss='mean_squared_error', optimizer='adam') The first dataset, when retrain is set to 1, is around 10 000 entries with around 3k epoch and 5% batch size. The second dataset is a single entry data. as in one row, with again 3k epochs and batch_size=1 Solved I was reloading the scaler incorrectly: scaler = joblib.load('scaler.{}.data'.format(interval)) dataset = scaler.fit_transform(dataset) Correct: scaler = joblib.load('scaler.{}.data'.format(interval)) dataset = scaler.transform(dataset) fit_transform recalculates the multipliers for the scaled values, that means there will be an offset from the original data.
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87722722
score: 0
has text: You seem to be expecting `read()` to read *lines*. It doesn't work that way, it operates at the byte level. You have to assemble the input into what you consider to be lines. You can call `readlines()` which behaves closer to what you expect, but it will not return until you indicate end-of-file by typing control-z.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50352720

http://stackoverflow.com/a/50310995
has comment: http://stackoverflow.com/comment/87638240
has comment: http://stackoverflow.com/comment/87638344
has comment: http://stackoverflow.com/comment/87638413
has comment: http://stackoverflow.com/comment/87638426
answers question: http://stackoverflow.com/q/50310878
has comment: http://stackoverflow.com/comment/87638503
type: Answer
has comment: http://stackoverflow.com/comment/87638494
has comment: http://stackoverflow.com/comment/87638296
has comment: http://stackoverflow.com/comment/87638534
has comment: http://stackoverflow.com/comment/87638354
downvote count: 0
has comment: http://stackoverflow.com/comment/87638224
has comment: http://stackoverflow.com/comment/87638266
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87638453
has comment: http://stackoverflow.com/comment/87638573
has body: During development, you can serve user-uploaded media files from MEDIA_ROOT. This is te absolute filesystem path to the directory that will hold user-uploaded files. in your settings, you should provide: # MEDIA_ROOT = os.path.join(BASE_DIR,'your_directory') MEDIA_ROOT = os.path.join(BASE_DIR,'media') # media most of the time MEDIA_URL, URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. add this in your settings # MEDIA_URL = '/your_url/' MEIDA_URL = '/media/' # most of the time You will need to do this as well by adding the following snippet to your root urls.py: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) NOTE: This helper function works only in debug. Know more here ISSUES / SUGGESTIONS In this field, rather than uploading a file to static directory, just provide your media directory, in that case, it's media. image = models.ImageField(upload_to='uploads/', verbose_name='image') Django will automatically create a directory: 'uploads' inside the MEDIA_ROOT which is media, So access all your the images that you have with # file.url {{ coin.logo.url }}
has comment: http://stackoverflow.com/comment/87638220

http://stackoverflow.com/comment/87691762
comment on: http://stackoverflow.com/q/50337074
has text: @deets it is instantly detecting a match before the game has even started
score: 0
type: Comment
type: QuestionComment

rotational-matrices
type: Tag
tag name: rotational-matrices
tags question: http://stackoverflow.com/q/50310511

http://stackoverflow.com/comment/87742505
comment on: http://stackoverflow.com/a/50363116
type: AnswerComment
has text: as usual, the country is not always at the same position - anyways, thanks for your input
score: 0
type: Comment

http://stackoverflow.com/comment/87560258
type: AnswerComment
has text: I have not seen your code and I do not know exactly what you want. I wrote a button that changes the background of the element. Write a sample of your code in the question, and we'll see.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50270715

http://stackoverflow.com/q/50324651
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87698762
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50324950
has comment: http://stackoverflow.com/comment/87698745
has answer: http://stackoverflow.com/a/50341333
answer count: 3
linked to: http://stackoverflow.com/q/21956956
score: 1
linked to: http://stackoverflow.com/q/36709165
has body: I've been trying to get this to work, but keep getting the same TypeError object has no len(). The BeautifulSoup documentation hasn't been any help. This seems to work on every tutorial I watch, and read, but not for me. What am I doing wrong? import requests from bs4 import BeautifulSoup http = requests.get("https://www.imdb.com/title/tt0366627/?ref_=nv_sr_1") print(http) This returns Response [200], but if I try to add soup... I get the len error: import requests from bs4 import BeautifulSoup http = requests.get("https://www.imdb.com/title/tt0366627/?ref_=nv_sr_1") soup = BeautifulSoup(http, 'lxml') print(soup)
favorite count: 0
type: Question
has title: bs4 object of type 'Response' has no len()
has answer: http://stackoverflow.com/a/50324754

http://stackoverflow.com/comment/87726038
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50323491
type: Comment
has text: `[x for x in range(1,30) if x <= 20 or x >=25]` or `list(range(1,21)) + list(range(25,31))`

http://stackoverflow.com/q/50232599
tagged with: cross-validation
downvote count: 0
tagged with: grid-search
tagged with: python
type: AnsweredQuestion
has body: I would like to know the difference between the score returned by GridSearchCV and the R2 metric calculated as below. In other cases I receive the grid search score highly negative (same applies for cross_val_score) and I would be grateful for explaining what it is. from sklearn import datasets from sklearn.model_selection import (cross_val_score, GridSearchCV) from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import accuracy_score, r2_score from sklearn import tree diabetes = datasets.load_diabetes() X = diabetes.data[:150] y = diabetes.target[:150] X = pd.DataFrame(X) parameters = {'splitter':('best','random'), 'max_depth':np.arange(1,10), 'min_samples_split':np.arange(2,10), 'min_samples_leaf':np.arange(1,5)} regressor = GridSearchCV(DecisionTreeRegressor(), parameters, scoring = 'r2', cv = 5) regressor.fit(X, y) print('Best score: ', regressor.best_score_) best = regressor.best_estimator_ print('R2: ', r2_score(y_pred = best.predict(X), y_true = y))
accepted answer: http://stackoverflow.com/a/50233171
has title: Interpreting sklearns' GridSearchCV best score
has comment: http://stackoverflow.com/comment/87483036
has answer: http://stackoverflow.com/a/50233171
has answer: http://stackoverflow.com/a/50233868
tagged with: scikit-learn
upvote count: 10
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50233868
linked to: http://stackoverflow.com/q/42362027
score: 10

http://stackoverflow.com/q/50291583
score: 0
has body: I have a problem with my code, I just want to write the result in csv and i got IndexError seleksi = [] p = FeatureSelection(fiturs, docs) seleksi[0] = p.select() with open('test.csv','wb') as selection: selections = csv.writer(selection) for x in seleksi: selections.writerow(selections) In p.select is: ['A',1] ['B',2] ['C',3] etc and i got error in: seleksi[0] = p.select() IndexError: list assignment index out of range Process finished with exit code 1 what should i do?
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50291610
has title: IndexError: list assignment index out of range - python
tagged with: python-2.7
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50291671
has comment: http://stackoverflow.com/comment/87599277
linked to: http://stackoverflow.com/q/8528178
has answer: http://stackoverflow.com/a/50291697
type: Question

http://stackoverflow.com/q/50349433
has answer: http://stackoverflow.com/a/50349532
has answer: http://stackoverflow.com/a/50349482
upvote count: 1
has body: For data storage purposes I am trying to recover lists of floats from a .txt file. From the string like: a = '[1.3, 2.3, 4.5]' I want to recover: a = [1.3, 2.3, 4.5] I was expecting a simple solution like list(a), but I cannot find anything like that.
has comment: http://stackoverflow.com/comment/87714633
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50349461
answer count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1894269
downvote count: 2
has title: Convert a string to a list of floats (in python)
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50349506
has comment: http://stackoverflow.com/comment/87714595
has answer: http://stackoverflow.com/a/50349546

http://stackoverflow.com/q/50361370
score: 0
upvote count: 1
has body: I have a dict likes this: mydict = { 'Peter': [21, 2, 42.0], 'Kate': [15, 3, 45.0], 'Tom': [16, 6, 96.0], 'Lucy': [28, 4, 112.0], } The key is string,value is list. I want to print mydict according to the first element in the dictionary value descending order. For example, I want this output： 'Lucy',28,4,112.0 'Peter',21,2,42.0 'Tom',16,6,96.0 'Kate',15,3,45.0 How can I output such a result？
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87739263
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50361389
accepted answer: http://stackoverflow.com/a/50361389
has title: Python print the dictionary according to the first element in the dictionary value descending order
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50273449
favorite count: 0
has comment: http://stackoverflow.com/comment/87565045
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87564542
has comment: http://stackoverflow.com/comment/87564118
tagged with: tkinter
has answer: http://stackoverflow.com/a/54679478
tagged with: frame-rate
score: 0
has body: is it possible to use the .after()-method with fps instead of defining the milliseconds. So I want a Label depicted for 6 Frames (60 Hz). --> root.after(6) instead of defining the time in ms. For example: root = tk.Tk() ListofStimuli = ["\u00B6","\u0126"] labelprint = tk.Label(root,text="+", font = ('Sans','80','bold'), bg = "white") labelprint.place(relx=.5, rely=.5, anchor="c") for elem in ListofStimuli: labelprint.config(text=elem) root.after(100, lambda: var.set(0)) root.wait_variable(var)
has comment: http://stackoverflow.com/comment/87564388
has title: Python - Tkinter - Using after method and cotroll for framerate
upvote count: 1
downvote count: 1
answer count: 1

list
tags question: http://stackoverflow.com/q/50377067
type: Tag
tags question: http://stackoverflow.com/q/50363797
tags question: http://stackoverflow.com/q/50304457
tags question: http://stackoverflow.com/q/50297639
tags question: http://stackoverflow.com/q/50317610
tags question: http://stackoverflow.com/q/50302951
tags question: http://stackoverflow.com/q/50344999
tags question: http://stackoverflow.com/q/50239927
tags question: http://stackoverflow.com/q/50269584
tags question: http://stackoverflow.com/q/50272482
tags question: http://stackoverflow.com/q/50342811
tags question: http://stackoverflow.com/q/50300948
tags question: http://stackoverflow.com/q/50338469
tags question: http://stackoverflow.com/q/50322875
tags question: http://stackoverflow.com/q/50305446
tags question: http://stackoverflow.com/q/50294043
tags question: http://stackoverflow.com/q/50285193
tags question: http://stackoverflow.com/q/50277831
tags question: http://stackoverflow.com/q/50312305
tags question: http://stackoverflow.com/q/50342113
tags question: http://stackoverflow.com/q/50294988
tags question: http://stackoverflow.com/q/50305723
tags question: http://stackoverflow.com/q/50367030
tags question: http://stackoverflow.com/q/50288130
tags question: http://stackoverflow.com/q/50321160
tags question: http://stackoverflow.com/q/50363050
tags question: http://stackoverflow.com/q/50243867
tags question: http://stackoverflow.com/q/50254107
tags question: http://stackoverflow.com/q/50343734
tags question: http://stackoverflow.com/q/50383109
tags question: http://stackoverflow.com/q/50382729
tags question: http://stackoverflow.com/q/50275535
tags question: http://stackoverflow.com/q/50378928
tags question: http://stackoverflow.com/q/50372642
tags question: http://stackoverflow.com/q/50348710
tags question: http://stackoverflow.com/q/50232940
tags question: http://stackoverflow.com/q/50263311
tags question: http://stackoverflow.com/q/50328748
tags question: http://stackoverflow.com/q/50328443
tags question: http://stackoverflow.com/q/50258653
tags question: http://stackoverflow.com/q/50272166
tags question: http://stackoverflow.com/q/50273322
tags question: http://stackoverflow.com/q/50373737
tags question: http://stackoverflow.com/q/50258511
tags question: http://stackoverflow.com/q/50254450
tags question: http://stackoverflow.com/q/50355412
tags question: http://stackoverflow.com/q/50233738
tags question: http://stackoverflow.com/q/50354360
tags question: http://stackoverflow.com/q/50360760
tags question: http://stackoverflow.com/q/50296546
tags question: http://stackoverflow.com/q/50315029
tags question: http://stackoverflow.com/q/50262652
tags question: http://stackoverflow.com/q/50330413
tags question: http://stackoverflow.com/q/50267427
tags question: http://stackoverflow.com/q/50366607
tags question: http://stackoverflow.com/q/50316132
tags question: http://stackoverflow.com/q/50230160
tags question: http://stackoverflow.com/q/50251594
tags question: http://stackoverflow.com/q/50340232
tags question: http://stackoverflow.com/q/50321843
tags question: http://stackoverflow.com/q/50314685
tags question: http://stackoverflow.com/q/50242147
tags question: http://stackoverflow.com/q/50375883
tags question: http://stackoverflow.com/q/50306315
tags question: http://stackoverflow.com/q/50243859
tags question: http://stackoverflow.com/q/50350456
tags question: http://stackoverflow.com/q/50274072
tags question: http://stackoverflow.com/q/50336690
tags question: http://stackoverflow.com/q/50317949
tags question: http://stackoverflow.com/q/50379319
tags question: http://stackoverflow.com/q/50239123
tags question: http://stackoverflow.com/q/50282633
tags question: http://stackoverflow.com/q/50240332
tags question: http://stackoverflow.com/q/50334685
tags question: http://stackoverflow.com/q/50301594
tags question: http://stackoverflow.com/q/50263151
tags question: http://stackoverflow.com/q/50240135
tags question: http://stackoverflow.com/q/50234355
tags question: http://stackoverflow.com/q/50268093

http://stackoverflow.com/comment/87627762
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50305553
has text: Getting more and more complicated!!, just simply how to do that?
type: Comment

http://stackoverflow.com/comment/87656707
type: AnswerComment
comment on: http://stackoverflow.com/a/50320464
has text: note that the code above will give you all `href`s inside the article
type: Comment
score: 0

http://stackoverflow.com/comment/87596922
score: 0
has text: I am looping through different_id list and load each different_id into arg_1 and this arg_1 i am using as paramether in sql where clause. sqlstmt2 = "select * from legislators where id in:arg_1" then I want to select all rows with different_id (compare between ID's in Oracle database and ID's from Google Sheets) and this rows insert into Google Sheets. I had this "worksheet.insert_row(rows,index)" inide loop, but it was slow. Now I want to create list of list and use it in this code: wks.insert_rows(row=1, number=1, values=values_list)
type: Comment
comment on: http://stackoverflow.com/q/50290030
type: QuestionComment

http://stackoverflow.com/q/50374882
has body: I have brain anatomy measurements from 2 different groups of individuals. One group has more individuals than the other (say n and m individuals each). I have to run the KS test on this data. I am a little unclear about the arguments to pass to the scipy two sample KS test. Will arguments to the scipy 2 sample ks test be every individual from group 1 against every individual in group 2 in a for loop ? Or is it every feature in group 1 against every other feature in group 2 ? I wrote this code but it's obviously wrong as i am using iteritems() to loop over the columns when perhaps it should be n*m ? for group1, group2 in zip(group1.transpose().iteritems(), group2.transpose().iteritems()): value, pvalue = ks_2samp(np.array(group1[1]), np.array(group2[1])) print(value, pvalue) if pvalue &gt; 0.05: print('Samples are likely drawn from the same distributions (fail to reject H0)') else: print('Samples are likely drawn from the different distributions (reject H0)')
has comment: http://stackoverflow.com/comment/87781218
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87766457
tagged with: statistics
has answer: http://stackoverflow.com/a/50375549
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87767914
tagged with: scipy
has comment: http://stackoverflow.com/comment/87767516
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87766465
has title: Two-sample Kolmogorov-Smirnov Test in Python Scipy on brain data
has comment: http://stackoverflow.com/comment/87781271

http://stackoverflow.com/comment/87617717
score: 0
type: Comment
has text: And then I still don't understand why it actually works by clicking on the link; when I inspect the code, it looks identical but one time, the script is executed the other time it isn't.
type: AnswerComment
comment on: http://stackoverflow.com/a/50300341

http://stackoverflow.com/comment/87682437
type: Comment
score: 0
has text: thank you very much.... i fixed that with html_doc = ascii(driver.page_source)
type: QuestionComment
comment on: http://stackoverflow.com/q/50331257

http://stackoverflow.com/comment/87681097
comment on: http://stackoverflow.com/q/50331601
has text: Later I removed the `@staticmethod` decorator, added `self` to the function signature and everything seems to work as intended.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50245522
has body: Is there a way to read a particular value in a text file and store it in a variable? For example, I have the following value for loss in my file: Loss per inch @ 2.500000e+00 GHz = -0.578 dB Is there a way I can retrieve only the frequency point and the value after the equals sign and store that value in a variable which can be returned by a function in python?
has comment: http://stackoverflow.com/comment/87508518
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/50245587
possible better answer: http://stackoverflow.com/a/50245586
has answer: http://stackoverflow.com/a/50245587
tagged with: text
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50245586
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has title: Store a value in a text file to a variable and return it

http://stackoverflow.com/comment/87598512
comment on: http://stackoverflow.com/q/50291216
type: Comment
type: QuestionComment
has text: Why do you say that "the "i" variable is not defined in the `(ip not in i)` case". `i` still has the value it had at the end of the `for` loop.
score: 0

http://stackoverflow.com/a/50254406
type: Answer
answers question: http://stackoverflow.com/q/50253560
score: -1
upvote count: 0
has body: If you directly want to run the script, you could do so via spark-submit: spark-submit master local[*]/yarn other_parameters path_to_your_script.py But I would suggest to go for spark API's as they are easy to use. It will lower the coding overhead. First you have to create a spark session variable so that you could access all spark functions: spark = SparkSession .builder() .appName("SparkSessionZipsExample") .config("parameters", "value") .getOrCreate() Next, if you want to load a csv file: file = spark.read.csv("path to file") You can specify optional parameters like headers, inferschema, etc: file=spark.read.option("header","true").csv("path to your file") 'file' will now be a pyspark dataframe. You can now write the end output like this: file.write.csv("output_path") Please refer to the documentation : spark documentation for transformations and other information.
downvote count: 1

http://stackoverflow.com/q/50359668
linked to: http://stackoverflow.com/q/21974169
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
type: Question
score: 3
has title: Why is an AWS Lambda python call to a MySQL RDS being cached?
tagged with: python
tagged with: mysql
accepted answer: http://stackoverflow.com/a/51516676
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51516676
upvote count: 3
tagged with: amazon-rds
answer count: 1
downvote count: 0
has body: Simplifying my program, I have a MySQL RDS DB, and I want to develop a Lambda function to get the last value inserted in a specific column. I have got the following code in a lambda function, based on this AWS tutorial: # Connexion to DB outside the handler, per AWS recomendation def lambda_handler(event, context): with conn.cursor() as cur: cur.execute("SELECT column FROM DB.table ORDER BY create_time DESC LIMIT 1;") row = cur.fetchone() return row[0] I am using pymysql. Basically, in the first call (after saving the lambda function, for example) it works as supposed to, and it returns the last value in the table. However, for any other call during a short interval (some minutes), it continues to return the same value, independent of any DB changes. Saving or Waiting for some minutes leads to the correct result. Is it possible that I'm unintentionally caching the result?
has comment: http://stackoverflow.com/comment/87736188

http://stackoverflow.com/q/50232031
answer count: 2
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/50232076
has answer: http://stackoverflow.com/a/50232074
possible better answer: http://stackoverflow.com/a/50232074
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
has title: Why all element are all NaN when construct a multiIndex Dataframe
has body: suppose I have a Dataframe like this. I want to convert this to a 2-level multiIndex Dataframe. dt st close volume 0 20100101 000001.sz 1 10000 1 20100101 000002.sz 10 50000 2 20100101 000003.sz 5 1000 3 20100101 000004.sz 15 7000 4 20100101 000005.sz 100 100000 5 20100102 000001.sz 2 20000 6 20100102 000002.sz 20 60000 7 20100102 000003.sz 6 2000 8 20100102 000004.sz 20 8000 9 20100102 000005.sz 110 110000 But when I try this code: data = pd.read_csv('data/trial.csv') print(data) idx = pd.MultiIndex.from_product([data.dt.unique(), data.st.unique()], names=['dt', 'st']) col = ['close', 'volume'] df = pd.DataFrame(data, idx, col) print(df) I find that all the element are NaN close volume dt st 20100101 000001.sz NaN NaN 000002.sz NaN NaN 000003.sz NaN NaN 000004.sz NaN NaN 000005.sz NaN NaN 20100102 000001.sz NaN NaN 000002.sz NaN NaN 000003.sz NaN NaN 000004.sz NaN NaN 000005.sz NaN NaN How to handle this situation? Thanks.
tagged with: python
upvote count: 4
accepted answer: http://stackoverflow.com/a/50232076

http://stackoverflow.com/q/50255521
has body: I've decided to put together what I need myself—this means that I've to implement some javascript in a Django form. My current form looks like this: class SoundTestPairForm(forms.Form): LANGUAGE_CHOICES = [[d['language'], d['language']] for d in Sound.objects.order_by('language').values('language').distinct()] lesson_name = forms.CharField(widget=forms.HiddenInput()) sound_pk = forms.CharField(widget=forms.HiddenInput()) master_phrase1 = forms.CharField(widget=forms.HiddenInput()) master_phrase2 = forms.CharField(widget=forms.HiddenInput()) sex = forms.MultipleChoiceField( choices=Sound.SEX_CHOICES ) starts_with = forms.MultipleChoiceField( choices=Sound.POS_CHOICES ) language = forms.MultipleChoiceField( choices=LANGUAGE_CHOICES ) user_sound = forms.ModelMultipleChoiceField( queryset=Sound.objects.all(), ) class Media: js = ('filter_queryset.js') But when I form_instance = SoundTestPairForm() and call form_instance.media.render, I get: [u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' '] For some reason, it's looking at every letter of the file name instead of the file name as a whole? render_js() gives the same result. Have I found a bug?
has answer: http://stackoverflow.com/a/50255596
type: AnsweredQuestion
has title: Django Form: When rendering 'js' attribute in Media class, Django calls on each letter of title?
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: django
accepted answer: http://stackoverflow.com/a/50255596
tagged with: python

http://stackoverflow.com/comment/87633775
comment on: http://stackoverflow.com/q/50302222
score: 0
has text: Go through the list of in that post. Make sure you have a space between cd and the directory you're trying to go into, as what you've copied here has no space. `cd` is a command that changes your current directory.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87594298
type: QuestionComment
comment on: http://stackoverflow.com/q/50275057
score: 0
has text: Geopy distance routines don't support vectorization currently. Perhaps @cffk, the author of geodesic routines, might suggest a solution there? This issue is being tracked in https://github.com/geopy/geopy/issues/189
type: Comment

http://stackoverflow.com/q/50298255
score: 0
answer count: 2
tagged with: file
possible better answer: http://stackoverflow.com/a/50298302
has comment: http://stackoverflow.com/comment/87613451
has comment: http://stackoverflow.com/comment/87613436
type: Question
accepted answer: http://stackoverflow.com/a/50298317
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50298317
has title: Copy a random file to another location (python)
tagged with: python
has answer: http://stackoverflow.com/a/50298302
has body: I want to get a random file from a folder and copy it to another folder; So, I get the files in the folder root_src = 'D:\Downloads' files = os.listdir(root_src) file = random.choice(files) new_root = os.path.join(root_src, 'new') copyfile(file, new_path) I get the following error: FileNotFoundError: [Errno 2] No such file or directory: 'file-12.jpg' So, I guess when I do random.choice I don't get the path
type: AnsweredQuestion

http://stackoverflow.com/comment/87758985
has text: Thank you, So much. It worked like a charm. Wasn't aware about this.
type: AnswerComment
comment on: http://stackoverflow.com/a/50348571
score: 0
type: Comment

http://stackoverflow.com/q/50242223
score: 0
has answer: http://stackoverflow.com/a/50242355
has body: I'm reading a bunch of txt.gz files but they have different encoding (at least UTF-8 and cp1252, they are old dirty files). I try to detect the encoding of fIn before reading it in text-mode but I get the error: TypeError: 'GzipFile' object is not callable The corresponding code: # detect encoding with gzip.open(fIn,'rb') as file: fInEncoding = tokenize.detect_encoding(file) #this doesn't works print(fInEncoding) for line in gzip.open(fIn,'rt', encoding=fInEncoding[0], errors="surrogateescape"): if line.find("From ") == 0: if lineNum != 0: out.write("\n") lineNum +=1 line = line.replace(" at ", "@") out.write(line) Traceback $ ./mailmanToMBox.py list-cryptography.metzdowd.com ('Converting ', '2015-May.txt.gz', ' to mbox format') Traceback (most recent call last): File "./mailmanToMBox.py", line 65, in &lt;module&gt; main() File "./mailmanToMBox.py", line 27, in main if not makeMBox(inFile,outFile): File "./mailmanToMBox.py", line 48, in makeMBox fInEncoding = tokenize.detect_encoding(file.readline()) #this doesn't works File "/Users/simon/anaconda3/lib/python3.6/tokenize.py", line 423, in detect_encoding first = read_or_stop() File "/Users/simon/anaconda3/lib/python3.6/tokenize.py", line 381, in read_or_stop return readline() TypeError: 'bytes' object is not callable EDIT I tried to use the following code: # detect encoding readsource = gzip.open(fIn,'rb').__next__ fInEncoding = tokenize.detect_encoding(readsource) print(fInEncoding) I have no error but it always return utf-8 even when it isn't. My text editor (sublime) detect correctly the cp1252 encoding.
tagged with: python
has comment: http://stackoverflow.com/comment/87513019
type: Question
tagged with: python-3.x
answer count: 1
linked to: http://stackoverflow.com/q/436220
accepted answer: http://stackoverflow.com/a/50242355
has comment: http://stackoverflow.com/comment/87502160
has title: "TypeError: object not callable" while using tokenize.detect_encoding()
type: AnsweredQuestion

http://stackoverflow.com/comment/87656808
type: AnswerComment
has text: ahh nice thanks! I got it. but in what i was returning i guess i was trying to get the 3 links in 1 that's why it wasn't working. now i just need to get 1 lin and it should be all good. thank a lot
score: 0
comment on: http://stackoverflow.com/a/50320464
type: Comment

http://stackoverflow.com/comment/87844856
type: Comment
comment on: http://stackoverflow.com/q/50286057
type: QuestionComment
has text: Honestly, I would like to use raw sql in such situation. django orm did not give any help on readable code and querying efficiency
score: 1

http://stackoverflow.com/comment/87583937
has text: I'm assuming d.items would be rainfall_and_state?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50283771
type: AnswerComment

http://stackoverflow.com/comment/87707030
score: 0
comment on: http://stackoverflow.com/q/50345331
has text: You should calculate vector towards center mass, yes. One way to do this to more complex objects (not polygons) could be getting the contour and "zooming out by 2 px" and placing the zoomed mask back in center mass coordinates.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50284847
tagged with: heroku
has comment: http://stackoverflow.com/comment/89092681
has comment: http://stackoverflow.com/comment/87585791
has comment: http://stackoverflow.com/comment/87585793
has title: heroku push error python 3-6
has answer: http://stackoverflow.com/a/50888987
favorite count: 0
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/9794413
has answer: http://stackoverflow.com/a/51118677
answer count: 2
has comment: http://stackoverflow.com/comment/87605664
type: UnansweredQuestion
has body: I have an issue publishing my python code to heroku keep in mind that this is my first project on heroku and first with anything to do with repositories Counting objects: 18, done. Delta compression using up to 4 threads. Compressing objects: 100% (16/16), done. Writing objects: 100% (18/18), 21.80 KiB | 0 bytes/s, done. Total 18 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----&gt; Installing python-3.6 remote: ! Requested runtime (python-3.6) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to project. remote: To https://git.heroku.com/project.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/project.git'
downvote count: 0
tagged with: python
score: 4

http://stackoverflow.com/comment/87617997
has text: But the error says it cant find ANY version of the module, so what you propose is good practice I agree, but wont solve the issue.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50295451
type: Comment

http://stackoverflow.com/a/50296090
type: Answer
has body: You're trying to save the two converted coordinates to the one location p[i], so you only ever get a single float added as a dict item, not a list of two floats. Actually, it's better to use a tuple for the coordinates (a coordinate pair is an ordered heterogeneous sequence, and a tuple consumes less RAM than a list). Here's a repaired version of your code. I've added a little bit of extra error checking to ensure that the coords can be converted to floats. p = {} for i in range(4): while True: p_input = input("Enter starting point X,Y Coordinates:") p_components = p_input.split(',') if len(p_components) != 2: print("Missing coordinate or too many coordinates, please try again.") continue try: x = float(p_components[0]) y = float(p_components[1]) except ValueError: print("Invalid coordinates", p_components, "please try again.") else: p[i] = (x, y) break print(p) demo output Enter starting point X,Y Coordinates:1,2 Enter starting point X,Y Coordinates:3,4,5 Missing coordinate or too many coordinates, please try again. Enter starting point X,Y Coordinates:3 Missing coordinate or too many coordinates, please try again. Enter starting point X,Y Coordinates:a,b Invalid coordinates ['a', 'b'] please try again. Enter starting point X,Y Coordinates: 5 , 6 Enter starting point X,Y Coordinates:7,8 Enter starting point X,Y Coordinates:3,4 {0: (1.0, 2.0), 1: (5.0, 6.0), 2: (7.0, 8.0), 3: (3.0, 4.0)}
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87609258
upvote count: 1
answers question: http://stackoverflow.com/q/50295884
has comment: http://stackoverflow.com/comment/87609661

http://stackoverflow.com/comment/134994915
comment on: http://stackoverflow.com/a/50671638
score: 0
type: Comment
type: AnswerComment
has text: If you want it, I could send you that .pyd for Py 2.7 on Windows...

http://stackoverflow.com/q/50360120
answer count: 1
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50360154
has body: I have Property and need to get the text "Property". I found the href element but when I tried get_attribute("value") on it, it returns "None"
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: webdriver
type: Question
has title: How do you get text between tags using python and webdriver?
upvote count: 3
accepted answer: http://stackoverflow.com/a/50360154

http://stackoverflow.com/comment/87753790
score: 0
type: Comment
type: QuestionComment
has text: I don't know if this is a bug or not, the docs aren't clear as they don't show what the behaviour is when passing `datetime.datetime` so there it looks like the coercion is not behaving as expected
comment on: http://stackoverflow.com/q/50367585

http://stackoverflow.com/q/50340963
has comment: http://stackoverflow.com/comment/87698203
tagged with: django
tagged with: python
tagged with: django-rest-framework
score: 0
has answer: http://stackoverflow.com/a/50341038
answer count: 1
has body: I am trying to set the field of a model to the authenticated user by overriding the perform_create() method of a viewset, but I get an error. This is my model: class Reservation(models.Model): booking = models.CharField(max_length=15, primary_key=True) creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name='user_reservations') agency = models.ForeignKey('GeneralApp.Agency', on_delete=models.PROTECT, related_name='agency_reservations') comment = models.TextField(null=True, blank=True) status = models.ForeignKey(ReservationStatus, on_delete=models.PROTECT, related_name='status_reservations') arrival_date = models.DateField() departure_date = models.DateField() register_date = models.DateField(auto_now_add=True) confirmation = models.CharField(max_length=15, null=True, blank=True) is_invoiced = models.BooleanField(default=False) def __str__(self): return "[{}]{}".format(self.booking, self.agency) def clean(self, *args, **kwargs): if self.arrival_date &gt;= self.departure_date: raise ValidationError('Departure date must be later than Arrival date.') elif self.arrival_date &lt;= timezone.datetime.now().date(): raise ValidationError('Arraival date must be later than today.') def save(self, *args, **kwargs): self.full_clean() super(Reservation, self).save(*args, **kwargs) This is my serializer: class ReservationSerializer(serializers.HyperlinkedModelSerializer): creator = serializers.ReadOnlyField(source='creator.username') class Meta: model = models.Reservation fields = ('booking', 'creator', 'agency', 'comment', 'status', 'arrival_date', 'departure_date') This is my view set: class ReservationViewSet(viewsets.ModelViewSet): queryset = models.Reservation.objects.all() serializer_class = serializers.ReservationSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) This is the error I get: TypeError at /reservations_manager/reservations/ Got a `TypeError` when calling `Reservation.objects.create()`. This may be because yo…
has title: Django rest framework overriding creation rises error
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/50321777
type: AcceptedAnswer
has body: You can use a staticmethod: class c: def __init__(self, a, b): self.a = a self.b = b @staticmethod def f(*args): return sum(args) print(c.f(2, 2)) Output: 4
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50321768
score: 1
answers question: http://stackoverflow.com/q/50321768
type: Answer

http://stackoverflow.com/comment/87486029
has text: From my understanding of the question, it is possible to change the variable via admin interface. How would you save and restore the variable if there is any change after a system/application restart? If variables are hard coded in django, a new deployment is needed for any new value?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50234254

http://stackoverflow.com/comment/111248033
comment on: http://stackoverflow.com/a/52629551
type: AnswerComment
has text: Suggest do not add `can explore on superset`, this will allowed explore chart and try different filter and condition, use `can dashboard on Superset` instead.
score: 3
type: Comment

http://stackoverflow.com/comment/87615273
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50299139
type: Comment
has text: You have multiple warnings about win32com not being found. Maybe check that first?

http://stackoverflow.com/comment/91552204
type: Comment
comment on: http://stackoverflow.com/q/50356535
score: 0
type: QuestionComment
has text: @Arihant thank you for the kind reply. Unfortunately those are global margins and will not work with the page designs for the document.

http://stackoverflow.com/a/50259920
has body: I looked at the api https://api.github.com/repos/bsullins/data/contents/MonthlySales.csv, and the response has a key,value download_url:"https://raw.githubusercontent.com/bsullins/data/master/MonthlySales.csv" This url actually contains the raw format of the csv so lets use that, as it reduces the code as well. from pprint import pprint as pp import requests import io import csv response = requests.get('https://raw.githubusercontent.com/bsullins/data/master/MonthlySales.csv') csv_val = response.text pp(csv_val) csv_dict = csv.DictReader(io.StringIO(csv_val)) dict_list = [] for a in csv_dict: dict_list.append(a) for a in dict_list: print(a) You need to use StringIO to parse string value of csv_val as csv needs in-memory stream of the string. See Python csv.DictReader: parse string?
type: Answer
has comment: http://stackoverflow.com/comment/87576401
score: 0
has comment: http://stackoverflow.com/comment/87586481
answers question: http://stackoverflow.com/q/50259649

http://stackoverflow.com/comment/105576878
has text: @mLstudent33 `import skimage.measure`
score: 7
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/55067289

http://stackoverflow.com/q/50316154
has answer: http://stackoverflow.com/a/50316298
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/50316288
has answer: http://stackoverflow.com/a/50316288
type: Question
score: 0
has title: Django: ModelForm and show data on the same url
answer count: 2
possible better answer: http://stackoverflow.com/a/50316298
tagged with: django
has body: I'm new to django and trying to create my first app and I think I might need some little help :) I have a ModelForm on a site to submit and want to show the data on the same page. I'm having trouble to set up two functions on the same page, I think i might have to use a class and set it in urls.py but I'm not able to make it work :( the code looks like this: forms.py: from django import forms from .models import Eintrag class NameForm(forms.ModelForm): class Meta: model = Eintrag fields = ['Anmeldung', 'Essen'] urls.py from django.urls import path from . import views app_name = 'form' urlpatterns = [ path('', views.get_name, name='form'), ] views.py from django.shortcuts import render from django.utils import timezone from django.contrib.auth.decorators import login_required from .forms import NameForm from .models import Eintrag @login_required() def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): eintrag = form.save(commit=False) # process the data in form.cleaned_data as required # ... # redirect to a new URL: eintrag.Name = request.user # Set the user object here eintrag.pub_date = timezone.now() # Set the user object here eintrag.save() return render(request, 'form/name.html', {'form': form}) # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'form/name.html', {'form': form}) def post_list(request): posts = Eintrag.objects.all() return render('form/post_list.html', {'posts': posts}) name.html ... {% include "form/post_list.html" %} &lt;form action="/form/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; ... post_list.html {% for post in posts %} {{ post }} {% endfor %} So the problem is in urls.py only get_name is handled and I'm clueless how I sh…

http://stackoverflow.com/comment/87541947
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50261604
has text: have you tried converting your columns to [`numeric`](http://pandas.pydata.org/pandas-docs/version/0.19/generated/pandas.to_numeric.html)?
score: 0

http://stackoverflow.com/comment/87496992
comment on: http://stackoverflow.com/q/50239611
score: 0
type: Comment
has text: I guess you have used namespace to register this url, means this url is inside your app urls.py file not in root urls.py file if so you need to prepend namespace seprated by colon i.e `{% url 'namespace:home' msg.user.pk %}`
type: QuestionComment

http://stackoverflow.com/a/50270935
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50270844
type: Answer
has comment: http://stackoverflow.com/comment/87559273
answers question: http://stackoverflow.com/q/50270844
has body: When you see a syntax error on a line that seems fine, look at the preceding line. In this case you forgot closing parenthesis. print(fdist_onegram.plot(30)
score: 2
upvote count: 3

http://stackoverflow.com/comment/87596878
score: 0
has text: Thanks for your expanded answer, @Ernest!
type: Comment
comment on: http://stackoverflow.com/a/50289677
type: AnswerComment

pipeline
type: Tag
tags question: http://stackoverflow.com/q/50333374
tag name: pipeline
tags question: http://stackoverflow.com/q/50272416
tags question: http://stackoverflow.com/q/50285973
tags question: http://stackoverflow.com/q/50329855
tags question: http://stackoverflow.com/q/50285452
tags question: http://stackoverflow.com/q/50265993

http://stackoverflow.com/comment/87614901
score: 2
comment on: http://stackoverflow.com/q/50298982
type: Comment
type: QuestionComment
has text: Frankly, I was surprised to learn that exceptions *were* iterable. According to [this answer](https://stackoverflow.com/a/258930/1126841), it was a hack to accommodate the old-old-style string exceptions.

http://stackoverflow.com/q/50288620
tagged with: pandas
has answer: http://stackoverflow.com/a/50288876
has answer: http://stackoverflow.com/a/50288681
downvote count: 1
has title: Apply function to dataframe row in pandas based on value in specific column
favorite count: 0
type: Question
upvote count: 4
has body: Suppose I have pandas dataframe, where first column is threshold: threshold,value1,value2,value3,...,valueN 5,12,3,4,...,20 4,1,7,8,...,3 7,5,2,8,...,10 And for each row I want set elements in columns value1..valueN to zero if it less then threshold: threshold,value1,value2,value3,...,valueN 5,12,0,0,...,20 4,0,7,8,...,0 7,0,0,8,...,10 How can I do this without explicit for loops?
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 2

http://stackoverflow.com/comment/87508627
has text: Thanks for the reply. However, it gives me the following error: json_obj = json.loads(match.group(1), object_pairs_hook=OrderedDict) AttributeError: 'NoneType' object has no attribute 'group'
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50245304
score: 0

django
tags question: http://stackoverflow.com/q/50265801
tags question: http://stackoverflow.com/q/50369636
tags question: http://stackoverflow.com/q/50312181
tags question: http://stackoverflow.com/q/50255222
tags question: http://stackoverflow.com/q/50256852
tags question: http://stackoverflow.com/q/50382306
tags question: http://stackoverflow.com/q/50374702
tags question: http://stackoverflow.com/q/50365289
tags question: http://stackoverflow.com/q/50330638
tags question: http://stackoverflow.com/q/50362140
tags question: http://stackoverflow.com/q/50287548
tags question: http://stackoverflow.com/q/50281488
tags question: http://stackoverflow.com/q/50327858
tags question: http://stackoverflow.com/q/50291425
tags question: http://stackoverflow.com/q/50303686
tags question: http://stackoverflow.com/q/50230551
tags question: http://stackoverflow.com/q/50361015
tags question: http://stackoverflow.com/q/50365436
tags question: http://stackoverflow.com/q/50356723
tags question: http://stackoverflow.com/q/50373229
tags question: http://stackoverflow.com/q/50343380
tags question: http://stackoverflow.com/q/50244024
tags question: http://stackoverflow.com/q/50335467
tags question: http://stackoverflow.com/q/50364171
tags question: http://stackoverflow.com/q/50347536
tags question: http://stackoverflow.com/q/50380630
tags question: http://stackoverflow.com/q/50347401
tags question: http://stackoverflow.com/q/50324934
tags question: http://stackoverflow.com/q/50369644
tags question: http://stackoverflow.com/q/50259820
tags question: http://stackoverflow.com/q/50286057
tags question: http://stackoverflow.com/q/50316675
tags question: http://stackoverflow.com/q/50240485
tags question: http://stackoverflow.com/q/50363059
tags question: http://stackoverflow.com/q/50254754
tags question: http://stackoverflow.com/q/50248626
tags question: http://stackoverflow.com/q/50278592
tags question: http://stackoverflow.com/q/50264798
tags question: http://stackoverflow.com/q/50327242
tags question: http://stackoverflow.com/q/50275890
tags question: http://stackoverflow.com/q/50341867
tags question: http://stackoverflow.com/q/50347844
tags question: http://stackoverflow.com/q/50347080
tags question: http://stackoverflow.com/q/50273979
tags question: http://stackoverflow.com/q/50259117
tags question: http://stackoverflow.com/q/50374192
tags question: http://stackoverflow.com/q/50298114
tags question: http://stackoverflow.com/q/50350268
tags question: http://stackoverflow.com/q/50285479
tags question: http://stackoverflow.com/q/50311477
tags question: http://stackoverflow.com/q/50342528
tags question: http://stackoverflow.com/q/50260242
tags question: http://stackoverflow.com/q/50316939
tags question: http://stackoverflow.com/q/50374139
tags question: http://stackoverflow.com/q/50378166
tags question: http://stackoverflow.com/q/50355591
tags question: http://stackoverflow.com/q/50255991
tags question: http://stackoverflow.com/q/50316488
tags question: http://stackoverflow.com/q/50360404
tags question: http://stackoverflow.com/q/50238905
tags question: http://stackoverflow.com/q/50259546
tags question: http://stackoverflow.com/q/50279511
tags question: http://stackoverflow.com/q/50316317
tags question: http://stackoverflow.com/q/50375320
tags question: http://stackoverflow.com/q/50378361
tags question: http://stackoverflow.com/q/50344721
tags question: http://stackoverflow.com/q/50268694
tags question: http://stackoverflow.com/q/50367562
tags question: http://stackoverflow.com/q/50245685
tags question: http://stackoverflow.com/q/50280265
tags question: http://stackoverflow.com/q/50273640
tags question: http://stackoverflow.com/q/50310338
tags question: http://stackoverflow.com/q/50260133
tags question: http://stackoverflow.com/q/50298061
tags question: http://stackoverflow.com/q/50316154
tags question: http://stackoverflow.com/q/50233842
tags question: http://stackoverflow.com/q/50286437
tags question: http://stackoverflow.com/q/50359575
tags question: http://stackoverflow.com/q/50248969
tags question: http://stackoverflow.com/q/50338729

nlp
tags question: http://stackoverflow.com/q/50326147
tags question: http://stackoverflow.com/q/50343099
tags question: http://stackoverflow.com/q/50366293
tags question: http://stackoverflow.com/q/50362506
tags question: http://stackoverflow.com/q/50327354
tags question: http://stackoverflow.com/q/50344228
tags question: http://stackoverflow.com/q/50317073
tags question: http://stackoverflow.com/q/50368930
tags question: http://stackoverflow.com/q/50282082
tags question: http://stackoverflow.com/q/50336395
tags question: http://stackoverflow.com/q/50264369
tags question: http://stackoverflow.com/q/50261008
tags question: http://stackoverflow.com/q/50302910
tags question: http://stackoverflow.com/q/50305252
tags question: http://stackoverflow.com/q/50373248
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/50384894
tags question: http://stackoverflow.com/q/50302569
tags question: http://stackoverflow.com/q/50257925
tags question: http://stackoverflow.com/q/50347481
tags question: http://stackoverflow.com/q/50352777
tags question: http://stackoverflow.com/q/50295529
tags question: http://stackoverflow.com/q/50275100
tags question: http://stackoverflow.com/q/50255752
tags question: http://stackoverflow.com/q/50340611
tags question: http://stackoverflow.com/q/50288006
tags question: http://stackoverflow.com/q/50383746

http://stackoverflow.com/a/50357223
score: 0
type: Answer
has body: Try putting Index in single quotes like this: c.execute("INSERT INTO 'Index' VALUES (:token, :frequency, :docID)", {'token': token, 'frequency': frequency, 'docID': docID}) Index is a reserved keyword.
answers question: http://stackoverflow.com/q/50357142

http://stackoverflow.com/q/50233972
tagged with: python
has comment: http://stackoverflow.com/comment/87495125
tagged with: regex
tagged with: text
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87485370
upvote count: 1
has title: text selection using greedy and reluctant
favorite count: 0
has comment: http://stackoverflow.com/comment/87491319
tagged with: pattern-matching
type: Question
has body: I am trying to extract text between markers. But these markers are word tokens and repeat frequently. input is EDGAR txt files. My markers are ITEM some number ie. ITEM 1 and ITEM2. my regex is MDA_regex = 'item[^a-zA-Z\n]*\d\s*\.\s*management\'s discussion and analysis.*?item[^a-zA-Z\n]*\d\s*' It is working fine but it fails if keyword item\d... occur between ITEM 1 AND ITEM 2. If i use .* it goes to other unwanted marker as the reports may contains other item\d.... If use .*? it will stuck at first occurance of item. I cannot hardcode 1 and 2 because different reports can have different position/header ie. item 7 to item 8 for my required text. I am using python for fileName in os.listdir(path): fileName = os.path.join(path, fileName) if os.path.isfile(fileName): print("opening new file " + fileName) with open(fileName, 'r', encoding='utf-8', errors='replace') as in_file: content = in_file.read().replace('\n',' ') mda_list=re.findall(MDA_regex,content, re.IGNORECASE|re.DOTALL) print(mda_list) print(len(mda_list)) My input is like Management's Discussion and Analysis of Financial Condition and Results of Operations............................................. 22 Item 3. ITEM 1 . MANAGEMENT'S DISCUSSION AND ANALYSIS OF FINANCIAL CONDITION AND RESULTS OF OPERATIONS. FORWARD-LOOKING STATEMENTS This report contains forward-looking statements. Additional written or oral forward-looking statements may be made by AMERCO from time to time in filings with the Securities and Exchange Commission or otherwise. Management believes such forward-looking statements are within the meaning of the safe-harbor provisions. Such item 1 statements may include, but not be limited to, projections of revenues, income or &lt;PAGE&gt; 33 ITEM 2. QUANTITATIVE AND QUALITATIVE DISCLOSURES ABOUT MARKET RISK DFDFDLF;DF SDLKD dlfldfkdffd;fl;l sdsl; dklkkdsmm,sd item 4 DDFLDFL dlkdsldkf dldfd;lf;f Also 'item' can not be caps because some reports have caps and some don,t. Can someone suggest how to h…
type: UnansweredQuestion

http://stackoverflow.com/q/50356802
possible better answer: http://stackoverflow.com/a/50357047
favorite count: 0
has answer: http://stackoverflow.com/a/50357047
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50357098
answer count: 3
tagged with: filenames
score: 1
has comment: http://stackoverflow.com/comment/88839425
has body: Heyo! I am trying to change the filenames of all of the pictures in folder to a new naming schema so that a program I am using can recognize it. the current naming schema is 'cam1_###.png' where the ### is the number in the sequence. For example, the first photo is named, "cam1_000.png". What I am trying to get to is the following naming schema: 'cam1_r###_####_rgb.png' where the 'r###' and the '####' increases by one everytime. For example, the first image in the folder, 'cam1_000.png", would be renamed 'cam1_r000_0000_rgb.png' and the 100th photo would be renamed from 'cam1_099.png' to 'cam1_r099_0099_rgb.png' I feel like this should be super easy, but I'm having trouble with the formatting :/ here is what I currently have: files = os.listdir(".") i = 1 for file in files: os.rename(file, file + 'r_'+i+'_'+i+'.png') i = i+1 Thanks in advance for any advice/redirection!
type: Question
tagged with: python-3.x
has title: Multi-Variable File Naming Convention
accepted answer: http://stackoverflow.com/a/50357060
downvote count: 0
upvote count: 1
tagged with: python
tagged with: string
has answer: http://stackoverflow.com/a/50357060

http://stackoverflow.com/q/50302238
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
has title: How can these 2 loops be vectorized in Python?
tagged with: kalman-filter
score: 1
has body: I'm retrieving close to 400k values in values, which is pretty slow by itself (that code is not being shown), and then I try to do a prediction of those values through a Kalmann filter, the first loop is taking a little over a minute to run, and the second aroun 2 and half minutes, I think the first can be vectorized, but I'm not sure how, specially the window_sma. The second loop I'm not sure how I could deal with the i increasing the x array (x = np.append(x, new_x_col, axis=1)). This is the first one, which tries to do a prediction based on the values from SMA, using polyfit and polyval: window_sma = 200 sma_index = 500 offset = 50 SMA = talib.SMA(values, timeperiod = window_sma) vector_X = [1, 2, 3, 15] sma_predicted = [] start_time = time.time() for i in range (sma_index, len(SMA)): j = int(i - offset) k = int(i - offset / 2) window_sma = [SMA[j], SMA[k], SMA[i]] polyfit = np.polyfit([1, 2, 3], window_sma, 2) y_hat = np.polyval(polyfit, vector_X) sma_predicted.append(y_hat[-1]) And the second one, which attemps to filter the output of the first for loop to have a better prediction of the values I got from SMA: # Kalman Filter km = KalmanFilter(dim_x = 2, dim_z = 1) # state transition matrix km.F = np.array([[1.,1.], [0.,1.]]) # Measurement function km.H = np.array([[1.,0.]]) # Change in time dt = 0.0001 a = 1.5 # Covariance Matrix km.Q = np.power(a, 2) * \ np.array([[np.power(dt,4)/4, np.power(dt,3)/2], [np.power(dt,3)/2, np.power(dt,2)]]) # Variance km.R = 1000 # Identity Matrix I = np.array([[1, 0], [0, 1]]) # Measurement Matrix km.Z = np.array(sma_predicted) # Initial state x = np.zeros((2,1)) x = np.array([[sma_predicted[0]], [0]]) # Initial distribution state's covariance matrix km.P = np.array([[1000, 0], [0, 1000]]) for i in range (0, len(sma_predicted) - 1): # Prediction new_x_col = np.dot(km.F, x[:, i]).reshape(2, 1) x = np.append(x, new_x_col, axis=1) km.P = km.F * km.P * km.F.T + km.Q # Correction K = np.dot(km.P, km.H.T) / (np.dot(np.dot(km.H, km.P)…
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50302342
tagged with: for-loop

http://stackoverflow.com/q/50238800
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87496620
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: opencv
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87497111
has comment: http://stackoverflow.com/comment/87496444
has title: TLS error when pip installing with virtual env
upvote count: 1
tagged with: virtualenv
has body: I'm trying to install opencv using pip install opencv-python in the virtual env I have tensor flow installed in and I get the error Collecting opencv-python Cache entry deserialization failed, entry ignored Could not fetch URL https://pypi.python.org/simple/opencv-python/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Could not find a version that satisfies the requirement opencv-python (from versions: ) No matching distribution found for opencv-python It installs when I use a diff env, but it only installs 3.4.0.12 and I want 3.4.1

http://stackoverflow.com/q/50260339
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87538655
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/54528859
type: Question
has comment: http://stackoverflow.com/comment/87538735
has comment: http://stackoverflow.com/comment/87538710
tagged with: python-unittest
tagged with: python
has comment: http://stackoverflow.com/comment/87538727
has title: When is unittest.addCleanup() executed?
linked to: http://stackoverflow.com/q/37534021
has comment: http://stackoverflow.com/comment/87543157
has comment: http://stackoverflow.com/comment/87538695
has body: I have some doubt with respect to addCleanup() -- When addCleanup() will be executed, only when there is a failure in any steps or it will be executed in normal scenarios too (when there is no failure)? If there is some failure in test, tearDown() will be called but if some steps in tearDown() fails, can we add addCleanup() in tearDown() to call some function which can do a proper cleanup?
has comment: http://stackoverflow.com/comment/87538787
upvote count: 2
has comment: http://stackoverflow.com/comment/87547223

http://stackoverflow.com/a/57520238
upvote count: 15
has comment: http://stackoverflow.com/comment/102498992
answers question: http://stackoverflow.com/q/50361218
has comment: http://stackoverflow.com/comment/101805039
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/101662134
score: 15
accepted answer of: http://stackoverflow.com/q/50361218
has comment: http://stackoverflow.com/comment/101805211
has comment: http://stackoverflow.com/comment/101804528
has comment: http://stackoverflow.com/comment/131684686
has body: Sphinx 2.2 adds templating for the reST files generated by sphinx-apidoc. Use the --templatedir option to set the path to a dir containing module.rst_t, package.rst_t and toc.rst_t files. The files can be created from the corresponding files in site-packages/sphinx/templates/apidoc. Then, in package.rst_treplace {{- [submodule, "module"] | join(" ") | e | heading(2) }} with {{- submodule | e | heading(2) }} Repeat for module.rst_t.

http://stackoverflow.com/q/50231298
downvote count: 1
has answer: http://stackoverflow.com/a/50260776
favorite count: 0
has title: Loading FITS images with PyTorch
type: Question
tagged with: python
tagged with: astropy
has answer: http://stackoverflow.com/a/51149169
possible better answer: http://stackoverflow.com/a/50241044
tagged with: fits
has answer: http://stackoverflow.com/a/50241044
tagged with: pytorch
type: AnsweredQuestion
score: 0
has body: I'm trying to create a CNN using PyTorch but my images need importing from the FITS format rather than conventional .png or .jpeg etc. Is there a way to accomplish this easily using torch.utils.data.DataLoader or is there a place in the source code where I can put in a clause which will handle FITS files while loading in? I have looked in the documentation and the most relevant thing I've found is the ToPILImage transformer which converts a tensor or ndarray into a PIL Image. Currently I'm using an image loading routine as follows: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision batch_size = 4 transform = transforms.Compose( [transforms.Resize((32,32)), transforms.ToTensor(), ]) trainset = dset.ImageFolder(root="Documents/Image_data",transform=transform) train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,shuffle=True) Astropy: http://www.astropy.org/ Pytorch: https://pytorch.org/ torch.utils: https://pytorch.org/docs/master/data.html UPDATE: Perhaps using torchvision.datasets.DatasetFolder instead of DataLoader, an inserting in my own FITS handler would work? When trying to use this class I get the following error: AttributeError: module 'torchvision.datasets' has no attribute 'DatasetFolder' Is DatasetFolder actually supported by torchvision at this point in time?
answer count: 3
accepted answer: http://stackoverflow.com/a/50260776
upvote count: 1

http://stackoverflow.com/q/50260732
has comment: http://stackoverflow.com/comment/87543191
tagged with: python
has body: I created celery task and it should start each hour at the 0th minute, but it does not run. What doing wrong? celery from __future__ import absolute_import, unicode_literals import os import pytz from celery import Celery from datetime import datetime from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app', broker='amqp://rabbit:5672') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(crontab(minute=0, hour='0,1,2,3,4,5,6,7,8,9,10,11,12, \ 13,14,15,16,17,18,19,20,21,22,23,24'), task.s()) @app.task def task(): #any code In the terminal, I see this info, but the task is not running [2018-05-09 19:05:16,275: INFO/Beat] beat: Starting...
type: Question
has comment: http://stackoverflow.com/comment/87543316
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50262746
has comment: http://stackoverflow.com/comment/87543520
tagged with: celery
linked to: http://stackoverflow.com/q/40832819
score: 0
has title: Celery task not run at the specified time

http://stackoverflow.com/comment/87591905
score: 0
comment on: http://stackoverflow.com/q/50287816
has text: try to add user field in profile as `user = models.OneToOneField(User, on_delete=models.CASCADE) and migrate the changes. `
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87767091
comment on: http://stackoverflow.com/a/50300654
score: 0
has text: Some people still contribute to `pyethereum` because they have legacy dependencies, but you are correct, there isn't much support. It is considered deprecated, and will be phased out soon.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50318613
has answer: http://stackoverflow.com/a/50319104
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50319027
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has title: convert directory-tree like strings into nested list data structure python
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has body: I have a list of 'directory-tree-like' strings. I want to convert it into a nested list (or another kind of data structure), to emphasize the dependencies. for example, the input: hierarchy_list dir1 dir1/dir1.1 dir1/dir1.2 dir1/dir1.3/dir1.3.1/dir1.3.1.1 dir1/dir1.1/dir1.1.1 dir1/dir1.1/dir1.1.2 need to be converted to: dir1 -&gt; dir1.1 -&gt; dir1.1.1 , dir1.1.2 dir1.2 dir1.3 -&gt; dir1.3.1 , dir1.3.2 where the '->' symbolize 'contains' (in a form of array attribute or equivalent). dir1 contains list of dir1.1 , 1.2 , 1.3 dir1.1 contains list of dir1.1.1 , dir1.1.2 and so on... Does someone have an idea how to do it in Python (algorithm and implementation)?
tagged with: sorting
tagged with: data-structures

http://stackoverflow.com/comment/87741947
has text: getChanEXR is just a def I created based on openEXR python code from the documentation. This is how I get the channel data. `def getChanEXR(curEXRStr, curChannel, dataType): #import OpenEXR, Imath, array pt = 'none' if dataType == 'HALF': pt = Imath.PixelType(Imath.PixelType.HALF) if dataType == 'FLOAT': pt = Imath.PixelType(Imath.PixelType.FLOAT) if dataType == 'UINT': pt = Imath.PixelType(Imath.PixelType.UINT) chanstr = OpenEXR.InputFile(curEXRStr).channel(curChannel, pt) chan = array.array('f', chanstr) return chan`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50324495

http://stackoverflow.com/comment/87726866
type: Comment
comment on: http://stackoverflow.com/q/50304156
type: QuestionComment
has text: To clarify, does the model run after these messages?
score: 1

http://stackoverflow.com/comment/87487509
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50234207
has text: run `sessionInfo()` in your python's R implementation
type: Comment

http://stackoverflow.com/a/50328420
answers question: http://stackoverflow.com/q/50327628
score: 0
has body: My approach would be to just duplicate the existing axes and give them different tick Labels, namely those of the two futher columns: fig = plt.figure() plt.plot(df['percentage'],df['confidence']) plt.ylabel('confidence') plt.xlabel('percent of population') plt.xticks(df['percentage']) plt.yticks(df['confidence']) yt = plt.yticks() yl = plt.ylim() plt.twinx() plt.yticks(yt[0], df['threshold']) plt.ylim(yl) plt.ylabel('threshold') xt = plt.xticks() xl = plt.xlim() plt.twiny() plt.xticks(xt[0], df['size']) plt.xlim(xl) plt.xlabel('size') plt.tight_layout()
type: Answer

http://stackoverflow.com/comment/105528642
type: QuestionComment
comment on: http://stackoverflow.com/q/50351457
type: Comment
score: 0
has text: did you solve this? If yes please tell me how?

http://stackoverflow.com/comment/87692333
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50338038
has text: Is there a reason you're not using `numpy`? Also, you haven't show your code to get that output for us to assist with.

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/50351474
type: Tag

http://stackoverflow.com/a/50361499
answers question: http://stackoverflow.com/q/50361096
score: 2
has comment: http://stackoverflow.com/comment/87757094
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87755743
has body: Looking at the error invalid literal for int() We see that the problem is that the expected type of the label is not an array, but a single value corresponing to the class of the sample. In other words, you need to convert the label from multi label binarization encoding to a single number. One way to do it is by first converting the array to a string and then use a StringIndexer: to_string_udf = udf(lambda x: ''.join(str(e) for e in x), StringType()) df = df.withColumn("labelstring", to_string_udf(df.label)) indexer = StringIndexer(inputCol="labelstring", outputCol="label") indexed = indexer.fit(df).transform(df) This will make a separate category (class label) for each unique array.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50361096
type: Answer

http://stackoverflow.com/comment/87686331
score: 0
type: Comment
has text: Honestly I don't understand what problem do you mean (as I said, I new in keras). I feed input data with shape (62714, 60)
comment on: http://stackoverflow.com/a/50321980
type: AnswerComment

http://stackoverflow.com/comment/87621875
comment on: http://stackoverflow.com/q/50302730
score: 0
has text: I have python 3
type: Comment
type: QuestionComment

python-3.5
tags question: http://stackoverflow.com/q/50365332
type: Tag
tags question: http://stackoverflow.com/q/50384549
tags question: http://stackoverflow.com/q/50353517
tags question: http://stackoverflow.com/q/50342960
tags question: http://stackoverflow.com/q/50316400
tags question: http://stackoverflow.com/q/50295180
tag name: python-3.5
tags question: http://stackoverflow.com/q/50316789
tags question: http://stackoverflow.com/q/50379559
tags question: http://stackoverflow.com/q/50358110

http://stackoverflow.com/a/50299312
has comment: http://stackoverflow.com/comment/87646226
type: Answer
has comment: http://stackoverflow.com/comment/87642916
answers question: http://stackoverflow.com/q/50274194
has comment: http://stackoverflow.com/comment/87645985
downvote count: 0
upvote count: 1
has body: If this is something that is repeated often, and you want to centralize the logic and not have to deal with variables at all, then a Custom Locator Strategy, An example inspired by your question: *** Test Cases *** Test Case Add Location Strategy table Custom Locator Strategy Page Should Contain Element table=3 *** Keywords *** Custom Locator Strategy [Arguments] ${browser} ${criteria} ${tag} ${constraints} ${element}= Get Webelement css=.tr &gt; td:nth-child(${criteria}) [Return] ${element} This will then work for all keywords that takes a locator as an input argument. The Custom Locator Strategy only needs to return an Web element. An alternative that in my view fulfills the inline criteria, but in my opinion is not more readable (leave that to the reader) is to use the string object functions. They are described in and around the Advanced Variable Syntax section of the Robot Framework Guide: *** Variables *** ${locator_template} css=.tr &gt; td:nth-child(%) *** Test Cases *** TC Log Locator Template: "${locator_template}" ${locator} Set Variable ${locator_template.replace("%", "9")} Log Locator Variable: "${locator}" Log Inline Variable: "${locator_template.replace("%", "9")}" Log Locator Template: "${locator_template}" This example shows how to use the object functions inline. As the Python String object has the method replace, it will provide for a stable way of replacing the same variable and using it's replace output for further assignment in keywords. It will yield the following result: Starting test: Robot.String Replace.TC 20180513 12:25:21.057 : INFO : Locator Template: "css=.tr &gt; td:nth-child(%) 20180513 12:25:21.058 : INFO : ${locator} = css=.tr &gt; td:nth-child(9) 20180513 12:25:21.059 : INFO : Locator Variable: "css=.tr &gt; td:nth-child(9)" 20180513 12:25:21.060 : INFO : Inline Variable: "css=.tr &gt; td:nth-child(9)" 20180513 12:25:21.061 : INFO : Locator Template: "css=.tr &gt; td:nth-child(%)" Ending test: Robot.String Replace.TC As you can te…
score: 1
accepted answer of: http://stackoverflow.com/q/50274194
type: AcceptedAnswer

http://stackoverflow.com/q/50286355
has comment: http://stackoverflow.com/comment/87589400
tagged with: javascript
tagged with: python
tagged with: jquery
has title: How to prevent setInterval function from executing twice in Javascript?
tagged with: ajax
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50287054
has comment: http://stackoverflow.com/comment/87588842
answer count: 3
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/50286440
accepted answer: http://stackoverflow.com/a/50287054
has answer: http://stackoverflow.com/a/50286440
linked to: http://stackoverflow.com/q/5786851
has body: I am making JS Ajax call to update the contents of a page every 2 seconds. To do this I am using setInterval method. I have noticed that my setInterval method executed twice and as a result i get duplicate output. Check the images for reference. My Flask backend - routes.py @app.route('/image/<im>') @login_required def image(im): image_src=[im+'/'+i for i in os.listdir(os.path.join(app.static_folder,im))] rows=math.ceil(len(image_src)/3) print(image_src) return render_template('dashboard.html',title='Welcome',images=image_src,rows=rows,image_date=im) My HTML - dashboard.html {% extends "base.html" %} {% block content %} DASHBOARD {% if images %} {% set ns = namespace(counter=0) %} {% for row in range(rows) %} {% for data in range(3) %} {% if ns.counter < images|length %} {% set ns.counter = ns.counter + 1 %} {% endif %} {% endfor %} {% endfor %} {% endif %} {% endblock %} base.HTML - {{ moment.include_jquery() }} {{ moment.include_moment() }} {% if title %} {{ title }} {% else %} Welcome_segregator {% endif %} {% if current_user.username %} Welcome ! {% else %} Welcome {% endif %} Home Dashboard About Us Feedback {% if current_user.is_anonymous %} Login {% else %} Logout {% endif %} {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} {% block content %}{% endblock %} The setInterval method updates the page every 2 seconds and then calls the update() function. update function implements a custom notification at the end of the HTML file which notifies the user if there is any new item. As you can see in Image 1 and 2 , the notifications are being delivered twice on the page. IMPORTANT :- The duplicate values are not being added immediately. For the case when there is no new image, the message "No new images" is added after 2 seconds i.e there is a gap of 2 seconds between the display of duplicate "No new images". However, when there is a …
type: Question
has answer: http://stackoverflow.com/a/50287241

http://stackoverflow.com/comment/87722251
score: 0
type: Comment
has text: How do I verify if all values are strings?
type: QuestionComment
comment on: http://stackoverflow.com/q/50352653

http://stackoverflow.com/comment/87697047
has text: @niefpaarschoenen I don't know how many you're looking to pick and how you're looking to distribute them, but yes, filtering the groups with `random.sample` or `letter for letter in group if random.random() > q` or whatever _before_ the `product` will be hugely faster, even if it may (depending on what you want to do) be more complicated.
type: AnswerComment
comment on: http://stackoverflow.com/a/50340206
score: 1
type: Comment

http://stackoverflow.com/comment/87505183
has text: There are [529 existing questions on SSL: CERTIFICATE_VERIFY_FAILED](https://stackoverflow.com/search?q=SSL%3A+CERTIFICATE_VERIFY_FAILED), please figure out which is your solution then close this as duplicate.
score: 4
comment on: http://stackoverflow.com/q/50236117
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50297777
has answer: http://stackoverflow.com/a/50298068
tagged with: dataframe
has title: Remove low frequency words
has comment: http://stackoverflow.com/comment/87612435
favorite count: 0
type: Question
answer count: 2
downvote count: 2
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/50297841
has comment: http://stackoverflow.com/comment/87612668
has comment: http://stackoverflow.com/comment/87612497
has comment: http://stackoverflow.com/comment/87612670
tagged with: text
tagged with: replace
score: 4
possible better answer: http://stackoverflow.com/a/50298068
has answer: http://stackoverflow.com/a/50297841
tagged with: pandas
type: AnsweredQuestion
has body: I have a dataframe with 2 columns, 1 column has string of words, ex: Col1 Col2 0 1 how to remove this word 1 5 how to remove the word I would like to remove all words that occurred once in the whole dataframe (threshold =1), I would get for example: (better if I can specify the threshold) Col1 Col2 1 5 how to remove word Any suggestions ? Thanks !

http://stackoverflow.com/a/50318914
type: Answer
has comment: http://stackoverflow.com/comment/87654107
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50318887
has body: One thing you can do is add a __init__.py file under my-package so that the my-package will become a package directory so that the modules inside it can be imported to the file
score: 1

http://stackoverflow.com/q/50358598
has body: I have a pandas DataFrame with 1,000 columns and 30 million sample rows. I need to perform some operations(lets say addition,multiplication etc.,) on each column. If some value in any column after operation changes to 0, then I need to stop applying operations further on remaining columns and rows. Also, I would like to know at which column and row it changed to 0. I have used iterrows with a few checks, but there is a performance issue as there is lots of data. Also, is there any alternatives to apply, iterrows? ID PID PC TID 10 1005 8017 3 11 10335 5019 2 12 1000 8017 1 13 243 8870 1 14 4918 8305 3 15 9017 8305 3 Apply operations column-wise: Col1 subtract by 9. Col2 subtract by 1000. Col3 divide by 100. Col4 subtract by 1. After doing apply on second column, 3rd value is 0 and then whole process should be stopped and return the 2nd column 3rd row. Output: If Column wise operations are performed: ID PID PC TID 1 5 8017 3 2 9335 5019 2 3 0 8017 1 4 243 8870 1 5 4918 8305 3 6 9017 8305 3 If row wise operations are performed : ID PID PC TID 1 5 80.17 2 2 9335 50.19 1 3 0 8017 1 13 243 8870 1 14 4918 8305 3 15 9017 8305 3
has answer: http://stackoverflow.com/a/50359156
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87812584
type: Question
tagged with: python-3.x
has title: Stop apply when condition is met
score: 3
has comment: http://stackoverflow.com/comment/87734774
has comment: http://stackoverflow.com/comment/87734669
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87734952
has answer: http://stackoverflow.com/a/50359571
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87734166
has comment: http://stackoverflow.com/comment/87733846
has comment: http://stackoverflow.com/comment/87733801
upvote count: 4
has comment: http://stackoverflow.com/comment/87812697
has comment: http://stackoverflow.com/comment/87734072
answer count: 2
has comment: http://stackoverflow.com/comment/87734859
tagged with: pandas
has comment: http://stackoverflow.com/comment/87734150

http://stackoverflow.com/q/50383022
has answer: http://stackoverflow.com/a/50383046
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50383046
upvote count: 7
downvote count: 1
score: 6
has body: I have a column FileName in pandas dataframe which consists of strings containing filenames of the form . The filename can contain dots('.') in them. For example, a a.b.c.d.txt is a txt file. I just want to have another column FileType column containing only the file extensions. Sample DataFrame: FileName a.b.c.d.txt j.k.l.exe After processing: FileName FileType a.b.c.d.txt txt j.k.l.exe exe I tried the following: X['FileType'] = X.FileName.str.split(pat='.') This help me split the string on .. But how do I get the last element i.e. the file extension? Something like X['FileType'] = X.FileName.str.split(pat='.')[-1] X['FileType'] = X.FileName.str.split(pat='.').pop(-1) did not give the desired output.
tagged with: string
favorite count: 0
has title: Extracting the file extensions from file names in pandas
type: Question
has answer: http://stackoverflow.com/a/50383151
possible better answer: http://stackoverflow.com/a/50383151

http://stackoverflow.com/q/50324848
type: Question
has answer: http://stackoverflow.com/a/50325499
has answer: http://stackoverflow.com/a/50325511
linked to: http://stackoverflow.com/q/45999792
has title: Python Pandas: How do I apply a function requiring an extended class (datetime)?
tagged with: datetime
downvote count: 0
tagged with: python
has body: How can I use pandas apply for a function that requires an extension of a standard class (datetime)? Specifically, I would like to import datetime_modulo from the excellent gist at https://gist.github.com/treyhunner/6218526. This code extends the standard datetime class to allow the modulo operation to be applied to datetime objects, e.g. from datetime_modulo import datetime from datetime import timedelta d = datetime.now() print d % timedelta(seconds=60) Now I need to apply this modulo operation to a pandas DataFrame column/Series, e.g. df['dates'] = pd.to_datetime(df.index.values) df['datetime_mod'] = df['dates'].apply(lambda x: x % timedelta(minutes=15)) But pandas is not able to detect the extended datetime class (unless I am just using it wrongly): TypeError: unsupported operand type(s) for %: 'Timestamp' and 'datetime.timedelta' How to proceed?
possible better answer: http://stackoverflow.com/a/50325511
type: AnsweredQuestion
score: 3
tagged with: class-extensions
answer count: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/50325234
accepted answer: http://stackoverflow.com/a/50325499
favorite count: 0

http://stackoverflow.com/comment/87559130
type: Comment
has text: Can you post the full traceback?
type: QuestionComment
comment on: http://stackoverflow.com/q/50270917
score: 0

http://stackoverflow.com/comment/87528257
score: 0
type: AnswerComment
type: Comment
has text: This worked - thanks very much. Will look into Aho-Corasick as well.
comment on: http://stackoverflow.com/a/50241659

http://stackoverflow.com/a/50273501
answers question: http://stackoverflow.com/q/50273461
has comment: http://stackoverflow.com/comment/87564216
has body: This is the line causing the error: args = {'form': form, 'name': name, 'sn': sn, 'desc': desc} name, sn, and desc are not defined here. So, you need to grab the saved object and access its attributes: if form.is_valid(): inventory = form.save() args = {'form': form, 'name': inventory.name, 'sn': inventory.sn, 'desc': inventory.desc} ...though this will fail when the form is not valid. So, you might need to add some code to handle that condition.
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/52787324
answers question: http://stackoverflow.com/q/50258287
has comment: http://stackoverflow.com/comment/101283666
has body: You can pass a number of keyword arguments to tifffile's imsave function. It's not very well documented, so what I found most helpful was to read the docstring for the save function in the TiffWriter class: https://github.com/blink1073/tifffile/blob/master/tifffile/tifffile.py#L750 For ImageJ metadata specifications, TiffWriter.save then refers to imagej_metadata_tags where you can see what types of data you can store in the variable metadata_types (line 7749): https://github.com/blink1073/tifffile/blob/master/tifffile/tifffile.py#L7710 metadata_types = ( ('Info', b'info', 1, _string), ('Labels', b'labl', None, _string), ('Ranges', b'rang', 1, _doubles), ('LUTs', b'luts', None, _ndarray), ('Plot', b'plot', 1, _bytes), ('ROI', b'roi ', 1, _bytes), ('Overlays', b'over', None, _bytes)) You can create LUTs to visualize your data using different colormaps. Presumably your data is uint8, then the LUTs you will need have the shape (3, 256) for the 3 color channels and 256 intensity values. So for gray, green and red LUTs you will need to something along the lines: import numpy as np import tifffile # Create a random test image im_3frame = np.random.randint(0, 255, size=(3, 150, 250), dtype=np.uint8) # Intensity value range val_range = np.arange(256, dtype=np.uint8) # Gray LUT lut_gray = np.stack([val_range, val_range, val_range]) # Red LUT lut_red = np.zeros((3, 256), dtype=np.uint8) lut_red[0, :] = val_range # Green LUT lut_green = np.zeros((3, 256), dtype=np.uint8) lut_green[1, :] = val_range # Create ijmetadata kwarg ijmeta = {'LUTs': [lut_gray, lut_red, lut_green]} # Save image tifffile.imsave( save_name, im_rgb, imagej=True, metadata={'mode': 'composite'}, ijmetadata=ijmeta, )
type: Answer
has comment: http://stackoverflow.com/comment/96294544
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/comment/87583901
has text: brother? are you still there
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50262194
type: Comment

http://stackoverflow.com/q/50265044
tagged with: masonite
tagged with: python
linked to: http://stackoverflow.com/q/27835619
has title: Masonite - craft new command throws module 'urllib' has no attribute 'urlopen' error
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50265045
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50265045
has body: I'm trying to use the Masonite framework and I just installed the masonite-cli package and whenever I run craft new, an Attribute Error - module 'urllib' has no attribute 'urlopen' is thrown. My base Python version is 2.7 but I have 3.6 installed.
tagged with: frameworks

http://stackoverflow.com/a/50307215
accepted answer of: http://stackoverflow.com/q/50307049
has comment: http://stackoverflow.com/comment/87631272
upvote count: 6
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/87631765
has comment: http://stackoverflow.com/comment/87631326
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87631145
answers question: http://stackoverflow.com/q/50307049
has comment: http://stackoverflow.com/comment/87630840
has comment: http://stackoverflow.com/comment/87630738
has body: You can do it without ImageField. Use model's @property for this. You need to copy badge images(e.g. badge_img1.jpg, badge_img2.jpg, etc.) to director with static files(check docs how to manage static with Django). Rewrite Profile like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(default='', blank=True, null=True) @property def badge_image(self): if self.user.posts.count() &gt;= 20: badge_image = 'badge_img1.jpg'# I don't know how to make a image variable in views and models. I know how to use it in Django templates with {{image.url}} elif self.user.posts.count() &gt;= 3: badge_image = 'badge_img2.jpg' else: badge_image ='badge_img3.jpg' return badge_image you can display current user's image like this: {% load static %} &lt;img src={% static user.profile.badge_image %}&gt;

http://stackoverflow.com/q/50318247
has comment: http://stackoverflow.com/comment/87656282
has comment: http://stackoverflow.com/comment/87652344
has comment: http://stackoverflow.com/comment/87656819
type: Question
has answer: http://stackoverflow.com/a/50321059
has answer: http://stackoverflow.com/a/50326506
has body: I am not sure of why this is happening but I am not able to load image using imread(). I am able to open that image in paint and after saving that image, the image is being loaded and displayed. I am using Jupyter notebook. import os import cv2 import numpy as np from matplotlib import pyplot as plt %matplotlib inline def displayImage(image): plt.imshow(image) plt.show() image = cv2.imread('path/to/image') displayImage(image) Output Expected Output:
has answer: http://stackoverflow.com/a/50325732
has answer: http://stackoverflow.com/a/50320297
tagged with: python
has title: Unable to load image using imread()
answer count: 4
accepted answer: http://stackoverflow.com/a/50326506
tagged with: opencv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50325732
score: 0
has comment: http://stackoverflow.com/comment/87652424
has comment: http://stackoverflow.com/comment/87667150
tagged with: image-loading

http://stackoverflow.com/a/50381937
has comment: http://stackoverflow.com/comment/87780043
score: 0
answers question: http://stackoverflow.com/q/50381828
has comment: http://stackoverflow.com/comment/87780311
has comment: http://stackoverflow.com/comment/87780333
has comment: http://stackoverflow.com/comment/87779979
has comment: http://stackoverflow.com/comment/87780278
has comment: http://stackoverflow.com/comment/87780267
has comment: http://stackoverflow.com/comment/87780178
has comment: http://stackoverflow.com/comment/87780100
has body: You need to change the name of your rename_files function to main(). Then put the call to rename_files in the main() but pass a parameter called file_list i.e. rename_files(file_list). Then make a new function called rename_file(file_list). Like this: import os, string def main(): #1 we need to take the files out from the folder file_list = os.listdir("/Users/mirzasamibaig/Documents/prank") #print(file_list) saved_path = os.getcwd() print("Current Working Directory is " + saved_path) os.chdir("/Users/mirzasamibaig/Documents/prank") rename_files(file_list, saved_path) def rename_files(file_list, saved_path): for file_name in file_list: translation_table = str.maketrans("0123456789", "", "0123456789") filename.translate(translation_table) os.chdir(saved_path) print (str.translate(file_list)) if __name__ == "__main__": main()
has comment: http://stackoverflow.com/comment/87779920
type: Answer

http://stackoverflow.com/comment/87821240
comment on: http://stackoverflow.com/a/50383536
score: 0
type: Comment
has text: @user2 do you see in django admin if user added to the post's likes?
type: AnswerComment

http://stackoverflow.com/a/50352758
has body: Problem was connected with files, i was showing only the path to the folder, and program didnt know which files should use. this line of code helped me to solve the problem, and get specific extension of the files: filenames= glob.glob(os.path.join('path',"*.xxx")) Cheers
answers question: http://stackoverflow.com/q/50330933
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/50232988
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87513255
type: Question
has body: I'm willing to create a plot which would look like this: That is, I want it to contain shaded regions based on some condition. If I take the following time series case (from plot.ly): import plotly.plotly as py import plotly.graph_objs as go import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv") data = [go.Scatter( x=df.Date, y=df['AAPL.Close'])] py.plot(data) I would want it to display a shaded band whenever the process is below 100. Is there a neat way of doing that?
tagged with: plotly
has title: Plot with switching regimes
has comment: http://stackoverflow.com/comment/87513972

http://stackoverflow.com/q/50337837
answer count: 1
has comment: http://stackoverflow.com/comment/87693547
tagged with: virtualenv
tagged with: virtualenvwrapper
type: Question
tagged with: python-3.x
has title: How do you set the environment variable PROJECT_HOME and WORKON_HOME in Virtualenvwrapper for Windows?
type: UnansweredQuestion
tagged with: windows
tagged with: python
has body: How do you set the environment variable PROJECT_HOME and WORKON_HOME in virtualenvwrapper for Windows?
linked to: http://stackoverflow.com/q/32463212
has comment: http://stackoverflow.com/comment/87693531
linked to: http://stackoverflow.com/q/3803581
has answer: http://stackoverflow.com/a/50547995
score: 0

http://stackoverflow.com/a/50329298
downvote count: 0
has comment: http://stackoverflow.com/comment/87681043
upvote count: 1
answers question: http://stackoverflow.com/q/50328737
has comment: http://stackoverflow.com/comment/87677470
has comment: http://stackoverflow.com/comment/87674893
has comment: http://stackoverflow.com/comment/87711563
has comment: http://stackoverflow.com/comment/87680572
has comment: http://stackoverflow.com/comment/87711347
has body: From what you wrote it looks to me that you should access RGB with channel_data = (data['CloudData']['RGB'][0:1]) or channel_data = (data['CloudData']['RGB']['data_values'][0:1]) depending on how you .mat file is constructed in matlab.
has comment: http://stackoverflow.com/comment/87695840
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87710502
has comment: http://stackoverflow.com/comment/87710939
has comment: http://stackoverflow.com/comment/87708882
has comment: http://stackoverflow.com/comment/87676993

http://stackoverflow.com/q/50377100
tagged with: psycopg2
has title: cursor factory parameters has no effect
has body: I have a database class like: rlock = RLock() class PostgresDB: host = Settings.DB_HOST name = Settings.DB_NAME username = Settings.DB_USERNAME pwd = Settings.DB_PWD def __init__(self): self.con = None def _create_connection(self): if self.con is None or self.con.closed: self.con = psycopg2.connect("host={h} dbname={n} user={u} password={p}".format( h=self.host, n=self.name, u=self.username, p=self.pwd, cursor_factory=RealDictCursor)) @contextlib.contextmanager def reading_cursor(self, sql, params=None): rlock.acquire() self._create_connection() try: cur = self.con.cursor() cur.execute(sql, params) yield cur except DatabaseError as e: traceback.print_exc() yield Exception() finally: self.con.close() rlock.release() @contextlib.contextmanager def writing_cursor(self, sql, params=None): rlock.acquire() self._create_connection() try: cur = self.con.cursor() cur.execute(sql, params) yield cur self.con.commit() except DatabaseError as e: traceback.print_exc() yield Exception() finally: self.con.close() rlock.release() Note that I am explicitly asking for RealDictCursor. However, when any request is done, the result is a list of tuples, not dicts. I am not sure what I am missing?
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/87772095
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50386538
has comment: http://stackoverflow.com/comment/87775030
tagged with: python

http://stackoverflow.com/comment/87703302
comment on: http://stackoverflow.com/a/50343627
type: Comment
score: 0
type: AnswerComment
has text: all good it was my fault. the error was taiga from a typepo from the template.

http://stackoverflow.com/q/50256081
has comment: http://stackoverflow.com/comment/87532371
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87530030
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87530467
has title: Python os.system returns 103
score: 0
answer count: 0
has body: I'm trying to call a py script (let say sub-script) within a main-script via os.system('script_customer_update') When I'm call the main script it runs through without any exception and the sub-script wasn't performed. When I'm call the Python Shell and put in the following in import os os.system('script_customer_update') I'm receiving a returncode 103 When I open the sub-script direct and run it via F5, it runs through without any exceptions. Any idea what is wrong? Python 3 is installed.
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87584729
type: QuestionComment
comment on: http://stackoverflow.com/q/50284220
score: 0
has text: what is your question ?
type: Comment

http://stackoverflow.com/a/50372383
has comment: http://stackoverflow.com/comment/87760883
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50372342
has comment: http://stackoverflow.com/comment/87761792
has comment: http://stackoverflow.com/comment/87761688
downvote count: 0
has comment: http://stackoverflow.com/comment/134920764
score: 4
has comment: http://stackoverflow.com/comment/87760790
has comment: http://stackoverflow.com/comment/87761132
has comment: http://stackoverflow.com/comment/87763582
type: Answer
has comment: http://stackoverflow.com/comment/87760697
answers question: http://stackoverflow.com/q/50372342
has comment: http://stackoverflow.com/comment/134927699
upvote count: 4
has body: You can subclass set and give it a decorator method: class MySet(set): def register(self, method): self.add(method) return method class MyClass: red_rules = MySet() blue_rules = MySet() hard_rules = MySet() soft_rules = MySet() @red_rules.register def rule_one(self): return 1 @blue_rules.register @hard_rules.register def rule_two(self): return 2 @hard_rules.register def rule_three(self): return 3 @blue_rules.register @soft_rules.register def rule_four(self): return 4 Or if you find using the .register method ugly, you can always define the __call__ method to use the set itself as a decorator: class MySet(set): def __call__(self, method): """Use set as a decorator to add elements to it.""" self.add(method) return method class MyClass: red_rules = MySet() ... @red_rules def rule_one(self): return 1 ... This looks better, but it's less explicit, so for other collaborators (or future yourself) it might be harder to grasp what's happening here. To call the stored functions, you can just loop over the set you want and pass in the instance as the self argument: my_instance = MyClass() for rule in MyClass.red_rules: rule(my_instance) You can also create an utility function to do this for you, for example you can create a MySet.invoke() method: class MySet(set): ... def invoke(self, obj): for rule in self: rule(obj) And now just call: MyClass.red_rules.invoke(my_instance) Or you could have MyClass handle this instead: class MyClass: ... def invoke_rules(self, rules): for rule in rules: rule(self) And then call this on an instance of MyClass: my_instance.invoke_rules(MyClass.red_rules)
has comment: http://stackoverflow.com/comment/87761422

http://stackoverflow.com/a/50374040
score: 1
has comment: http://stackoverflow.com/comment/87764716
type: Answer
accepted answer of: http://stackoverflow.com/q/50373848
has comment: http://stackoverflow.com/comment/87764625
downvote count: 0
has comment: http://stackoverflow.com/comment/87764382
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50373848
has comment: http://stackoverflow.com/comment/87764571
has body: Try to wait until modal window with OK button appeared: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver.find_element_by_id("saveQuestionsSection").click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='OK']"))).click()

http://stackoverflow.com/q/50272754
tagged with: python
has answer: http://stackoverflow.com/a/50272830
accepted answer: http://stackoverflow.com/a/50272830
type: AnsweredQuestion
downvote count: 0
upvote count: 1
answer count: 1
has title: create multiple columns in dataframe from function
favorite count: 0
type: Question
has body: can someone help me create two new columns in this dataframe? The desire is to parse the state out, "s" and then ensure that the state is removed from the original title string. The result would be to include the original title, the cleaned title (without the trailing State) and finally the state name. df=pd.Series(['Accommodation Payroll Employment in Texas', 'Accounting, Tax Preparation, Bookkeeping, and Payroll Services Payroll Employment in Texas']).to_frame() df.columns=['title'] def state_code(row): t=None s=None if len(row['title'].split(' in '))==2: s=str(row['title'].split(' in ')[1]) t=str(row['title'].split(' in ')[0]) elif len(row['title'].split(' in '))==3: s=str(row['title'].split(' in ')[2]) t=str(row['title'].split(' in ')[0]+row['title'].split(' in ')[1]) elif len(row['title'].split(' for '))==2: s=str(row['title'].split(' for ')[1]) t=str(row['title'].split(' for ')[0]) return t,s df'title_clean','state'=df.apply(state_code,axis=1)
tagged with: pandas
score: 1

http://stackoverflow.com/q/50298305
score: 8
type: Question
tagged with: multiple-axes
tagged with: axes
has answer: http://stackoverflow.com/a/50299307
answer count: 2
type: UnansweredQuestion
tagged with: imshow
tagged with: python
has title: How to force same size between matplotlib subplot image axes
has answer: http://stackoverflow.com/a/50302141
has body: Suppose I have the following code to create three side-by-side images: n=10 x = np.random.rand(n,1) y = np.random.rand(1,n) z = np.random.rand(n,n) fig, ax = plt.subplots(1, 3) ax[0].imshow(x) ax[1].imshow(z) ax[2].imshow(y) However, the axes autoscale so that the vertical axis in the first image is larger than the vertical axis in the second. Is there a way to programmatically force all image dimensions of size n to look the same in the three plots, regardless of window size? I'm looking for a way to either link the axes or the images so that the vertical axis of the first plot is the same size as the vertical axis of the second plot, and the horizontal axis of the third plot is the same size as the horizontal axis of the second plot, regardless of window size. i.e. something like this:
downvote count: 0
tagged with: matplotlib
upvote count: 8
favorite count: 0

http://stackoverflow.com/comment/87915880
comment on: http://stackoverflow.com/q/50311516
has text: I followed up with Google Cloud support and they told me that the GAE IP is blocked for this website play.google.com/store/getreviews
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50323656
has comment: http://stackoverflow.com/comment/87663034
favorite count: 0
score: -1
has title: Split and append to 2 arrays from input
tagged with: split
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/87663057
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87663283
has comment: http://stackoverflow.com/comment/87663111
tagged with: dictionary
answer count: 1
downvote count: 1
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50323758
has comment: http://stackoverflow.com/comment/87663023
has comment: http://stackoverflow.com/comment/87663265
has comment: http://stackoverflow.com/comment/87663251
has body: I want something like this. String -> split -> append each without creating new 2 variables(or 1 list) a=[] b=[] sum = 0; for i in range(n): map(lambda x, y: a.append(x),b.append(y),raw_input().split(" ")); Yeah,thats doesn't work couse append return null. But that's so ugly.x for i in range(n): buf = map(int,raw_input().split(" ")); a.append(buf[0]) b.append(buf[1])

http://stackoverflow.com/q/50301793
tagged with: newline
linked to: http://stackoverflow.com/q/3277503
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50301825
score: 0
answer count: 3
tagged with: file-io
has body: I am attempting to return user location data while scrapping twitter. I am having trouble with the regex, specifically, I wish to exclude "\n" from the output. Current regex: data = open("user_locations.txt", "r") valid_ex = re.compile(r'([A-Z][a-z]+), ([A-Za-z]+[^\n])') user_locations.txt: California, USA You are your own ExclusiveLogo Around The World Galatasaray ★DM 4 PROMO / CONTENT REMOVAL★ Glasgow, Scotland United States Berlin, Germany Global Expected output: ['California, USA', 'Glasgow, Scotland', 'Berlin, Germany'] Actual output: ['California, USA\n', 'Glasgow, Scotland\n', 'Berlin, Germany\n'] An alternate reason for the discrepancy between expected vs actual output, may be the way in which I am using search() in printing the list. That is: for line in data: result = valid_ex.search(line) if result: locations_list.append(line) print(locations_list) Thank you, any help would be greatly appreciated! :)
has comment: http://stackoverflow.com/comment/87645404
has comment: http://stackoverflow.com/comment/87620181
type: Question
has answer: http://stackoverflow.com/a/50301863
duplicate of: http://stackoverflow.com/q/3277503
has answer: http://stackoverflow.com/a/50301825
has title: Exclude \n when reading input from file
has comment: http://stackoverflow.com/comment/87645547
has answer: http://stackoverflow.com/a/50301819
possible better answer: http://stackoverflow.com/a/50301819

http://stackoverflow.com/a/50355846
score: 0
has body: You can compare two lists, with a function like this one. The way it works is it loops through your shorter list, and every time it finds the next word in the long list, cuts off the first part of the longer list at that point. If it can't find the word it returns false. def is_sub_sequence(long_list, short_list): for word in short_list: if word in long_list: i = long_list.index(word) long_list = long_list[i+1:] else: return False return True Now you have a function to tell you if the list is the desired type, you can filter out all the lists you need from the 'list of lists' using a list comprehension like the following: a = [['she', 'is', 'a', 'student'], ['she', 'is', 'a', 'lawer'], ['she', 'is', 'a', 'great', 'student'], ['i', 'am', 'a', 'teacher'], ['she', 'is', 'a', 'very', 'very', 'exceptionally', 'good', 'student']] b = ['she', 'is', 'student'] filtered = [x for x in a if is_sub_sequence(x,b)] The list filtered will include only the lists of the desired type.
answers question: http://stackoverflow.com/q/50355412
type: Answer

http://stackoverflow.com/q/50241308
has title: Running jupyter notebook in a virtualenv (with permission issue)
tagged with: linux
has body: I am trying to run jupyter notebook in a virtualenv on a cloud computing platform running Linux, but I am unable to install a ipykernel for jupyter notebook. Here are the steps that I have done: Install a virtual environment for python 3 at my local storage space. The tag --system-site-packages has been used, to minimize the size of the virtual environment folder. So it should inherit the global python 3.6 and libraries. Activated the virtual environment, installed sympy, started python3, import sympy and it worked. (Note that without the virtualenv, pip does not work as we have no permission to write to the global version of python) Tried to run jupyter notebook in the same virtual environment, but trying to import sympy returns No module named 'sympy'. Using print(sys.executable) reveals that it is running on the global python3.6. (When running python3 in virtualenv and printing executable, it prints the path of python3 in myvirtualenv/bin/python3) Tried to follow these instructions. pip install jupyter and pip install ipykernel worked properly, saying requirement already satisfied. But python -m ipykernel install --user --name testenv --display-name "MyEnv" does not work, returning [Errno 13] Permission denied: '/tmp/tmpc2ebdyp9_kernels/python3/kernel.json' Perhaps you want `sudo` or `--user`? which really confuses me, as I thought the --user tag should make it install at my local directory already. I also tried specifying the path of my virtualenv by using --prefix, but it is still saying I have no permission to access the system's kernel.json. I also tried ipython kernel install --name "xx" --user and specifying path with --prefix but it returns the same error. So my question is: Did this error arise because even though the ipython kernel was installed locally, the kernel.json at the system directory still needs to be changed? Or did the tags --user or --prefix not work for some reason? How can I create a kernel truly locally? I suppose after that I can create …
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33496350
tagged with: python
tagged with: jupyter-notebook
score: 2
upvote count: 2
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/35561126
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/87765355
has comment: http://stackoverflow.com/comment/87608343
favorite count: 0
type: Question

http://stackoverflow.com/comment/106231037
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50277258
has text: 'Note: in Py3.7 the standard library has added, datetime.fromisoformat().' The SF date doesn't follow this format.

http://stackoverflow.com/q/50304216
downvote count: 0
has answer: http://stackoverflow.com/a/50304406
has answer: http://stackoverflow.com/a/50419327
has comment: http://stackoverflow.com/comment/87624835
has title: To split and save text in a file using python
has answer: http://stackoverflow.com/a/50304454
possible better answer: http://stackoverflow.com/a/50304246
favorite count: 0
has answer: http://stackoverflow.com/a/50304246
has answer: http://stackoverflow.com/a/50304237
type: AnsweredQuestion
answer count: 5
accepted answer: http://stackoverflow.com/a/50304406
tagged with: python
type: Question
score: 2
upvote count: 2
has body: Below is the input file sample_text.txt 10001ScottTiher100040 10002ScoteTijer100042 10003ScotrTieer100043 10004ScotfTiler100044 10005ScotyTiper100046 10006ScotlTioer100047 10007ScotiTiwer100049 I need to save this in the same file as below, can you please help me on this.... 10001,Scott,Tiher,100040 10002,Scote,Tijer,100042 10003,Scotr,Tieer,100043 10004,Scotf,Tiler,100044 10005,Scoty,Tiper,100046 10006,Scotl,Tioer,100047 10007,Scoti,Tiwer,100049 I have tried the below code, but unable to save the b in new file or same file with open('D:\Programs\python\sql_test.txt','r+') as f: for line in f: for word in line.split(): b = str(word[0:5])+ ',' + str(word[5:10]) + ',' + str(word[10:15])+','+ str(word[15:21]) print(b)

http://stackoverflow.com/comment/87500258
type: Comment
has text: Seems silly to use `ast` here, it's way more work than just trying to cast to `int` and catch if you can't. I'm also of the belief that if you want your code to handle floats, you should have to refactor your code to handle floats.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50241321

http://stackoverflow.com/q/50271208
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87559837
tagged with: string
has answer: http://stackoverflow.com/a/50273485
favorite count: 0
has title: Wildcard search in python string and then updating the string
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87563348
type: Question
downvote count: 2
has body: I have a column named as city. I want to bring the city names to one format ex. Column sample data : City Sydney Sydney-EZ Bangalore Bengalore SEZ Delhi New Delhi Sydney and Sydney-EZ or any other row containing word Sydney should be replaced by Sydney. Bangalore and Bangalore SEZ ( or any other row containing word Bangalore ) should be replaced by Bangalore . Delhi and New Delhi ( or any other row containing word Delhi ) should be replaced by Delhi.

http://stackoverflow.com/q/50323460
has comment: http://stackoverflow.com/comment/87662615
favorite count: 0
type: Question
has title: valid parameters to pandas method
has answer: http://stackoverflow.com/a/50323505
accepted answer: http://stackoverflow.com/a/50323505
tagged with: python
linked to: http://stackoverflow.com/q/1769403
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50323541
possible better answer: http://stackoverflow.com/a/50323541
has comment: http://stackoverflow.com/comment/87662616
answer count: 2
tagged with: pandas
score: 1
has body: Pandas seems to ignore the extra (invalid) parameters. For e.g. import pandas as pd df=pd.read_excel('myfile.xlsx', some_dummy_param=True) I expected (but did not get) an error something like ... TypeError: __init__() got an unexpected keyword argument 'some_dummy_param' The problem is, since there is no error, I consider "some_dummy_param" to be valid. This is certainly not expected. Is there any way to make sure only valid parameters are passed to read_excel method?
downvote count: 1

http://stackoverflow.com/comment/87515663
comment on: http://stackoverflow.com/a/50246437
has text: I have django app in the docker container and there is no history, when I exit from and enter again, I should scroll up to the command(what I need), after that I copy and scroll down. It is not so convenient
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87652101
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50318160
has text: Please edit your question to include a sample of your file. See how to create a [mcve].

http://stackoverflow.com/comment/87711563
type: AnswerComment
has text: Yeah, so if you do `channel = data['CloudData']['RGB']`, `channel` is an `np.ndarray` containing the data of `RGB`. You can now access `channel` like you would access any `np.ndarray`. If you have trouble with that, you should take a look into the `numpy` documentation and some `numpy` tutorials.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50329298

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/50349686
tags question: http://stackoverflow.com/q/50378688
tags question: http://stackoverflow.com/q/50383706
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/50377965
tags question: http://stackoverflow.com/q/50350051
tags question: http://stackoverflow.com/q/50254813
tags question: http://stackoverflow.com/q/50239503

eclipse
tags question: http://stackoverflow.com/q/50308036
tag name: eclipse
tags question: http://stackoverflow.com/q/50311415
type: Tag

http://stackoverflow.com/q/50324563
score: 0
has comment: http://stackoverflow.com/comment/87665011
has comment: http://stackoverflow.com/comment/87664945
answer count: 1
tagged with: selenium
tagged with: webdriver
tagged with: unit-testing
type: Question
has title: Python Selenium TypeError Expect 3 arguments (1given)
accepted answer: http://stackoverflow.com/a/50324697
tagged with: python
has answer: http://stackoverflow.com/a/50324697
has body: I am not able to solve the following issue : Below is my python-selenium code. import unittest import time import argparse, sys, os import traceback from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class SeleniumTestPack(unittest.TestCase): driver = webdriver.Firefox() timeout = 30 def test_all(self): admin_base_url = args.url cognito_url = "test.auth.us-west-2.amazoncognito.com" user_full_name = "test User" email = "test@test.com" firstName = "Selenium" lastName = "User" try: self.test_redirect_to_congito_login_page(admin_base_url, cognito_url) self.delete_geckodriver_log() except Exception: self.driver.save_screenshot('exception.png') self.fail("Exception: %s" % (traceback.format_exc())) def test_redirect_to_congito_login_page(self, admin_base_url, cognito_url): print "Test navigating to home page redirects to cognito login page" self.driver.get(admin_base_url) self.wait_for_element_loaded(By.ID, "div-forms") page_url = self.driver.current_url assert cognito_url in page_url def wait_for_element_loaded(self, id_type, id_locator): min_timeout = 2 tries = 0 retry_limit = 13 while tries &lt;= retry_limit: try: tries = tries + 1 element_present = EC.presence_of_element_located((id_type, id_locator)) WebDriverWait(self.driver, min_timeout).until(element_present) break except Exception: if tries &lt;= retry_limit: continue self.fail("Exception waiting for page to load %s : %s" % (id_locator,traceback.format_exc())) def delete_geckodriver_log(self): #running function at the end of all other invocation ensures all test cases have already ran successfully geckodriverfile="geckodriver.log" if os.path.isfile(geckodriverfile): os.remove(geckodriverfile) else: print("Error: %s file not found" % geckodriverfile) @classmethod def tearDown(self): # close the browser window self.dri…
tagged with: selenium-webdriver
type: AnsweredQuestion

http://stackoverflow.com/a/50263613
answers question: http://stackoverflow.com/q/50263311
has comment: http://stackoverflow.com/comment/87572579
has comment: http://stackoverflow.com/comment/87547353
has comment: http://stackoverflow.com/comment/87547469
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/87547397
has comment: http://stackoverflow.com/comment/87547428
has comment: http://stackoverflow.com/comment/87597160
has comment: http://stackoverflow.com/comment/87547387
has comment: http://stackoverflow.com/comment/87547484
type: Answer
has body: lst = [] flag = 0 with open('a.txt') as f: for line in f: try: if float(line.split()[0].strip('.')) &gt;0: flag = 1 if flag == 1: lst += [float(i.strip('.')) for i in line.split()] except: pass
score: -3

http://stackoverflow.com/comment/87714874
type: AnswerComment
has text: Hmm, interesting, then cast to `boolean` like `df = df[df.groupby('A')['C'].transform(lambda x: set(x) >= set(neededVals)).astype(bool)]`
comment on: http://stackoverflow.com/a/50349306
score: 0
type: Comment

http://stackoverflow.com/comment/87647645
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50314943
has text: if you are using Python 2, add `from __future__ import print_function` to the top
score: 0

http://stackoverflow.com/comment/87765859
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50374672
has text: This saves the compression to a file ... not something that I need

http://stackoverflow.com/q/50380218
downvote count: 0
answer count: 1
favorite count: 0
tagged with: cx-freeze
has title: CX_Freeze - Building a .msi with Admin permissions
type: Question
tagged with: python
type: UnansweredQuestion
has body: I am trying to create an executable from my python/tkinter code that can be installed by other users. I have been able to successfully do this with cx_Freeze, however, the .exe is unable to write to files in the working or specified directories. After researching this issue, I discovered that this may be because the .exe does not have the appropriate read/write permissions. Sure enough, when I tried running the .exe with Admin permissions, I was able to perform the relevant functions. Since this worked, I was wondering whether there is a way to build the cx_Freeze .msi while specifying user permissions in the setup.py file. I have not been able to find any documentation about this, so I am hoping that you can help with this. Any help is greatly appreciated!
has answer: http://stackoverflow.com/a/58547581
score: 4
upvote count: 4

apache-spark-sql
tags question: http://stackoverflow.com/q/50350496
tags question: http://stackoverflow.com/q/50243847
tags question: http://stackoverflow.com/q/50339462
tags question: http://stackoverflow.com/q/50377394
tags question: http://stackoverflow.com/q/50346998
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/50305770
tags question: http://stackoverflow.com/q/50348192
tags question: http://stackoverflow.com/q/50353370
tags question: http://stackoverflow.com/q/50349633
tags question: http://stackoverflow.com/q/50338026
tags question: http://stackoverflow.com/q/50247667
tags question: http://stackoverflow.com/q/50278985
tags question: http://stackoverflow.com/q/50303307
tags question: http://stackoverflow.com/q/50284760
type: Tag
tags question: http://stackoverflow.com/q/50353999
tags question: http://stackoverflow.com/q/50246487

http://stackoverflow.com/a/50273931
has body: I tried this, l=df.columns.values cols = ['name' , 'c'] col_position = [1 , 2] for u in zip(cols,col_position): l.remove(u[0]) l.insert(u[1],u[0]) df=df[l]
type: Answer
answers question: http://stackoverflow.com/q/50273742
score: 0

http://stackoverflow.com/comment/87648778
has text: What did you expect to happen ?
comment on: http://stackoverflow.com/q/50316445
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/50282633
type: Question
tagged with: python-3.x
has title: Find a path among pairs of items based on their intersection
type: UnansweredQuestion
tagged with: algorithm
has answer: http://stackoverflow.com/a/50282868
has answer: http://stackoverflow.com/a/50282634
linked to: http://stackoverflow.com/q/38797507
has comment: http://stackoverflow.com/comment/87582099
tagged with: python
has comment: http://stackoverflow.com/comment/87582155
has body: What is the most efficient way (preferably in python-3.5+) to find the find a path among pairs of items based on following conditions: For two given pairs (s1, e1) and (s2, e2) they should be connected if either e1 == s2 or e2 == s1. There are no duplicate paths here and each pair is contain two different names. Also, each pair can connects to only one other path and there is no isolated pair here, i.e. all of them can be connected. For example if the input is: [('Bergerac','Pau'), ('Nice','Montpelier'), ('Pau','Paris'), ('Marseille','Nice'), ('Montpelier','Bergerac'), ('new','Marseille'), ('old','new'), ('Paris', 'last'), ('dsd', 'sds')] The output should be as following: ('old', 'new', 'Marseille', 'Nice', 'Montpelier', 'Bergerac', 'Pau', 'Paris', 'last') P.S. This is a simple question but I couldn't find any duplicate so please leave the link in comments if you found one so that I can close/delete the question.
has comment: http://stackoverflow.com/comment/87582631
score: 0
has comment: http://stackoverflow.com/comment/87582707
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50282844

http://stackoverflow.com/a/50239944
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50239200
score: 2
answers question: http://stackoverflow.com/q/50239200
upvote count: 2
has body: Agreed that you should save the songs in a list, you could also make a dj class so you could extend it beyond that class DJSongify: def __init__(self): self.previous = location.music self.songlist = [] def songlist_continue(self,song) self.previous = song self.songlist.append(song) This would let you keep track and also do other operations on your DJ class, such as doing garbage collection on the list of songs if it gets too big for the Rasberry Pi. You could even set a song list limit and handle it through the class that way.
type: AcceptedAnswer

http://stackoverflow.com/q/50257925
has answer: http://stackoverflow.com/a/50258046
tagged with: python
tagged with: regex
tagged with: nlp
has body: I have a long list of 1.5m sentences and a similarly long list of words that I am looking for within the list of sentences. For example: list_of_words = ['Turin', 'Milan'] list_of_sents = ['This is a sent about turin.', 'This is a sent about manufacturing.'] I have the following function that is able to quickly identify those sentences with the keywords and computational time is rather important so I would like to avoid for loops if able: def find_keyword_comments(test_comments,test_keywords): keywords = '|'.join(test_keywords) word = re.compile(r"^.*\b({})\b.*$".format(keywords), re.I) newlist = filter(word.match, test_comments) final = list(newlist) return final Instead of returning a list of strings that contain the keyword, I would like it to return a list of tuples with the word matched on and the string that contains the location. So it currently returns: final = ['This is a sent about turin.'] and I would like it to return final = [('Turin', 'This is a sent about turin.')] Is there a syntax functionality that I am misusing or forgetting?
has comment: http://stackoverflow.com/comment/87534957
answer count: 2
upvote count: 2
score: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50258102
tagged with: python-3.x
type: UnansweredQuestion
has title: python filter: Return tuple from list of strings with target strings

http://stackoverflow.com/q/50300076
tagged with: avro
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: I'm a newbie to Avro. I'm trying to parse a simple CSV file containing one string value and one int value, but I'm getting the error: avro.io.AvroTypeException: The datum is not an example of the schema The schema I'm using is: {"namespace": "paymenttransaction", "type": "record", "name": "Payment", "fields": [ {"name": "TransactionId", "type": "string"}, {"name": "Id", "type": "int"} ] } The CSV file has the content: TransactionId,Id 2018040101000222749,1 And the Python code that I am running for the producer is: from confluent_kafka import avro from confluent_kafka.avro import AvroProducer import csv value_schema = avro.load('/home/daniela/avro/example.avsc') AvroProducerConf = {'bootstrap.servers': 'localhost:9092', 'schema.registry.url': 'http://localhost:8081', } avroProducer = AvroProducer(AvroProducerConf, default_value_schema=value_schema) with open('/home/usertest/avro/data/paymenttransactions.csv') as file: reader = csv.DictReader(file, delimiter=",") for row in reader: avroProducer.produce(topic='test', value=row) print(row) avroProducer.flush() What am I doing wrong?
has answer: http://stackoverflow.com/a/50392685
accepted answer: http://stackoverflow.com/a/50392685
downvote count: 0
score: 1
answer count: 1
favorite count: 0
has title: Avro Python from CSV - avro.io.AvroTypeException: The datum is not an example of the schema
type: Question

http://stackoverflow.com/a/50362690
type: Answer
answers question: http://stackoverflow.com/q/50360553
score: 0
has body: JMeter threads are totally independent and don't know anything about each other. So you can parameterise HTTP Header Manager using any suitable way (functions, CSV Data Set Config, whatever) so each user would have its own authentication header. You can verify this using View Results Tree listener If you consider Python scripting easier to implement/debug you can take a look at Locust framework, you will be able to create/debug load tests in Python and view the load test flow in web interface. See How to Run Locust with Different Users article for more information on implementing your scenario with Locust.

http://stackoverflow.com/q/50316978
has comment: http://stackoverflow.com/comment/87650259
has comment: http://stackoverflow.com/comment/87649743
tagged with: multithreading
has comment: http://stackoverflow.com/comment/87656340
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50340257
has body: Sorry to ask this question as a new python starter, I have a working python program to be converted into multiprocessing or multithreading, here is the working py's structure: class XMLToJson(): def __init__(self, region=None, flow=None, path=None, output=None): def run(self): def run_from_cmd(): XMLToJson().run() if __name__ == '__main__': XMLToJson().run() It would be greatly appreciated if anyone can tell me how to do the conversion. Thank you very much. P.S. The following is the framework I am thinking how to fit into it: from threading import Thread, current_thread, Lock import time def worker(l): while True: l.acquire() print ('in worker:' + str(current_thread())) l.release() time.sleep(0.5) if __name__ == '__main__': l = Lock() print ('in main: ' + str(current_thread())) threads = [Thread(target=worker, args=[l]) for i in range(5)] for t in threads: t.start() for t in threads: t.join() I modified the original working program from run() to main_process(), and set the target from worker to main_process, if __name__ == '__main__': l = Lock() print ('in main: ' + str(current_thread())) threads = [Thread(target=main_process, args=[l]) for i in range(5)] for t in threads: t.start() for t in threads: t.join() but the program doesn't even pass the compile, error out in target=main_process. Thank you very much.
has comment: http://stackoverflow.com/comment/87649734
answer count: 1
has title: How do I convert current python program to multi prosessing/multi threading
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/87649848
type: UnansweredQuestion

http://stackoverflow.com/comment/87795818
has text: I once realised the fastest is `df = df.sort_values(by=['delta'], ascending=False).drop_duplicates('Id')`, is possible add to timings?
comment on: http://stackoverflow.com/a/50389889
type: Comment
type: AnswerComment
score: 3

http://stackoverflow.com/comment/87618759
comment on: http://stackoverflow.com/q/50300635
has text: Yes that is desired. How would you like it to be instead? And what's more, in how far do other questions on that topic do not help?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87811833
has text: Yes, in class Second you do everything you need, including calling analyze. When you need to transfer data from the Second window to display and other calculations, you create the Example class constructor and pass the data to the desired method of this class for display or further processing.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50381702
type: Comment

http://stackoverflow.com/comment/87504498
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50243181
has text: Renaming the columns from an aggregate [Naming returned columns in Pandas aggregate function](https://stackoverflow.com/questions/19078325/naming-returned-columns-in-pandas-aggregate-function)

http://stackoverflow.com/q/50266240
has comment: http://stackoverflow.com/comment/87550367
has comment: http://stackoverflow.com/comment/87550468
has answer: http://stackoverflow.com/a/50266463
has comment: http://stackoverflow.com/comment/87550597
tagged with: python
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/87550650
has comment: http://stackoverflow.com/comment/87550427
has body: Given: setA = [(1, 25), (2, 24), (3, 23), (4, 22), (5, 21), (6, 20), (7, 19), (8, 18), (9, 17), (10, 16), (11, 15), (12, 14), (13, 13),(14, 12), (15, 11), (16, 10), (17, 9), (18, 8), (19, 7),(20, 6), (21, 5), (22, 4), (23, 3), (24, 2), (25, 1)] setB = [(1, 19), (2, 18), (3, 17), (4, 16), (5, 15), (6, 14), (7, 13), (8, 12), (9, 11), (10, 10), (11, 9), (12, 8), (13, 7), (14, 6), (15, 5), (16, 4), (17, 3), (18, 2), (19, 1)] How can I combine the two sets using the first element of each tuple in each set as a common key value. So for tuple at position 1 in each set it would be (1,25) and (1,19) respectively. Joined together would yield: (25,1,19) (25,1,19) (24,2,18) (23,3,17) ... (7,19,1) (6,20,none) ... (2,24,none) (1,25,none) Note: that order of output tuple must be maintained. Example: (setA value, common value, setB value) (setA value, common value, setB value)etc... Note: Must use Python 2.7x standard libraries I'm trying to do something like [(a,b,c) for (a,b),(b,c) in zip(setA,setB)] but I don't fully understand the proper syntax and logic. Thank you.
upvote count: 2
has comment: http://stackoverflow.com/comment/87550624
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50266709
has comment: http://stackoverflow.com/comment/87550688
has answer: http://stackoverflow.com/a/50266559
tagged with: set
has comment: http://stackoverflow.com/comment/87550472
has comment: http://stackoverflow.com/comment/87550516
tagged with: set-union
score: 1
downvote count: 1
favorite count: 0
has title: Joining two sets of tuples at a common value
has answer: http://stackoverflow.com/a/50266454

http://stackoverflow.com/q/50248969
has title: Not saved checkbox-es to Django admin db
favorite count: 0
has comment: http://stackoverflow.com/comment/87517946
type: Question
has answer: http://stackoverflow.com/a/50250367
has comment: http://stackoverflow.com/comment/87516594
accepted answer: http://stackoverflow.com/a/50250367
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87516850
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87517264
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87517798
has body: Django == 1.11 I have a simple models.py with task and label (it should be checkboxes that can be selected). class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.PROTECT) name_task = models.CharField(max_length=1000) label_task = models.ManyToManyField(LabelTask) def __str__(self): return self.name_task and label class LabelTask(models.Model): name = models.CharField(max_length=1000) def __str__(self): return self.name forms.py look like class CreateTask(forms.ModelForm): label_task = forms.ModelMultipleChoiceField(queryset=LabelTask.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Task exclude = ['author'] And my views.py @login_required def secret_page(request): form = CreateTask(request.POST or None) if form.is_valid(): print('Valid') instance = form.save(commit=False) instance.author = request.user instance.save() messages.success(request, "Successfully Created") else: print('Not valid') form = CreateTask() return render(request, 'task/task.html', {'form': form}) For example, go to a browser and type some data in the form - https://www.dropbox.com/s/rf7tbbvushln94d/Screenshot%20from%202018-05-09%2011-33-24.png?dl=0 And press submit. What do we see? https://www.dropbox.com/s/h27kdqddl1ns0r1/Screenshot%20from%202018-05-09%2011-33-56.png?dl=0 We chose only the Python, but in admin, we see the whole selection. I don't understand why is it so. Thank you.
upvote count: 1
has comment: http://stackoverflow.com/comment/87516744

http://stackoverflow.com/comment/87803777
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50337847
type: AnswerComment
has text: I'm still having some problems here, I'm sorry. https://gyazo.com/d8c2f50e389f1800bfa031239cfe3bbc

http://stackoverflow.com/a/50246912
type: Answer
has body: I think need concat only, because data is list of DataFrames: df = pd.concat(data, ignore_index=True) df.to_csv(file, header=False, index=False)
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/50245102
has comment: http://stackoverflow.com/comment/87525486

http://stackoverflow.com/comment/87731592
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50357490
score: 2
has text: Please show us what you've tried so far

http://stackoverflow.com/comment/87724382
comment on: http://stackoverflow.com/a/50337326
score: 0
type: Comment
has text: @wvxvw If Python code stores a reference to your object somewhere, that Python code increfs it. So you don’t have to worry about what Python code might do—the interpreter already gets those refcounts right, or it would be constantly segfaulting even without your extension. Just look at the functions you call to give it to Python code in the first place. If it doesn’t say it steals your reference, you still have a reference to decref.
type: AnswerComment

http://stackoverflow.com/comment/87704811
score: 0
type: Comment
has text: then use `d[39]`
type: AnswerComment
comment on: http://stackoverflow.com/a/50344411

http://stackoverflow.com/q/50362476
favorite count: 0
type: Question
upvote count: 3
has body: I am creating a kivy app where I have used router showing this error- AttributeError: 'MainRouter' object has no attribute '_disabled_count' Any solution?
has answer: http://stackoverflow.com/a/50370623
tagged with: python
tagged with: kivy
has title: AttributeError: 'MainRouter' object has no attribute '_disabled_count'
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50370623
has answer: http://stackoverflow.com/a/54846006
possible better answer: http://stackoverflow.com/a/54846006
score: 3

http://stackoverflow.com/comment/87515519
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50249025
has text: you want to compact your 2 `if`s into a more elegant line, or the `for` loop?
type: QuestionComment

http://stackoverflow.com/q/50339065
favorite count: 0
tagged with: series
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/72385796
score: 38
has answer: http://stackoverflow.com/a/66708781
has answer: http://stackoverflow.com/a/50339224
accepted answer: http://stackoverflow.com/a/50339260
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50339260
has answer: http://stackoverflow.com/a/56892555
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/56720624
tagged with: pandas
has title: How to get maximum length of each column in the data frame using pandas python
upvote count: 38
has body: I have a data frame where most of the columns are varchar/object type. Length of the column varies a lot and could be anything within the range of 3 - 1000+ . Now, for each column, I want to measure maximum length. I know how to calculate maximum length for a col. If its varchar then: max(df.char_col.apply(len)) and if its number (float8 or int64) then: max(df.num_col.map(str).apply(len)) But my dataframe has hundreds of column and I want to calculate maximum length for all columns at the same time. The problem for that is, there are different data types, and I dont know how to do all at once. So Question 1: How to get maximum column length for each columns in the data frame Now I am trying to do that only for varchar/object type columns using following code: xx = df.select_dtypes(include = ['object']) for col in [xx.columns.values]: maxlength = [max(xx.col.apply(len))] I selected only object type columns and tried to write a for loop. But its not working. probably using apply() within for loop is not a good idea. Question 2: How to get maximum length of each column for only object type columns Sample data frame: d1 = {'name': ['john', 'tom', 'bob', 'rock', 'jimy'], 'DoB': ['01/02/2010', '01/02/2012', '11/22/2014', '11/22/2014', '09/25/2016'], 'Address': ['NY', 'NJ', 'PA', 'NY', 'CA'], 'comment1': ['Very good performance', 'N/A', 'Need to work hard', 'No Comment', 'Not satisfactory'], 'comment2': ['good', 'Meets Expectation', 'N', 'N/A', 'Incompetence']} df1 = pd.DataFrame(data = d1) df1['month'] = pd.DatetimeIndex(df1['DoB']).month df1['year'] = pd.DatetimeIndex(df1['DoB']).year
possible better answer: http://stackoverflow.com/a/60925864
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/60925864

http://stackoverflow.com/comment/87654706
type: QuestionComment
has text: Convert the `Week` column to a datetime with `df['Week'] = pd.to_datetime(df.Week)` and then your first method of setting the index and plotting should work without issue
comment on: http://stackoverflow.com/q/50319409
score: 1
type: Comment

http://stackoverflow.com/q/50350996
has comment: http://stackoverflow.com/comment/87718029
tagged with: matplotlib
has body: In my simple example below, how to make x-axis tick values to appear between grids? import numpy as np import matplotlib.pyplot as plt np.random.seed(1) x = range(10) y = np.random.random(10) plt.plot(x,y) plt.xticks(x) plt.grid(True) plt.show() The following make ticks to be where I want but the grid lines also moves. np.random.seed(1) x = range(10) y = np.random.random(10) plt.plot(x,y) plt.xticks(x) plt.grid(True) plt.xticks(np.arange(10)+0.5, x) plt.show() I would like the result to be:
upvote count: 6
score: 6
tagged with: python
has title: How to make axes ticks in between grid lines
accepted answer: http://stackoverflow.com/a/50351357
type: AnsweredQuestion
answer count: 2
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50351357
has answer: http://stackoverflow.com/a/50351070
possible better answer: http://stackoverflow.com/a/50351070

http://stackoverflow.com/q/50256838
tagged with: python
has title: How to get the cluster to which a cell belongs, using AllenSDK?
type: AnsweredQuestion
score: 0
tagged with: allen-sdk
accepted answer: http://stackoverflow.com/a/50821759
answer count: 1
has answer: http://stackoverflow.com/a/50821759
has body: On the "A Cellular Taxonomy of the Mouse Visual Cortex" page, "Explore the Data" section, the top row shows the list of cluster names of mouse visual cortex cells: Question: Given a mouse visual cortex cell's specimen ID (e.g. 505808144), how do I find the cluster name to which that cell belongs? I am able to get cell metadata via AllenSDK get_cell(id) method, but the returned metadata does not seem to contain the name of the cluster.
type: Question

http://stackoverflow.com/comment/139888430
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50355874
has text: Just want to second what @user108569 said about not using `len(dataframe)` columnar parquet. I timed the two methods he suggested for loading my parquet data (a tiny subset of the giant C4 dataset). I get this output: `Time to get len(data): 1.17129 # 10,000 samples \nTime to get data.index.size.compute(): 0.00381 # 10,000 samples` So the difference is ~300x.
type: Comment

http://stackoverflow.com/comment/139537815
has text: Thanks for the comments. But I am not familiar with DLL. So what should I write in PyInit_foo() so that other modules can access methods and classes in this foo.pyd?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/60208567

http://stackoverflow.com/comment/87739887
type: Comment
comment on: http://stackoverflow.com/a/50361389
score: 0
type: AnswerComment
has text: Sir,I used your most recent"for a, b in sorted(mydict.items(), key=lambda x:x[-1][0] if isinstance(x, list) else x, reverse = True): print('{},{}'.format(a, ','.join(map(str, b)) if isinstance(b, list) else b))"But the result is no sorted.

http://stackoverflow.com/a/50254093
score: 0
has comment: http://stackoverflow.com/comment/87551113
has body: It's a bit (well, a lot) more complicated than then that. However, simplistically, yes every python object is a pointer to a PyObject or PyVarObject as defined in object.c /* Nothing is actually declared to be a PyObject, but every pointer to * a Python object can be cast to a PyObject*. This is inheritance built * by hand. Similarly every pointer to a variable-size Python object can, * in addition, be cast to PyVarObject*. */ typedef struct _object { _PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt; struct _typeobject *ob_type; } PyObject; typedef struct { PyObject ob_base; Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject;
has comment: http://stackoverflow.com/comment/87525680
has comment: http://stackoverflow.com/comment/87526714
type: Answer
answers question: http://stackoverflow.com/q/50253776

http://stackoverflow.com/a/50310102
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50309948
has body: Instead of parsing each line, parse the whole thing at once: import urllib2 import re content = urllib2.urlopen("https://ipinfo.io/AS32244").read() ver_regex = re.compile(r"(?:\d{1,3}\.){3}\d{1,3}(?:/\d\d?)?") print ver_regex.search(content) This will print the first occurrence of the number you are looking for or None if there is none. If you instead want to find all possible occurrences, use findall instead of search
downvote count: 0

http://stackoverflow.com/a/50331073
has comment: http://stackoverflow.com/comment/87717257
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50330835
score: 1
type: Answer
has body: Easy solution: Simply add the batch dimension to your calcs and reshapes def kronecker_product(mat1, mat2): #Computes the Kronecker product of two matrices. batch, m1, n1 = mat1.get_shape().as_list() mat1_rsh = K.reshape(mat1, [-1, m1, 1, n1, 1]) batch, m2, n2 = mat2.get_shape().as_list() mat2_rsh = K.reshape(mat2, [-1, 1, m2, 1, n2]) return K.reshape(mat1_rsh * mat2_rsh, [-1, m1 * m2, n1 * n2]) def kronecker_product3D(tensors): tensor1 = tensors[0] tensor2 = tensors[1] #Separete slices of tensor and computes appropriate matrice kronecker product batch, m1, n1, o1 = tensor1.get_shape().as_list() batch, m2, n2, o2 = tensor2.get_shape().as_list() x_list = [] for ind1 in range(o1): for ind2 in range(o2): x_list.append(kronecker_product(tensor1[:,:,:,ind1], tensor2[:,:,:,ind2])) return K.reshape(Concatenate()(x_list), [-1, m1 * m2, n1 * n2, o1 * o2]) For the hard solution, I would try to figure out a way to avoid iterating, but that may be way more complex than I thought....
answers question: http://stackoverflow.com/q/50330835
has comment: http://stackoverflow.com/comment/87722206
has comment: http://stackoverflow.com/comment/87718357

http://stackoverflow.com/comment/87706343
has text: is that way true to fed a features in a deep learning model?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50339728

http://stackoverflow.com/comment/87756577
has text: Is it possible to extract the timestamp from the id generated with this method?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50368265
score: 0

http://stackoverflow.com/comment/87605763
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50294626
has text: Hint: once parsed with `json.load()`, this translates to a Python dict of dicts. Then it's just a matter of iterating over this dict to deduplicate it's content.

http://stackoverflow.com/comment/87596479
type: QuestionComment
has text: @serj _Selenium Client_ / _WebDriver_ / _WebClient_ variant and versions please.
score: 0
comment on: http://stackoverflow.com/q/50287106
type: Comment

http://stackoverflow.com/a/50373778
score: 2
has body: A possible problem with your code is that the animation function (generate) is not supposed to run in an infinite loop. Furthermore, you are supposed to pass a reference to that function to FuncAnimate, but instead you are calling the function (i.e. you need to omit the parentheses in FuncAnimation(..., generate, ...) The second problem is that you are treating graph._offset3d as if it was a function, when it is merely a tuple of lists. You should assign a new tuple to it, instead of trying to call the function (which I believe is what the error message alludes to). I simplified your code and the following works fine: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation def update_lines(num): dx, dy, dz = np.random.random((3,)) * 255 * 2 - 255 # replace this line with code to get data from serial line text.set_text("{:d}: [{:.0f},{:.0f},{:.0f}]".format(num, dx, dy, dz)) # for debugging x.append(dx) y.append(dy) z.append(dz) graph._offsets3d = (x, y, z) return graph, x = [0] y = [0] z = [0] fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111, projection="3d") graph = ax.scatter(x, y, z, color='orange') text = fig.text(0, 1, "TEXT", va='top') # for debugging ax.set_xlim3d(-255, 255) ax.set_ylim3d(-255, 255) ax.set_zlim3d(-255, 255) # Creating the Animation object ani = animation.FuncAnimation(fig, update_lines, frames=200, interval=50, blit=False) plt.show()
type: Answer
accepted answer of: http://stackoverflow.com/q/50342300
upvote count: 2
answers question: http://stackoverflow.com/q/50342300
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/50235305
downvote count: 0
answers question: http://stackoverflow.com/q/50234149
type: Answer
has body: You should consider something like: blogone = topicone.objects.all() blogtwo = topictwo.objects.all() return render(request, 'blog/index.html', {'blogone': blogone, 'blogtwo': blogtwo}) As the render params are request, template, and context. Reference: https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/
accepted answer of: http://stackoverflow.com/q/50234149
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87540988
type: AnswerComment
has text: you could try to increase the batch size as well, 20 may be too small.
type: Comment
comment on: http://stackoverflow.com/a/50260735
score: 0

http://stackoverflow.com/comment/119475684
type: AnswerComment
comment on: http://stackoverflow.com/a/67056435
has text: in Pandas, shape will output both number of rows and columns. I don't think showing number of columns answers OP's question.
type: Comment
score: 0

http://stackoverflow.com/comment/87548606
type: AnswerComment
comment on: http://stackoverflow.com/a/50264764
score: 0
type: Comment
has text: follow up question if you don't mind. I have another list of strings like so: quote = ['i dont want this', '\r\n ', '\r\n ', ' "this is the quote i want to extract" ', '" and also this one"', '\r\n "and me"'] any suggestion how to get only the quotes inside the list of strings? tried following https://stackoverflow.com/questions/171480/regex-grabbing-values-between-quotation-marks with no luck

http://stackoverflow.com/comment/87632328
score: 0
has text: While it **is** possible, you would be embedding parts of your `circle()` function inside the `fract()` function which would turn it into a different function which my theoretical *other* programmer would no longer be able to reuse.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50305134

http://stackoverflow.com/comment/94381372
type: Comment
score: 0
type: QuestionComment
has text: I am facing the same issue. Did you solve it?
comment on: http://stackoverflow.com/q/50299749

http://stackoverflow.com/comment/136047926
type: AnswerComment
comment on: http://stackoverflow.com/a/50367307
has text: Long argument name: `cmds.ls(nodeTypes=True)`. Documentation states _“Lists all registered node types.”_
score: 1
type: Comment

http://stackoverflow.com/a/50324500
type: Answer
accepted answer of: http://stackoverflow.com/q/50319733
type: AcceptedAnswer
score: 0
has body: After comments we get it strip if traling wthitespaces with apply and join by line break: df['Description'] = df['Description'].str.strip() (df.groupby(['Plugin ID','Issue'])['HostAffected'] .apply('\n'.join) .reset_index())
answers question: http://stackoverflow.com/q/50319733

http://stackoverflow.com/a/50281942
score: 4
answers question: http://stackoverflow.com/q/50281898
has body: Why don't you use urllib and os.path for that? from urllib.parse import urlparse s=u'https://cdn-a.sonyentertainmentnetwork.com/grc/images/ratings/hd/eirin/R-18.png' a=urlparse(s) import os p=a.path # /grc/images/ratings/hd/eirin/R-18.png bn=os.path.basename(p) # R-18.png print(os.path.splitext(bn)[0]) # R-18 For python2 replace the first import with from six.moves.urllib.parse import urlparse
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/q/50327432
tagged with: google-chrome
score: 8
upvote count: 8
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/44724185
type: UnansweredQuestion
has body: I'm writing a script to download a set of files on a website using Selenium and its Chrome driver in Python, but I find it disgusting to see the browser opens and gets a focus whenever the program opens a new tab or clicks on the download button. So I rather want to use headless mode. But then, the element always gets me the following error: WebDriverException: Message: unknown error: Element ... is not clickable at point (435, 575). Other element would receive the click: ... (Session info: headless chrome=66.0.3359.139) (Driver info: chromedriver=2.37.544337 (8c0344a12e552148c185f7d5117db1f28d6c9e85),platform=Mac OS X 10.13.4 x86_64) This error once happened in my non-headless mode, but since I changed the size of the browser by driver.maximize_window(), the error had gone out. This may make it clear the button must be visible on the screen, in order for it to be pushed on Chrome. But in the headless mode, it might be true that the button is hidden and that's way the element is always unclickable, leading to the error. So it there any way to make the button clickable even on the headless mode? The relevant code is the following, and the last line causes the error: def login(driver, url, username, password): driver.get(url) uname = driver.find_element_by_name("login") uname.send_keys(username) passw = driver.find_element_by_name("password") passw.send_keys(password) submit_button = driver.find_element_by_class_name("button") action = webdriver.ActionChains(driver) action.move_to_element(submit_button) submit_button.click()
has comment: http://stackoverflow.com/comment/87671391
tagged with: python
has answer: http://stackoverflow.com/a/50328050
has title: Is it possible to use `element.click()` on Selenium with Chrome even on headless mode?
has comment: http://stackoverflow.com/comment/87671018
has answer: http://stackoverflow.com/a/60505472
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/58893269
tagged with: selenium
has comment: http://stackoverflow.com/comment/87671181

http://stackoverflow.com/q/50329184
upvote count: 1
tagged with: scikit-learn
tagged with: python
has title: Pipelining transformer stages in IBEX, column access problems in Scikit-Learn and Pandas
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: I'm trying to create a scikit-learn based pipeline to pipeline through a pandas dataframe. At each stage, only a subset of features should be touched, the rest should pass through unmodified. I'm using IBEX for this since DataFrameMapper doesn't seem to do the job for me since the untouched fields are not retained, for sake of completeness, here the DataFrameMapper code (which is NOT working for me, but maybe fore someone else): from sklearn_pandas import DataFrameMapper from sklearn.preprocessing import StandardScaler mapper = DataFrameMapper([ (['x','y','z'], StandardScaler()) ]) df_scaled = mapper.fit_transform(df) The dataframe has following fields x y z source class Using IBEX I run the following code: from ibex.sklearn.preprocessing import StandardScaler from ibex.sklearn.preprocessing import LabelEncoder from ibex import trans pipeline = (trans(LabelEncoder(), in_cols=['class']) + trans(None, ['source', 'x','y','z'])) | (trans(StandardScaler(), in_cols=['x','y','z']) + trans(None, ['source', 'class'])) df_scaled = pipeline.fit_transform(df) Now I get the following error since it seems that the fields are not retained in the 2nd pipeline stage: KeyError: "['x' 'y' 'z'] not in index" See GIST of complete error
accepted answer: http://stackoverflow.com/a/50339214
has comment: http://stackoverflow.com/comment/87676187
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50339214
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50364857
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87745951
has comment: http://stackoverflow.com/comment/87746129
answer count: 2
downvote count: 4
has title: How do I split a String Array into 2 serperately parts
has body: How do I split a string Array in some separately parts? that I can print separately I even don't know how to start can anyone help to give me push to the right direction thank you
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87746189
has comment: http://stackoverflow.com/comment/87746073
has answer: http://stackoverflow.com/a/50365198
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/50365000

http://stackoverflow.com/comment/87677334
score: 0
type: QuestionComment
has text: I know tha CNN is more for 2D data like images, but I have 1D vector with 1040 values, where I need to apply convolution
comment on: http://stackoverflow.com/q/50330549
type: Comment

http://stackoverflow.com/a/50341814
answers question: http://stackoverflow.com/q/50341554
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87701280
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50341554
type: Answer
has body: For fun, use the string partition method in Python 3. It searches a string for a substring, and returns a 3-tuple. When there's a match, it's (string before the match, the match, string after the match) Once you're used to it, it's very pleasant - no indexing needed, and it makes it easy to get the right results. So while this code is longer than some other ways, you should be able to reason about it easily: def findallprefix(s, sep): sofar = "" while True: head, matched, s = s.partition(sep) if matched: assert matched == sep sofar += head yield sofar sofar += matched else: break s = "I like lettuce and carrots and onions and dressing." for match in findallprefix(s, " and"): print(repr(match)) which prints 'I like lettuce' 'I like lettuce and carrots' 'I like lettuce and carrots and onions'

http://stackoverflow.com/comment/87687258
score: 1
type: Comment
has text: Yep I know what features are but I was talking about the 'feature columns' mentioned here: https://www.tensorflow.org/get_started/feature_columns
type: AnswerComment
comment on: http://stackoverflow.com/a/50334977

http://stackoverflow.com/a/50243557
upvote count: 1
has body: Have you tried using the Requests library instead, example of a post request below import requests header = {"Content-Type": "multipart/form-data"} data1="something" data2= "otherthing" session_requests = requests.session() result = session_requests.post("http://localhost/", data=dict(data1, data2), headers=header)
answers question: http://stackoverflow.com/q/50243235
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87544572
score: 1

http://stackoverflow.com/q/50253138
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
has title: ConvLSTM2D initial_state assertion error
downvote count: 0
has body: I have an issue with the latest version of Keras. I would like to provide an auxiliary input to ConvLSTM2D that will act as the initializer of the layer memory. This feature is supposed to be implemented, however, the following code from keras.layers import Input from keras.models import Model from keras.layers.convolutional_recurrent import ConvLSTM2D latent_dim, mesh_size = 10, (20, 20) prior_in = Input(shape=mesh_size + (latent_dim, )) core_in = Input(shape=(None, ) + mesh_size + (1, )) core_out = ConvLSTM2D(latent_dim, activation='elu', kernel_size=(3, 3), padding='same')(core_in, initial_state=[prior_in, prior_in]) model = Model([prior_in, core_in], core_out) raises File "tst.py", line 9, in &lt;module&gt; padding='same')(core_in, initial_state=[prior_in, prior_in]) File "python-3.5.4.amd64\lib\site-packages\keras\layers\convolutional_recurrent.py", line 320, in __call__ output = super(ConvRNN2D, self).__call__(full_input, **kwargs) File "python-3.5.4.amd64\lib\site-packages\keras\layers\recurrent.py", line 497, in __call__ inputs, initial_state, constants, self._num_constants) File "python-3.5.4.amd64\lib\site-packages\keras\layers\recurrent.py", line 2247, in _standardize_args assert initial_state is None and constants is None AssertionError On the other hand, this feature seems to be unit tested. After some debugging, I have found the difference between the code that is unit tested and my code is that K.is_keras_tensor(initial_state) is True only for the code posted above. This is important when the program reaches convolutional_recurrent.py line 313. If I manually disable the if clause by changing the line 313 to if False and K.is_keras_tensor(additional_inputs[0]): The error is not raised and it is possible to train, save, load the model and to use it for prediction without any issues. The question is: Does anybody observe the same behavior? Do you have any suggestion how to solve the issue on the client side (without modifying Keras source code)? Can anyb…
tagged with: keras
favorite count: 0
type: Question

openpyxl
tags question: http://stackoverflow.com/q/50248467
tags question: http://stackoverflow.com/q/50356663
tags question: http://stackoverflow.com/q/50368127
tags question: http://stackoverflow.com/q/50336393
tags question: http://stackoverflow.com/q/50274456
type: Tag
tags question: http://stackoverflow.com/q/50236928
tags question: http://stackoverflow.com/q/50341591
tags question: http://stackoverflow.com/q/50316400
tags question: http://stackoverflow.com/q/50341962
tag name: openpyxl
tags question: http://stackoverflow.com/q/50282961
tags question: http://stackoverflow.com/q/50334591

http://stackoverflow.com/comment/87540168
score: 0
has text: I greatly appreciate your response. I will admit, I am relatively new to Tensorflow. If it is not too much of a stretch would you mind helping me maybe create a good example for this question. To give people better insight into how to migrate from Graph/Session models to a Eager approach? I'd be happy to set up a gist with boiler plate code. Thank you, Nate
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50260668

http://stackoverflow.com/comment/87772082
score: 0
has text: Thanks for this, however, I can not see something related to my problem. Additionally, there is something confusing me: It says "Python streaming pipeline execution is experimentally available [...] starting with Beam SDK version 2.5.0." (currently the latest release is 2.4.0) which is in line with the Release notes of the Dataflow SDK for python. However, a pipeline like the one I posted above is working for me in streaming mode with some (for my purposes minor) limitations. Am I missing something?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50367670

http://stackoverflow.com/q/50299143
has comment: http://stackoverflow.com/comment/88543296
tagged with: python
possible better answer: http://stackoverflow.com/a/50299165
has body: In situations where you want to import a nested module into your namespace, I've always written it like this: from concurrent import futures However, I recently realized that this can be expressed using the "as" syntax as well. See the following: import concurrent.futures as futures Which has the subjective advantage of looking more similar to other imports: import sys import os import concurrent.futures as futures ... with the disadvantage of added verbosity. Is there a functional difference between the two, or is one officially preferred in a PEP or otherwise?
has title: Difference between "from x.y import z" and "import x.y.z as z"
answer count: 2
tagged with: python-import
upvote count: 14
has comment: http://stackoverflow.com/comment/87615015
has answer: http://stackoverflow.com/a/50299165
has comment: http://stackoverflow.com/comment/87615092
has comment: http://stackoverflow.com/comment/87615069
downvote count: 0
has answer: http://stackoverflow.com/a/50299663
has comment: http://stackoverflow.com/comment/87615067
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/710551
score: 14
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50299663

http://stackoverflow.com/q/50277390
tagged with: methods
has body: I have a class which exposes two methods. These methods are actually visual syntax sugar, they ultimately point to the same code which behaves differently, depending on the payload it receives: class Action: def on(self): self.action(1) def off(self): self.action(2) def action(self, payload): # a long function which does many things and uses the payload from on() and off() print(payload) a = Action() a.on() a.off() Is there a way to define on() and off() so that they point to the same code (the one in action()), which would behave differently depending on the name of the method which was called? I could of course pass the action in the call: class Action: def action(self, what): payload = 1 if what == 'on' else 0 # a long function which does many things and uses the payload from on() and off() print(payload) a = Action() a.action('on') a.action('off') but I want to keep an on/off structure of the class methods.
has comment: http://stackoverflow.com/comment/87571490
possible better answer: http://stackoverflow.com/a/50278880
type: Question
has comment: http://stackoverflow.com/comment/87572080
has answer: http://stackoverflow.com/a/50278880
has comment: http://stackoverflow.com/comment/87571480
tagged with: python
has comment: http://stackoverflow.com/comment/87571546
has title: Can two methods point to the same code?
tagged with: class
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87571511
has comment: http://stackoverflow.com/comment/87571485
answer count: 3
accepted answer: http://stackoverflow.com/a/50280654
has answer: http://stackoverflow.com/a/50277548
has answer: http://stackoverflow.com/a/50280654

http://stackoverflow.com/q/50316901
answer count: 1
tagged with: python
has title: Python Beautiful Soup Web Scraping?
type: Question
tagged with: python-3.x
has body: I have utilised beautiful soup and the class_ to web scrape. When I used find it was ok as I could use get.text() to find the text within the tags. However I want several of the values that are in the following below. boal_data = boal_soup(class_="investment-info__item grid__item lap--1-2 desk--1-2") print (boal_data) This then produces, when you print, the following. [ Investment Date Apr 2018 , Country Netherlands , Revenue at ACQ. €156m , Employees at ACQ. 370 ] I would like to be able to extra the following. [this text here] How am I able to do so?
accepted answer: http://stackoverflow.com/a/50317269
has answer: http://stackoverflow.com/a/50317269
tagged with: beautifulsoup
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/108130584
type: QuestionComment
type: Comment
has text: Does this answer your question? [Reading an Excel file in python using pandas](https://stackoverflow.com/questions/17063458/reading-an-excel-file-in-python-using-pandas)
score: 0
comment on: http://stackoverflow.com/q/50362664

http://stackoverflow.com/a/50291808
type: Answer
has comment: http://stackoverflow.com/comment/87602702
score: 0
has comment: http://stackoverflow.com/comment/87603956
has body: That was quite a lot of code. I had to reduce it to track down the issue. I found a symptom but I'm unable to see exactly how this should be done. It has something to do with the parent of Checkbutton. Examine my almost working code: from tkinter import * class MainFrame(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) chk = IntVar() chk.set(1) used1 = Checkbutton(parent, text='Used1', variable=chk) used1.pack() print(self.winfo_children()[0]) root = Tk() MainFrame(root) root.mainloop() Now, this code results in the Checkbutton being checked, but the last line in the class, print(self.winfo_children()[0]) generates an error: Traceback (most recent call last): File "C:\Users\qwerty\Documents\Python\test.py", line 15, in &lt;module&gt; MainFrame(root) File "C:\Users\qwerty\Documents\Python\test.py", line 12, in __init__ print(self.winfo_children()[0]) IndexError: list index out of range If I remove that line the error disappears, but also the checked state of the Checkbutton. I can't seem to understand this at the moment. I think I need a large coffee. (I'm using Python 3.6.5 under win10)
answers question: http://stackoverflow.com/q/50289748
has comment: http://stackoverflow.com/comment/87602797

http://stackoverflow.com/q/50381025
score: 0
has answer: http://stackoverflow.com/a/50381702
has title: How to get information from one Main Window to another Main Window after running a function PyQt?
tagged with: python
tagged with: pyqt
has comment: http://stackoverflow.com/comment/87779228
answer count: 1
tagged with: pyqt5
type: Question
has body: I am having trouble trying to get a file from a different window after running a function. The end goal is to get a file from one window and display the entire file on the Main Window. I have textedit set up for displaying the file. The code is below: from PyQt5.QtWidgets import (QMainWindow, QTextEdit, QAction, QFileDialog, QApplication, QWidget, QDialog, QInputDialog, QLineEdit, QLabel, QGridLayout, QPushButton) from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt import sys import analyzer as AN pathtoJSON = "C:\\Tools" class Second(QMainWindow): def __init__(self, parent=None): super(Second, self).__init__(parent) self.initUI() def initUI(self): self.button = QPushButton('1', self) self.button.clicked.connect(self.analyze) self.button.resize(self.button.sizeHint()) self.button.move(167, 220) self.text = "2".format(0, 0) self.label = QLabel(self.text, self) self.label.move(20,15) self.textbox1 = QLineEdit(self) self.textbox1.move(55, 20) self.textbox1.resize(300,20) self.text = "3".format(0, 0) self.label = QLabel(self.text, self) self.label.move(20,65) self.textbox2 = QLineEdit(self) self.textbox2.move(150, 70) self.textbox2.resize(100,20) self.text = "4".format(0, 0) self.label = QLabel(self.text, self) self.label.move(20,115) self.textbox3 = QLineEdit(self) self.textbox3.move(150, 120) self.textbox3.resize(200,20) self.text = "5".format(0, 0) self.label = QLabel(self.text, self) self.label.move(20,165) self.textbox4 = QLineEdit(self) self.textbox4.move(150, 170) self.textbox4.resize(200, 20) self.setGeometry(200, 200, 400, 260) self.setFixedSize(self.size()) self.setWindowTitle('Settings') def analyze(self): #This command here generates a file from the following inputs from Second Window. This file appears at the following path in the variable pathtoJSON. # AN.checkStream(self.textbox1.text(), self.textbox2.text(), self.textbox3.text(), self.textbox4.text()) global urlBox urlBox = self.textbox1.text() global durationBox durationBox = self.textbox2.text() …
accepted answer: http://stackoverflow.com/a/50381702
type: AnsweredQuestion

http://stackoverflow.com/q/50295442
answer count: 0
has comment: http://stackoverflow.com/comment/87761983
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow
has title: Hyperas TypeError: bad operand type for unary -: 'list'
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has body: I'm making this convolutional neural network that can detect between 4 types of images (for now its Cats, Dogs, Airplanes and Motorcycles which I use as test) and I want to optimize certain parameters using Hyperas. Now I'm only optimizing the Dropout rate, as a test. I Keep getting this error however, and I dont know what it even means and what I can do to fix it. This is my code: import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import os from keras import layers, models, optimizers from keras.preprocessing.image import ImageDataGenerator from hyperas import optim from hyperopt import Trials, STATUS_OK, tpe from hyperas.distributions import choice, uniform, conditional from PIL import Image as im from os import listdir from keras.datasets import mnist from keras.utils import np_utils from scipy import misc from keras import backend as K K.set_image_dim_ordering('tf') def data(): tag_dict = {'airplane':0, 'cat':1, 'dog':2, 'motorbike':3} base_directory = "." train_data_dir = base_directory + "/Train" validation_data_dir = base_directory + "/Validation" maxsize = (100, 100) trainlen = sum([len(files) for r, d, files in os.walk(train_data_dir)]) validlen = sum([len(files) for r, d, files in os.walk(validation_data_dir)]) train_array = np.ones((trainlen, 100, 100, 3)) train_tags = np.ones((trainlen,)) val_array = np.ones((validlen, 100, 100, 3)) val_tags = np.ones((validlen,)) itemcounter = 0 for folder in listdir(train_data_dir): for picture in listdir(train_data_dir + "/" + folder): tempdirec = train_data_dir + "/" + folder + "/" + picture img = im.open(tempdirec) img = img.resize(maxsize, im.ANTIALIAS) data = np.asarray(img, dtype='int32') if data.shape != (100, 100, 3): data = np.stack((data, data, data), axis=2) train_array[itemcounter] = data train_tags[itemcounter] = tag_dict[folder] itemcounter += 1 itemcounter = 0 for folder in listdir(validation_data_dir): for picture in listdir(validation_data_dir + "/" + folder): tempdirec…
has comment: http://stackoverflow.com/comment/87608965
has comment: http://stackoverflow.com/comment/89334888

http://stackoverflow.com/comment/87613794
score: 0
comment on: http://stackoverflow.com/a/50298237
has text: Thanks, this works. Had found another solution to click on one of the options above and press enter, but this is more elegant solution.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87781004
score: 0
has text: It's too slow to do that with CPUs, even GPUs, now you'll need a farm of [ASIC](https://en.wikipedia.org/wiki/Application-specific_integrated_circuit)s.
comment on: http://stackoverflow.com/q/50382629
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87622529
type: Comment
comment on: http://stackoverflow.com/q/50302994
type: QuestionComment
score: 0
has text: Just to be clear, you mean to say `print(my_string)` give what you are showing?

http://stackoverflow.com/a/50316342
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50316330
type: AcceptedAnswer
has body: The fnmatch.fnmatch() function works with any string, not just filenames: &gt;&gt;&gt; from fnmatch import fnmatch &gt;&gt;&gt; aa = ['a.b.*', 'a.b.x', '*'] &gt;&gt;&gt; fnmatch('a.b.c', aa[0]) True &gt;&gt;&gt; fnmatch('a.b.c', aa[1]) False &gt;&gt;&gt; fnmatch('a.b.c', aa[2]) True The first parameter is named filename because the glob pattern style matching is traditionally used to filter filenames. And as the documentation states, the filename separator (/ on a POSIX system) is not special to fnmatch() and won't alter how a string is matched. If you want to test if there are any patterns that match a given string, use the any() function: &gt;&gt;&gt; teststring = 'a.b.c' &gt;&gt;&gt; any(fnmatch(teststring, p) for p in aa) True
accepted answer of: http://stackoverflow.com/q/50316330
score: 3

http://stackoverflow.com/q/50278875
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87574454
has answer: http://stackoverflow.com/a/50279312
accepted answer: http://stackoverflow.com/a/50279312
has comment: http://stackoverflow.com/comment/87574742
has comment: http://stackoverflow.com/comment/87574761
tagged with: python
has comment: http://stackoverflow.com/comment/87574899
has comment: http://stackoverflow.com/comment/87574625
has comment: http://stackoverflow.com/comment/87574791
has title: Why doesn't this digital root function work?
type: Question
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87574523
answer count: 1
has body: I'm doing a challenge on codewars, and I'm supposed to write a digital root function in Python. I can't figure out why it's not working. This is my first attempt at recursion. I would really like to wrap my head around this. def digital_root(num): #Check to see if num has more than one digit if num &gt; 9: x = 0 z = 1 #Create an array of the digits in num digits = [int(d) for d in str(num)] #Convert string elements in digits[] to ints for n in digits: digits[x] = int(x) x = x + 1 #Add each element in digits[] to digits[0] for n in digits: digits[0] = digits[0] + digits[z] #If digits[0] has more than one digit, then run digital_root with digits[0] in the parameters if digits[0] &gt; 9: digital_root(digits[0]) else: return digits[0] else: return num digital_root(15) &gt;&gt; Program finished with exit code 0
has comment: http://stackoverflow.com/comment/87574571
has comment: http://stackoverflow.com/comment/87574397

http://stackoverflow.com/comment/87701739
score: 0
type: Comment
type: QuestionComment
has text: Well then this question has nothing to do with php as I see it. The problem is with the execution of the pythonscript or the pythonscript itself.
comment on: http://stackoverflow.com/q/50342869

http://stackoverflow.com/a/50316094
accepted answer of: http://stackoverflow.com/q/50308014
type: Answer
score: 4
upvote count: 4
has body: Override create_view method of ProductView. class ProductView(ModelView): column_display_pk = True @expose('/new/', methods=('GET', 'POST')) def create_view(self): # render your view here return "Hello World"
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50308014

http://stackoverflow.com/a/50360704
has comment: http://stackoverflow.com/comment/87737974
type: Answer
has body: If you're looking for clean code that doesn't do too much, I'd recommend a two step process involving the re module— split your string into smaller chunks on comma using str.split for each chunk, extract coordinates with re.findall For performance, I'd recommend pre-compiling a regex-pattern using re.compile, since we'll be calling it repeatedly inside a loop. &gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile(r'\d+(?:\.\d+)?') &gt;&gt;&gt; [list(map(int, p.findall(x)) for x in mstring.split(',')] [[10, 10], [10, 40], [40, 40], [30, 30], [40, 20], [30, 10]] Note, mstring is your string data. Details \d+ # match one or more digits (?: # specify non-capturing group \. # literal period/decimal \d+ )? # optional Semantically, this regex will match integers OR floats (Ajax1234's solution currently only accounts for integers, and is guaranteed to be finish searching in fewer cycles).
has comment: http://stackoverflow.com/comment/87738069
has comment: http://stackoverflow.com/comment/87738108
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87738849
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87738075
has comment: http://stackoverflow.com/comment/87738650
accepted answer of: http://stackoverflow.com/q/50360643
has comment: http://stackoverflow.com/comment/87737964
has comment: http://stackoverflow.com/comment/87813792
has comment: http://stackoverflow.com/comment/87813706
has comment: http://stackoverflow.com/comment/87813728
answers question: http://stackoverflow.com/q/50360643
has comment: http://stackoverflow.com/comment/87738638

http://stackoverflow.com/comment/87487972
has text: I changed that, no changes. If I give my tk.Frame a background color I see that it is smaller as the frame in my main where I placed my custom widget. How do I get them to the same size?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50235197

http://stackoverflow.com/comment/87911222
score: 0
type: Comment
has text: Thanks much facetoe! Didn't even realize that was an option and thats probably much more efficient. Thanks a ton for zenpy, has made my life much easier.
type: QuestionComment
comment on: http://stackoverflow.com/q/50242222

http://stackoverflow.com/comment/87543654
type: AnswerComment
has text: @jbch I may be going wrong but just thought to clarify. I wanted to write the modified contents of this file (every line) in a newly created file. And hence was using the dictionary method. So I will make a dictionary for the entire file or each line? P.S. haven't used dictionary much. Sorry.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50262705

keras
tags question: http://stackoverflow.com/q/50370581
tags question: http://stackoverflow.com/q/50297594
tags question: http://stackoverflow.com/q/50367540
tags question: http://stackoverflow.com/q/50383888
tags question: http://stackoverflow.com/q/50359526
tags question: http://stackoverflow.com/q/50240752
tags question: http://stackoverflow.com/q/50306863
tags question: http://stackoverflow.com/q/50249205
tags question: http://stackoverflow.com/q/50302172
tags question: http://stackoverflow.com/q/50283057
tags question: http://stackoverflow.com/q/50243086
tags question: http://stackoverflow.com/q/50300010
tags question: http://stackoverflow.com/q/50259170
tags question: http://stackoverflow.com/q/50311056
tags question: http://stackoverflow.com/q/50288258
tags question: http://stackoverflow.com/q/50345305
tags question: http://stackoverflow.com/q/50347159
tags question: http://stackoverflow.com/q/50284898
tags question: http://stackoverflow.com/q/50266975
tags question: http://stackoverflow.com/q/50259290
tags question: http://stackoverflow.com/q/50382613
tags question: http://stackoverflow.com/q/50259158
tags question: http://stackoverflow.com/q/50267032
tags question: http://stackoverflow.com/q/50248736
tags question: http://stackoverflow.com/q/50322660
tags question: http://stackoverflow.com/q/50345072
tags question: http://stackoverflow.com/q/50382382
tags question: http://stackoverflow.com/q/50381504
tags question: http://stackoverflow.com/q/50230222
tags question: http://stackoverflow.com/q/50352347
tags question: http://stackoverflow.com/q/50306988
tags question: http://stackoverflow.com/q/50338865
tags question: http://stackoverflow.com/q/50276488
tags question: http://stackoverflow.com/q/50375207
tags question: http://stackoverflow.com/q/50344058
tags question: http://stackoverflow.com/q/50266996
tags question: http://stackoverflow.com/q/50327354
tags question: http://stackoverflow.com/q/50307985
tags question: http://stackoverflow.com/q/50359055
tags question: http://stackoverflow.com/q/50232685
tags question: http://stackoverflow.com/q/50311253
tags question: http://stackoverflow.com/q/50271548
tags question: http://stackoverflow.com/q/50246723
tags question: http://stackoverflow.com/q/50321437
tags question: http://stackoverflow.com/q/50282989
tags question: http://stackoverflow.com/q/50338209
tags question: http://stackoverflow.com/q/50356436
tags question: http://stackoverflow.com/q/50330835
tags question: http://stackoverflow.com/q/50342680
tags question: http://stackoverflow.com/q/50260459
tags question: http://stackoverflow.com/q/50339622
tags question: http://stackoverflow.com/q/50277397
tags question: http://stackoverflow.com/q/50362045
tags question: http://stackoverflow.com/q/50308811
tags question: http://stackoverflow.com/q/50284939
tags question: http://stackoverflow.com/q/50288786
tags question: http://stackoverflow.com/q/50383844
tags question: http://stackoverflow.com/q/50355483
tags question: http://stackoverflow.com/q/50325848
tags question: http://stackoverflow.com/q/50295442
tags question: http://stackoverflow.com/q/50237761
tags question: http://stackoverflow.com/q/50339728
tags question: http://stackoverflow.com/q/50351248
tags question: http://stackoverflow.com/q/50240354
tags question: http://stackoverflow.com/q/50309488
tags question: http://stackoverflow.com/q/50369331
tags question: http://stackoverflow.com/q/50275860
tags question: http://stackoverflow.com/q/50251821
tags question: http://stackoverflow.com/q/50341647
tags question: http://stackoverflow.com/q/50381050
tags question: http://stackoverflow.com/q/50339038
tags question: http://stackoverflow.com/q/50264065
tag name: keras
tags question: http://stackoverflow.com/q/50269901
tags question: http://stackoverflow.com/q/50364706
tags question: http://stackoverflow.com/q/50366626
tags question: http://stackoverflow.com/q/50295148
tags question: http://stackoverflow.com/q/50371163
tags question: http://stackoverflow.com/q/50305252
tags question: http://stackoverflow.com/q/50252585

http://stackoverflow.com/a/73535209
has body: I could not find an implementation of the Kendall tau distance, but as you mentioned, scipy does have a Kendell tau correlation coefficient (scipy.stats.kendalltau). It is important not to confuse the two, as a normalized distance of 0 is the same as a correlation of 1 and a normalized distance of 1 is the same as a correlation of -1. I would write my derivation in math notation, but unfortunately, stackoverflow does not support mathjax tau_dist := B/N tau_coef := (A-B)/N where A is the number of agreeing orderings, B is the number of disagreeing orderings, and N is the number of items (aka, N = A + B). To convert a value of tau_coef to tau_dist, it turns out to be a linear relationship with negative slope. The previous answer assumes a positive linear relationship, but the actual relationship is negative. from scipy.stats import kendalltau def _kendall_convert_coef_to_dist(tau_coef): '''Convert kendall correlation coefficient to normalized distance''' return (1 - tau_coef) / 2 def kendalldist(*args, **kwargs): '''Return the normalized Kendall tau distance (0 &lt;= tau &lt;= 1) This function wraps around scipy.stats.kendalltau() and forwards all arguments to that function. ''' tau_coef, p_value = kendalltau(*args, **kwargs) return _kendall_convert_coef_to_dist(tau_coef)
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50249736

http://stackoverflow.com/comment/87668281
comment on: http://stackoverflow.com/a/50266597
type: AnswerComment
has text: I did install without cuda, but the error appeared.
score: 0
type: Comment

http://stackoverflow.com/comment/87764829
type: Comment
comment on: http://stackoverflow.com/a/50374021
type: AnswerComment
score: 0
has text: That seems like a logical approach. I know I did the JSON into dict, but I think I had some trouble with file 2 being a list of dictionaries. You've given a good direction though - I'm going to give this another shot. Thanks.

http://stackoverflow.com/q/50375225
has answer: http://stackoverflow.com/a/53348990
tagged with: raspbian
tagged with: python-3.x
tagged with: opencv
has comment: http://stackoverflow.com/comment/87767063
has title: Installing opencv on python 3.5.3 on raspbian OS
linked to: http://stackoverflow.com/q/48146273
tagged with: python
has comment: http://stackoverflow.com/comment/87767757
score: 0
has body: While installing opencv and face_recognition, it turns out the face_recognition library is not possible on python 2.7.13, but it is working fine on python python 3.5 where as opencv is working fine on python 2.7 but it is not installing on python 3.5. I want to compile both on Python ! Any suggestions?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87791885
answer count: 1
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/87766824
type: Question

http://stackoverflow.com/a/50380637
has comment: http://stackoverflow.com/comment/87777682
has comment: http://stackoverflow.com/comment/87777729
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50380017
downvote count: 1
has body: This depends entirely on the encoding of the file. Either way, you need to decode the line first, and then re-encode it so that it's utf-16. with open(file_path, "r") as fh: for line in fh: string = line.decode("utf-8").encode("utf-16")
has comment: http://stackoverflow.com/comment/87777730
type: Answer
answers question: http://stackoverflow.com/q/50380017
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/101687127
comment on: http://stackoverflow.com/a/50355874
type: Comment
score: 4
type: AnswerComment
has text: i've been doing `df.index.size.compute()` which is faster than running `len(df)` ... but my data is stored in columnar parquet... so it depends on what your underlying data architecture is.

http://stackoverflow.com/q/50369636
answer count: 1
has title: Django-, display and filter particular fields from a foreign key in a model form
tagged with: django-forms
has answer: http://stackoverflow.com/a/50384306
type: Question
has body: I am using a model form, and the field is a foreign key, to another the model, the foreign key model contains a choice field(status) which i want filter based on user group,such that if a user belongs to a group, for example if the user in a group DEVELOPER, the status choices available will be 'Weekly Task' and 'Daily Task' models.py class ScrumyGoals(models.Model): user_name=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null= True) status_id = models.ForeignKey('GoalStatus', on_delete=models.CASCADE,null=True) goal_type = models.CharField(choices=GOAL_TYPE, max_length=64, default='DT') def __str__(self): return '{},{}'.format(self.user_name,self.status_id) class GoalStatus(models.Model): GOALS_TYPE= (('DT','Daily Task'), ('WT','Weekly Task'), ('V','Verified'), ('D','Done'), ) title = models.CharField(max_length=254, null=True) task_id=models.IntegerField(default=1,null=False) description =models.CharField(max_length=254) verified_by=models.ForeignKey('ScrumyUser', on_delete= models.CASCADE, null=True) status=models.CharField(choices=GOALS_TYPE, max_length=2, default='DT') forms.py class ChangeTaskForm(forms.ModelForm): class Meta: model = ScrumyGoals fields = ['status_id'] def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(ChangeTaskForm, self).__init__(*args, **kwargs) if user.groups.filter(name ='DEVELOPER').exists(): self.fields['status'].choices = (('WT','Weekly Task'), ('DT','Daily Task'),) views.py def changetask(request): if request.method == 'POST': form = ChangeTaskForm(request.POST, user=request.user) if form.is_valid(): return HttpResponseRedirect('/index/') else: form = ChangeTaskForm(user=request.user) return render(request, 'oderascrumy/changetask.html', {'form': form}) The form only currently shows the status_id , it doesn't show the choices (ie "status") so in essence what i want is this if the logged in user is in group say "DEVELOPER", The user can only change the goal (ie "status_id") choice (ie "status") fro…
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/comment/87515172
type: Comment
score: 0
type: AnswerComment
has text: I tried this but it just prints { "name": "Segments", "children": [] }
comment on: http://stackoverflow.com/a/50246757

http://stackoverflow.com/comment/87771001
comment on: http://stackoverflow.com/q/50377394
has text: Replace `mydf.coalesce(5)` with `mydf.repartition(5)`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50345862
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50346005
tagged with: csrf
tagged with: django
tagged with: python
has body: Is there anyway in django that if user has two open tabs, both logged out, then logs in in one tab, tell that he has logged in in another tab? I mean something like github that tells you you have signed in, please refresh the page. The problem is now If I login in one tab and then in the second tab, I get csrf token missing incorrect.
has answer: http://stackoverflow.com/a/50346494
answer count: 2
linked to: http://stackoverflow.com/q/28230845
downvote count: 0
score: 1
upvote count: 1
has title: django detect user login in another tab
tagged with: django-csrf
favorite count: 0
type: Question

http://stackoverflow.com/comment/87652608
has text: Python 2 doesn't allow arbitrary Unicode like that non-standard `с` in variable names. That's why that specific character is highlighted.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50318330

http://stackoverflow.com/comment/87554146
type: Comment
type: AnswerComment
has text: maybe could be my return at detail view? how it should be?
score: 0
comment on: http://stackoverflow.com/a/50268085

http://stackoverflow.com/q/50320793
has body: I am looking for a Python expression that would transform this chunk of text: z= 10 zi = 300 print(z) print(z * 180) print(z - 3241) y=z print(type(z)) print(type(y)) print(type(z[0])) print(type(z[1])) into the following chunk of text: K= 10 zi = 300 print(K) print(K * 180) print(K - 3241) y=K print(type(K)) print(type(y)) print(type(K[0])) print(type(K[1])) I have tried: newdata = filedata.replace("z", "K") But, this replaces all instances of z, whereas I would only like to replace words whose only letters are z.
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 2
has title: Find and replace strings which are distinct words, but not substrings?
linked to: http://stackoverflow.com/q/1324676
upvote count: 2
accepted answer: http://stackoverflow.com/a/50320835
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50320835
favorite count: 0
type: Question

http://stackoverflow.com/q/50284939
has answer: http://stackoverflow.com/a/53989446
tagged with: python
type: Question
score: 2
has title: The length of word index in the Keras Tokenizer
upvote count: 3
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87586377
tagged with: keras
has body: Consider the following code applied to the IMDB dataset. The printed length of word_index is always 88582 regardless of the value of max_words. I think it should be min(max_words,88582). What is wrong? from keras.preprocessing.text import Tokenizer max_words = 100 tokenizer = Tokenizer(num_words=max_words) tokenizer.fit_on_texts(texts) print(len(tokenizer.word_index))
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87586008

http://stackoverflow.com/comment/87539646
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50260803
has text: Email them and ask them if you can have the data. If you can't, you're likely competition. Presumably they would monetise it through ads or something (I'm not sure why a government would build such a thing but I can definitely be wrong without knowing enough about the location).
score: 2

http://stackoverflow.com/comment/87596018
type: QuestionComment
has text: actually `os.path.isfile` should handle this already
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50289925

http://stackoverflow.com/q/50368569
has title: Looping back to the top of Python script
type: Question
has body: Would you be able to assist a newbie here with a small Python script? Editing my question. As the below code worked for what it was intended. Now what I am trying to achieve is that i also have a second script. (posted below) That controls a PIR Sensor which ALSO turns the light on. But I would like to try and merge the two scripts into 1 single script. It should as default use the PIR sensor to turn the light on when movement is detected. But! If the button is pushed it should override the sensor and leave the light on for 15 minutes. As I have it set up now the pir does its job. But if there is no movement in front of it and I push the button it turns the light on then quickly off again as the pir is detecting no movement. Both scripts below. All help I can get is very very much appreciated. import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(4, GPIO.IN) #Read output from PIR motion sensor while True: i=GPIO.input(4) if i==0: #When output from motion sensor is LOW print "No movement detected - Turning lights off",i exec(open("./LightsOff.py").read(), globals()) time.sleep(0.1) elif i==1: #When output from motion sensor is HIGH print "Movement detected - Turning lights on",i exec(open("./LightsOn.py").read(), globals()) time.sleep(60 * 15) import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: input_state = GPIO.input(18) if input_state == False: print('Button Pressed') execfile("LightsOn.py") time.sleep(0.2)
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87965742
score: 0
has answer: http://stackoverflow.com/a/50374676
has comment: http://stackoverflow.com/comment/87753491
tagged with: raspberry-pi

http://stackoverflow.com/q/50379072
tagged with: https
type: Question
has title: python socket, HTTPS request load full html code
has body: I'm learning how to use socket to make https request, and my problem is that I can success request (status 200), but I will only have a part of the webpage content (can't understand why it's splitted in this way) I will receive my Http header, with a part of the html code. I tried it with at least 3 different website (including github), and I always have the same result. I'm able to connect with my account to a website, having my cookies to use my account, load a new page with those cookie and get a status 200, and juste have a part of the website... Like just having site's navbars. If someone have any clue. import socket import ssl HOST = 'www.python.org' PORT = 443 MySock = socket.socket() MySock = ssl.wrap_socket(MySock, ssl_version=ssl.PROTOCOL_SSLv23) MySock.connect((HOST,PORT)) MySock.send("""GET / HTTP/1.1 Host: {} """.format(HOST).encode()) #Create file to check reponse content with open('PythonOrg.html', 'w') as File: print(MySock.recv(50000).decode(), file=File)
type: UnansweredQuestion
tagged with: sockets
has answer: http://stackoverflow.com/a/50381650
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
answer count: 1
tagged with: http

http://stackoverflow.com/comment/87837445
has text: +1 I didn't know that when indexing and slicing a hdf5 file the whole file data is not loaded into memory and only that specific portion is loaded. In this regard, this solution is much better than mine.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50406642
score: 0

http://stackoverflow.com/comment/101826620
type: AnswerComment
comment on: http://stackoverflow.com/a/50311243
score: 0
type: Comment
has text: @ely can you answer a similar question https://stackoverflow.com/q/57690048/10227958 ! I will be very grateful.

http://stackoverflow.com/comment/87758866
comment on: http://stackoverflow.com/a/50370885
score: 0
has text: hi, i have changed `my_sub=subprocess.Popen(['exe file','files in folder'],stderr=STADOUT,stdout=PIPE)\ .communicate()[0] ` to `my_sub=subprocess.check_output(['exe file','files in folder'],stderr=STDOUT) ` but still the same problem, could You edit my all code? maybe i dont see something
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87669727
type: AnswerComment
comment on: http://stackoverflow.com/a/50326863
has text: @Chris_Rands The data looks like it has the data *before* the name of the country in the example.
score: 0
type: Comment

http://stackoverflow.com/a/50327505
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/50257509
has body: Thanks to @ImportanceOfBeingErnest, indeed the issue was with PyCharm. (I am using 2017.2.3) Therefore if anyone's having the same issue - just try outside of PyCharm!
answers question: http://stackoverflow.com/q/50257509
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/50279841
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50279749
has body: Replace word.replace('è','&amp;egrave;') with word = word.replace('è','&amp;egrave;') and print the result to check. word.replace('è','&amp;egrave;') does work, but it doesn't actually make any changes to the word content itself. Check str.replace()
score: 2
downvote count: 0

http://stackoverflow.com/comment/87557097
comment on: http://stackoverflow.com/a/50264311
type: Comment
has text: For the rest, it's up to you to interpret this as you like. But there is a real implementation difference and I showed the implication it brings.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/126192827
type: QuestionComment
comment on: http://stackoverflow.com/q/50305725
score: 0
type: Comment
has text: Does this answer your question? [Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64](https://stackoverflow.com/questions/50125472/issues-with-installing-python-libraries-on-windows-condahttperror-http-000-co)

http://stackoverflow.com/q/50288933
has body: I read some parameters from a text file using the following code: H, OD, c, b, orc = np.genfromtxt('textfile.txt', unpack = True) I plot them two by two using the simple code plt.plot(H[i], c[i], 'bo') Finally we have 10 plots for these 5 parameters. The plots are something like solid circle or solid elliptic or a closed solid figure using 300,000 points. similar to How could I plot the boundary line or fit line, I mean the outer line surrounded the figure. similar to (source: springernature.com)
score: 0
has title: How to plot the best line or outer line of an elliptic scatter figure in Python
linked to: http://stackoverflow.com/q/1768197
tagged with: matplotlib
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/88046935
tagged with: python
linked to: http://stackoverflow.com/q/4128699
has comment: http://stackoverflow.com/comment/88139574
has comment: http://stackoverflow.com/comment/87593977
has comment: http://stackoverflow.com/comment/87667973
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87594018
has comment: http://stackoverflow.com/comment/87593896
tagged with: plot
has comment: http://stackoverflow.com/comment/87594064
type: Question

http://stackoverflow.com/q/50313521
tagged with: scikit-learn
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50314787
has answer: http://stackoverflow.com/a/50314787
score: 9
upvote count: 9
possible better answer: http://stackoverflow.com/a/50315084
has body: I want to use sklearn.preprocessing.StandardScaler on a subset of pandas dataframe columns. Outside a pipeline this is trivial: df'A', 'B' = scaler.fit_transform(df'A', 'B') But now assume I have column 'C' in df of type string and the following pipeline definition from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline pipeline = Pipeline([ ('standard', StandardScaler()) ]) df_scaled = pipeline.fit_transform(df) How can I tell StandardScaler to only scale columns A and B? I'm used to SparkML pipelines where the features to be scaled can be passed to the constructor of the scaler component: normalizer = Normalizer(inputCol="features", outputCol="features_norm", p=1.0) Note: The feature column is containing a sparse vector with all the numerical feature columns created by Spark's VectorAssembler
has title: Using scikit StandardScaler in Pipeline on a subset of Pandas dataframe columns
has answer: http://stackoverflow.com/a/50315084
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/48673402
linked to: http://stackoverflow.com/q/50329184
downvote count: 0

http://stackoverflow.com/comment/87654252
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50319136
has text: @Lemayzeur neither STATIC_URL = '/home/robin/www/trader/templates/trader/' nor STATICFILES_DIRS = '/home/robin/www/trader/templates/trader/' worked
type: Comment

http://stackoverflow.com/a/50277513
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50267780
has body: Thank you all I have get the answer from robbmcleod in Github for NumExpr 2.6 you'll need arrays around 128 - 256 kElements to see a speed-up. NumPy always starts faster as it doesn't have to synchronize at a thread barrier and otherwise spin-up the virtual machine Also, once you call numexpr.evaluate() the second time, it should be faster as it will have already compiled everything. Compilation takes around 0.5 ms for simple expressions, more for longer expressions. The expression is stored as a hash, so the next time that computational expense is gone. related url: https://github.com/pydata/numexpr/issues/301#issuecomment-388097698
answers question: http://stackoverflow.com/q/50267780
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/q/50285686
answer count: 1
has title: Python Error in print command. Syntax Error
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87587227
tagged with: python
accepted answer: http://stackoverflow.com/a/50286029
has answer: http://stackoverflow.com/a/50286029
type: Question
has comment: http://stackoverflow.com/comment/87587596
upvote count: 0
score: -2
has body: I wrote the following code from sklearn import tree features = [[140,0],[130,1],[150,0],[170,0]] labels = [0,0,1,1] clf = tree.DecisionTreeClassifier() clf = clf.fit(features,labels) result = clf.predict([[160,0]]) print (result) This code is fine but my debugger is regularly showing error on print command. print (result) ... Have not any reason why. Debugger says SyntaxError: invalid syntax
downvote count: 2

http://stackoverflow.com/a/50352715
type: Answer
accepted answer of: http://stackoverflow.com/q/50343129
score: 0
type: AcceptedAnswer
has body: pip3 install pygame Installing pygame and setting the PATH correctly fixed this issue.
answers question: http://stackoverflow.com/q/50343129

lstm
tags question: http://stackoverflow.com/q/50352777
tags question: http://stackoverflow.com/q/50308811
tags question: http://stackoverflow.com/q/50251821
tags question: http://stackoverflow.com/q/50303670
tags question: http://stackoverflow.com/q/50297504
tags question: http://stackoverflow.com/q/50311263
tags question: http://stackoverflow.com/q/50322857
tags question: http://stackoverflow.com/q/50272802
tags question: http://stackoverflow.com/q/50298058
tags question: http://stackoverflow.com/q/50243334
tags question: http://stackoverflow.com/q/50249205
tags question: http://stackoverflow.com/q/50284898
type: Tag
tags question: http://stackoverflow.com/q/50322660
tags question: http://stackoverflow.com/q/50338865
tags question: http://stackoverflow.com/q/50281775
tags question: http://stackoverflow.com/q/50262174
tag name: lstm
tags question: http://stackoverflow.com/q/50340289

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/50322001
type: Tag

http://stackoverflow.com/q/50250345
linked to: http://stackoverflow.com/q/49748063
type: Question
has answer: http://stackoverflow.com/a/55111183
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87519544
tagged with: pip
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/50454886
score: 0
has comment: http://stackoverflow.com/comment/87517949
has answer: http://stackoverflow.com/a/50694899
has comment: http://stackoverflow.com/comment/87518065
answer count: 3
has comment: http://stackoverflow.com/comment/87546537
has title: No matching distribution found for django for python 3.6.5
has comment: http://stackoverflow.com/comment/87518125
has comment: http://stackoverflow.com/comment/87534701
has body: I am building new Django app with a new version of Django. I found Django 2.0 is available (2.0.5) https://www.djangoproject.com/download/, and now trying to install it with pip. pip install Django==2.0.5 But it's not working for me. Collecting Django==2.0.5 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x044F7630&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x044F7850&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x044F7A50&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x044F74D0&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x044F7C30&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/django/ Could not find a version that satisfies the requirement Django==2.0.5 (from versions: ) No matching distribution found for Django==2.0.5 I am using python 3.6.5 and pip 9.0.3. What's wrong here?

http://stackoverflow.com/a/50263336
has body: Create the private IJMetadata (50839) and IJMetadataByteCounts (50838) TIFF tags on your own and pass them to tifffile.imsave as extratags. IJMetadata contains application internal metadata in a binary format. The color information is in the luts metadata: import struct import numpy import tifffile def imagej_metadata_tags(metadata, byteorder): """Return IJMetadata and IJMetadataByteCounts tags from metadata dict. The tags can be passed to the TiffWriter.save function as extratags. """ header = [{'&gt;': b'IJIJ', '&lt;': b'JIJI'}[byteorder]] bytecounts = [0] body = [] def writestring(data, byteorder): return data.encode('utf-16' + {'&gt;': 'be', '&lt;': 'le'}[byteorder]) def writedoubles(data, byteorder): return struct.pack(byteorder+('d' * len(data)), *data) def writebytes(data, byteorder): return data.tobytes() metadata_types = ( ('Info', b'info', 1, writestring), ('Labels', b'labl', None, writestring), ('Ranges', b'rang', 1, writedoubles), ('LUTs', b'luts', None, writebytes), ('Plot', b'plot', 1, writebytes), ('ROI', b'roi ', 1, writebytes), ('Overlays', b'over', None, writebytes)) for key, mtype, count, func in metadata_types: if key not in metadata: continue if byteorder == '&lt;': mtype = mtype[::-1] values = metadata[key] if count is None: count = len(values) else: values = [values] header.append(mtype + struct.pack(byteorder+'I', count)) for value in values: data = func(value, byteorder) body.append(data) bytecounts.append(len(data)) body = b''.join(body) header = b''.join(header) data = header + body bytecounts[0] = len(header) bytecounts = struct.pack(byteorder+('I' * len(bytecounts)), *bytecounts) return ((50839, 'B', len(data), data, True), (50838, 'I', len(bytecounts)//4, bytecounts, True)) filename = 'FluorescentCells.tif' image = tifffile.imread(filename) grays = numpy.tile(numpy.arange(256, dtype='uint8'), (3, 1)) red = numpy.zeros((3, 256), dtype='uint8') red[0] = numpy.arange(256, dtype='uint8') green = numpy.zeros((3, 256), dtype='uint8') green[1]…
score: 9
accepted answer of: http://stackoverflow.com/q/50258287
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50258287
upvote count: 9
has comment: http://stackoverflow.com/comment/96294813
type: Answer
has comment: http://stackoverflow.com/comment/87546791

http://stackoverflow.com/a/50308627
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87633231
accepted answer of: http://stackoverflow.com/q/50308620
answers question: http://stackoverflow.com/q/50308620
type: AcceptedAnswer
has body: Use map: starterkit = {"SKKP":4,'SKP1':3,'SKP1':3,'SKPK':1,'SKC1':1 } df.qty += df.sku.map(starterkit) print (df) proid sku qty 0 p009 SKPK 1.0 1 p009 SKKP 6.0 2 p008 SKPK 1.0 3 p008 SKC1 5.0 4 p008 SKKP 4.0
downvote count: 0

pyspark
tags question: http://stackoverflow.com/q/50346998
tags question: http://stackoverflow.com/q/50289566
tags question: http://stackoverflow.com/q/50366604
tags question: http://stackoverflow.com/q/50317601
tags question: http://stackoverflow.com/q/50329878
tags question: http://stackoverflow.com/q/50348192
tags question: http://stackoverflow.com/q/50361096
tags question: http://stackoverflow.com/q/50349633
tags question: http://stackoverflow.com/q/50338012
tags question: http://stackoverflow.com/q/50253560
tags question: http://stackoverflow.com/q/50257583
tags question: http://stackoverflow.com/q/50338026
tags question: http://stackoverflow.com/q/50247667
tags question: http://stackoverflow.com/q/50255409
tags question: http://stackoverflow.com/q/50278985
tags question: http://stackoverflow.com/q/50303307
tags question: http://stackoverflow.com/q/50284760
tags question: http://stackoverflow.com/q/50381076
tags question: http://stackoverflow.com/q/50256573
tags question: http://stackoverflow.com/q/50379541
tags question: http://stackoverflow.com/q/50311732
tags question: http://stackoverflow.com/q/50348188
tags question: http://stackoverflow.com/q/50356836
type: Tag
tags question: http://stackoverflow.com/q/50287363
tags question: http://stackoverflow.com/q/50338747
tags question: http://stackoverflow.com/q/50353999
tags question: http://stackoverflow.com/q/50321506
tags question: http://stackoverflow.com/q/50346213
tags question: http://stackoverflow.com/q/50366396
tags question: http://stackoverflow.com/q/50246487
tags question: http://stackoverflow.com/q/50256995
tags question: http://stackoverflow.com/q/50347734
tags question: http://stackoverflow.com/q/50258093
tags question: http://stackoverflow.com/q/50242843
tags question: http://stackoverflow.com/q/50295783
tags question: http://stackoverflow.com/q/50361495
tags question: http://stackoverflow.com/q/50346020
tags question: http://stackoverflow.com/q/50367947
tags question: http://stackoverflow.com/q/50255346
tag name: pyspark
tags question: http://stackoverflow.com/q/50350496
tags question: http://stackoverflow.com/q/50363947
tags question: http://stackoverflow.com/q/50359384
tags question: http://stackoverflow.com/q/50362116
tags question: http://stackoverflow.com/q/50243130
tags question: http://stackoverflow.com/q/50309000
tags question: http://stackoverflow.com/q/50244187
tags question: http://stackoverflow.com/q/50306421
tags question: http://stackoverflow.com/q/50321549
tags question: http://stackoverflow.com/q/50255356
tags question: http://stackoverflow.com/q/50326780
tags question: http://stackoverflow.com/q/50330593
tags question: http://stackoverflow.com/q/50243847
tags question: http://stackoverflow.com/q/50374435
tags question: http://stackoverflow.com/q/50339462
tags question: http://stackoverflow.com/q/50377394

http://stackoverflow.com/a/50278453
answers question: http://stackoverflow.com/q/50274372
has body: Soo I read all the answers,thanks for sparing your time to answer my question,I really appreciate that.But I found the most suitable answer for me and the code is: num = [1,2,3,4,5,2,0,3,9] for i in range(len(num)): if(num[i]&gt;num[i-1]): print(num[i], end = " ")
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50274372

http://stackoverflow.com/comment/87577965
comment on: http://stackoverflow.com/q/50239473
type: QuestionComment
has text: @hoefling This is correct for passing the SWIG options, thanks.
score: 0
type: Comment

http://stackoverflow.com/comment/87674989
type: Comment
has text: @DeepSpace You are totally right. However, the above example is only a minimal example from a much larger script, where I do much more stuff.
type: QuestionComment
comment on: http://stackoverflow.com/q/50329479
score: 0

http://stackoverflow.com/comment/87654350
type: Comment
type: QuestionComment
has text: Return something ?? This is what you can do with `WSGI`
comment on: http://stackoverflow.com/q/50319273
score: 0

http://stackoverflow.com/comment/87596053
type: AnswerComment
has text: I think my example is not a good example because I put the months values as numerical values (1 till 12). But what if the month values are january, february, ... ? (if my qualitative variable can't be represented as numerical variable (like groupe-a, groupe-b, ...))
comment on: http://stackoverflow.com/a/50288862
score: 0
type: Comment

http://stackoverflow.com/q/50290177
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-oauth
answer count: 0
has title: DjangOAuthToolkit - How to have different read/write scope for a View?
score: 2
has body: I'm using DRF and OAuthToolkit. Here is my view:- class UserDetailView(RetrieveUpdateDestroyAPIView): serializer_class = UserUpdateSerializer permission_classes = [TokenHasResourceScope] required_scopes = ['user_detail'] Now, the above view will support GET, PUT, PATCH, and DELETE methods. Now, if I create a token with a scope as user_detail, it will give access to all the methods. However, I want different read/write scopes for SAFE and UNSAFE methods. Upon reading OAuthToolkit code for TokenHasResourceScope, it create scopes for SAFE and UNSAFE methods, ie user_detail:read and user_detail:write. Now, if the client request for user_detail:read scope, the library returns invalid scope. How do I support scopes for read and write of a particular view differently?
downvote count: 0

http://stackoverflow.com/comment/87504707
has text: But you are storing the entire _list_ in memory, and the list will be _much_ larger than the text file. Maybe tell us what you are trying to do?
score: 2
comment on: http://stackoverflow.com/q/50243495
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50335909
accepted answer: http://stackoverflow.com/a/50556283
has answer: http://stackoverflow.com/a/50336023
answer count: 3
has answer: http://stackoverflow.com/a/50556283
upvote count: 5
has title: Option with two arguments with docopt
favorite count: 0
has body: I want to have an option that takes two arguments. I.e. would like to be able to use $ ./foo --path "old" "new" Or what I really want is: $ ./foo --path "old" "new" --path "old" "new" But I don't know how to do it? (In fact I fear that it might not be possible...) What I don't want, but which is close I know how to have a repeating option (see below), but that is really not what I want here. #!/usr/bin/env python3 '''foo Usage: foo [--path ARG]... Options: --path=ARG Repeating option. ''' import docopt args = docopt.docopt(__doc__) print(args) Could be called with $ ./foo --path "old" --path "new"
type: Question
score: 5
has answer: http://stackoverflow.com/a/50336078
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50336023
type: AnsweredQuestion
tagged with: docopt

http://stackoverflow.com/q/50303627
score: 1
has title: Output related error in multiprocessing
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87623678
favorite count: 0
tagged with: python-multiprocessing
type: Question
has answer: http://stackoverflow.com/a/76755422
has answer: http://stackoverflow.com/a/50303729
possible better answer: http://stackoverflow.com/a/76755422
accepted answer: http://stackoverflow.com/a/50303729
has comment: http://stackoverflow.com/comment/87623778
has comment: http://stackoverflow.com/comment/87623713
has body: Here is my multiprocessing code. from multiprocessing import Process def print_func(continent = 'Asia'): print('The name of continent is: ',continent) if __name__ == "__main__": names = ['America','Russia','Africa'] procs = [] proc = Process(target = print_func) procs.append(proc) proc.start() for name in names: proc = Process(target = print_func,args =(name,)) procs.append(proc) proc.start() for proc in procs: proc.join() But it shows no output! What am I doing wrong? I want output like this: The name of continent is: Asia The name of continent is: America The name of continent is: Russia The name of continent is: Africa
tagged with: python
tagged with: python-idle
has comment: http://stackoverflow.com/comment/87623865
has comment: http://stackoverflow.com/comment/87623858
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35293178
answer count: 3
has answer: http://stackoverflow.com/a/50303726

http://stackoverflow.com/q/50305976
has comment: http://stackoverflow.com/comment/87628056
type: AnsweredQuestion
score: 3
has title: Is array.count() orders of magnitude slower than list.count() in Python?
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87628116
linked to: http://stackoverflow.com/q/176011
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50306591
has comment: http://stackoverflow.com/comment/87628648
type: Question
has comment: http://stackoverflow.com/comment/87628551
has answer: http://stackoverflow.com/a/50306591
has comment: http://stackoverflow.com/comment/87638101
has comment: http://stackoverflow.com/comment/87628089
tagged with: arrays
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/87632657
has comment: http://stackoverflow.com/comment/87628032
has comment: http://stackoverflow.com/comment/87628161
upvote count: 4
has body: Currently I am playing with Python performance, trying to speed up my programs (usually those which compute heuristics). I always used lists, trying not to get into numpy arrays. But recently I've heard that Python has 8.7. array — Efficient arrays of numeric values so I thought I would try that one. I wrote a piece of code to measure an array.count() vs. a list.count(), as I use it in many places in my code: from timeit import timeit import array a = array.array('i', range(10000)) l = [range(10000)] def lst(): return l.count(0) def arr(): return a.count(0) print(timeit('lst()', "from __main__ import lst", number=100000)) print(timeit('arr()', "from __main__ import arr", number=100000)) I was expecting a slight performance improvement when using array. Well, this is what happened: &gt; python main.py 0.03699162653848456 74.46420751473268 So, according to timeit the list.count() is 2013x faster than the array.count(). I definitely didn't expect that. So I've searched through SO, python docs etc. and the only thing I found was that the objects in array have to be first wrapped into int-s, so this could slow things down, but I was expecting this to happen when creating an array.array-instance, not when random accessing it (which I believe is what .count() does). So where's the catch? Am I doing something wrong? Or maybe I shouldn't use standard arrays and go straight to numpy.arrays?

http://stackoverflow.com/q/50287816
has answer: http://stackoverflow.com/a/50288564
accepted answer: http://stackoverflow.com/a/50288564
has comment: http://stackoverflow.com/comment/87592135
downvote count: 0
has comment: http://stackoverflow.com/comment/87592815
has comment: http://stackoverflow.com/comment/87591642
score: 1
upvote count: 1
tagged with: django-models
has title: How can i add extra model fields to default auth_user model using django
tagged with: django-forms
has comment: http://stackoverflow.com/comment/87591785
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87592098
has body: I'm new to Django. I need to include an extra model fields in my User Model (auth_user table in the database) as well as i want to include ForeignKey fields also inside auth_user i have four models classes like Semestertype, Programtype, Programchoice: import datetime from django.utils import timezone from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class Semestertype(models.Model): value = models.CharField(max_length=100, null=True, blank=True) class Meta: db_table = 'semestertype' class Programtype(models.Model): value = models.CharField(max_length=100, null=True) class Meta: db_table = 'programtype' class Programchoice(models.Model): value = models.CharField(max_length=100, null=True, blank=True) class Meta: db_table = 'programchoice' I included Semestertype , Programtype, Programchoice models in my auth_user models using AbstractUser like below class User(AbstractUser): semestertype = models.ForeignKey(Semestertype, on_delete=models.CASCADE,null=True, blank=True) programtype = models.ForeignKey(Programtype, on_delete=models.CASCADE,null=True, blank=True) programchoice = models.ForeignKey(Programchoice, on_delete=models.CASCADE,null=True, blank=True) filenumber = models.CharField(null=True, max_length=9, blank=True) personalemail = models.EmailField(max_length=254, blank=True) nameofbachelorsdegree = models.CharField(max_length=200, null=True, blank=True) And This is my profile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) description = models.CharField(max_length=100, default = '') city = models.CharField(max_length=100, default = '') phone = models.IntegerField(default=0) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_…
answer count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87591905
has comment: http://stackoverflow.com/comment/87592021
type: AnsweredQuestion

http://stackoverflow.com/a/50317908
score: 0
has comment: http://stackoverflow.com/comment/87652264
has comment: http://stackoverflow.com/comment/87651919
answers question: http://stackoverflow.com/q/50311145
has comment: http://stackoverflow.com/comment/87652178
type: Answer
has body: This error message... Select only works on select elements, not on input ...implies that you have initialized a Select object and tried to pass an input tag to the Select object. As per the HTML you have shared the desired object is within an &lt;input&gt; tag. So you can't assign the input tag to a Select instance. Instead to click and expand the selection box you can try the following code block : driver.find_element_by_xpath("//span[@class='custom-combobox']/input[@class='custom-combobox-input ui-widget ui-widget-content ui-corner-left ui-autocomplete-input']")
has comment: http://stackoverflow.com/comment/87651788

http://stackoverflow.com/comment/88632591
type: AnswerComment
has text: You'll have to post the ValueError. Also, if you're not on the latest version of exchangelib already, try upgrading to 1.11.4.
type: Comment
comment on: http://stackoverflow.com/a/50407053
score: 0

http://stackoverflow.com/comment/87532916
comment on: http://stackoverflow.com/q/50251570
has text: @ImportanceOfBeingErnest thank you, I will try to do do so going fwds. I was missing a comma at the end, in "blit=True save_count=500". I have edited the code to reflect this. Any advice is very welcome.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87583646
comment on: http://stackoverflow.com/q/50283612
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations

http://stackoverflow.com/comment/87515775
has text: Thanks for the suggestions. As @GilHamilton has said, the `recv` command included an implicit wait. I am using Python2.7 so I've now used the three quotation marks like so """XML DATA""" which has enabled my data to be passed as a string. The problem I'm facing now is `socket.error: [Errno 10054] An exisiting connection was forcibly closed by the remote host`. This is probably due to the actual payload of the string, so I'll have a tinker and see what's happening using WireShark. I'll feedback what I have found.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50237213
type: QuestionComment

http://stackoverflow.com/comment/87620914
comment on: http://stackoverflow.com/q/50302207
has text: Also please have [tag:python-3.x] or [tag:python-2.7] too.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/77767627
answers question: http://stackoverflow.com/q/50346326
score: 0
type: Answer
has body: Just to add a solution for an additional possible way this failure could occur. I was struggling with the session tables not being created. I tried the fake migration reset strategy suggested by @seuling and still was not getting the tables created. It turns out that the enterprise installation I am working on has a highly sharded database, and the session tables are not in the same database as the default database. So to get this to work, I performed the above fake migration steps, and also had to specify the database: --database &lt;session_db&gt; e.g. manage.py migrate --database session

sqlalchemy
tags question: http://stackoverflow.com/q/50298923
tags question: http://stackoverflow.com/q/50366530
tags question: http://stackoverflow.com/q/50245422
tags question: http://stackoverflow.com/q/50327160
tags question: http://stackoverflow.com/q/50231564
tags question: http://stackoverflow.com/q/50276826
tags question: http://stackoverflow.com/q/50275767
tags question: http://stackoverflow.com/q/50296416
tags question: http://stackoverflow.com/q/50349559
tags question: http://stackoverflow.com/q/50316965
tags question: http://stackoverflow.com/q/50232239
tags question: http://stackoverflow.com/q/50326052
tags question: http://stackoverflow.com/q/50252114
tags question: http://stackoverflow.com/q/50341071
tags question: http://stackoverflow.com/q/50317889
tags question: http://stackoverflow.com/q/50273278
tags question: http://stackoverflow.com/q/50343523
tags question: http://stackoverflow.com/q/50242065
tags question: http://stackoverflow.com/q/50262542
tags question: http://stackoverflow.com/q/50310228
tags question: http://stackoverflow.com/q/50325599
tags question: http://stackoverflow.com/q/50240289
tags question: http://stackoverflow.com/q/50310979
tags question: http://stackoverflow.com/q/50304880
tags question: http://stackoverflow.com/q/50372057
tags question: http://stackoverflow.com/q/50237082
tags question: http://stackoverflow.com/q/50252743
tags question: http://stackoverflow.com/q/50330935
tags question: http://stackoverflow.com/q/50277792
tags question: http://stackoverflow.com/q/50297130
tags question: http://stackoverflow.com/q/50260840
tags question: http://stackoverflow.com/q/50267626
tags question: http://stackoverflow.com/q/50271589
tags question: http://stackoverflow.com/q/50293947
tags question: http://stackoverflow.com/q/50274211
tags question: http://stackoverflow.com/q/50283933
tags question: http://stackoverflow.com/q/50365608
tags question: http://stackoverflow.com/q/50350268
tags question: http://stackoverflow.com/q/50237877
tags question: http://stackoverflow.com/q/50315407
tags question: http://stackoverflow.com/q/50335507
tags question: http://stackoverflow.com/q/50260499
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/50356012
tags question: http://stackoverflow.com/q/50300832
type: Tag
tags question: http://stackoverflow.com/q/50351922

http://stackoverflow.com/comment/87704850
score: 0
comment on: http://stackoverflow.com/q/50334441
type: Comment
type: QuestionComment
has text: @Satendra thank you very much. I have started this project few days back i could not continue due to some other project work. Forgot basic things I will make note of it.

http://stackoverflow.com/a/50280325
type: Answer
answers question: http://stackoverflow.com/q/50279865
has body: If you're looking for the correlation between the two variables, price, and longitude, I recommend a 2d histogram. fig = plt.figure(figsize=(10,6)) plt.hist2d(x=data['price'], y=data['longitude'],bins=50, cmin=1); plt.grid(True); plt.xlabel('Price', fontsize=16); plt.ylabel('Longitude',fontsize=16);
score: 0

http://stackoverflow.com/comment/87633842
score: 0
comment on: http://stackoverflow.com/q/50302418
type: QuestionComment
has text: is the second fragment, the one that starts with: "{% for portal in portal_list %} "
type: Comment

http://stackoverflow.com/comment/87634735
has text: Thx guys, it really helps !
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50309338

http://stackoverflow.com/comment/87663501
type: Comment
type: QuestionComment
has text: I don't understand. You want to use the regex *on* the variables? So something like `reg_a = re.match(some_regex, a)` and `reg_b = re.match(some_regex, b)`? Please try to clarify your question and add some example in- and output.
comment on: http://stackoverflow.com/q/50323767
score: 0

http://stackoverflow.com/q/50242364
has comment: http://stackoverflow.com/comment/87502385
tagged with: pandas
has title: Multiple Aggregate Functions based on Multiple Columns in Pandas
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I am working with a Pandas df in Python. I have the following input df: Color Shape Value Blue Square 5 Red Square 2 Green Square 7 Blue Circle 9 Blue Square 2 Green Circle 6 Red Circle 2 Blue Square 5 Blue Circle 1 I would like the following output: Color Shape Count Sum Blue Square 3 12 Red Square 1 2 Green Square 1 7 Blue Circle 2 10 Green Circle 1 6 Red Circle 1 2 Looking for something like pivot_table() but do not want the hierarchical index.
accepted answer: http://stackoverflow.com/a/50257171
favorite count: 0
has answer: http://stackoverflow.com/a/50257171
type: Question
has comment: http://stackoverflow.com/comment/87532253
tagged with: pivot-table
downvote count: 0
tagged with: python
answer count: 1

http://stackoverflow.com/q/50330829
has comment: http://stackoverflow.com/comment/87678380
has body: I am watching CS50's python lecture. David J Malan writes a program to take a positive integer from the user. Here he uses a function called get_int() written in CS50 python library. I am trying to emulate him. def main(): num = get_int("Enter an integer") print(num) def get_int(prompt): i =(input(prompt)) try: i = int(i) if type(i) == int: return i except ValueError: return "not an integer" if __name__ == "__main__": main() I have to use the value returned in the program get_positive_int from get_int import get_int def main(): i = get_positive_int("Positive integer please") print(i) def get_positive_int(prompt): while True: n = get_int(prompt) if(n&gt;=1): # problem here if user enters anything else than int break return n if __name__ == "__main__": main() Hence how do I write a better get_int() so that I don't get the error : TypeError: '&gt;=' not supported between instances of 'str' and 'int'
has comment: http://stackoverflow.com/comment/87677617
answer count: 3
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/64998498
has title: Getting only integer from user
favorite count: 0
type: Question
tagged with: python-3.x
score: -2
has answer: http://stackoverflow.com/a/50395735
accepted answer: http://stackoverflow.com/a/50395735
tagged with: python
has answer: http://stackoverflow.com/a/50330931
possible better answer: http://stackoverflow.com/a/50330931
type: AnsweredQuestion

http://stackoverflow.com/q/50267032
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50267127
score: 0
tagged with: python
has body: Can Tensorflow programs use off-the-shelf Keras callbacks, when the machine learning program is using native Tensorflow and no other apis from Keras?
type: Question
linked to: http://stackoverflow.com/q/44269387
answer count: 2
accepted answer: http://stackoverflow.com/a/50267421
has title: Can Tensorflow programs use off-the-shelf Keras callbacks?
tagged with: machine-learning
tagged with: keras
has answer: http://stackoverflow.com/a/50267421
possible better answer: http://stackoverflow.com/a/50267127

http://stackoverflow.com/q/50355583
tagged with: python
accepted answer: http://stackoverflow.com/a/50355836
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50355836
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87727467
upvote count: 1
has title: Trapz integration of grouped data for certain range
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87727522
has comment: http://stackoverflow.com/comment/87727847
has comment: http://stackoverflow.com/comment/87727762
has body: I have a DataFrame list as below: Device TimeSec Current 1 0.1 0.02 1 0.25 0.05 1 0.32 0.07 1 0.45 0.01 1 0.67 0.05 1 1.01 0.08 1 1.12 0.11 1 1.32 0.15 2 0.11 0.04 2 0.22 0.06 2 0.28 0.07 2 0.35 0.02 2 0.41 0.05 2 0.51 0.08 2 0.61 0.12 .... In each device set of data, there is a current minimum I would like to groupby the DataFrame by "Device" and do trapz integration The integration should be from the beginning of TimeSec of each "Device" data to the "Current" minimum Previously I asked similar question, I got helped and figured out how to groupby the data by "Device" and trapz integrate for each "Device" group. The code for the whole "Device" data integration is: DeviceGroup = df.groupby('Device') Result = DeviceGroup.apply(lambda x: integrate.trapz(x.Current, x=x.TimeSec)) This time I need to integrate from 1st TimeSec data to the "Current" minimum data. Can you tell me how to do that?

http://stackoverflow.com/q/50373248
has body: I am trying to generate Word2vec vectors. I have pandas data frame. I transformed it into tokens. df["token"] Used Word2vec from gensim.models model = w2v.Word2Vec( sentences=df["token"], seed=seed, workers=num_workers, size=num_features, min_count=min_word_count, window=context_size, sample=downsampling ) How do I transform my dataframe df now? That is what is the equivalent of doing model.transform(df)
tagged with: nlp
has title: How to generate Word2vec Vectors in Python?
score: 2
type: AnsweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/88479079
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50735740
upvote count: 2
has answer: http://stackoverflow.com/a/50735740
tagged with: neural-network
tagged with: word2vec
tagged with: python
tagged with: text-mining

http://stackoverflow.com/comment/87532371
type: Comment
type: QuestionComment
score: 0
has text: Thanks a lot. That will also give me the following information: File "C:\Users\abc\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 336, in check_output **kwargs).stdout File "C:\Users\abc\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 418, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command 'script_customer_update.py' returned non-zero exit status 103.
comment on: http://stackoverflow.com/q/50256081

http://stackoverflow.com/a/50304743
has comment: http://stackoverflow.com/comment/87638064
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50302209
has comment: http://stackoverflow.com/comment/87640463
answers question: http://stackoverflow.com/q/50302209
score: 3
upvote count: 3
type: Answer
has body: You are very close. First you should understand Compose and MapCompose classes. Compose is meant for applying some functions to list of items, while MapCompose is used to apply some functions for every item in the list of items. So you want: from scrapy.loader.processors import MapCompose, Compose, Join clean_text = Compose( MapCompose(str.strip), # strip every item in list MapCompose(lambda item: f'"{item}"'), # wrap every value in quotes Join(','), # join all items in list as one using , as separator ) If you test it: test = ['item1', 'item2', 'item3'] clean_text(test) #'item1,item2,item3'
has comment: http://stackoverflow.com/comment/87651258
has comment: http://stackoverflow.com/comment/87640933

http://stackoverflow.com/q/50305796
tagged with: pandas
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Find a differencing between year for sales
favorite count: 0
type: Question
has body: I have a data that analysing sales. I made some progress and this is the last part I did that show each store sales total for each year (2016-2017-2018). Store_Key Year count Total_Sales 0 5.0 2016 28 6150.0 1 5.0 2017 39 8350.0 2 5.0 2018 27 5150.0 3 7.0 2016 3664 105370.0 4 7.0 2017 3736 116334.0 5 7.0 2018 3863 99375.0 6 10.0 2016 3930 79904.0 7 10.0 2017 3981 91227.0 8 10.0 2018 4432 97226.0 9 11.0 2016 4084 91156.0 10 11.0 2017 4220 99565.0 11 11.0 2018 4735 113584.0 12 16.0 2016 4257 135655.0 13 16.0 2017 4422 144725.0 14 16.0 2018 4630 133820.0 I want to see each store's sales difference between years. So I used pivot table and show each year with a difference column. Store_Key 2016 2017 2018 5.0 6150.0 8350.0 5150.0 7.0 105370.0 116334.0 99375.0 10.0 79904.0 91227.0 97226.0 11.0 91156.0 99565.0 113584.0 16.0 135655.0 144725.0 133820.0 18.0 237809.0 245645.0 88167.0 20.0 110225.0 131999.0 83302.0 24.0 94087.0 101062.0 108888.0 If stores were constant, I would quickly find the difference when using the difference between columns, but unfortunately each year so many new stores are founding and shutting down. So my question is: is there any way to get difference in stores with showing new stores and closing stores? I can find stores with NULL values and separate it but I would love to check if there are some better options.
tagged with: python
has answer: http://stackoverflow.com/a/50306122

http://stackoverflow.com/comment/87770848
has text: yes 100% certain!
score: 0
comment on: http://stackoverflow.com/q/50377322
type: Comment
type: QuestionComment

storage
tag name: storage
type: Tag
tags question: http://stackoverflow.com/q/50242487

http://stackoverflow.com/q/50252761
accepted answer: http://stackoverflow.com/a/50252848
possible better answer: http://stackoverflow.com/a/50252964
tagged with: string
has answer: http://stackoverflow.com/a/50252848
favorite count: 0
has answer: http://stackoverflow.com/a/50253619
has body: I have a dataframe column like this: 1 Applied Learning, Literacy &amp; Language 2 Literacy &amp; Language, Special Needs 3 Math &amp; Science, Literacy &amp; Language 4 Literacy &amp; Language, Math &amp; Science 6 Math &amp; Science, Applied Learning 7 Applied Learning 8 Literacy &amp; Language 10 Math &amp; Science... There are comma seperated values in each row. What I want is to count the occurance of all the unique values. For eg: Math &amp; Science appears 4 times. So the count for Math &amp; Science should be 4. I tried the following code: cato=response['Category'].str.split(',') cat_set=[] for i in cato.dropna(): cat_set.extend(i) plt1=pd.Series(cat_set).value_counts().sort_values(ascending=False).to_frame() But the problem is, this code works for small datasets, but it takes a lot of time for a large dataset. Any solutions for this? Thanks
type: Question
answer count: 5
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50253153
has answer: http://stackoverflow.com/a/50252964
tagged with: pandas
type: AnsweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/61880793
has title: How to count comma seperated repeated values in a pandas column?
downvote count: 0

http://stackoverflow.com/a/50282560
type: Answer
has comment: http://stackoverflow.com/comment/87683553
has comment: http://stackoverflow.com/comment/87699104
has comment: http://stackoverflow.com/comment/87683602
has comment: http://stackoverflow.com/comment/87607965
downvote count: 0
has comment: http://stackoverflow.com/comment/87608880
score: 3
answers question: http://stackoverflow.com/q/50282080
has comment: http://stackoverflow.com/comment/87680430
upvote count: 3
has body: Update: There is nothing wrong with your current solution. There is no float to str to decimal.Decimal round-trip. As the docs explain (my emphasis): parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). Initial answer below Passing a float value to decimal.Decimal does not ensure the precision you require. This is because, by its nature, float is not stored as a decimal but in binary. This can be alleviated if you are able to pass string inputs into decimal.Decimal: from decimal import Decimal res1 = Decimal(3.8)*Decimal(10) res2 = Decimal('3.8')*Decimal('10') print(res1) # 37.99999999999999822364316060 print(res2) # 38.0 So one solution would be to ensure you store / read in JSON numeric data as strings instead of floats. Be careful, an implementation as below may work but relies on str doing a particular job, i.e. rounding a float correctly for decimal representation. def lambda_handler(event): value = event['value'] print(Decimal(str(value))) lambda_handler({"value": 3.8}) # 3.8

http://stackoverflow.com/comment/87751451
score: 0
type: Comment
has text: `import json import requests url = "http://localhost:5000/" data = json.dumps({'Clean_Text_Body':"The product was amazing, i just love it"}) headers = {'accept-language': 'en', 'content-type': 'application/json'} r = requests.post(url, data = data, headers=headers)` **I did the modification as mentioned above, while r is getting executed but when i print** `print("results == ", json.loads(r.text)['results'])` **it is giving the following error** `JSONDecodeError: Expecting value: line 1 column 1 (char 0)` @Hugo
comment on: http://stackoverflow.com/a/50366237
type: AnswerComment

http://stackoverflow.com/a/64452792
answers question: http://stackoverflow.com/q/50305725
has comment: http://stackoverflow.com/comment/127720982
type: Answer
has comment: http://stackoverflow.com/comment/123765361
downvote count: 0
upvote count: 13
has body: On windows 10 machine: Navigate to "Environment Variables" - How to navigate to [environment_variables][1] Click on "Path" Click "New" and copy and add the following path: "C:\Users\yourusername\Anaconda3" "C:\Users\yourusername\Anaconda3\Scripts" "C:\Users\yourusername\Anaconda3\Library\bin"
score: 13

http://stackoverflow.com/comment/87489986
type: AnswerComment
comment on: http://stackoverflow.com/a/50234491
score: 0
type: Comment
has text: Thanks for your answer, this is what I needed

http://stackoverflow.com/comment/87631278
score: 0
has text: I managed to run a profile using Django-extensions runprofileserver and checked the .prof files. It seems most of the time is taken by connections to the backend db - postgres. This seems to be a known issue for Django: https://stackoverflow.com/questions/1125504/django-persistent-database-connection
comment on: http://stackoverflow.com/q/50307042
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50384964
type: Answer
score: 0
has body: Try converting your column to a float object before apply Ex: import pandas as pd X1o = pd.to_numeric(X3_a, errors='coerce').apply(replace)
answers question: http://stackoverflow.com/q/50384842

http://stackoverflow.com/a/50281912
answers question: http://stackoverflow.com/q/50281656
upvote count: 7
has body: Instead of: requests.get("https://api.telegram.org/"+botID+"/sendMessage?chat_id=" +chatid+"&amp;text="+movieSearch+"&amp;parse_mode=HTML") Do this: params = { "chat_id": chatid, "text": movieSearch, "parse_mode": "HTML", } requests.get( "https://api.telegram.org/{}/sendMessage".format(botID), params=params ) I think the problem happens because you have &amp; in the value of the "text" parameter in the URL but are not escaping it as %26. It is better to use a dictionary instead and let the requests library escape it for you. You still have to escape the &amp; as &amp;amp;: movieSearch = "https://www.imdb.com/search/title?release_date={}" "-01-01,2018-12-31&amp;amp;user_rating={}&amp;amp;genres={}".format( year, score, genres)
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/87580457
accepted answer of: http://stackoverflow.com/q/50281656
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/61786493
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50254745
has body: I know this post is old, but it's still relevant. The trick that worked for me was creating an array instance of the type FTD2XX_NET.FT_DEVICE_INFO_NODE[], with a length set to number of FTDI devices: # -*- coding: utf-8 -*- """ Created on Wed May 13 15:50:22 2020 @author: chogh """ # For Windows, from a Anaconda Prompt cmd window: # conda install -c ipython pythonnet # so import System classes are exposed # conda install -c ipython ftd2xx # so import FTD2XX_NET classes are exposed # ############################################################################# import System # available after running conda install -c ipython pythonnet in Anaconda Prompt cmd window import clr from System import Array # to import .Net Array functions for FTD2XX_NET from System import Byte # to import .Net Array functions for FTD2XX_NET from array import array clr.AddReference("System") clr.AddReference('FTD2XX_NET') from FTD2XX_NET import FTDI myFtdiDevice=FTDI() ft_status = myFtdiDevice.FT_STATUS.FT_DEVICE_NOT_FOUND DeviceNum=0 ft_status,DeviceNum=myFtdiDevice.GetNumberOfDevices(DeviceNum) DeviceList=Array.CreateInstance(myFtdiDevice.FT_DEVICE_INFO_NODE, DeviceNum) ft_status=myFtdiDevice.GetDeviceList(DeviceList) print("ft_status:", ft_status) print("Device Description: ",DeviceList[0].Description) print("Device Serial Number: ",DeviceList[0].SerialNumber) print("Device Device ID: ",DeviceList[0].ID) print("Device Device Type: ",DeviceList[0].Type) This results in the following output: Reloaded modules: System, FTD2XX_NET ft_status: 0 Device Description: Hazelnut Device Serial Number: FTWLN0XM Device Device ID: 67330068 Device Device Type: 8

http://stackoverflow.com/comment/87651683
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50317635
type: QuestionComment
has text: testlist _1 it is just example (it included into another dictionary in my future code)

http://stackoverflow.com/a/50231776
answers question: http://stackoverflow.com/q/50230503
score: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50230503
has body: @halfelf posted right answer in comments so I'll copy it here: I guess it's just your cmd/powershell's buffer can't contain 1910 lines of that file, and the beginning lines has been scrolled I just increased buffer size in cmd properties and now it shows all lines. Thank you all for your answers, I appreciate it.

http://stackoverflow.com/comment/87579490
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50281351
has text: You've boiled the problem down a lot here, which is great. But could you not just `np.roll` the column and assign it to another column? That way you have values offset by 1 index in the same row. Not sure I can test now but it might avoid the `for` loops.

http://stackoverflow.com/comment/87693301
type: AnswerComment
comment on: http://stackoverflow.com/a/50338307
score: 0
type: Comment
has text: still getting blank output. to be clear, i should still retain the above two lines for getting input, right ?

http://stackoverflow.com/comment/87612788
score: 0
has text: can you give example by code please?
type: QuestionComment
comment on: http://stackoverflow.com/q/50297915
type: Comment

http://stackoverflow.com/comment/87618182
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50283794
type: Comment
has text: @Miky `multiprocessing.Process` will create a separate Python **process** to run your code in. Too much overhead if you ask me. Running your code in a separate **thread** will do the job. Also, the preferred way to spawn threads or processes when using Tornado (or asyncio) is by using [`ThreadPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor) or [`ProcessPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor). These functions make things easier than using `multiprocessing.Process` or `threading.Thread` directly.

http://stackoverflow.com/comment/87759754
type: Comment
type: QuestionComment
score: 1
has text: So show us your code. + Your question title does not describe your problem.
comment on: http://stackoverflow.com/q/50371683

http://stackoverflow.com/comment/119874265
type: Comment
has text: plt.subplots_adjust(0,0,1,1,0,0) This is what one needs to do
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50313833

http://stackoverflow.com/q/50373920
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87766208
has answer: http://stackoverflow.com/a/50374461
has title: Using variables from another Python file & function in module not running?
has comment: http://stackoverflow.com/comment/87764456
tagged with: python
linked to: http://stackoverflow.com/q/50353079
tagged with: replit
score: 0
has comment: http://stackoverflow.com/comment/87764410
has comment: http://stackoverflow.com/comment/87764141
answer count: 1
has comment: http://stackoverflow.com/comment/87764087
has body: This is a continuation of my previous question, with more details. (Formatting should be better, as I am on a computer now!) So I am trying to create a game in Python, where if a number reaches a certain amount you lose. You try to keep the number under control to keep it from reaching the number it shouldn't. Now, I had an error in my previous question that said: AttributeError: module 'core temp' has no attribute 'ct' However, I've modified my code a bit and no longer get any errors. However, when I run the code, a function in a module I made won't run. To make sure that anyone trying to figure out the solution has all the resources they need, I'll provide all my code. This is the code in the file main.py: from termcolor import colored from time import sleep as wait import clear from coretemp import ct, corestart print(colored("Begin program", "blue")) wait(1) clear.clear() def start(): while True: while True: cmd = str(input("Core&gt; ")) if cmd == "help": print( "List of commands:\nhelp - Show a list of commands\ntemp - Show the current temperature of the core in °C\ninfo - Show core info\ncool - Show coolant control" ) break elif cmd == "temp": if ct &lt; 2000: print( colored("Core temperature: " + str(ct) + "°C", "green")) elif ct &lt; 4000: print( colored("Core temperature: " + str(ct) + "°C", "yellow")) elif ct &gt;= 3000: print( colored("Core temperature: " + str(ct) + "°C", "red")) print("Welcome to SprinkleLaboratories Main Core System") wait(1) print( "\nYou have been hired as the new core operator.\nYour job is to maintain the core, and to keep the temperature at a stable number. Or... you could see what happens if you don't..." ) wait(3) print("\nTo view available commands, use the \"help\" command!") cont = input("Press enter to continue&gt; ") clear.clear() start() corestart(10) This is the code in the file clear.py: print("clear.py working") def clear(): print("\n"*100) This is the code in the file coolant.py: from time import sleep as wait print("c…
type: Question
accepted answer: http://stackoverflow.com/a/50374461

http://stackoverflow.com/a/50255852
score: 1
type: AcceptedAnswer
has body: If you want a numpy solution , I will using select np.select([x&lt;0.5,x&gt;=0.5],[x*2,x+1]) Out[905]: array([0. , 0.2, 0.4, 0.6, 0.8, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ])
downvote count: 1
answers question: http://stackoverflow.com/q/50255668
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50255668
type: Answer

http://stackoverflow.com/a/50343782
answers question: http://stackoverflow.com/q/50343734
has comment: http://stackoverflow.com/comment/114590430
score: 0
has body: Using max and lambda: &gt;&gt;&gt; data = [[12345678, 14, 1],[135763365, 12, 0],[1234, 9, 0]] &gt;&gt;&gt; max(data, key=lambda x: x[0])[0] 135763365
type: Answer

http://stackoverflow.com/comment/87632090
type: QuestionComment
has text: I think the answer is alluded to near the end of the blog post: `x % 1.0` for small, negative `x`.
score: 1
comment on: http://stackoverflow.com/q/50308057
type: Comment

http://stackoverflow.com/comment/87540394
type: QuestionComment
has text: @StanZeez Ah, so its passing a `list` of clauses to the `or_()` function, right? `or_(instance1.street==instance2.stree, instance1.zip_code==instance2.zip_code)`. I get it now. Thanks!
score: 0
comment on: http://stackoverflow.com/q/50260840
type: Comment

http://stackoverflow.com/comment/87636288
type: AnswerComment
comment on: http://stackoverflow.com/a/50302455
has text: @MarkC no. If the app generates the files, so long as you know the absolute path they are written to you're fine. This is for files where you don't know the absolute path (files you add to the executable/installer) and so need to resolve them relative to the application binary
score: 0
type: Comment

http://stackoverflow.com/a/50259986
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87538597
type: Answer
answers question: http://stackoverflow.com/q/50256012
downvote count: 0
has body: Here is another way: dat.remove_rows(np.where([c.data for c in dat.mask.itercols()])[-1]) But I agree with you that this filtering of invalid values should be supported by a masked table.

http://stackoverflow.com/q/50249754
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: javascript
has title: creating an alert box in odoo using execjs
has body: I'm trying to create a scheduled alert box that reminds the user in a certain date. So I installed execjs and created this method: import execjs class Project(models.Model): _inherit = 'project.project' @api.multi def alert(self): js = """ alert("Hello World!!") """ execjs.eval(js) but when I run this method it appears this error: 2018-05-09 09:00:49,302 6508 ERROR erp_invoicefr odoo.addons.base.ir.ir_cron: Call of self.env[u'project.project'].alert(*()) failed in Job #8 Traceback (most recent call last): File "D:\Projet\201802_invoicefr\odoo\addons\base\ir\ir_cron.py", line 126, in _callback getattr(model, method_name)(*args) File "D:\Projet\201802_invoicefr\invoicefr_addons\invoicefr_project\models\project_project.py", line 90, in alert execjs.eval(js) File "C:\Python27\lib\site-packages\execjs\__init__.py", line 51, in eval return get().eval(source, cwd) File "C:\Python27\lib\site-packages\execjs\_abstract_runtime.py", line 25, in eval return self.compile('', cwd=cwd).eval(source) File "C:\Python27\lib\site-packages\execjs\_abstract_runtime_context.py", line 27, in eval return self._eval(source) File "C:\Python27\lib\site-packages\execjs\_external_runtime.py", line 78, in _eval return self.exec_(code) File "C:\Python27\lib\site-packages\execjs\_abstract_runtime_context.py", line 18, in exec_ return self._exec_(source) File "C:\Python27\lib\site-packages\execjs\_external_runtime.py", line 88, in _exec_ return self._extract_result(output) File "C:\Python27\lib\site-packages\execjs\_external_runtime.py", line 167, in _extract_result raise ProgramError(value) ProgramError: ReferenceError: alert is not defined
tagged with: odoo
tagged with: execjs
score: 1
tagged with: python
favorite count: 0
type: Question

relative-path
tags question: http://stackoverflow.com/q/50309643
type: Tag
tag name: relative-path

http://stackoverflow.com/q/50382559
score: 0
has body: When using Safari's develop tool to obtain the webpage's source code, there seems two columns, one is Elements, another is Resources. For some webpages, they are different, while for others, they are the same. And there is only Elements in Chrome. In Safari's Elements I can easily locate the elements I want, but in Resources I can't. This surely matters cuz I want to scrape a webpage whose Elements and Resources are different...And when I code like this: from bs4 import BeautifulSoup import requests params = {"TPL_username": "xxxx", "TPL_password": "1xxx"} tb = requests.post("https://login.xxxx.com/",data=params) r = requests.get('http://www.xxxx.com',cookies=tb.cookies) content = r.content print(content) soup = BeautifulSoup(content, "html.parser") timelists = bs.find_all("span", {"class": "bought-wrapper-mod__create-time___yNWVS"}) print(timelists) the print output(content) is the Resources rather than the Elements which I want. So I can't locate the element with Resources, and it is obvious that the code I see in Resources is not the real source code of the webpage. So why is that? requests.get doesn't return the real source code of the webpage?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/87805009
type: UnansweredQuestion
has title: When use Safari‘s Develop->Show page source, what's the difference between Elements and Resources?
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/87780859
type: Question
tagged with: safari

http://stackoverflow.com/a/50345412
answers question: http://stackoverflow.com/q/50345204
type: Answer
upvote count: 13
downvote count: 0
score: 13
has body: Very old python 2 versions (&lt; 2.6) don't accept the octal prefix in 0o644. If you really need to be compliant with python 2.5 or earlier you can parse an octal string with int int('644',8) note that compatibility tricks catching ImportError, NameError, ... exceptions don't work here because you cannot catch the SyntaxError, the parser doesn't let that happen: # that doesn't work try: x = 0644 # either crashes here except SyntaxError: x = 0o644 # or here # that doesn't work

http://stackoverflow.com/q/50288193
has answer: http://stackoverflow.com/a/50289747
has body: I would like to extract data from a website, and I need to know if it contains some of the equipment. As the example below, I know A has CD, but he doesn't have CDA. HTML: A CD VCD CDA B b11 b22 My code: res = requests.get('https://www.acd.com/carinfo-4434.php') soup=BeautifulSoup(res.text,'lxml') for item in soup.find_all(attrs={'class':'ABC'}): for link in item.find_all('li'): print(link) From my code, I will extract all the li from the HTML, like this: CD VCD CDA b11 b22 But that's not what I want. What I wanna do, is to extract from "li class" and text, the hope the result will be like this: specChecked, CD specChecked, VCD , CDA (Or maybe I can just replace specChecked as 1 and blank space as 0)
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50288244
tagged with: beautifulsoup
has title: Python: extract class and text
type: Question
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/50289747
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50288244

http://stackoverflow.com/comment/87545183
has text: Click the link to see what is missing to make it an mcve. Also: Getting rude this way won't help you.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50263472
type: QuestionComment

http://stackoverflow.com/a/50378412
answers question: http://stackoverflow.com/q/50378361
has comment: http://stackoverflow.com/comment/87772990
type: Answer
score: -2
has comment: http://stackoverflow.com/comment/87772984
has body: The issue is with the regular expression "^(?$", you have to correct it. What is you expected behavior of that regular expression? ( is added to grouping the matches, but the parenthesis is not closed.
upvote count: 0
downvote count: 2

http://stackoverflow.com/q/50326816
linked to: http://stackoverflow.com/q/34878942
has comment: http://stackoverflow.com/comment/88246790
tagged with: python
has title: CYTHON, How can i pass a member function as a callback to native
type: Question
has comment: http://stackoverflow.com/comment/87687431
answer count: 0
has body: I am able to get normal callbacks from native to Cython. But, how do i set a member function to be callback in cython. My sampleCallback.h file is : namespace mango { class sampleCalls { public: typedef void (*Callback)(char *name); sampleCalls(Callback method, char *name); void execute(); private: Callback _method; char *_key; }; } And my sampleCallback.cpp file contains simple implementation : namespace mango { sampleCalls::sampleCalls(Callback method, char *name) { _method = method; _key = name; }; void sampleCalls::execute() { return _method(_key); }; } Now i have written a very simple cython wrapper callback.pyx: ctypedef void (*Callback)(char *name) cdef extern from "sampleCallback.h" namespace "mango" : cdef cppclass sampleCalls: sampleCalls(Callback method, char *name) void execute() cdef void callbackCY(char* name): print "I AM ", name cdef class pyCallback: cdef sampleCalls* sc def __init__(self): self.sc = new sampleCalls(callbackCY, "BATMAN") def execute(self): self.sc.execute() This builds and works fine when i run a simple python code : import callback cb = callback.pyCallback() cb.execute() This works just fine and outputs :: I AM BATMAN But this is not what i want. I want the callback function to be a part of the cython defined class, so i implemented the class something like this : cdef class pyCallback: cdef sampleCalls* sc def __init__(self): self.sc = new sampleCalls(cb, "BATMAN") def execute(self): self.sc.execute() cdef void cb(self, char* name): print name, " WINS" This does not work of course as callback prototype do not match. WHAT IS THE PROPER WAY TO DO IT? I also tried std::bind something like this :: cdef place1 "std::placeholder1" cdef bind_py "std::bind" cdef class pyCallback: cdef sampleCalls* sc def __init__(self): self.sc = new sampleCalls(bind_py(self.cb, self, place1), "BATMAN") This does not work either. The error :: Error compiling Cython file: ------------------------------------------------------------ ... cdef class pyCallbac…
has comment: http://stackoverflow.com/comment/88311479
linked to: http://stackoverflow.com/q/46187281
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: cythonize
tagged with: stdbind
downvote count: 0
tagged with: cython
tagged with: callback
favorite count: 0

http://stackoverflow.com/a/52015818
has comment: http://stackoverflow.com/comment/110211509
downvote count: 1
answers question: http://stackoverflow.com/q/50321549
has comment: http://stackoverflow.com/comment/111852343
has comment: http://stackoverflow.com/comment/94098871
type: Answer
upvote count: 42
has comment: http://stackoverflow.com/comment/111819047
has comment: http://stackoverflow.com/comment/111871470
score: 41
has body: I think the easier way is just to use a simple dictionary and df.withColumn. from itertools import chain from pyspark.sql.functions import create_map, lit simple_dict = {'india':'ind', 'usa':'us', 'japan':'jpn', 'uruguay':'urg'} mapping_expr = create_map([lit(x) for x in chain(*simple_dict.items())]) df = df.withColumn('col1_map', mapping_expr[df['col1']])\ .withColumn('col2_map', mapping_expr[df['col2']]) df.show(truncate=False)

http://stackoverflow.com/q/50236427
has comment: http://stackoverflow.com/comment/87492622
has comment: http://stackoverflow.com/comment/87490813
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87976185
has comment: http://stackoverflow.com/comment/87491803
has comment: http://stackoverflow.com/comment/87976200
score: 0
duplicate of: http://stackoverflow.com/q/20763012
answer count: 0
has comment: http://stackoverflow.com/comment/87490892
tagged with: pandas
has comment: http://stackoverflow.com/comment/87493464
linked to: http://stackoverflow.com/q/20763012
has comment: http://stackoverflow.com/comment/87493428
has body: I have a numpy array with the following shape: numpy_x.shape (9982, 26) I want turn this numpy to dataframe: x_new_df = pd.DataFrame(numpy_x) And my new dataframe is: x_new_df How to can I generate the dataframe with index and columns names?
has comment: http://stackoverflow.com/comment/87490245
type: Question
tagged with: numpy
has title: Creating Dataframe with numpy array with index and columns

http://stackoverflow.com/q/50271841
has comment: http://stackoverflow.com/comment/87560670
upvote count: 1
answer count: 1
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/50271885
type: Question
type: UnansweredQuestion
has body: I'm working on my python script I have got a very weird error when I'm trying to use the method cv2.getGaussianKernel() import numpy as np import cv2 g_kernel =cv2.getGaussianKernel((300, 300), 8.0, ktype= cv2.CV_32F) img = cv2.imread('LR_intermediate_.jpg') filtered_img = cv2.filter2D(img, cv2.CV_8UC3, g_kernel) h, w = g_kernel.shape[:2] g_kernel = cv2.resize(g_kernel, (3*w, 3*h), interpolation=cv2.INTER_CUBIC) cv2.imshow('gabor kernel (resized)', g_kernel) cv2.waitKey(0) cv2.destroyAllWindows() I get this error : Traceback (most recent call last): File "C:/Users/Mohammed/PycharmProjects/GaborFilter/Gaborscript.py", line 3, in g_kernel =cv2.getGaussianKernel((300, 300), 8.0, ktype= cv2.CV_32F) TypeError: an integer is required May anyone know how to fix it?
has title: python error: an integer is required
tagged with: python
downvote count: 2

http://stackoverflow.com/q/50356124
score: 0
has body: I have a code like this: def datauji(self): uji = [] for x in self.fiturs: a = [x[0],x[-5:]] #I think the problem in this line uji.append(a) return uji with open('DataUjiBaru.csv','wb') as dub: testing = csv.writer(dub) datatest = d.datauji() datatest.pop(0) for x in datatest: testing.writerow(x) I want to pair the value in self.fiturs, In self.fiturs: F37,0,1,0,1,1,1,0,1,0,2,1,0,0,0,1 F10,8,4,3,3,3,6,8,5,8,4,8,4,5,6,4 F8,1,0,2,0,0,0,2,0,0,0,0,0,2,0,0 So i want to pair index[0] and index[-5:] and write it to the csv, and the output on the csv like this: F37,"['1', '0', '0', '0', '1']" F10,"['8', '4', '5', '6', '4']" F8,"['0', '0', '2', '0', '0']" My Expectation in that csv is like this: F37,1,0,0,0,1 F10,8,4,5,6,4 F8,0,0,2,0,0 How can I fix that?
tagged with: python
has answer: http://stackoverflow.com/a/50356263
accepted answer: http://stackoverflow.com/a/50356263
answer count: 1
has title: How to pair 2 list into 1 list
type: Question
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/50345305
tagged with: keras
type: Question
tagged with: numpy
has title: Error is output layer shape in neural network, can't figure out the mistake in dimensions
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87706402
has body: I am starting out with neural networks. I have built a model, and trained it on my training dataset. But when I try to evaluate the model, I get a dimension mismatch error: ValueError: Error when checking target: expected dense_16 to have shape (3,) but got array with shape (1,). For the life of me, can't seem to be able to figure out where in the model definition its arising from. Any help is appreciated. Model definition: Training: Evaluation (error): Code: # Building a model - build a simple feedforward neural network for this problem. # Specify all the parameters we will be using in our network input_num_units = (32, 32, 3) hidden_num_units = 1000 output_num_units = 3 epochs = 10 batch_size = 128 from keras.models import Sequential from keras.layers import Dense, Flatten, InputLayer # Define the network/model model = Sequential([ InputLayer(input_shape=input_num_units), Flatten(), Dense(units=hidden_num_units, activation='relu'), Dense(units=output_num_units, activation='softmax'), ]) model.summary() # Compile our network and let it train for a while, with cross validation model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(train_x, train_y, batch_size=batch_size,epochs=epochs,verbose=1, validation_split=0.2) score = model.evaluate(test_x, test_y, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])
score: 0
has comment: http://stackoverflow.com/comment/87706737
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50345515
answer count: 1

http://stackoverflow.com/comment/87583599
type: AnswerComment
type: Comment
has text: for some reason switch_to_frame( Name/ID) kept giving me issues so I used the switch_to.frame(i) and it worked like a charm
comment on: http://stackoverflow.com/a/50280344
score: 0

http://stackoverflow.com/comment/87661219
type: Comment
has text: this does not give the expected results. ` path = 'C:\apps\python' print(path) #=> C:pps\python path1 = r'{}'.format(path) print(path1) #=> C:pps\python`
score: 0
comment on: http://stackoverflow.com/a/50314511
type: AnswerComment

http://stackoverflow.com/a/50406925
has comment: http://stackoverflow.com/comment/87833945
has comment: http://stackoverflow.com/comment/87832474
has comment: http://stackoverflow.com/comment/88054941
has comment: http://stackoverflow.com/comment/87833969
type: Answer
score: 4
upvote count: 4
has body: I don't think this is possible for Backtrader as mentioned in their FAQs Optimization is slow and consumes RAM Indeed. Parameter overfitting is also a great and formidable enemy of algorithmic trading. I want to use the GPU for optimization Nice idea, but the multiprocessing module in Python won't do that. https://community.backtrader.com/topic/381/faq Cuda and all can be used in cases where you want to offload a computation to the GPU. Like below example import numpy as np from timeit import default_timer as timer from numba import vectorize @vectorize(['float32(float32, float32)'], target='cuda') def pow(a, b): return a ** b def main(): vec_size = 100000000 a = b = np.array(np.random.sample(vec_size), dtype=np.float32) c = np.zeros(vec_size, dtype=np.float32) start = timer() c = pow(a, b) duration = timer() - start print(duration) if __name__ == '__main__': main() PS: Example credits to https://weeraman.com/put-that-gpu-to-good-use-with-python-e5a437168c01
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50246917
has comment: http://stackoverflow.com/comment/88020715
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88020678
answers question: http://stackoverflow.com/q/50246917
has comment: http://stackoverflow.com/comment/88020613
has comment: http://stackoverflow.com/comment/88021773

http://stackoverflow.com/comment/87583249
has text: It returns -->ValueError: invalid literal for int() with base 10: 'how'
comment on: http://stackoverflow.com/a/50283411
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50292750
has answer: http://stackoverflow.com/a/50316839
downvote count: 0
has body: I'm reading an implementation of im2col from a deep learning book(At chapter 7, CNN), which its purpose is to transform a 4 dimensional array into 2 dimensional. I don't know why there is a 6 dimensional array in the implementation. I'm very interested about what's the idea behind the algorithm the author used. I've tried to search many papers of the implementation of im2col, but none of them using high dimensional array like this. The currently materials I found useful for visualization of the process of im2col is the picture of this paper - HAL Id: inria-00112631 def im2col(input_data, filter_h, filter_w, stride=1, pad=0): """ Parameters ---------- input_data : (batch size, channel, height, width), or (N,C,H,W) at below filter_h : kernel height filter_w : kernel width stride : size of stride pad : size of padding Returns ------- col : two dimensional array """ N, C, H, W = input_data.shape out_h = (H + 2*pad - filter_h)//stride + 1 out_w = (W + 2*pad - filter_w)//stride + 1 img = np.pad(input_data, [(0,0), (0,0), (pad, pad), (pad, pad)], 'constant') col = np.zeros((N, C, filter_h, filter_w, out_h, out_w)) for y in range(filter_h): y_max = y + stride*out_h for x in range(filter_w): x_max = x + stride*out_w col[:, :, y, x, :, :] = img[:, :, y:y_max:stride, x:x_max:stride] col = col.transpose(0, 4, 5, 1, 2, 3).reshape(N*out_h*out_w, -1) return col
upvote count: 6
tagged with: arrays
score: 6
favorite count: 0
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50316839
has answer: http://stackoverflow.com/a/50319350
has title: Python: The implementation of im2col which takes the advantages of 6 dimensional array?
accepted answer: http://stackoverflow.com/a/50319350
tagged with: python
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/q/50306840
possible better answer: http://stackoverflow.com/a/50306868
has body: I have recently been trying to code a number sorter. I searched the internet and decided to try out this piece of code: numbers=([]) amount=input("How many numbers are in your list? ") print("") counter = 0 ran = 0 while counter &lt; int(amount): counter = counter + 1 ran = ran + 1 num3 = input(str(ran) + ". Input: ") try: val = int(num3) except ValueError: num3 = input(str(ran) + ". Input: ") sort(numbers) numbers.append(num3) At the beginning (when I try to run it), it seems to work; here are the first few lines of output: How many numbers are in your list? (I input 7) 1. Input: (I input 3) But then, this error appears right after I input 3 and press enter: Traceback (most recent call last): File "D:/ZGMDCL8364/Documents/AllPyCharmProjects001/NumberSorter.py", line 39, in &lt;module&gt; sort(numbers) NameError: name 'sort' is not defined And then I get this: Process finished with exit code 1 How do I fix this? Please help.
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87629656
linked to: http://stackoverflow.com/q/3426108
has comment: http://stackoverflow.com/comment/87629772
duplicate of: http://stackoverflow.com/q/3426108
has answer: http://stackoverflow.com/a/50306868
has answer: http://stackoverflow.com/a/50307207
accepted answer: http://stackoverflow.com/a/50307207
tagged with: python
downvote count: 5
has title: Python NameError due to undefined function
type: AnsweredQuestion
answer count: 2
upvote count: 1
score: -4

http://stackoverflow.com/q/50313542
tagged with: flask-ask
type: Question
has title: Flask-ASK & Amazon S3
tagged with: amazon-s3
accepted answer: http://stackoverflow.com/a/51598071
has body: Trying to deploy an Alexa Skill. I have used node.js to deploy skills before, but never python. I used the Flask-ASK framework to develop the code and tested using HTTPS enpoint and ngrok. Testing the code was successful, so I'm trying to deploy. I followed the AWS instructions on zipping the python files and dependencies in the same root folder and zipping only the contents, not the folder itself. The .zip file is too large for me to upload directly to lamda (16.1 MB -- times out trying to upload) so I'm attempting to use Amazon S3 cloud services. This is very straight forward, so I don't think I'm making any mistakes on this end. Created my bucket and uploaded my zip. Input the path into lambda. This next step is where I'm not certain what is right/wrong. I have to define the lambda_handler. My only python script that was edited and created by me is titled main.py --> main.lambda_handler I'm assuming {How do I add python libraries to an AWS lambda function for Alexa?}. Alexa Developer Portal is configured correctly to the lambda function ID. I save that, build the function, switch to test, invoke the skill and I get the "There was a problem ... etc." response. Show's root directory for zip (folder is just unzipped to show preview of contents) -- main.py file &amp; dependences are on same folder level Shows S3 path and upload name (it was actually uploaded - I just grabbed the picture before I uploaded a new version) Shows developer console settings
linked to: http://stackoverflow.com/q/38877058
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51598071
answer count: 1

http://stackoverflow.com/comment/87621038
type: Comment
comment on: http://stackoverflow.com/q/50302291
has text: oh, thank you! it is a CSV, i didn't realize it stood for that. pretty obvious now lol. cheers mate
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87620972
comment on: http://stackoverflow.com/q/50302207
score: 0
has text: it just saved line 1 and 3 only..
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87666745
type: Comment
has text: Good point on the migrate command. Do you run this manually each time you deploy a migrated variable - or are you just suggesting deploying to a test environment first?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50322398

http://stackoverflow.com/comment/87571662
type: QuestionComment
has text: @thebjorn if your asking abt error , no it will end with test.py
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50277478

http://stackoverflow.com/a/50296022
has body: As described in this AWS Lambda Limits link: But there are limits that AWS Lambda imposes that include, for example, the size of your deployment package or the amount of memory your Lambda function is allocated per invocation. Here, the issue you are having is because of "amount of memory Lambda function is allocated per invocation" needed. Unfortunately, Lambda is not an applicable solution for this case. You need to go with EC2 approach. When your overall memory requirement is high, I don't think Lambda is great solution. I am not about how the specified file types work, but in general read/processing large files use chunked approach to avoid large memory requirements. Whether chunked approach works or not depends on your business requirement.
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50295964

http://stackoverflow.com/a/50286569
score: 0
has comment: http://stackoverflow.com/comment/87589192
has body: The csv.writerow() function takes a list of items and writes it to your file with the required delimiters (by default this is a comma). So for example: The list ['a', 'b', 'c'] is written to the file as a,b,c import csv def csv_reader(file,path): with open(path, 'w', newline='') as f_output, open(file, 'r', newline='') as f_input: csv_output = csv.writer(f_output) csv_input = csv.reader((line.replace('\0', '') for line in f_input)) for row in csv_input: if len(row) and row[3] != "Trade": if row[6] == "": output_row = [row[0], row[0], 'A', row[8], row[9], row[0]] else: output_row = [row[0], row[0], 'B', row[6], row[7], row[0]] print(','.join(output_row)) csv_output.writerow(output_row) if __name__ == "__main__": path="sales.csv" csv_path = "FlowEdge-TRTH-Time_Sales.csv" csv_reader(csv_path, path) When using csv readers and writers, you should open the file with the newline='' argument.
answers question: http://stackoverflow.com/q/50286190
type: Answer
has comment: http://stackoverflow.com/comment/87589231

http://stackoverflow.com/comment/87569332
score: 0
comment on: http://stackoverflow.com/q/50276202
has text: Your code works for me with cpython. Perhaps the problem is a bug in Anaconda.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87770127
score: 0
has text: "if i convert dictionary in a list will it be fix". No, because JSON can handle `dict`. What it can't handle is the `Queryset`s inside the `dict`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50376556

http://stackoverflow.com/a/50307810
upvote count: 1
has comment: http://stackoverflow.com/comment/87632171
has comment: http://stackoverflow.com/comment/87631922
has comment: http://stackoverflow.com/comment/87632118
has body: The input args filter to tf.nn.conv2d_transpose is the weights matrix itself and not just the size of the filter. The modified code that fixes the above problem is shown below: cnn_layer10 = tf.placeholder(tf.float32, (10, 36, 36, 1024)) def deconv2d(x, W,stride): x_shape = tf.shape(x) weights = tf.Variable(tf.random_normal(W)) output_shape = tf.stack([x_shape[0], x_shape[1]*2, x_shape[2]*2, x_shape[3]//2]) decon = tf.nn.conv2d_transpose(x, weights, output_shape, strides=[1, stride, stride, 1], padding='SAME') return decon deconvolution1 = deconv2d(x=cnn_layer10, W=[2,2,512,1024], stride=2) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('Decon Shape:',sess.run(deconvolution1, {cnn_layer10: np.random.random((10, 36,36,1024))}).shape) #Output #Decon Shape: (10, 72, 72, 512) Note: Its better to use tf.layers.conv2d_transpose API, where the filters arg is the filter size and the weights initialization happens within.
type: Answer
accepted answer of: http://stackoverflow.com/q/50307579
has comment: http://stackoverflow.com/comment/87633328
has comment: http://stackoverflow.com/comment/87632521
answers question: http://stackoverflow.com/q/50307579
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87566693
score: 0
type: QuestionComment
has text: When asking about code that produces an Exception you should always include the complete Traceback in the question. Copy the Traceback and paste it in the question, then format it as code (select it and type ctrl-k).
comment on: http://stackoverflow.com/q/50275028
type: Comment

http://stackoverflow.com/comment/87529255
type: Comment
comment on: http://stackoverflow.com/q/50237213
type: QuestionComment
score: 0
has text: Yes. Whole different question though. Python has several options for parsing XML: https://docs.python.org/2.7/library/xml.html?highlight=xml#module-xml

http://stackoverflow.com/comment/87772828
type: Comment
type: AnswerComment
has text: @Chris Okey, but in the case of AÑO column, what can I do to convert that to datetime64?
comment on: http://stackoverflow.com/a/50371782
score: 0

http://stackoverflow.com/q/50235752
possible better answer: http://stackoverflow.com/a/50237578
has body: Using matplot to create a little gauge with the code below: group_size=[10,10,10,10,10,50] labels=['AAAA','BBBB','CCCC','DDDD','EEEE',''] fig, ax = plt.subplots() ax.axis('equal') pie = ax.pie(group_size, radius=2.2, colors=['k'] ,startangle=180,counterclock=False) pie2 = ax.pie([10,10,10,10,10,50], radius=2, labeldistance=0.7, labels=labels, rotatelabels = 270, startangle=180,counterclock=False) plt.show() I am trying to get the labels to go horizontally and align with the midpoint of each wedge like this (but with the text inside the wedges): Using rotatelabel=True, I get the following: Any ideas on how I can achieve the horizontal rotation of the labels for the graph?
tagged with: data-visualization
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50237578
has title: matplot pie: rotate labels horizontally
linked to: http://stackoverflow.com/q/55267993
favorite count: 0
type: Question
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/50236418
tagged with: pie-chart
has answer: http://stackoverflow.com/a/50236418
downvote count: 0
tagged with: python
score: 4
type: AnsweredQuestion

http://stackoverflow.com/a/50369956
type: Answer
upvote count: 1
has body: They are the same, tensorflow.contrib.lookup.lookup_ops.* being simply imported as-is in tf.contrib.lookup. Use tf.contrib.lookup.* rather than tf.python.ops.lookup_ops.*, not only because it is shorter, but simply because the former is part of the official python API, and not the later. As for why they used tf.python.ops.lookup_ops.index_table_from_file directly in the example you provide, I am not sure. Maybe they felt that a file named utils/vocab_utils.py is an "internal" thing that they own and that could by-pass the public API. Not a practice to import into your own code IMHO.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50364516

http://stackoverflow.com/comment/87691709
type: QuestionComment
comment on: http://stackoverflow.com/q/50312405
has text: what is Scatter3d?
type: Comment
score: 0

http://stackoverflow.com/q/50284072
has comment: http://stackoverflow.com/comment/87613222
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has title: TypeError when feeding Tensorflow dataset with dictionary type
answer count: 0
has body: I am not very sure if this is a Tensorflow problem or a python problem. I am very new to both. My code is based on the wide_deep.py example Tensorflow tutorial provided. I modified the input_fn function so it can take in my dataset (Train_data.csv) Here is the code: def input_fn(data_file, num_epochs, shuffle, batch_size): """Generate an input function for the Estimator.""" assert tf.gfile.Exists(data_file), ( '%s not found. Please make sure you have run data_download.py and ' 'set the --data_dir argument to the correct path.' % data_file) features_interim = pd.read_csv(data_file, usecols=['vgs', 'vbs', 'vds', 'current']) labels_interim = pd.read_csv(data_file, usecols=['plo_tox', 'plo_dxl', 'plo_dxw', 'parl1', 'parl2', 'random_fn']) features_numpy = features_interim.as_matrix().transpose() features = dict(zip(_CSV_FEATURE_COLUMNS, features_numpy)) labels_numpy = labels_interim.as_matrix().transpose() labels = dict(zip(_CSV_LABEL_COLUMNS, labels_numpy)) dataset = tf.data.Dataset.from_tensor_slices((features, labels)) if shuffle: dataset = dataset.shuffle(buffer_size=_NUM_EXAMPLES['train']) dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) return dataset But when I execute the code, it has this error: The main function of this code is here : def main(unused_argv): # Clean up the model directory if present shutil.rmtree(FLAGS.model_dir, ignore_errors=True) model = build_estimator(FLAGS.model_dir, FLAGS.model_type) train_file = "Tensorflow_training_data.csv" test_file = "Tensorflow_testing_data.csv" train_hooks = hooks_helper.get_train_hooks( FLAGS.hooks, batch_size=FLAGS.batch_size, tensors_to_log={'average_loss': 'head/truediv', 'loss': 'head/weighted_loss/Sum'}) # Train and evaluate the model every `FLAGS.epochs_between_evals` epochs. for n in range(FLAGS.train_epochs // FLAGS.epochs_between_evals): model.train( input_fn=lambda: input_fn(train_file, FLAGS.epochs_between_evals, True, FLAGS.batch_size), hooks=train_hooks) results = model.evaluat…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87732288
has comment: http://stackoverflow.com/comment/87617622
tagged with: python
has comment: http://stackoverflow.com/comment/87613741
score: 2
downvote count: 0

http://stackoverflow.com/a/50438954
accepted answer of: http://stackoverflow.com/q/50352018
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50352018
score: 2
downvote count: 0
type: Answer
has body: When instantiating a serializer, you can specify exactly what fields are needed for that particular case using the only or include. For example, if you wanted to serialize only a book's id and title, you could do something like this: schema = BookSchema(only=('id', 'title')) or using exclude: schema = BookSchema(exclude=('authors',)) Docs: https://marshmallow.readthedocs.io/en/latest/api_reference.html#schema
upvote count: 2

http://stackoverflow.com/a/50434616
answers question: http://stackoverflow.com/q/50277848
score: 0
type: Answer
has body: Check out this link to tesserocr Instead of pip, install it with conda. This will solve your problem. conda install -c mcs07 tesserocr

http://stackoverflow.com/a/50291266
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/50290723
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/50290723
has body: "idx" is usually short for index. Python loops allows items in a nested list to be accessed directly like so: &gt;&gt;&gt; lst = [[1, 2], [3, 4], [5, 6]] &gt;&gt;&gt; &gt;&gt;&gt; for a,b in lst: print a,b 1 2 3 4 5 6 Using enumerate in Python allows for something similar: &gt;&gt;&gt; for idx,val in enumerate(['a','b','c']): print('index of ' + val + ': ' + str(idx)) index of a: 0 index of b: 1 index of c: 2 The equivalent of enumerate(array) in JavaScript is array.entries(), and can be used in much the same way as Python: zone_indices = [] for (let i = 0; i &lt; maxz.length, i++) { for (let [idx, val] of classified.entries()) { if (zone+1 === val) { zone_indices.push(idx); }; }; };

http://stackoverflow.com/comment/92412642
has text: This is very helpful, thank you! I modified it slightly to round to the nearest 30 minute interval and it works beautifully.
comment on: http://stackoverflow.com/a/50453285
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50363674
has comment: http://stackoverflow.com/comment/87743569
type: Question
has title: Extracting links from XML file using python
accepted answer: http://stackoverflow.com/a/50363828
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a sitemap XML file and I want to run a script which extracts all the urls and print it. I have tried re.findall(r'(https?://\S+)', url) but this prints the closing tags like : "https://www.tutorialspoint.com/python/python_reg_expressions.htm /liv" I don't want to print the suffix ' /liv ' how do I implement this using regex ?
has comment: http://stackoverflow.com/comment/87743945
favorite count: 0
has comment: http://stackoverflow.com/comment/87743589
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
score: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/50363828

http://stackoverflow.com/comment/87605998
has text: I tried to explain it a bit more in detail. Feel free to ask about what exactly is not clear if that doesn't help.
comment on: http://stackoverflow.com/a/50283567
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87596173
type: Comment
comment on: http://stackoverflow.com/a/50289057
has text: I'm glad to see it helps :)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87785572
has text: @user2 I can see only ne issue instead of `if user.is_authenticated()` yu shoudl use `if user.is_authenticated` for Django >=1.10.
comment on: http://stackoverflow.com/a/50383536
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50382256
accepted answer: http://stackoverflow.com/a/50382353
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/50382353
downvote count: 0
favorite count: 0
type: Question
has body: I'm using Visual Studio Code to learn Python. How can I make DEBUG CONSOLE as default tab in Visual Studio Code? Whenever I debug, this tool loads terminal which has lot of text which is confusing. I click on DEBUG CONSOLE tab to see my output. Wondering if there is any way to get rid of that terminal tab (just the tab, I understand we need terminal for code to work). I tried right clicking on TERMINAL tab and hiding it, but it hides only temporarily. Help appreciated. Also, what does OUTPUT tab do?
tagged with: visual-studio-code
tagged with: python
score: 2
type: AnsweredQuestion
has title: How to make DEBUG CONSOLE as default tab in Visual Studio Code?

http://stackoverflow.com/q/50318656
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50318747
score: -1
tagged with: rss
upvote count: 0
has body: I want to figure out constantly monitor an RSS feed (Python 2.7, using feedparser) or any other library. Means if blog add a new article we get alert. and if article in db != new article then add this article in our db. I don't know how to do that.
tagged with: web-scraping
has title: Monitor RSS/Atom feed
tagged with: rss-reader
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/87679203
has text: What are the first and second column here?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50331541

http://stackoverflow.com/q/50264688
tagged with: python
has answer: http://stackoverflow.com/a/50264764
tagged with: regex
accepted answer: http://stackoverflow.com/a/50264764
tagged with: special-characters
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/171480
has comment: http://stackoverflow.com/comment/87547510
answer count: 1
favorite count: 0
has body: I have a list of strings and I want to use regex to filter the list to certain strings. Ex. Here is the original list: quoteTitle = ['\r\n ', ' ', '\r\n ', '\r\n ', '\r\n ', '\r\n ', '\r\n ', '30. Loyalty', '29. Speed Scale', '28. Security', '27. Every Position', '26. Superior Brain Power', '25. A Long Line of Fighters', '24. Dwight Surveillance', '23. Friends ', '22. Pull the Plug ', '21. Second Life', '20. Accidentally vs. On Purpose', '19. Menstruation Wishes ', '18. Ideal Choice', '17. Healthcare in the Wild', '16. Superior Cousins', '15. Regular Ideas', '14. Immunity Logic', '13. The Person You Least, Medium and Most Suspect', '12. Real Heroes ', '11. Water Cooler Gossip', '10. Stress', '9. All These People!', '8. The “R” Sound', '7. A Woman’s Defects ', '6.Werewolf Hunting Experience ', '5. An Ideal World ', '4. Attention', '3. The Thing About Bear Attacks ', '2. Resume Critiquing', '1. Yeast Infections ', 'Tags', 'Recently in TV', '5/8/2018 3:45:00 PM', '5/3/2018 2:00:00 PM', '5/3/2018 12:00:00 PM', 'Most Popular', '5/3/2018 11:00:00 AM', '5/3/2018 12:00:00 PM', '5/8/2018 3:45:00 PM', '4/13/2018 5:00:00 PM', '4/18/2018 8:22:31 PM', '5/3/2018 2:00:00 PM', '5/8/2018 6:02:54 PM', '5/7/2018 4:52:04 PM', '5/7/2018 2:57:00 PM', '5/3/2018 5:04:43 PM', '5/3/2018 1:06:18 PM', 'Music', '5/3/2018 12:00:00 AM', 'Music', '5/3/2018 12:00:00 AM', 'Music', '5/2/2018 12:00:00 AM', '11/28/2017 8:00:00 AM', '11/30/2017 11:00:00 AM', '5/3/2018 11:00:00 AM', '5/3/2018 2:00:00 PM', '5/3/2018 12:00:00 PM', '12/11/2017 1:00:00 PM', '12/15/2017 8:00:00 AM', '1/9/2018 3:00:00 PM', '1/4/2017 12:30:00 PM', '4/13/2013 12:13:00 PM', 'TV', '4/3/2018 10:00:00 AM', 'TV', '4/3/2018 9:25:00 AM', 'Comedy', '3/22/2018 1:00:28 PM', 'TV', '3/15/2018 10:00:00 AM', 'Comedy', '3/13/2018 2:00:00 PM', 'TV', '3/10/2018 10:00:00 AM', 'TV', '3/2/2018 11:00:00 AM', 'TV', '2/25/2018 10:30:00 PM', 'TV', '2/23/2018 1:00:00 PM', '5/3/2018 11:00:00 AM', '5/3/2018 12:00:00 PM', '5/8/2018 3:45:00 PM', '4/13/2018 …
type: Question
has title: Using regex with list of strings of quotes

http://stackoverflow.com/a/50329104
has comment: http://stackoverflow.com/comment/87674948
answers question: http://stackoverflow.com/q/50328840
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: You seem to have a mismatch between your settings.py (generated using Django 2.0.2.) and your logs (Django version 1.9). Your LoginRequiredMiddleware looks like new-style middleware (requires Django 1.10+), so you should be using the MIDDLEWARE setting instead of MIDDLEWARE_CLASSES. Run your server using the latest 2.0.x release instead. If you can’t upgrade to Python 3 and Django 2.0, then you should use MIDDLEWARE_CLASSES instead of MIDDLEWARE with Django &lt; 1.10. However your LoginRequiredMiddleware is designed for new style MIDDLEWARE and will not work with MIDDLEWARE_CLASSES. Finally, note that Django 1.10 and older are unsupported and do not receive security fixes, so you should try to use at least Django 1.11 LTS.

http://stackoverflow.com/comment/87780448
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50382254
has text: Recommending globals, even if the OP is asking for it, is something I don't condone.
type: Comment

http://stackoverflow.com/q/50261144
favorite count: 0
type: Question
has body: If we run the following code np.random.seed(0) features = ['f1','f2','f3'] df = pd.DataFrame(np.random.rand(5000,4), columns=features+['target']) for f in features: df[f] = np.digitize(df[f], bins=[0.13,0.66]) df['target'] = np.digitize(df['target'], bins=[0.5]).astype(float) df.groupby(features)['target'].agg(['mean','count']).head(9) We get average values for each grouping of the feature set: mean count f1 f2 f3 0 0 0 0.571429 7 1 0.414634 41 2 0.428571 28 1 0 0.490909 55 1 0.467337 199 2 0.486726 113 2 0 0.518519 27 1 0.446281 121 2 0.541667 72 In the table above, some of the groups has too few observations and I want to merge it into 'adjacent' group by some rules. For example, I may want to merge the group [0,0,0] with group [0,0,1] since it has no more than 30 observations. I wonder if there is any good way of operating such group combinations according to columns values without creating a separate dictionary? More specifically, I may want to merge from the smallest count group to its adjacent group (the next group within the index order) until the total number of groups is no more than 10.
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50261818
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87540678
has title: Merge subgroup into adjacent subgroup after groupby
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50261818

http://stackoverflow.com/comment/88004553
type: QuestionComment
comment on: http://stackoverflow.com/q/50378919
score: 0
has text: Thanks for the help. I was able to solve my problem by using the django-googgle-cloud-storage library and using the instructions in https://libraries.io/pypi/django-google-cloud-storage and https://stackoverflow.com/questions/40451440/how-to-use-django-google-cloud-storage-for-gcs-in-django-on-gae links.
type: Comment

http://stackoverflow.com/q/50330126
has comment: http://stackoverflow.com/comment/87677317
score: 0
has comment: http://stackoverflow.com/comment/87677654
answer count: 1
tagged with: selenium
tagged with: web-scraping
has body: I am trying to scrape a dynamic list of options from a form on a site. The site works in a way that when you enter some data in the query box, it takes them as keywords and searches from its own database and accordingly generates results. I am trying to extract the whole complete list by scraping using selenium. Initially in the inspect element section, I have: and this is what changes when we write some keywords there in the form: for i in range(1,100): try: depart.append(browser.find_elements_by_class_name("accessabilityBar textIndent")[i].text) except Exception as e: break print(depart) So, here is what I get as output: [u''] Can somebody help me out with this?
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87701139
has answer: http://stackoverflow.com/a/50330332
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87676489
tagged with: python
has title: Scraping dynamic data from a form on a site

http://stackoverflow.com/comment/87658948
type: Comment
comment on: http://stackoverflow.com/q/50321308
type: QuestionComment
has text: Why do you need to open a .txt with urllib? urllib does not handle local files
score: 0

http://stackoverflow.com/a/50363108
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87742557
answers question: http://stackoverflow.com/q/50362969
type: Answer
has body: Here before you assigning values to 2-d array Vertion you have to create an empty list with the exact number of rows and columns you want. Then only you can assign values to each each columns in each rows. Here you can take a look : Vertion = [[0 for x in range(128)] for y in range(2)] Update : So for assign values to columns in each rows you can try like this : for i in range(2): for j in range(128): Vertion[i][j] = Block()

http://stackoverflow.com/comment/87519535
score: 0
type: AnswerComment
has text: Since I can't post answers anymore, I suggest you to use `random.choice()`, and use a loop to print the number of sentences you want.
type: Comment
comment on: http://stackoverflow.com/a/50251050

http://stackoverflow.com/q/50335812
type: Question
has title: Operating with class variables yields zero?
upvote count: 0
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/1267869
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
tagged with: oop
duplicate of: http://stackoverflow.com/q/1267869
has answer: http://stackoverflow.com/a/50335912
accepted answer: http://stackoverflow.com/a/50335912
tagged with: python
score: -1
has body: I have the following method inside a class: def initialize_overlaps(self): """Initialize the overlap list for each band_nk """ for n in range(self.nbands): for k in range(self.nkpts - 1): for n_prim in range(self.nbands): print("Currently overlapping n: " + str(n) + ". k: " +str(k) +". n': " + str(n_prim) + "\t" +str(n/self.nbands) + " percent completed.") When running it, the indices of the loops change fine, but I dont know why the operation n/self.nbands always yields zero: Currently overlapping n: 3. k: 12. n': 10 0 percent completed. Currently overlapping n: 3. k: 12. n': 11 0 percent completed. Currently overlapping n: 3. k: 13. n': 0 0 percent completed. Currently overlapping n: 3. k: 13. n': 1 0 percent completed. Currently overlapping n: 3. k: 13. n': 2 0 percent completed. Currently overlapping n: 3. k: 13. n': 3 0 percent completed. Currently overlapping n: 3. k: 13. n': 4 0 percent completed.

http://stackoverflow.com/comment/87651051
has text: .......@jpp - Ok!
type: AnswerComment
comment on: http://stackoverflow.com/a/50315142
score: 0
type: Comment

http://stackoverflow.com/a/50311495
downvote count: 2
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/87644682
has body: One way is to use operator.itemgetter with set: from operator import itemgetter lst = [(1, 2, 'Adam', 'M', '2', '12'), (1, 2, 'Ewa', 'W', '2.0 (E)', '44'), (1, 2, 'Ewa', 'W', '2.0 (E)', '44'), (2, 3, 'Adam', 'M', '2', '12'), (2, 3, 'Ewa', 'W', '2.0 (E)', '44')] res = set(map(itemgetter(2, 5), lst)) print(res) {('Adam', '12'), ('Ewa', '44')}
upvote count: 1
answers question: http://stackoverflow.com/q/50311469

pygobject
type: Tag
tags question: http://stackoverflow.com/q/50271879
tags question: http://stackoverflow.com/q/50281987
tag name: pygobject
tags question: http://stackoverflow.com/q/50258880
tags question: http://stackoverflow.com/q/50262296
tags question: http://stackoverflow.com/q/50360564

http://stackoverflow.com/comment/115141407
has text: Thank you for your reminder. I just registered and tried to propose my own solution for the first time. I will do better.
comment on: http://stackoverflow.com/a/65049935
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87641289
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50312470
has text: I posted the real case what I have in my code. But basically I created objects in MainClass and I tried to inherit from MainClass, all classes. In a post, I have a similar example of my actual code.
score: 0

http://stackoverflow.com/comment/87653652
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50318117
score: 0
has text: @StephenRauch thanks yeah been coding for a bit but first time using SO :). 1 final question is there anyway to order the output by the first element i.e. A1, A2, A3 etc. For the larger data set i've got up to A30

http://stackoverflow.com/a/50556283
has comment: http://stackoverflow.com/comment/88182482
has comment: http://stackoverflow.com/comment/88182588
score: 3
answers question: http://stackoverflow.com/q/50335909
has comment: http://stackoverflow.com/comment/88181446
has comment: http://stackoverflow.com/comment/88168102
type: Answer
has comment: http://stackoverflow.com/comment/88182248
accepted answer of: http://stackoverflow.com/q/50335909
has comment: http://stackoverflow.com/comment/88139174
has body: This can be easily archived with docopt. Syntax: Usage: ./foo [--path &lt;src&gt; &lt;dst&gt;]... Input: ./foo --path src1 dst1 --path src2 dst2 Code: &gt;&gt;&gt; from docopt import docopt &gt;&gt;&gt; doc = "Usage: ./foo [--path &lt;src&gt; &lt;dst&gt;]..." &gt;&gt;&gt; argv = "--path old1 new1 --path old2 new2".split() &gt;&gt;&gt; args = docopt(doc, argv) Result: { "--path": 2, "&lt;dst&gt;": [ "dst1", "dst2" ], "&lt;src&gt;": [ "src1", "src2" ] } And now do something with it: &gt;&gt;&gt; if bool(args["--path"]): &gt;&gt;&gt; n = 1 if args["--path"] is True else if args["--path"] &gt;&gt;&gt; for i in range(0, n)]: &gt;&gt;&gt; print("{}, {}".format(args["&lt;old&gt;"][i], args["&lt;new&gt;"][i])) src1, dst1 src2, dst2 To add a multiple positional arguments, require path option and arguments to be in the correct order with parens "( )". Usage: ./foo [(--path &lt;src&gt; &lt;dst&gt;)]... &lt;arg&gt;... Attention: docopt doesn't raise a SystemExit in case the user mixes up the syntax and inputs ./foo arg --path src dst if you use options with multiple arguments like that. You will have to handle it yourself or add another (sub)command in front of it. Usage: ./foo [(--path &lt;src&gt; &lt;dst&gt;)]... bar &lt;arg&gt;...
has comment: http://stackoverflow.com/comment/88181942
upvote count: 3
has comment: http://stackoverflow.com/comment/88137469
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50266208
accepted answer: http://stackoverflow.com/a/50282516
has answer: http://stackoverflow.com/a/50282516
upvote count: 1
tagged with: python
answer count: 1
has body: I have 218k+ 33-channel images, and I need to find the mean and variance of each channel. I've tried to use multiprocessing, but this seems unbearably slow. Here's a brief code sample: def work(aggregates, genput): # received (channel, image) from generator channel = genput[0] image = genput[1] for row in image: for pixel in row: # use welford's to update a list of "aggregates" which will # later be finalized as means and variances of each channel aggregates[channel] = update(aggregates[channel], pixel) def data_stream(df, data_root): '''Generator that returns the channel and image for each tif file''' for index, sample in df.iterrows(): curr_img_path = data_root # read the image with all channels tif = imread(curr_img_path) #33x64x64 array for channel, image in enumerate(tif): yield (channel, image) # Pass over each image, compute mean/variance for each channel for each image def preprocess_mv(df, data_root, channels=33, multiprocessing=True): '''Calculates mean and variance on the whole image set for use in deep_learn''' manager = Manager() aggregates = manager.list() [aggregates.append(([0,0,0])) for i in range(channels)] proxy = partial(work, aggregates) pool = Pool(processes=8) pool.imap(proxy, data_stream(df, data_root), chunksize=5000) pool.close() pool.join() # finalize data below My suspicion is that the time it takes to pickle the aggregates array and transfer that back and forth from parent to child processes takes a horrendously long time, and that this is the major bottleneck - I could see this drawback completely eliminating the multi-process advantage since each child is having to wait for other children to pickle and unpickle data. I've read that this is sort of a limitation of the multiprocessing library, and from the pieces I've put together reading other posts here, I've come to realize this may be the best I can do. That said, does anyone have suggestions for how this could be improved? Additionally, I'm wondering if there are better libraries/to…
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-multiprocessing
type: Question
has title: Folding in array mutations using multiprocessing in python

http://stackoverflow.com/comment/87601573
score: 0
type: Comment
has text: @Fian If an instance uses `self.thdRunning = False` it will create a new instance attribute that overrides `thdRunning`. It would change the class attribute only if it used `TransmitThread.thdRunning = False` for the assignment.
comment on: http://stackoverflow.com/q/50272021
type: QuestionComment

http://stackoverflow.com/a/51207673
has body: You are using very large values. Look at the mean relative absolute error (mean(abs((output - target) / target))) to get a better estimation of the model's performance during evaluation, that is independent of the input scale. Furthermore consider using smaller values, e.g. in range [0; 10] restricting outputs to range [0; 100], to avoid exploding gradients. You could divide the input by some scale (&gt;&gt; 1) accordingly and multiply the output by scale^2. If you do NOT use the trick with ln and exp to transform multiplication into addition, you need much more layers and also should consider residual connections.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50260459

http://stackoverflow.com/comment/87636312
comment on: http://stackoverflow.com/a/50307479
has text: you mean the column 'index' or 'job positions'?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50328401
tagged with: python
accepted answer: http://stackoverflow.com/a/50328564
has comment: http://stackoverflow.com/comment/87673625
has comment: http://stackoverflow.com/comment/87672649
has title: Skipp the error while scraping a list of urls form a csv
type: AnsweredQuestion
upvote count: 0
tagged with: screen-scraping
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87674355
favorite count: 0
linked to: http://stackoverflow.com/q/50294494
has answer: http://stackoverflow.com/a/50328564
type: Question
has body: I managed to scrape a list of urls from a CSV file, but I got a problem, the scraping stops when it hits a broken link. Also it prints a lot of None lines, is it possible to get rid of them ? Would appreciate some help here. Thank you in advance ! Here is the code : #!/usr/bin/python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup #required to parse html import requests #required to make request #read file with open('urls.csv','r') as f: csv_raw_cont=f.read() #split by line split_csv=csv_raw_cont.split('\n') #specify separator separator=";" #iterate over each line for each in split_csv: #specify the row index url_row_index=0 #in our csv example file the url is the first row so we set 0 #get the url url = each.split(separator)[url_row_index] #fetch content from server html = requests.get(url).content #soup fetched content soup = BeautifulSoup(html,'lxml') tags = soup.find("div", {"class": "productsPicture"}).findAll("a") for tag in tags: print(tag.get('href')) And the result with the error looks like this : https://www.tennis-point.com/asics-gel-resolution-7-all-court-shoe-men-white-silver-02013802720000.html None https://www.tennis-point.com/cep-ultralight-run-sports-socks-men-black-light-green-12143000063000.html None https://www.tennis-point.com/asics-gel-solution-speed-3-clay-court-shoe-men-white-grey-02013802634000.html None https://www.tennis-point.com/asics-gel-solution-speed-3-all-court-shoe-men-white-silver-02013802723000.html None https://www.tennis-point.com/asics-gel-challenger-9-indoor-carpet-shoe-men-white-grey-02012401735000.html None https://www.tennis-point.com/asics-gel-court-speed-clay-court-shoe-men-dark-blue-yellow-02014202833000.html None https://www.tennis-point.com/asics-gel-court-speed-all-court-shoe-men-white-silver-02014202832000.html None Traceback (most recent call last): File "/Users/imaging-adrian/Desktop/Python Scripts/close_to_work.py", line 33, in &lt;module&gt; tags = soup.find("div", {"class": "productsPicture"}).findAll("a")…
has comment: http://stackoverflow.com/comment/87673384
score: -2
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/87564360
has text: this is just a representation - if you would save it to file - it will be stored correctly: `df.to_csv(r'/path/to/out.csv', index=False)`
score: 0
comment on: http://stackoverflow.com/q/50273127
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50367403
has answer: http://stackoverflow.com/a/52117681
type: Question
type: UnansweredQuestion
tagged with: spss
has answer: http://stackoverflow.com/a/65878499
tagged with: python
score: 0
answer count: 2
tagged with: pandas
has body: I am trying to compute an ICC(3,k) for k=2 or more for columns in a pandas dataframe. I could not find any toolboxes for this, only this post from 2016 (the Brain toolbox does not exist anymore). There is a code sample for ICC(3,1) but numpy and not pandas based. I am a little lost on how to re-work this. Basically, I want to mimic the IBM SPSS toolbox for dataframes I already have created. I have a number of measurements performed by 2 (or more) independent observers on a number of subjects. I have a dataframe of the form (columns are multiindex): meas1 meas2 meas3 obs1 obs2 obs1 obs2 obs1 obs2 subject1 subject2 subject3 ... I would like to compute the ICC for every measurement.
has title: Interclass Correlation Coefficient (ICC(3,k)) with pandas
linked to: http://stackoverflow.com/q/40965579

http://stackoverflow.com/a/50286506
has comment: http://stackoverflow.com/comment/87589052
score: 0
has body: If you just want to read particular set of columns from one .csv file and output them to another file, you might try pandas module. import pandas as pd data = pd.read_csv('to_load.csv', usecols=['col1', 'col2']) data.to_csv('to_save.csv', index=False) What it does it first loads csv to a variable named data. Only columns you define in usecols get imported. You can reference columns by their names or by index (eg. you can usecols=[0, 1, 2] - this will import first 3 columns). Then the variable can be easily saved to csv file again thanks to .to_csv method.
answers question: http://stackoverflow.com/q/50286190
type: Answer

http://stackoverflow.com/comment/87498360
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50240427
score: 0
has text: You can run a script to replace the existing of DB

http://stackoverflow.com/q/50259795
has body: I just installed the discord.py rewrite branch, but attempting to use import discord or from discord.ext import commands simply results in a TypeError. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/discord/__init__.py", line 20, in &lt;module&gt; from .client import Client, AppInfo File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 30, in &lt;module&gt; from .guild import Guild File "/usr/local/lib/python3.6/site-packages/discord/guild.py", line 39, in &lt;module&gt; from .channel import * File "/usr/local/lib/python3.6/site-packages/discord/channel.py", line 31, in &lt;module&gt; from .webhook import Webhook File "/usr/local/lib/python3.6/site-packages/discord/webhook.py", line 27, in &lt;module&gt; import aiohttp File "/usr/local/lib/python3.6/site-packages/aiohttp/__init__.py", line 6, in &lt;module&gt; from .client import * # noqa File "/usr/local/lib/python3.6/site-packages/aiohttp/client.py", line 15, in &lt;module&gt; from . import connector as connector_mod File "/usr/local/lib/python3.6/site-packages/aiohttp/connector.py", line 17, in &lt;module&gt; from .client_proto import ResponseHandler File "/usr/local/lib/python3.6/site-packages/aiohttp/client_proto.py", line 6, in &lt;module&gt; from .http import HttpResponseParser, StreamWriter File "/usr/local/lib/python3.6/site-packages/aiohttp/http.py", line 8, in &lt;module&gt; from .http_parser import (HttpParser, HttpRequestParser, HttpResponseParser, File "/usr/local/lib/python3.6/site-packages/aiohttp/http_parser.py", line 15, in &lt;module&gt; from .http_writer import HttpVersion, HttpVersion10 File "/usr/local/lib/python3.6/site-packages/aiohttp/http_writer.py", line 304, in &lt;module&gt; class URL(yarl.URL): File "/usr/local/lib/python3.6/site-packages/yarl/__init__.py", line 232, in __init_subclass__ "is forbidden".format(cls)) TypeError: Inheritance a class &lt;class 'aiohttp.http_writer.URL'&gt; from U…
has answer: http://stackoverflow.com/a/50260203
linked to: http://stackoverflow.com/q/50165167
tagged with: python
possible better answer: http://stackoverflow.com/a/52356980
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52356980
has title: TypeError from importing discord.py
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: discord
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87541620
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/50260203

http://stackoverflow.com/comment/87566108
type: QuestionComment
comment on: http://stackoverflow.com/q/50274731
has text: Have you thought about using break?
score: 0
type: Comment

http://stackoverflow.com/comment/87546021
type: Comment
type: QuestionComment
has text: This is mainly opinion based, but I tend to see #2 more and believe it is considered most pythonic
score: 0
comment on: http://stackoverflow.com/q/50263986

http://stackoverflow.com/comment/87784666
score: 0
type: Comment
type: QuestionComment
has text: @tdelaney what does "usually" mean? Is this documented? This could be related to my problem ...
comment on: http://stackoverflow.com/q/50384348

http://stackoverflow.com/comment/87582135
comment on: http://stackoverflow.com/q/50282015
type: Comment
type: QuestionComment
score: 0
has text: @juanpa.arrivillaga Why do you start your comment with a "..."? The only interpretation I can guess is that you want to express that the question is stupid or misguided. Is that what you wanted to express? What exactly is the point of your comment? I think I made my question perfectly clear. If you think that it doesn't warrant submission on this site, save your unnecessary comments and vote to close.

http://stackoverflow.com/comment/87788935
type: QuestionComment
has text: Thankyou, so I have converted my snmp function to async. I have another function that uses regex to extract data, now that would be a memory function and not need async? but I have functions that query and add records to a django DB, now that would need to be converted? but i dont think Django can be run async, so then for that function it would be need to be moved to an executor? hopefully im getting this right? thanks again
comment on: http://stackoverflow.com/q/50352077
type: Comment
score: 0

http://stackoverflow.com/q/50233738
has title: Removing Lists within Lists Efficiently in Python
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50233769
score: 2
upvote count: 2
tagged with: list
answer count: 2
downvote count: 0
has body: Say you’ve got a list like l=[[1,2,3],[1,3,4],[1,5,2],[4,2,1]], and you want to remove every list inside l that has 2 at index 1. What would be the most efficient way? At the moment I use a while loop that goes through each item and checks individually, however this uses up a large amount of CPU when the list becomes long. Is there a way that I could use the .remove() function to make this process easier?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50233754

http://stackoverflow.com/comment/87799155
has text: This worked very well, thank you Martin. All I had to change was the (existing_file_path, new_folder_path) to my variables and it worked.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50389860

http://stackoverflow.com/comment/87527322
score: 0
comment on: http://stackoverflow.com/q/50251870
has text: Ok, what is the problem then? Is the response content different? The cookies? Please be specific.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87762355
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50373189
has text: Use `eval` althought it's not recommended

http://stackoverflow.com/q/50234680
has comment: http://stackoverflow.com/comment/87516471
tagged with: python
has comment: http://stackoverflow.com/comment/87516429
has comment: http://stackoverflow.com/comment/87513331
has answer: http://stackoverflow.com/a/50234770
has comment: http://stackoverflow.com/comment/87518075
type: UnansweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87487183
downvote count: 0
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/87509417
has body: I am very new in Django REST API and Python. I have python script. and I created simple Django REST API for getting input from users. Now I want to do when user give input through Django REST API then after run my python script with it. so I want to integrate my python script with Django REST API. I tried to do googling but Not able to understand because in some forum they use subprocess and in some forum given REQUEST function. I am confuse and not able to understand. my view.py file as follows: from django.shortcuts import render from rest_framework import viewsets from . models import input_params from . serializers import input_paramsSerializer class inputViewSet(viewsets.ModelViewSet): queryset = input_params.objects.all() serializer_class = input_paramsSerializer url.py file from django.contrib import admin from django.conf.urls import url,include from base_search.views import inputViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'input',inputViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include(router.urls)) ] Question1 Now can anyone please tell me How can I connect my python script here? Question2: if I just connect my python script at endpoint so will it take automatically user input data from Django REST API and run my python script? If anyone have good example please let me know.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87513605
has title: How to run python script simultaneously when user input in Django REST api?
has comment: http://stackoverflow.com/comment/87518447
has comment: http://stackoverflow.com/comment/87510936

http://stackoverflow.com/a/50259126
answers question: http://stackoverflow.com/q/50243130
has comment: http://stackoverflow.com/comment/87537219
type: Answer
has body: Run the program in a debugger and pause it after sc = SparkContext(conf = conf) and then run ps aux | grep java and you will know which jvm is getting used for this Then you should setup the keystore for the same. After you know the correct JDK, use below link to setup the keyStore How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?
has comment: http://stackoverflow.com/comment/87537323
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50243130
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/130922720
comment on: http://stackoverflow.com/a/70596970
type: AnswerComment
score: 0
has text: @wim I guess there are many opinions about *should* in python, but since its development is in constant change people just use what works. Your own comment is not more useful that this answer, as you don't explain why it should not be used, when it works.
type: Comment

http://stackoverflow.com/comment/87580477
type: QuestionComment
score: 1
has text: And if you don't specify the parent, then the Widget's parent is the root window, the one that's attached to the Tcl interpreter.
comment on: http://stackoverflow.com/q/50281881
type: Comment

http://stackoverflow.com/q/50307390
has body: I would like to extend the admin view used to create a new entry in the database. For example I can create new books with their author, their categories, their date etc... When I create a new book I want to send a notification to all users whose the book's author is one of their favorite authors. The notification system is already working thanks to django-notifications So, I just have to add this kind of stuff just after the book.save() in the admin view : writer = &lt;the_author_selected_in_the_form&gt; # writer ID profiles = Profile.favorites_authors.through.objects.filter(authors_id=writer) for profile in profiles: notify.send(profile.profile_id, recipient=profile.profile_id, verb='New book, called &lt;book_title&gt;, from &lt;author_name&gt;') Thank you
tagged with: django-views
score: 0
has answer: http://stackoverflow.com/a/50307546
answer count: 1
type: Question
has title: How to extend an admin view in Django?
tagged with: django-admin
tagged with: django
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/50354883
score: 1
answers question: http://stackoverflow.com/q/50354622
type: Answer
has body: read the data into pandas. accept input and then filter, groupby &amp; size gives the desired result term = input("Enter the term you are looking for:") data[data.Term.str.lower() == term.lower()].groupby('Researcher').size() # Output with term = 'HIV' Dr. Lee 3 Dr.Roberts 1 prof. christopher 1 dtype: int64 In this method, researchers not associated with a term (i.e. have size == 0) are not shown. To show researchers with no terms with a count of zero, first set up a dataframe of researchers and outer join the result dataframe with it. researchers = pd.DataFrame({'Researcher': data.Researcher.unique()}) out = data[data.Term.str.lower() == term.lower()].groupby('Researcher').agg({'Terms': 'size'}) pd.merge(reserachers, out, how='outer').fillna(0).sort_values('Terms', ascending=False) # outputs: Researcher Terms 1 Dr. Lee 3.0 2 Dr.Roberts 1.0 4 prof. christopher 1.0 0 Dr. Roberts 0.0 3 Dr. Wang 0.0 5 prof. swaminathan 0.0
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87775227
score: 0
comment on: http://stackoverflow.com/q/50376402
has text: I figured out that if i don't use tf.data.Dataset, then the code works fine. But i wonder why?
type: Comment
type: QuestionComment

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/50251765
tags question: http://stackoverflow.com/q/50360680
tags question: http://stackoverflow.com/q/50330849
tags question: http://stackoverflow.com/q/50241195
tags question: http://stackoverflow.com/q/50354034
tags question: http://stackoverflow.com/q/50382119
type: Tag
tags question: http://stackoverflow.com/q/50237676
tags question: http://stackoverflow.com/q/50281516
tags question: http://stackoverflow.com/q/50349428

http://stackoverflow.com/a/50289992
answers question: http://stackoverflow.com/q/50289938
has comment: http://stackoverflow.com/comment/87596651
type: Answer
score: 0
has body: Simply do this, import pandas as pd dataframe = pd.read_csv('C:\\Users\\Ankit\\Downloads\\file.csv') pd.read_csv will read the csv file and return it in dataframe.

http://stackoverflow.com/a/50245814
score: 1
type: Answer
has body: I found that instance carries the original data, and validated_data carries the new data. I was saving the original data back. I had to replace instance data with validated_data data and then save instance: def update(self, instance, validated_data): company_data = validated_data.pop('company') company = models.Company.objects.get(id=instance.company.id) company.name = company_data.get('name') company.legal_name = company_data.get('legal_name') company.tax_id = company_data.get('tax_id') company.url = company_data.get('url') company.address = company_data.get('address') instance.company = company instance.code = validated_data.get('code', instance.code) instance.city = validated_data.get('city', instance.city) instance.category = validated_data.get('category', instance.category) instance.capacity = validated_data.get('capacity', instance.capacity) instance.position = validated_data.get('position', instance.position) instance.in_pickup = validated_data.get('in_pickup', instance.in_pickup) instance.is_active = validated_data.get('is_active', instance.is_active) company.save() instance.save() return instance put method works handsomely now.
answers question: http://stackoverflow.com/q/50244109
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50313657
answers question: http://stackoverflow.com/q/50313114
score: 7
has comment: http://stackoverflow.com/comment/132456657
upvote count: 8
has comment: http://stackoverflow.com/comment/110488929
has comment: http://stackoverflow.com/comment/104039815
type: Answer
has comment: http://stackoverflow.com/comment/110494496
downvote count: 1
has body: The entropy of an image is defined as follows: where n is the number of gray levels (256 for 8-bit images), pi is the probability of a pixel having gray level i, and b is the base of the logarithm function. Notice that the entropy of an image is rather different from the entropy feature extracted from the GLCM (Gray-Level Co-occurrence Matrix) of an image. Take a look at this post to learn more. As per your request, I'm attaching an example of how the entropy of a GLCM is computed: First we import the necessary modules: import numpy as np from skimage.feature import greycomatrix Then we read the image: img = io.imread('https://i.sstatic.net/07DZW.png') The GLCM (corresponding to the pixel to the right) of the image above is computed as follows: glcm = np.squeeze(greycomatrix(img, distances=[1], angles=[0], symmetric=True, normed=True)) And finally we apply this formula to calculate the entropy: where p(i, j) represents the entries of the GLCM. If we set b to 2, the result is expressed in bits. entropy = -np.sum(glcm*np.log2(glcm + (glcm==0))) # yields 10.704625483788325
has comment: http://stackoverflow.com/comment/104039701

http://stackoverflow.com/comment/87705347
type: AnswerComment
has text: This one worked. It opened a new terminal and then launched the browser. Thank you
comment on: http://stackoverflow.com/a/50344665
type: Comment
score: 0

http://stackoverflow.com/a/50294713
has comment: http://stackoverflow.com/comment/87701994
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50293876
type: Answer
has body: If you want to apply that condition to every view of the model (there are models with more than one form view displayed in different parts of Odoo), it would be better to specify it in Python. In the definition of each field, you should add states argument: your_field = fields.Whatever( ... readonly=False, states={ 'confirmed': [('readonly', True)], } ) This way, if the model is opened by the user through a view different from the one you have modified, the fields would be readonly if the state is confirmed, it doesn't matter that you haven't modified the opened view. On the other hand, if you want to apply your purpose only in a specific form view, you could do something quicker than adding the attrs to each field, and it would be adding it to tags which contain several fields, like group, for example. This also works and is faster for you: &lt;group attrs="{'readonly': [('state', '=', 'confirmed')]}"&gt; &lt;field name="your field_1"/&gt; &lt;field name="your field_2"/&gt; ... &lt;/group&gt;
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/50293876
downvote count: 0

http://stackoverflow.com/comment/87658409
has text: I am very far relative to the bucket. But my app will get traffic from all over the world so I don't think my location is a function for this. will Cloudfront solve this? I don't download images, I display them (changed content type to image/jpeg). For some reason it is still slow although they should be cached.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50320602

http://stackoverflow.com/a/50380962
has comment: http://stackoverflow.com/comment/87818851
has comment: http://stackoverflow.com/comment/87786155
type: Answer
has body: mock_stdout only catch the stdout of print statement, so add print(text) class GameDisplay: @staticmethod def prompt(text): input_value = input(text) print(text) return input_value This piece of code is tested and worked as expected @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('__builtin__.input', return_value='0') def test_prompt_output3(self, mock_input, mock_stdout): p = GameDisplay.prompt('Choose 0: ') self.assertEqual(p, '0') self.assertEqual(mock_stdout.getvalue(), 'Choose 0: \n') but then it would print Choose 0: twice Test the return_value of prompt() should be enough in real life. There is only 1 option left if you really want to mock input and output at the same time. This will do, as long as you do not mock the print at the same time: print(text) input_value = input() Or go for a insane way, fake the stdout: mock_stdout = StringIO('Choose 0: ') p = GameDisplay.prompt('Choose 0: ') self.assertEqual(mock_stdout.getvalue(), 'Choose 0: ') or this is similar to assign a return_value to mock object: with mock.patch('sys.stdout', new=StringIO("xxx")) as mock_stdout:
answers question: http://stackoverflow.com/q/50380066
score: 0

http://stackoverflow.com/q/50251956
has answer: http://stackoverflow.com/a/50252202
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50252022
has title: Sum of a Column in a Dictionary of Dataframes
has answer: http://stackoverflow.com/a/50252022
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/50252202
has body: How can I work with a dictionary of dataframes please? Or, is there a better way to get an overview of my data? If I have for example: Fruit Qty Year Apple 2 2016 Orange 1 2017 Mango 2 2016 Apple 9 2016 Orange 8 2015 Mango 7 2016 Apple 6 2016 Orange 5 2017 Mango 4 2015 Then I am trying to find out how many in total I get per year, for example: 2015 2016 2017 Apple 0 11 0 Orange 8 0 6 Mango 4 9 0 I have written some code but it might not be useful: import pandas as pd # Fruit Data df_1 = pd.DataFrame({'Fruit':['Apple','Orange','Mango','Apple','Orange','Mango','Apple','Orange','Mango'], 'Qty': [2,1,2,9,8,7,6,5,4], 'Year': [2016,2017,2016,2016,2015,2016,2016,2017,2015]}) # Create a list of Fruits Fruits = df_1.Fruit.unique() # Break down the dataframe by Year df_2015 = df_1[df_1['Year'] == 2015] df_2016 = df_1[df_1['Year'] == 2016] df_2017 = df_1[df_1['Year'] == 2017] # Create a dataframe dictionary of Fruits Dict_2015 = {elem : pd.DataFrame for elem in Fruits} Dict_2016 = {elem : pd.DataFrame for elem in Fruits} Dict_2017 = {elem : pd.DataFrame for elem in Fruits} # Store the Qty for each Fruit x each Year for Fruit in Dict_2015.keys(): Dict_2015[Fruit] = df_2015[:][df_2015.Fruit == Fruit] for Fruit in Dict_2016.keys(): Dict_2016[Fruit] = df_2016[:][df_2016.Fruit == Fruit] for Fruit in Dict_2017.keys(): Dict_2017[Fruit] = df_2017[:][df_2017.Fruit == Fruit]
tagged with: dictionary
type: Question
score: 2
answer count: 2
upvote count: 2
linked to: http://stackoverflow.com/q/47152691
downvote count: 0

http://stackoverflow.com/q/50298553
score: 4
has comment: http://stackoverflow.com/comment/87614362
linked to: http://stackoverflow.com/q/33154777
has comment: http://stackoverflow.com/comment/87614478
has comment: http://stackoverflow.com/comment/87615826
tagged with: selenium-webdriver
upvote count: 4
tagged with: css-selectors
has comment: http://stackoverflow.com/comment/87614927
has comment: http://stackoverflow.com/comment/87614893
answer count: 1
downvote count: 0
tagged with: selenium
linked to: http://stackoverflow.com/q/59777770
has comment: http://stackoverflow.com/comment/87614487
has body: I'm using ChromeDriver of Selenium with Python and I'm trying to find a button on my page that has the following HTML: &lt;input id="j_id0:SiteTemplate:j_id255:new" type="submit" name="j_id0:SiteTemplate:j_id255:new" value="New" class="kbutton-white"&gt; The only thing I know being constant is the id and name ending with "new" and I'm trying to use the following code to identify and click that element: test_runner.driver.find_element_by_css_selector('[id*=new]').click() However, I get this error when I run the code: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id*=new]"} What's my mistake here? Update: This element was inside an iframe and I had to switch to the iframe before trying to find the element. Please see comments for the answer.
tagged with: webdriver
linked to: http://stackoverflow.com/q/31248804
favorite count: 0
has comment: http://stackoverflow.com/comment/87614640
type: Question
has comment: http://stackoverflow.com/comment/87615780
has answer: http://stackoverflow.com/a/50299190
has comment: http://stackoverflow.com/comment/87615151
linked to: http://stackoverflow.com/q/65893747
linked to: http://stackoverflow.com/q/49582353
type: UnansweredQuestion
has title: Finding elements by CSS selector with ChromeDriver (Selenium) in Python
tagged with: python

http://stackoverflow.com/q/50383746
tagged with: word-embedding
has answer: http://stackoverflow.com/a/50752639
tagged with: word2vec
tagged with: nlp
score: 0
has body: #!/usr/bin/env python # -*- coding: utf-8 -*- import warnings warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') import logging import os.path import sys import multiprocessing # from gensim.corpora import WikiCorpus from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence if __name__ == '__main__': program = os.path.basename(sys.argv[0]) logger = logging.getLogger(program) logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', level=logging.INFO) logger.info("running %s" % ' '.join(sys.argv)) min_count=100 data_dir='/opt/mengyuguang/word2vec/' inp = data_dir + 'wiki.zh.simp.seg.txt' outp1 = data_dir + 'wiki.zh.min_count{}.model'.format(str(min_count)) outp2 = data_dir + 'wiki.zh.min_count{}.vector'.format(str(min_count)) # train cbow model = Word2Vec(LineSentence(inp), size=300, workers=multiprocessing.cpu_count(),min_count=min_count) # save model.save(outp1) model.wv.save_word2vec_format(outp2, binary=False) Firstly,I trained word embedding with the code above, I don't think there is anything wrong with it. And I created a list vocab to store the words in the vector file. Then vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length) pretrain = vocab_processor.fit(vocab) Vocab is a list of 415657 words. And I got a vocabulary of 412722. I know that vocab_processor.fit won't take upper and lower case as two words. This is really strange. How is this happening? I checked the vector file again. There are no overlapping words at all.
answer count: 1
tagged with: python
tagged with: tensorflow
has title: Got a smaller vocabulary after using tf.contrib.learn.preprocessing.VocabularyProcessor
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87810056

http://stackoverflow.com/a/50306399
type: Answer
answers question: http://stackoverflow.com/q/50304993
score: 0
type: AcceptedAnswer
has body: There's not a great amount of detail in your question, but if we assume that message.content contains a string like "add(500)", then your existing code would place the string "500" in text_out. To do the same thing where message.content looks like "add 500", you could split message.content by whitespace (.split()), then inspect the second element ([1]): if message.content.lower().startswith('add'): text_out = message.content.split()[1]
accepted answer of: http://stackoverflow.com/q/50304993

confusion-matrix
tags question: http://stackoverflow.com/q/50282420
tags question: http://stackoverflow.com/q/50274999
tag name: confusion-matrix
tags question: http://stackoverflow.com/q/50325786
type: Tag
tags question: http://stackoverflow.com/q/50336395
tags question: http://stackoverflow.com/q/50319858

http://stackoverflow.com/comment/87741036
type: AnswerComment
comment on: http://stackoverflow.com/a/50349644
type: Comment
has text: @John Doe csv is confidental? If not, can you send it to my email in my profile? Because it seems some data related problem.
score: 0

http://stackoverflow.com/q/50268887
has body: I have a very simple flask application that integrates flask-socketio, and I am trying to run my server using the flask run command on my terminal. I have read the documentation and this should do the job, however the output is the following, and I cannot reach my server on 127.0.0.1:5000 and here is my code: I would really appreciate any help :)
has comment: http://stackoverflow.com/comment/87558435
tagged with: flask-socketio
has title: flask run command on a flask app with flask-socketio extension
has comment: http://stackoverflow.com/comment/87555599
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87555532
answer count: 2
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50269031
has answer: http://stackoverflow.com/a/50271249

protocol-buffers
tags question: http://stackoverflow.com/q/50365756
type: Tag
tag name: protocol-buffers
tags question: http://stackoverflow.com/q/50299537

http://stackoverflow.com/comment/87544644
comment on: http://stackoverflow.com/q/50263299
score: 0
has text: could you paste the code so that i may look at it
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50275394
accepted answer: http://stackoverflow.com/a/50275473
tagged with: python
possible better answer: http://stackoverflow.com/a/50276203
favorite count: 0
has answer: http://stackoverflow.com/a/50276203
type: AnsweredQuestion
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/50275473
downvote count: 1
tagged with: regex
has body: I'm looking to obtain one person's chat text from a large string that has another person also featured in it. The other person's chat text needs to be removed from the string. Usually there's a punctuation mark or a \n tag in a simple case, but in this case there's nothing except the other person's name to show the end of a chat. And at times there are multiple chats in a row from one person. An example of a chat text string would be the following (where I'm looking for only Joe's chats): Joe: hey mike i was wondering what you're doing today Joe: im bored. Mike: hey joe not sure, do you have any plans? Joe: i was thinking about going to the baseball game Joe: I need to get out of the house. Mike: Sounds good I'll meet you there! Mike: Let me know what time you're leaving I would eventually need the string to be: hey mike i was wondering what you're doing today I'm bored. i was thinking of going to the baseball game I need to get out of the house. I'm fine with answers that leave the "Joe" tags in there, I just can't figure out a way to remove the "Mike" tags and chats using re in Python. Can anyone help me with this?
type: Question
upvote count: 2
has title: python re - Extract chat text of one person in a large string
has answer: http://stackoverflow.com/a/50275907

acl
tag name: acl
tags question: http://stackoverflow.com/q/50267256
type: Tag

http://stackoverflow.com/q/50275767
has comment: http://stackoverflow.com/comment/87569720
has comment: http://stackoverflow.com/comment/87570107
tagged with: python
has comment: http://stackoverflow.com/comment/87569927
has comment: http://stackoverflow.com/comment/87570021
has comment: http://stackoverflow.com/comment/87569770
downvote count: 0
has title: How do you get isolated SQL syntax error in SQLAlchemy
has comment: http://stackoverflow.com/comment/87569639
tagged with: sql
score: 1
has body: Using SQLAlchemy I would like to isolate any SQL syntax errors. For instance.. try: [row for row in db.execute(text("select * from userds"), **args)] except ProgrammingError as error: print(error) I get (psycopg2.ProgrammingError) relation "userds" does not exist LINE 1: select * from userds ^ [SQL: 'select * from userds'] (Background on this error at: http://sqlalche.me/e/f405) And I'm only interested in.. relation "userds" does not exist Anyone know if this is possible?
upvote count: 1
has comment: http://stackoverflow.com/comment/87568299
answer count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50276733
tagged with: exception
type: UnansweredQuestion

http://stackoverflow.com/q/50261835
type: Question
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87541948
tagged with: list
downvote count: 0
has comment: http://stackoverflow.com/comment/87541890
has answer: http://stackoverflow.com/a/50262040
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I am making a simple card game in python in which players compare a stat of a card, the card with the higher stat value wins the round and the loser gives them that card, removing it from their deck and putting it into the end of the winners deck. Here is my code for the game which includes a round of gameplay: import random class Ram(): def __init__(self, name, weight, milk, wool, offs, thigh, fert, meat, fat): self.name = name self.weight = weight self.milk = milk self.wool = wool self.offs = offs self.thigh = thigh self.fert = fert self.meat = meat self.fat = fat def __repr__(self): return f"{self.name,self.weight,self.milk,self.wool,self.offs,self.thigh,self.fert,self.meat,self.fat}" def Read(txtfile): datalist=[] f = open(txtfile, "r", encoding="utf-8") for line in f: datalist.append(line.split(',')) f.close() cardlist = [] for i in datalist: cardlist.append(Ram(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7])) return cardlist def RandomChoice(): l=["User","Computer"] return random.choice(l) cardlist=Read("hrutaspil.txt") random.shuffle(cardlist) split = len(cardlist) // 2 user_deck = cardlist[:split] computer_deck = cardlist[split:] game=input("Do you want to play?(y/n)") if game == "y": if RandomChoice() == "User": print("The user chooses first") print("Your top card is:",user_deck[0].name) print("1 = weight =",user_deck[0].weight) print("2 = milk =", user_deck[0].milk) print("3 = wool =", user_deck[0].wool) print("4 = offs =", user_deck[0].offs) print("5 = thigh =", user_deck[0].thigh) print("6 = fert =", user_deck[0].fert) print("7 = meat =", user_deck[0].meat) print("8 = fat =", user_deck[0].fat) choice=input("Choose stat: ") if choice == ("1"): print("Weight is:",float(user_deck[0].weight)) print("compared with computer:",float(computer_deck[0].weight)) if float(computer_deck[0].weight) &gt; float(user_deck[0].weight): print("Computer wins.") else: print("You win.") Now, how do I remove a card from the losers deck and add it to the bottom of the winners de…
has title: remove an item from one list and store it into the end of another list
has comment: http://stackoverflow.com/comment/87541964
favorite count: 0

http://stackoverflow.com/comment/87541832
comment on: http://stackoverflow.com/q/50261525
score: 0
type: Comment
has text: Flask should give a proper traceback in the server console/logs, or in the browser itself if you enable debug mode. Please post that traceback, it will say exactly why this is not working.
type: QuestionComment

http://stackoverflow.com/comment/87674944
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50324275
type: Comment
has text: that's an interesting suggestion. Can you post code that shows how you would do that?

http://stackoverflow.com/comment/87607132
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50295240
has text: There seems to be no `T3`, and how should the dictionary look?
score: 1

http://stackoverflow.com/comment/87697821
score: 0
type: AnswerComment
has text: I change tf.zeros([1]) to tf.random_uniform([1],0,1) but none of the value is chaged in each step, and the value is not equals to fake data.
type: Comment
comment on: http://stackoverflow.com/a/50340780

http://stackoverflow.com/comment/87705775
type: AnswerComment
comment on: http://stackoverflow.com/a/50344603
type: Comment
has text: Oh thank you! It was driving me crazy for last three days. But I don't totally understand how it is converting to list so much faster than accessing element one by one. Do you have maybe link to any good explanation of that? :)
score: 0

http://stackoverflow.com/q/50324416
score: 0
has body: 1 2016-10-01 01:00:00 1014.7 23.6 2 2016-10-01 02:00:00 1014.3 23.6 3 2016-10-01 03:00:00 1014.3 23.8 4 2016-10-01 04:00:00 1014.3 23.8 5 2016-10-01 05:00:00 1014.4 24.3 6 2016-10-01 06:00:00 1014.9 24.6 7 2016-10-01 07:00:00 1015.6 25.7 8 2016-10-01 08:00:00 1015.8 26 9 2016-10-01 09:00:00 1016.3 27.3 10 2016-10-01 10:00:00 1016.5 25.8 11 2016-10-01 11:00:00 1016.6 26 12 2016-10-01 12:00:00 1016.6 27.3 I have a dataframe as shown above with a timestamp column and some pressure columns. The problem is that the timestamps are hourly and i need a 10 minutes interval timeseries. I would therefore like to insert 5 new rows after each row where i add 10 minutes to the previous timestamp and just keep the pressure data. Can anyone help me with this, would be much appreciated.
tagged with: pandas
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50324463
answer count: 1
accepted answer: http://stackoverflow.com/a/50324463
has title: Insert new rows in pandas dataframe, altering some timestamps while keeping other data
type: AnsweredQuestion

http://stackoverflow.com/comment/87743057
has text: No,its `import ibm_db`.Please refer this link https://www.ibm.com/support/knowledgecenter/en/SSSNY3_10.1.0/com.ibm.swg.im.dbclient.python.doc/doc/t0054368.html
score: 0
comment on: http://stackoverflow.com/q/50357696
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50379103
answers question: http://stackoverflow.com/q/50379069
has comment: http://stackoverflow.com/comment/87774850
upvote count: 2
score: 2
downvote count: 0
has body: list1 = ['a','b','c'] list2 = ['1','2','3'] for x,y in zip(list1,list2): print(x) print(y) zip iterates the lists together.
type: Answer

http://stackoverflow.com/comment/87574358
score: 0
comment on: http://stackoverflow.com/a/50278843
type: AnswerComment
has text: While not in tuple output form this does help me get past my blinders and tunnel vision.Thanks for your help
type: Comment

http://stackoverflow.com/comment/87755855
score: 0
has text: Did the below answer help? If so, feel free to accept, or ask for clarification.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50296344

http://stackoverflow.com/comment/87777047
type: Comment
has text: Why the parentheses around the string?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50380247

indexing
tags question: http://stackoverflow.com/q/50362262
tags question: http://stackoverflow.com/q/50384147
tags question: http://stackoverflow.com/q/50261473
tags question: http://stackoverflow.com/q/50337660
tags question: http://stackoverflow.com/q/50336689
tag name: indexing
tags question: http://stackoverflow.com/q/50239981
tags question: http://stackoverflow.com/q/50335573
type: Tag
tags question: http://stackoverflow.com/q/50257687
tags question: http://stackoverflow.com/q/50359777
tags question: http://stackoverflow.com/q/50318574
tags question: http://stackoverflow.com/q/50249979
tags question: http://stackoverflow.com/q/50378657
tags question: http://stackoverflow.com/q/50298025
tags question: http://stackoverflow.com/q/50342246
tags question: http://stackoverflow.com/q/50345458
tags question: http://stackoverflow.com/q/50350975
tags question: http://stackoverflow.com/q/50315700
tags question: http://stackoverflow.com/q/50253979
tags question: http://stackoverflow.com/q/50365336
tags question: http://stackoverflow.com/q/50350539

http://stackoverflow.com/comment/131993461
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50286212
has text: This answer actually preserves the original records of the input `df`. This is exactly what I was looking for.
score: 0

http://stackoverflow.com/a/50938134
answers question: http://stackoverflow.com/q/50301094
type: Answer
downvote count: 4
upvote count: 0
has body: The only solution I could find was to remove the slider and then you can just use the regular zoom tool. layout = go.Layout( xaxis = dict( rangeslider = dict( visible = False ) ) )
score: -4

http://stackoverflow.com/comment/87755556
type: QuestionComment
has text: Did one of the below solutions help? Feel free to accept one (tick on left), or ask for clarification.
type: Comment
comment on: http://stackoverflow.com/q/50331541
score: 0

http://stackoverflow.com/q/50271295
type: Question
has title: upgrade TLS 1.0 to TLS 1.2 on macOS
score: 5
upvote count: 5
downvote count: 0
tagged with: python
type: AnsweredQuestion
tagged with: openssl
accepted answer: http://stackoverflow.com/a/50281610
linked to: http://stackoverflow.com/q/42131758
answer count: 1
has answer: http://stackoverflow.com/a/50281610
tagged with: tls1.2
tagged with: macos
favorite count: 0
has body: I have troubles installing some python packages I believe because I have TLS 1.0 version. How do I upgrade to TLS 1.2? python -c "import urllib2; import json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])" TLS 1.0 My macOS version: 10.13.4 (17E202) python version: Python 2.7.13 openssl version: LibreSSL 2.2.7 I tried to upgrade openssl, but it does not upgrade LibreSSL. I recall I was having some issue a year ago with openssl, I might have linked it manually or something :(

http://stackoverflow.com/comment/87887077
has text: Yes.Please let me know if you could help me with this -https://stackoverflow.com/questions/50434784/python-plot-month-wise-histogramnormalised
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50323344

http://stackoverflow.com/q/50338311
upvote count: 1
has body: I have two numpy arrays of pretty large size. First is arr1 of size (40, 40, 3580) and second is arr2 of size (3580, 50). What I want to achieve is arr_final = np.sum(arr1[..., None]*arr2, axis = 2) such that the size of arr_final is just (40, 40, 50). However, in doing the above, python probably caches internal array operations, so I keep on getting memory error. Is there any way so as to avoid internal caching and just have final result? I have looked at numexpr, but I am not sure how one can achieve arr1[..., None]*arr2, and then sum over axis=2 in numexpr. Any help or suggestion would be appreciated.
tagged with: arrays
has comment: http://stackoverflow.com/comment/87693738
has comment: http://stackoverflow.com/comment/87693080
has answer: http://stackoverflow.com/a/50338537
type: AnsweredQuestion
downvote count: 0
tagged with: numexpr
score: 1
has comment: http://stackoverflow.com/comment/87693185
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87693158
tagged with: memory
has comment: http://stackoverflow.com/comment/87693232
favorite count: 0
has comment: http://stackoverflow.com/comment/87694119
accepted answer: http://stackoverflow.com/a/50338537
type: Question
tagged with: numpy
has title: What could be the best way to bypass `MemoryError` in this case?
has comment: http://stackoverflow.com/comment/87694147

http://stackoverflow.com/q/50338341
has comment: http://stackoverflow.com/comment/87693966
tagged with: django-models
tagged with: python
has body: From: StartTable.objects.annotate(name=F('object_type_2__destination_table__name')) Django writes a query containing this automatically: LEFT OUTER JOIN "object" T4 ON ("start_table"."object_type_2_id" = T4."id") LEFT OUTER JOIN "destination_table" ON (T4."id" = "destination_table"."object_id") Is there a way to have Django make this more efficient by writing this instead?: JOIN destination_table ON destination_table.object_id = start_table.object_type_2_id Some context to keep in mind; the start_table has several foreign key fields that all refer to the same object table, but for different reasons, which is why I've given object_type_2_id as the column name.
has comment: http://stackoverflow.com/comment/87694114
linked to: http://stackoverflow.com/q/31735717
has title: Can Django ORM join on something other than pk?
has comment: http://stackoverflow.com/comment/87694162
answer count: 0
tagged with: psql
has comment: http://stackoverflow.com/comment/87693044
tagged with: sql
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87693894
downvote count: 0
upvote count: 1
tagged with: django
favorite count: 0
has comment: http://stackoverflow.com/comment/87693389
type: Question
has comment: http://stackoverflow.com/comment/87693817
has comment: http://stackoverflow.com/comment/87694153

http://stackoverflow.com/q/50310223
favorite count: 0
type: Question
tagged with: python-3.x
has body: How would I make a function called nextyear() that increases all the animals age by 1? class Animal: def __init__(self, age): self.age=age animal1 = Animal (5) animal2 = Animal (7) animal3 = Animal (3)
possible better answer: http://stackoverflow.com/a/50310298
has answer: http://stackoverflow.com/a/50310298
has answer: http://stackoverflow.com/a/50310281
accepted answer: http://stackoverflow.com/a/50310322
tagged with: python
has answer: http://stackoverflow.com/a/50310287
upvote count: 6
has answer: http://stackoverflow.com/a/50310322
answer count: 4
tagged with: class
score: 4
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87636714
has title: How to increase a variable shared by all objects in a class by 1?

http://stackoverflow.com/q/50275529
downvote count: 0
has answer: http://stackoverflow.com/a/50275736
possible better answer: http://stackoverflow.com/a/50275736
has comment: http://stackoverflow.com/comment/87568013
favorite count: 0
type: Question
score: 3
has body: In the urls.py of Django #urls.py url(r'^topics/(?P&lt;topic_id&gt;\d+)/$', views.topic, name='topic') The second part of the expression, /(?P&lt;topic_id&gt;\d+)/, matches an integer between two forward slashes and stores the integer value in an argument called topic_id. I try to understand it with regex In [6]: re.findall(r'topics/(?P&lt;topic_id&gt;\d+)/$', "topics/1/") Out[6]: ['1'] However, when I tried In [7]: re.findall(r'topics/(?P&lt;topic_id&gt;\d+)/$', "topics/1/").topic_id AttributeError: 'list' object has no attribute 'topic_id' It seems that the integer is not stored in topic_id , How to understand it?
tagged with: django
tagged with: python
has title: Retrieve the integer stored in (?P<topic_id>\d+)
has comment: http://stackoverflow.com/comment/87567852
has answer: http://stackoverflow.com/a/50275686
accepted answer: http://stackoverflow.com/a/50275686
type: AnsweredQuestion
upvote count: 3
answer count: 2

http://stackoverflow.com/q/50253289
has title: Docker on AWS Elastic Beanstalk - can't access environment variables from container
tagged with: python
has answer: http://stackoverflow.com/a/50321214
score: 4
has answer: http://stackoverflow.com/a/50322398
tagged with: amazon-elastic-beanstalk
type: Question
upvote count: 4
has body: I have tried to move our Python/Django app to Docker on AWS Elastic Beanstalk (single Docker container). I've written a basic Dockerfile as below, scraped together form various tutorials: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /var/app WORKDIR /var/app ADD requirements.txt /var/app RUN pip install -r requirements.txt ADD . /var/app EXPOSE 8000 RUN python3 manage.py migrate --settings=finimize_django.settings.aws --noinput CMD python3 manage.py runserver --settings=finimize_django.settings.aws This builds fine up until the migrate RUN command, at which point the app errors because it can't find the environment variables from the EB UI. I've noticed there is an example AWS image here, which I would rather not use (for a bunch of reasons e.g. simplicity, being able to use a similar image locally, wanting control etc.). Looking at the Dockerfile this uses I can't see how they have solved this problem either. Is there something I've missed?
answer count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: dockerfile
favorite count: 0
has answer: http://stackoverflow.com/a/50325552
tagged with: docker

http://stackoverflow.com/comment/87786024
has text: I'm sorry it works but I get single quote before and after the json. Eg : **['[{"id":1,"param":"data"}]']** I don't need these single quotes when I append. How can I insert data without it?
comment on: http://stackoverflow.com/a/50384929
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/50235284
answers question: http://stackoverflow.com/q/50234922
has body: I guess you could do something like this: def symbol_switcher(arg): switcher = { 1: DICTIONARY_LETTERS_UPPER, 2: DICTIONARY_LETTERS_LOWER, 3: DICTIONARY_NUMBERS_DEC, 4: DICTIONARY_SYMBOLS } return [switcher.get(key) for key in switcher if key &amp; arg]
has comment: http://stackoverflow.com/comment/87488176
has comment: http://stackoverflow.com/comment/87487936
type: Answer
has comment: http://stackoverflow.com/comment/87488261
score: 0

http://stackoverflow.com/comment/87485778
type: Comment
has text: Do you know my requirement? I want when create the `venv` I add the packages of `/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages` to it.
comment on: http://stackoverflow.com/a/50234121
type: AnswerComment
score: 0

http://stackoverflow.com/a/50238284
answers question: http://stackoverflow.com/q/50238190
downvote count: 0
upvote count: 2
type: Answer
has body: You can't. This is a one way hash, and it's meant to be that way - it's a common practice not to store plaintext passwords on the database, so that nobody can ever see what is the users password. The general concept is that given an user password (and a salt) you are able to compute the same hash value and compare it to see if the password is correct, but you are not able to (easily) get the password by obtaining the hash. To deal with 'what if I forget my password' issue you should implement a password reset procedure.
score: 2

http://stackoverflow.com/comment/87742091
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50362013
score: 0
has text: can you provide the output of : SELECT distinct TABLE_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'PASSFAIL';

http://stackoverflow.com/a/50311623
type: Answer
has comment: http://stackoverflow.com/comment/87812058
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87812077
downvote count: 0
has body: Answer to your questions in order No the lower level files can be called anything, as you specify the path and filename in the SConscript() call Each SConscript is evaluated in it's own scope. You can pass via Export() (or SConscripts exports= argument) and bring into the SConscript (whatever you end up calling it) via Import(). Entirely depends if you want to do any central/top level configuration to be propagated to your sub projects. This could still be done via Import() statements in the subproject's SConstruct and then checking if the variable you expect to have imported is defined (via try/except perhaps) This sub project has SConstructs has been done before. Likely it's cleaner to use Import() in your SConstructs in your sub project and then verify that whatever you expect to have passed is there or not before using it. Wrapping that with copious comments as to why you are doing so if the sub projects are also used standalone.. Does this answer your question?
has comment: http://stackoverflow.com/comment/87658816
answers question: http://stackoverflow.com/q/50298132
has comment: http://stackoverflow.com/comment/87699664
has comment: http://stackoverflow.com/comment/87699665
has comment: http://stackoverflow.com/comment/87800228

http://stackoverflow.com/comment/87575507
comment on: http://stackoverflow.com/a/50278847
type: Comment
type: AnswerComment
has text: Glad to help, if this answered your question, check out [What to do if someone answers my question](https://stackoverflow.com/help/someone-answers)?
score: 0

http://stackoverflow.com/comment/87679976
type: QuestionComment
comment on: http://stackoverflow.com/q/50331895
score: 0
has text: The output you want is unclear, please edit your answer to include the desired output.
type: Comment

http://stackoverflow.com/comment/87510578
comment on: http://stackoverflow.com/a/50246196
score: 0
type: AnswerComment
has text: @Alexander - Thank you, I am thinking if `0` should be `negative` or `positive`.
type: Comment

http://stackoverflow.com/q/50301939
has body: I have multiple python projects, each with its own virtual environment. Additionally I have a global python environment. I want to share the same package files between virtual/global environments without copying them multiple times (where possible). Environment Packages ---------------------------------------- GLOBAL: A B C D VENV_1: A B C E VENV_2: C D F So, in this example: all environments will share the same files for C. GLOBAL and VENV_1 will also share files for A and B. And GLOBAL and VENV_2 will share files for D. But since E and F are not globally installed, then the virtual environments will install those packages individually. I tried using virtualenv with the --system-site-packages flag, but that just makes all global packages accessible in the virtual environment. So when I export my environment using pip freeze it will contain unnecessary packages. How can I create a virtual environment with select packages, such that if a package is globally installed, a new copy of files for that package won't be made locally? Is this possible using conda or virtualenv or any other tool? I am using Windows 10 with python 3.6.
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/50303308
favorite count: 0
has title: How to share packages between virtual environments using conda or virtualenv?
answer count: 2
score: 5
downvote count: 0
tagged with: python
tagged with: virtualenv
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68984069

http://stackoverflow.com/a/50280786
type: Answer
score: 0
has body: If you want to get more sophisticated you could define a class that defines the '&lt;' operator in the way you want. Then you can either pass a list of instances of your new class to sorted. Or you use the class constructor to generate keys. For this simple example this seems to be overkill though. class Foo(list): def __lt__(self, other): return self[1] &gt; other[1] or (self[1] == other[1] and self[0] &lt; other[0]) sorted(l, key=Foo)
answers question: http://stackoverflow.com/q/50280423

http://stackoverflow.com/q/50306521
answer count: 0
has comment: http://stackoverflow.com/comment/87629660
type: UnansweredQuestion
tagged with: python
has body: Here is my code: def get_parser(): parser.add_argument('--batch_size', default=64, help='batch size to train network') return args while True: try: images_train = np.load(path + str(batch_idx)+'images.npy') labels_train = np.load(path + str(batch_idx)+'labels.npy') break except: batch_idx = sorted(os.listdir(path)) try: batch_idx = int(batch_idx[0].split('images.npy')[0]) except: batch_idx = int(batch_idx[0].split('labels.npy')[0]) batch_idx += 400 batch_idx += 1 feed_dict = {images: images_train[0:args.batch_size], labels: labels_train[0:args.batch_size], trainable: True} The file is the npz format with shape(64,112,112,3) The code can be executed correctly with args.batch_size = 64, but there will be an error with args.batch_size = 32 as follow Traceback (most recent call last): File "&lt;ipython-input-1-646ff1e212a5&gt;", line 1, in &lt;module&gt; runfile('D:/InsightFace_TF-master/train_nets_npy_2.py', wdir='D:/InsightFace_TF-master') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/InsightFace_TF-master/train_nets_npy_2.py", line 298, in &lt;module&gt; feed_dict = {images: images_train[0:args.batch_size], labels: labels_train[0:args.batch_size], trainable: True} NameError: name 'images_train' is not defined
downvote count: 1
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/87732313
has comment: http://stackoverflow.com/comment/87629514
tagged with: tensorflow
favorite count: 0
has title: "NameError: name 'images_train' is not defined", but it is defined
type: Question

http://stackoverflow.com/q/50337244
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50337280
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/50337280
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
has title: Cannot access form fields
tagged with: python
has body: I am trying to log into this page with my credentials: https://myibd.investors.com/secure/signin.aspx When I "Inspect" it - i can see the form of class gigya-login-form But when I "View source" this form is not present. I assume that the form is loaded via JS (or something similar). I researched SO but none of the solutions helped. Mainly people advice to wait for a page to load code with waiting for the element to load for 30s 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 url = 'https://myibd.investors.com/secure/signin.aspx' driver = webdriver.Chrome() driver.get(url) myElem = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME, 'gigya-input-text'))) Returns TimeoutException: Message: - which means that the element never loads. Can someone help me to fill in that form and click submit? Thank you! UPD. I also tried going inside of iframe but that did not work as well :( code below WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("signin-iframe")) username = driver.find_element_by_name("username") username.send_keys("my_user_name") It throws ElementNotVisibleException: Message: element not visible (I tried making it visible following ideas from SO, but no luck)

http://stackoverflow.com/q/50264629
upvote count: 1
type: UnansweredQuestion
tagged with: python
has body: In my virtual environment, when I use uwsgi --ini uwsgi.ini to run the uWSGI. I get the bellow error: mapped 543168 bytes (530 KB) for 20 cores *** Operational MODE: threaded *** Traceback (most recent call last): File "Qiyun02/wsgi.py", line 18, in &lt;module&gt; from 管理员后台.网站管理.admin_website_chat.views import sio File "./管理员后台/网站管理/admin_website_chat/views.py", line 2, in &lt;module&gt; from 管理员后台.用户管理admin_usermanage.models import User File "./管理员后台/用户管理/admin_usermanage/models.py", line 6, in &lt;module&gt; from django.contrib.auth.models import AbstractUser File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/lll/repo/QmyProjectyun02/venv_dist/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in &lt;module&gt; class AbstractBaseUser(models.Model): File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/home/lll/repo/myProject/venv_dist/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 32347) spawned uWSGI worker 1 (pid: 32349, cores: 20) spawned uWSGI http 1 (pid: 32350) But in my virtual environment I use the python check, there is no issues. (venv_dist) [ldl@www myProject]$ python3 manage.py check System check identified no issues (0 silenced). …
has title: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when I run uwsgi
has answer: http://stackoverflow.com/a/50267080
score: 1
has answer: http://stackoverflow.com/a/50267795
favorite count: 0
tagged with: uwsgi
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/50330950
tagged with: python-3.x
downvote count: 4
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/50331255
accepted answer: http://stackoverflow.com/a/50331255
type: AnsweredQuestion
tagged with: list
has title: Euler 22 code not returning correct answer
answer count: 1
has body: I have been trying to do Problem 22 on Project Euler, but I cannot seem to get the right answer or see any problem with my code. I copied and pasted the contents of the txt file rather than accessing it directly from my code. https://projecteuler.net/problem=22 namelst = open(names.txt) namedict = {} alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] for x in namelst: score = 0 #creates score for each word for y in x: score += alphabet.index(y.lower())+1 #adds alphabetic score for each letter namedict[x] = score namedict = sorted(namedict.values()) #creates list of scores ordered by size scoresum = 0 for x in namedict: index = namedict.index(x)+1 scoresum += x*index #multiplies score sum by order in the list print(scoresum) Unfortunately, this leaves me with an answer of 985466567, while 871198282 is the correct answer. Is there any error in my code or method? If anyone could help that would be great!
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50253522
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/87524586
has comment: http://stackoverflow.com/comment/87524456
type: Answer
answers question: http://stackoverflow.com/q/50253429
score: -1
has body: You should try mock os.listdir to return the mock test data.

http://stackoverflow.com/q/50258021
type: Question
has comment: http://stackoverflow.com/comment/87535067
has body: I am trying to run a script with PyQt4 but Spyder gives an ModuleNotFoundError: No module named 'PyQt4' although it is installed. What am I doing wrong? I found a few threads in the net on this but I couldn't resolve the Problem. Thanks in advance Edit: This is how I import it: import sys from PyQt4.QtGui import * from PyQt4.QtCore import * and this is where I got Spyder 3 (with Anaconda): https://anaconda.org/anaconda/python
has title: PyQt4 not working on Spyder 3
has comment: http://stackoverflow.com/comment/87534593
tagged with: pyqt4
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/87582771
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87583048
has comment: http://stackoverflow.com/comment/87534678
has comment: http://stackoverflow.com/comment/87533951
has comment: http://stackoverflow.com/comment/87534988

http://stackoverflow.com/a/50294846
answers question: http://stackoverflow.com/q/50287118
has body: I think the solution is rather simple, if it is okay for you to loop once over N: import numpy as np N=4 # set some arbitrary value for the dimension M=np.reshape(np.arange(N*3), (N,3)) # create a dummy matrix out=np.zeros((2*N,N)) # output matrix with size 2N x N, all zeros out[:,:]=M[:,0] # fill each column of the matrix with the first entry of M's rows for i in range(N): out[2*i,i]=M[i,1] # fill in the second value of M at position (2i, i) out[2*i+1,i]=M[i,2] # fill in the third value of M at position (2i+1, i)
score: 0
has comment: http://stackoverflow.com/comment/87611816
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50287118
type: Answer

http://stackoverflow.com/a/50263050
type: Answer
answers question: http://stackoverflow.com/q/50262856
has comment: http://stackoverflow.com/comment/87544338
downvote count: 0
upvote count: 1
has body: You can use a while loop depending on how many times you want to print this message, along with a for loop. You can break out of the loop when you’ve printed the message as many times as you want in order to avoid an infinite loop. Here is an example. message_number = 0 while message &lt;= 4: print(“Do something” + str(message_number)) message_number += 1 time.sleep(1) This will continue to print your message so long as the message count is &lt;= 4. The loop will automatically break once we have entered four messages (I chose for because you printed “Do something” 4 times). Each time through the loop it will increment message by += 1 until we print the message four times. We can add time.sleep(1) as the last line of code so that the loop will wait 1 second before executing the code again. We also combine the string with the message count each time we iterate through the while loop.
score: 1

http://stackoverflow.com/comment/87687403
has text: `In [17]: %timeit set(dict(a).keys()) & set(b) 1.82 µs ± 18.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50335524
type: Comment

http://stackoverflow.com/q/50305232
downvote count: 0
linked to: http://stackoverflow.com/q/12032214
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87626768
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87626852
tagged with: visual-studio-code
has title: Configure output screen in visual studio code
type: UnansweredQuestion
tagged with: python
has body: In visual studio code using python .. I want to clean the output window so I want two things : 1 - Hide the file path in the output window 2- When i execute the code the output print the result one after one ... I want the recent code over right the previous one
answer count: 0

http://stackoverflow.com/comment/87767716
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50375710
type: Comment
has text: A minor comment, I think `list()` over a range is redundant.

http://stackoverflow.com/comment/97835878
score: 0
comment on: http://stackoverflow.com/q/50364706
has text: Thank you @Sanchit. In the end I have used the preprocessing and experimented with different dense layers which did give a good result as you suggested. However, because my classifier was also reliant on some metadata for each image which I couldn't put into my network without heavily modifying the architecture, I ended up using bottleneck layer (merged with metadata) as an input for next classifiers.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50286334
answers question: http://stackoverflow.com/q/50286093
has body: Just assign A to something else. As @juanpa.arrivillaga said, Python will take care of the now "un-referenced" array and do any garbage collection itself. e.g. A = "new string"
type: Answer
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/87803337
has text: Still thinking if the `reduce` usage is worth it here. GvR tells to avoid `reduce` at almost any situation but in this particular case it is not really bad I guess.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50356786
type: AnswerComment

http://stackoverflow.com/comment/87626968
has text: Did you get the same results as Matlab as stated in the question? I followed an approach similar to yours, and based on the picture, the answer I got was `a = 0.00282551+0.00189634j`, `b = -0.03993077+0.12785669j`, and `c = -1.79188211-0.29308452j`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50305136

http://stackoverflow.com/comment/87565655
score: 0
has text: So the problem is not computing the initial list of precedents, right? That would be an input in this case?
comment on: http://stackoverflow.com/q/50274164
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87485571
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50231415
has text: @user3399495 That should be fixed now

http://stackoverflow.com/a/50307182
answers question: http://stackoverflow.com/q/50306898
type: Answer
has comment: http://stackoverflow.com/comment/87630635
score: 2
has body: You're using Python mappings of names to object differently than how they work (you might be confused by other languages' references). When you use for df in [A, B]: df = pd.concat([df, C], axis=1) Then df on the right side means "the object mapped to by the name df" (that is, A then B). df on the left side is just the name df. Your loop is therefore not modifying the original objects at all. You can use A, B = pd.concat([A, C], axis=1), pd.concat([B, C], axis=1) If you really must use a loop, you can use a dict. First place the object there, dfs = {'A': A, 'B': B} then refer to them only through the dict: for k, v in dfs.items(): dfs[k] = pd.concat([v, C], axis=1)
accepted answer of: http://stackoverflow.com/q/50306898
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87757208
comment on: http://stackoverflow.com/a/50369919
type: Comment
score: 0
type: AnswerComment
has text: Hi @Rumoku, thanks for your answer. After executing your line of code I get the following message: "TypeError: 'str' object is not callable". I wonder if maybe the function StringType() is the one that is causing problem in that line? I imported the module naturally with: "from pyspark.sql.types import StringType", previously.

http://stackoverflow.com/q/50256984
favorite count: 0
type: AnsweredQuestion
has title: Changing 2-dimensional list to standard matrix form
accepted answer: http://stackoverflow.com/a/50257104
tagged with: matrix
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/50257104
has body: org = [['A', 'a', 1], ['A', 'b', 2], ['A', 'c', 3], ['B', 'a', 4], ['B', 'b', 5], ['B', 'c', 6], ['C', 'a', 7], ['C', 'b', 8], ['C', 'c', 9]] I want to change the 'org' to the standard matrix form like below. transform = [['\t','A', 'B', 'C'], ['a', 1, 4, 7], ['b', 2, 5, 8], ['c', 3, 6, 9]] I made a small function that converts this. The code I wrote is below: import numpy as np def matrix(li): column = ['\t'] row = [] result = [] rest = [] for i in li: if i[0] not in column: column.append(i[0]) if i[1] not in row: row.append(i[1]) result.append(column) for i in li: for r in row: if r == i[1]: rest.append([i[2]]) rest = np.array(rest).reshape((len(row),len(column)-1)).tolist() for i in range(len(rest)): rest[i] = [row[i]]+rest[i] result += rest for i in result: print(i) matrix(org) The result was this: &gt;&gt;&gt;['\t', 'school', 'kids', 'really'] [72, 0.008962252017017516, 0.04770759762717251, 0.08993156334317577] [224, 0.004180594204995023, 0.04450803342634945, 0.04195010047081213] [385, 0.0021807662921382335, 0.023217182598008267, 0.06564858527712682] I don't think this is efficient since I use so many for loops. Is there any efficient way to do this?
type: Question
tagged with: numpy
tagged with: python-3.x
answer count: 2
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/50258327
tagged with: python
has answer: http://stackoverflow.com/a/50258327

http://stackoverflow.com/q/50271439
has answer: http://stackoverflow.com/a/50271549
has title: E: Unable to locate package python-image
downvote count: 5
tagged with: python
score: -4
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87559955
has body: I use This command for installation but I face this error: sudo apt-get install -y python-opencv python-picamera python-image python-pyexiv2 Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package python-image
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50271549
type: Question

http://stackoverflow.com/q/50325649
has answer: http://stackoverflow.com/a/50325927
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50325927
has title: pulling selective data from database server in python based on conditions
tagged with: python
tagged with: psycopg2
tagged with: postgresql
type: AnsweredQuestion
score: 0
has body: I have the below data: per_id month_id area_grp area_hrs level 754 201803 WNY 19.93 OVue 754 201802 MT 0.52 OVue 754 201802 WBS 0.34 OVue 754 201801 WYW 33.04 OVue 754 201801 VC 16.62 OVue 754 201801 PX 3.05 OVue 754 201712 RZN 5.05 OVue 754 201711 WYW 17.85 OVue 754 201711 NLN 0.8 OVue 754 201711 DJr 45.67 OVue 754 201711 TC 11.81 OVue 754 201710 MBN 1.61 OVue 754 201709 WAD 4.72 OVue 754 201709 DJr 23.82 OVue **147 201803 WBC 13.44 OVue 147 201803 WBS 4.17 OVue 147 201803 WYW 1.80 OVue 147 201802 VD 5.14 OVue 147 201802 LNY 0.05 OVue 147 201801 LEIF 6.94 OVue 147 201801 WBC 25.35 OVue 147 201801 VD 8.53 OVue** 147 201712 MVR 7.17 OSver 147 201711 WDA 9.89 OSver 147 201711 YS 1.65 OSver 147 201711 N1T 3.02 OSver 147 201710 LEIF 1.83 OSver 147 201710 Hi 3.15 OVue 147 201710 TLD 1.43 OVue 147 201710 WBC 21.56 OSver 147 201710 NTT 2.88 OSver 147 201710 WBS 5.64 OSver 147 201710 LNY 2.67 OSver 147 201710 BRV 2.91 OSver 147 201710 N1T 3.78 OSver Above is a sample of my data , sorted on the 1st and columns here. This data resides in a table in postgresql and I construct a query based on a parameter level. level_list = ['OSver','Ovue'] for i in range(0,len(level_list)): sql_per_hours = str("""select * from table_name where level = %s ;""") \ %("'"+''.join(level_list[i]) + "'") df_net = pd.read_sql(sql_per_hours,cnxn) Now, for per_id 754 since he has worked under a single level all records for him should be fetched. But for people who have worked across more than 1 level. Only the latest level info should be taken. So for per_id 147 only the top 8 records must be selected to be fetched. latest level is the value in level for each per_id where the month_id is max. So from that row , till there is a break in the value, rows are taken. How can I construct this sql query and call it from python? This will also help me reduce the data I am pulling for each level in level_list. Expected Output as df_net: per_id month_id area_grp area_hrs level 754 201803 WNY 19.93 OVue 754 20180…

http://stackoverflow.com/q/50252468
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/50252607
has comment: http://stackoverflow.com/comment/87522994
tagged with: opencv
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50253455
has title: Fill image up to a size with Python
linked to: http://stackoverflow.com/q/36255654
has body: I am writing a handwriting recognition app and my inputs have to be of a certain size (128x128). When I detect a letter it looks like this: That image for instance has a size of 40x53. I want to make it 128x128, but simply resizing it lowers the quality especially for smaller images. I want to somehow fill the rest up to 128x128 with the 40x53 in the middle. The background color should also stay relatively the same. I am using Python's opencv but I am new to it. How can I do this, and is it even possible?
has answer: http://stackoverflow.com/a/50253455
tagged with: image
has answer: http://stackoverflow.com/a/50252607
type: Question

http://stackoverflow.com/a/50391412
type: Answer
answers question: http://stackoverflow.com/q/50384704
score: 0
has body: You need to add headers in requests and call correct class i.e; zloOqf kpS1Ac vk_gy in BeautifulSoup module: #code: import requests headers = {"User-Agent": "Mozilla/5.0(Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36"} url = "https://www.google.co.in/search?rlz=1C1CHBD_enIN789IN790&amp;ei=iWj5WouoDsfGvgSr16bwDg&amp;q=United+States%09KEEP+SMILIN+FAMILY+DENTAL%092281+N+ZARAGOZA+RD+STE+102&amp;oq=United+States%09KEEP+SMILIN+FAMILY+DENTAL%092281+N+ZARAGOZA+RD+STE+102&amp;gs_l=psy-ab.12...1153407.1153407.0.1154512.0.0.0.0.0.0.0.0..0.0....0...1c.1.64.psy-ab..0.0.0....0.YvWjU-kIBUs" from bs4 import BeautifulSoup s=requests.get(url, headers=headers) soup =BeautifulSoup(s.content,'html.parser') data= soup.findAll("div",{"class":"zloOqf kpS1Ac vk_gy"}) print data final_output= data[0].find("span") print final_output.text output: Dental clinic in El Paso, Texas

http://stackoverflow.com/q/50251570
has answer: http://stackoverflow.com/a/50280373
tagged with: animation
tagged with: python
has comment: http://stackoverflow.com/comment/87525430
has title: Speeding up an animation in matplotlib
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87532916
has body: I am trying to figure out how to speed up this animation. I want the whole thing to finish at 30 seconds. I've tried adjusting the interval between frames, the save count, inside FuncAnimation, but it doesn't seem to work. Is there anyway to just set the total duration and have matplotlib squeeze everything into that time limit? import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation #1 n = 500 x = np.random.randn(n) %matplotlib notebook # generate 4 random variables from the random, gamma, exponential, and uniform distributions x1 = np.random.normal(-2.5, 1, 10000) x2 = np.random.gamma(2, 1.5, 10000) x3 = np.random.exponential(2, 10000)+7 x4 = np.random.uniform(14,20, 10000) def update(curr): # check if animation is at the last frame, and if so, stop the animation a if curr == n: a.event_source.stop() plt.cla() plt.hist(x1[:curr], normed=True, bins=20, alpha=0.5) plt.hist(x2[:curr], normed=True, bins=20, alpha=0.5) plt.hist(x3[:curr], normed=True, bins=20, alpha=0.5) plt.hist(x4[:curr], normed=True, bins=20, alpha=0.5) plt.axis([-7,21,0,0.6]) plt.text(x1.mean()-1.5, 0.5, 'Normal') plt.text(x2.mean()-1.5, 0.5, 'Gamma') plt.text(x3.mean()-1.5, 0.5, 'Exponential') plt.text(x4.mean()-1.5, 0.5, 'Uniform') plt.annotate('n = {}'.format(curr), [3,27]) fig = plt.figure() fig = plt.figure(figsize=(9,3)) a = animation.FuncAnimation(fig, update, interval=10, blit=True, save_count=500) The final product looks like this:
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87579604
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/42910622
type: UnansweredQuestion
tagged with: matplotlib

http://stackoverflow.com/comment/87528600
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50254155
has text: I use Python 2.

http://stackoverflow.com/q/50376532
type: Question
score: 0
has answer: http://stackoverflow.com/a/50377071
tagged with: python
tagged with: string
answer count: 1
has body: I would like to remove the \t from the second token. Was trying something with loops but was not successful. Any help please? import re regex = re.compile(r'[\t]') for sent in train_sents: for tuples in sent: print tuples[1] [('O', 'Identification\t'), ('O', 'of\t'), ('O', 'APC2,\t'), ('O', 'a\t'), ('O', 'homologue\t'), ('O', 'of\t'), ('O', 'the\t'), ('B-DISEASE', 'adenomatous\t'), ('I-DISEASE', 'polyposis\t'), ('I-DISEASE', 'coli\t'), ('I-DISEASE', 'tumour\t'), ('O', 'suppressor\t'), ('O', '.\t')], [('O', 'The\t'), ('B-DISEASE', 'adenomatous\t'), ('I-DISEASE', 'polyposis\t'), ('I-DISEASE', 'coli\t'), ('I-DISEASE', '(\t'), ('I-DISEASE', 'APC\t'), ('I-DISEASE', ')\t'), ('I-DISEASE', 'tumour\t'), ('O', '-suppressor\t'), ('O', 'protein\t'), ('O', 'controls\t'), ('O', 'the\t'), ('O', 'Wnt\t'), ('O', 'signalling\t'), ('O', 'pathway\t'), ('O', 'by\t'), ('O', 'forming\t'), ('O', 'a\t'), ('O', 'complex\t'), ('O', 'with\t'), ('O', 'glycogen\t'), ('O', 'synthase\t'), ('O', 'kinase\t'), ('O', '3beta\t'), ('O', '(\t'), ('O', 'GSK-3beta\t'), ('O', ')\t'), ('O', ',\t'), ('O', 'axin\t'), ('O', '/\t'), ('O', 'conductin\t'), ('O', 'and\t'), ('O', 'betacatenin\t'), ('O', '.\t')]
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87769313
has title: Remove \t from a list of lists
has comment: http://stackoverflow.com/comment/87769260
accepted answer: http://stackoverflow.com/a/50377071

http://stackoverflow.com/q/50269160
has answer: http://stackoverflow.com/a/50269484
type: UnansweredQuestion
has body: I want to compare two dictionaries. One is a template, and one is stored in a specific file. The code is this: #!/usr/bin/env python import json template = {"giorno": 21, "mese": "aprile", "ora": "21"} newww = "palestra.json" g_temp = template['giorno'] with open(newww, 'r') as f: n_temp = json.load(f) print n_temp n_temp_new = json.dumps(n_temp, ensure_ascii=False) print(n_temp_new) if g_temp == n_temp_new['giorno']: print("no") else: print("yes") palestra.json : {"giorno": 21, "mese": "aprile", "ora": "21"} output: {u'giorno': 21, u'mese': u'aprile', u'ora': u'21'} {"giorno": 21, "mese": "aprile", "ora": "21"} Traceback (most recent call last): File "./prova.py", line 25, in &lt;module&gt; if g_temp == n_temp_new['giorno']: TypeError: string indices must be integers How can I compare these two dictionaries?
has comment: http://stackoverflow.com/comment/87561628
tagged with: python
has comment: http://stackoverflow.com/comment/87555942
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87555990
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has title: Compare two json dictionary in Python
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87555610
has text: @EdChum Ah yes, it's a .22 thing. Although I should mention that it's got issues in terms of backwards compatibility pandas code and is a few microseconds slower than `notnull` to boot. Pandas devs are weird... xD
comment on: http://stackoverflow.com/a/50268265
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50308021
type: Answer
has body: So this is just one way to take all of your values and calculate the average. input_file = input("enter file name: ") open_file = open(input_file, 'r') Here I just put all of your values into notepad and read through it grades_list = [] for grade in open_file: grade_format = grade.strip() #how to remove extra blank space grades_list.append(grade_format) Then I used a for-loop to go through each line and put the grades into a list grade_convert = [] #new list for all of the converted values for grade in grades_list: convert = float(grade) #convert each value in the list into a float grade_convert.append(convert) I used another list for converted each value grade_convert = sorted(grade_convert) #very first element will be the lowest grade_convert.pop(0) #permanently removes the very first item grade_total = 0 #set a counter for grade in grade_convert: grade_total += grade #add all of the values to the counter grade_average = grade_total / len(grade_convert) #len is number of items print(grade_average)
answers question: http://stackoverflow.com/q/50307582
score: 0
accepted answer of: http://stackoverflow.com/q/50307582
type: AcceptedAnswer

http://stackoverflow.com/a/50312169
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50312134
score: 3
type: Answer
has body: Since you mentioned np.unique, it accepts a second argument called return_counts: u, c = np.unique(a, return_counts=True) c[i] is the corresponding count for u[i].

http://stackoverflow.com/comment/87663687
has text: You can, but it gets turned into a list anyway.
comment on: http://stackoverflow.com/q/50323707
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87549677
type: Comment
has text: Try increasing the fetch size this is the only way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50246378

http://stackoverflow.com/a/50271718
type: Answer
answers question: http://stackoverflow.com/q/50271354
score: 2
upvote count: 2
downvote count: 0
has body: In a given scope, you can only reference a variable's name from one given scope. Your variable cannot be global at some point and local later on or vice versa. For that reason, if x is ever to be declared in a scope, Python will assume that you are refering to the local variable everywhere in that scope, unless you explicitly state otherwise. This is why you first function, greet, works. The variable name is unambiguously coming from the closure. Although, in func2 the variable x is used in the scope and thus you cannot reference the x from the closure unless explicitly stating otherwise with nonlocal. The following errors might enlighten us on this. A variable cannot become global after use def func1(): x = 20 def func2(): print("x is ", x) global x print("Changed the local x to ",x) func2() This raises a SyntaxError: name 'x' is used prior to global declaration. This means that the closure's x cannot be used and then the global one. A global variable cannot become local Here is another case using global at the top of func2. def func1(): x = 20 def func2(): global x print("x is ", x) x = 2 print("Changed the local x to ",x) func2() This code was exectued without error, but notice that the assignment to x updated the global variable, it did not make x become local again.

http://stackoverflow.com/q/50300148
has title: Tensorflow Print fixing shape issues?
has comment: http://stackoverflow.com/comment/87618470
has body: I'm running across a very weird issue and was hoping to get someone who might be a bit more familiar. I'm attempting a basic LSTM to do some binary classification with the following coding: class FakeData(object): def __init__(self, n): self.x = np.random.randint(4, size=(n, 90, 4)) blah = np.random.randint(2, size=(n)) self.y = np.zeros((n,2)) self.y[:,0] = blah self.y[:,1] = 1 - blah self.mask = np.arange(n) self.cnt = 0 self.n = n def getdata(self, n): if self.cnt + n &gt; self.n: np.randoom.shuffle(self.mask) self.cnt = 0 mask = self.mask[self.cnt : self.cnt + n] return self.x[mask], self.y[mask] n_data = 10000 batch_size = 10 fd = FakeData(n_data) n_units = 200 n_classes = 2 x = tf.placeholder(tf.float32, shape=[None, 90, 4]) y_ = tf.placeholder(tf.float32, shape=[None, n_classes]) dropout = tf.placeholder(tf.float32) w_out = tf.Variable(tf.truncated_normal([n_units, n_classes])) b_out = tf.Variable(tf.truncated_normal([n_classes])) lstm = tf.contrib.rnn.LSTMCell(n_units) cell = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=1.0 - dropout) new_x = tf.unstack(x, 90, 1) new_x = tf.Print(new_x, [tf.shape(new_x)], message='newx is: ') output, state = tf.nn.dynamic_rnn(cell, new_x, dtype=tf.float32) output = tf.Print(output, [tf.shape(output)], message='output is: ') logits = tf.matmul(output[-1], w_out) + b_out logits = tf.Print(logits, [tf.shape(logits)], message='logits is: ') preds = tf.nn.softmax(logits) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_)) training = tf.train.GradientDescentOptimizer(0.5).minimize(loss) correct = tf.equal(tf.argmax(preds, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) # with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(10): batch_x, batch_y = fd.getdata(batch_size) sess.run([training], feed_dict={x: batch_x, y_: batch_y, dropout: 0}) if i % 100 == 0: print "Accuracy {}".format(accuracy.eval(feed_dict={x: batch_x, y_: bat…
accepted answer: http://stackoverflow.com/a/50357819
tagged with: python
has answer: http://stackoverflow.com/a/50357819
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87618425
has comment: http://stackoverflow.com/comment/87618568
answer count: 1
tagged with: tensorflow
type: Question

web-crawler
tags question: http://stackoverflow.com/q/50260803
tags question: http://stackoverflow.com/q/50323614
tags question: http://stackoverflow.com/q/50260744
tags question: http://stackoverflow.com/q/50243572
tags question: http://stackoverflow.com/q/50343117
tag name: web-crawler
tags question: http://stackoverflow.com/q/50272194
tags question: http://stackoverflow.com/q/50299868
tags question: http://stackoverflow.com/q/50342603
type: Tag

http://stackoverflow.com/comment/87551137
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50266526
has text: @DileeshDil - For me it working nice, but added alternatives with `iloc` or `iat`, please check edited answer.
type: Comment

http://stackoverflow.com/q/50351830
has comment: http://stackoverflow.com/comment/87722344
has comment: http://stackoverflow.com/comment/87722219
tagged with: python
tagged with: c9.io
has comment: http://stackoverflow.com/comment/87724066
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50354444
has body: I migrated my workspace from C9.io to Codeanywhere, and on C9.io my scripts worked fine; my scripts being a python terminal game/app that I've been working on. I have a test script to run the functions I've created so far, and the player.py file for creating different classes and player objects, with saving, loading, etc. On C9.io, this is the output. Strength: 15 Agility: 10 Critical Chance: 25 Spell Power: 15 Intellect: 5 Speed: 5 --- Health: 100/100 Stamina: 10 Armor: 20 Resilience: 2 --- Strength: 20.25 Agility: 10 Critical Chance: 43.75 Spell Power: 15 Intellect: 5 Speed: 4.0 --- Health: 100/100 Stamina: 7.5 Armor: 16.0 Resilience: 1.4 --- # more test info regarding other scripts But when I run the test script on Codeanywhere, this is what happens. Strength: 15 Strength: 15 Agility: 10 Critical Chance: 25 Spell Power: 15 Intellect: 5 Speed: 5 --- Health: 100/100 Stamina: 10 Armor: 20 Resilience: 2 --- Traceback (most recent call last): File "test.py", line 7, in &lt;module&gt; player2 = BerserkerCharacter('Jon', 'Snow') File "/home/cabox/workspace/grimside/assets/player.py", line 93, in __init__ super().__init__() TypeError: super() takes at least 1 argument (0 given) I've tried putting self infront of the super().__init__(), as well as throwing self in the argument, and I'm not that skilled in Python so I don't know what to fix. Here's my scripts. test.py from assets import * player = BaseCharacter() player.show_player_stats("offensive") print('---') player.show_player_stats("defensive") print('---') player2 = BerserkerCharacter('Jon', 'Snow') player2.show_player_stats("offensive") print('---') player2.show_player_stats("defensive") print('---') #more test info regarding other scripts player.py #import functions used by script #random is a math function used for creating random integers import random #pickle is for saving/loading/writing/reading files import pickle #sys is for system-related functions, such as quitting the program import sys #create a class ca…
answer count: 1
has comment: http://stackoverflow.com/comment/87722320
tagged with: codeanywhere
has title: Codeanywhere error on script vs C9.io working fine
has comment: http://stackoverflow.com/comment/87720600
type: Question
accepted answer: http://stackoverflow.com/a/50354444
has comment: http://stackoverflow.com/comment/87722425
has comment: http://stackoverflow.com/comment/87724027
has comment: http://stackoverflow.com/comment/87723872

http://stackoverflow.com/a/50359648
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50359526
has body: I think the other way around is easier. Multiply your predicted values by the exact zero you have, and the gradients for that element will simply not propagate. def customLoss(true,pred): nonZeroTrue = K.cast(K.not_equal(true,0),K.floatx()) maskedPred = pred * nonZeroTrue return anyStandardLoss(true,maskedPred) Where anyStandardLoss may be, for 'mse': K.mean(K.square(maskedPred - true), axis=-1) You can import loss functions from keras.losses and use there too.
score: 1

http://stackoverflow.com/comment/87534582
has text: Possible duplicate of [Get pip to work with git and github repository](https://stackoverflow.com/questions/14737500/get-pip-to-work-with-git-and-github-repository)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50249571
type: Comment

http://stackoverflow.com/q/50258168
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50264402
tagged with: sql
has body: I'm working with PostgreSQL 10 and Python 3. I know how to o simple selects or joins, buy I have issues when need to combine 4 tables related 2 by 2. I mention, that I use Phyton, in case is necessary to combine queries using code. I have the following tables: Company, CompanyLogo, Product, ProductImage, with the following Relations: Company Logo O1O with Company Product has FK to Company ProductImage FK with Product Structure Company Id | slug 1 1 Logo Id | path | company_id 1 url 1 ----------- Product Id | company_id 1 1 2 1 ProductImage Id | path | product_id 1 url 1 2 url 1 3 url 1 I need: Get list of all companies, and for each company get: the company slug the logo up to 3 products and their first image Get one company based on id and: the company slug the logo all product and their first image
has title: Geeting results from multipe(4) tables joins using SQL or code if needed (python)
answer count: 1
has comment: http://stackoverflow.com/comment/87535264
type: Question
tagged with: postgresql
score: 0
accepted answer: http://stackoverflow.com/a/50264402
tagged with: join
tagged with: python
has comment: http://stackoverflow.com/comment/87534864

http://stackoverflow.com/q/50308794
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87633540
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50308952
accepted answer: http://stackoverflow.com/a/50308914
has answer: http://stackoverflow.com/a/50308952
has answer: http://stackoverflow.com/a/50308978
favorite count: 0
type: Question
has body: I have a dataframe that looks like this customer Start_date End_date 100 2016-06-01 2018-01-01 101 2017-06-01 2019-01-01 102 2016-04-01 2017-04-01 103 2015-06-03 2016-01-01 104 2016-06-01 2018-01-01 Now I want to create a dataframe with a period index that has a column with a count of the amount of customer for each of its periods that looks like this: Period Customers 2017-01 3 2017-02 5 2017-03 8 2017-04 9 I have written a custom for loop to do it but it is VERY inefficient. There must be a faster way that uses the pandas functionality to get this done. Any help is greatly appreciated!
has answer: http://stackoverflow.com/a/50308914
has title: counting rows that fall in a period with pandas
tagged with: python

http://stackoverflow.com/a/50310569
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50310397
upvote count: 2
downvote count: 0
type: Answer
has body: A pixel is the smallest unit of an image, it corresponds to a how bright a single light on a monitor is (3 lights for RGB). You can not have half an element that takes up half a pixel, as a pixel is already the smallest unit of an image. If you have a 4x4 grid of lights you can turn them on to make a 4x4 square, as well as a 3x3, 2x2 and 1x1 (single light on) but you cant make a 0.5x0.5 square.
score: 2
answers question: http://stackoverflow.com/q/50310397

http://stackoverflow.com/q/50333033
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
has title: Installing matplotlib on Python 3.5.2 | Ubuntu 16.04 LTS
answer count: 3
has answer: http://stackoverflow.com/a/50333119
has body: I tried to install matplotlib by command line: sudo env 'PATH=$PATH:/home/lukasz/.local/bin' pip install matplotlibpip install --upgrade setuptools But this error occured: sudo env 'python setup.py egg_info" failed with error code 1 I was following steps from pip install returns "python setup.py egg_info" failed with error code 1 but i had error with command pip install --upgrade setuptools: PermissionError: [Errno 13] Permission denied: '/usr/lib/python3/dist-packages/__pycache__/easy_install.cpython-35.pyc. What can I do next?
has comment: http://stackoverflow.com/comment/87682220
linked to: http://stackoverflow.com/q/35991403
has answer: http://stackoverflow.com/a/55558958
has answer: http://stackoverflow.com/a/50333139

http://stackoverflow.com/comment/87700120
type: AnswerComment
has text: thanks so much, is there a way that I can replace the HTML in tripple quotes with my own HTML?.
score: 0
comment on: http://stackoverflow.com/a/50333409
type: Comment

http://stackoverflow.com/comment/87574108
type: Comment
type: QuestionComment
score: 0
has text: @gushitong Same error when I try to get the type
comment on: http://stackoverflow.com/q/50278592

http://stackoverflow.com/comment/87650458
score: 0
comment on: http://stackoverflow.com/q/50317308
has text: just type b when the question appears and then two figures will be showen
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88093524
score: 0
comment on: http://stackoverflow.com/q/50367739
type: Comment
has text: What version of DRF are you using?
type: QuestionComment

http://stackoverflow.com/a/50356056
upvote count: 22
score: 22
answers question: http://stackoverflow.com/q/50355487
type: Answer
has body: You have to give the full path to load_dotenv import os from dotenv import load_dotenv # Get the path to the directory this file is in BASEDIR = os.path.abspath(os.path.dirname(__file__)) # Connect the path with your '.env' file name load_dotenv(os.path.join(BASEDIR, '.env')) test_var = os.getenv("TEST_VAR") print(test_var)
downvote count: 0

http://stackoverflow.com/comment/87750640
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50366567
has text: I appreciate you taking the time to reply but I guess what I'm struggling with is more the concepts... I guess I'm obviously struggling with the code too but I was hoping more for some reading material or similar to help make the concepts stick. I don't even know the right words to ask about the concepts being employed. All the same, thanks

http://stackoverflow.com/comment/87628355
type: AnswerComment
score: 0
has text: But what will happen if you don’t declare namespace_packages=[“m_lib”]?
type: Comment
comment on: http://stackoverflow.com/a/50282888

http://stackoverflow.com/comment/87590727
type: QuestionComment
score: 0
has text: You need to show us what `close` is. A dataframe with what dimensions? what index?
comment on: http://stackoverflow.com/q/50287314
type: Comment

http://stackoverflow.com/q/50361502
has comment: http://stackoverflow.com/comment/87739514
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/87739531
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/87739517
has comment: http://stackoverflow.com/comment/87739543
has answer: http://stackoverflow.com/a/50361587
has comment: http://stackoverflow.com/comment/87739542
has answer: http://stackoverflow.com/a/50361668
has comment: http://stackoverflow.com/comment/87745622
tagged with: python-2.7
score: 0
has title: Can't figure out why appending to list isn't working
answer count: 3
has comment: http://stackoverflow.com/comment/87739738
favorite count: 0
has comment: http://stackoverflow.com/comment/87760556
type: Question
has body: I'm looping through a list to generate some json. But I have an error when i append to listToSave. listToSave = [] for i in range(len(ffts)): dataT = dataTemplate dataT['aClip']['info']['id'] = str(uuid.uuid4()) #More stuff added here print dataT['aClip']['info']['id'] listToSave.append(dataT) print 'Data formated - Ready to save' And the output: 493838a3-de8e-4bc4-86a4-92999bd625bd c7c6f984-85b5-478b-9395-48ebd8611ab8 d427dd05-063c-49de-bbff-70b09c56f1fa 98dc6ef5-182d-4963-bc0d-7537bd3ca9e2 74587d54-811c-485e-bbed-1428723a6da1 5052f46e-371d-4bec-b750-e231abd3448d Data formated - Ready to save But, when I look at listToSave list, I just see the last value generated repeated. print len(toSave) print toSave[0]['aClip']['info']['id'] print toSave[1]['aClip']['info']['id'] print toSave[2]['aClip']['info']['id'] print toSave[3]['aClip']['info']['id'] print toSave[4]['aClip']['info']['id'] print toSave[5]['aClip']['info']['id'] Output: 6 5052f46e-371d-4bec-b750-e231abd3448d 5052f46e-371d-4bec-b750-e231abd3448d 5052f46e-371d-4bec-b750-e231abd3448d 5052f46e-371d-4bec-b750-e231abd3448d 5052f46e-371d-4bec-b750-e231abd3448d 5052f46e-371d-4bec-b750-e231abd3448d Help? dataTemplate for a complete example. Although, I believe I tried it without this and it still ran. dataTemplate = { "aClip": { "info" : { "id" : None, "type" : None, "author" : None, "timeStamp" : None, "output" : None, }, "t": { "tData": None, "tFs" : None, "tLen" : None, }, "f" : { "fData" : None, "fFreq" : None, "fLen" : None, } } }
has answer: http://stackoverflow.com/a/50361558

redis
tags question: http://stackoverflow.com/q/50360981
tags question: http://stackoverflow.com/q/50305601
type: Tag
tags question: http://stackoverflow.com/q/50328971
tags question: http://stackoverflow.com/q/50318875
tag name: redis
tags question: http://stackoverflow.com/q/50381338

http://stackoverflow.com/a/68104055
answers question: http://stackoverflow.com/q/50340906
score: 0
has body: just run: python manage.py run --run-syncdb
has comment: http://stackoverflow.com/comment/133943818
type: Answer

codec
tags question: http://stackoverflow.com/q/50278679
tag name: codec
type: Tag

http://stackoverflow.com/q/50261578
linked to: http://stackoverflow.com/q/20107414
tagged with: python
has answer: http://stackoverflow.com/a/75183977
answer count: 2
has body: I am trying to render a wordcloud that I can run on my computer w/o flask. I am using this question as a base Route @app.route('/wordcloud/&lt;vendor_duns&gt;') def images(vendor_duns): words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all() # t = [r.__dict__ for r in words] # print(t) one_row = list(itertools.chain.from_iterable(words)) text = ' '.join(one_row) return render_template("wordcloud.html", text=text) @app.route('/fig/&lt;vendor_duns&gt;') def fig(vendor_duns): # TODO add test model and query words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all() one_row = list(itertools.chain.from_iterable(words)) text = ' '.join(one_row) wordcloud = WordCloud().generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") img = BytesIO() plt.savefig(img) img.seek(0) return send_file(img, mimetype='image/png') Template {% extends "base.html" %} {% block title %}Wordcloud{% endblock %} {% block content %} {{text}} &lt;div&gt; &lt;img src="{{ url_for('sam.fig', vendor_duns=vendor_duns) }}" alt="Image Placeholder" height="100"&gt; &lt;/div&gt; {% endblock %} First off the {{text}} in the template is just for view. If I nav to a specific vendor_duns I will get a long string of text, but no image. So two questions, where exactly do I need to run the query? in the fig or image function. The second question, I get a blank image, so I am not sure exactly how to write the wordcloud to a buffer.
has answer: http://stackoverflow.com/a/50263394
has title: Flask render a word cloud
type: UnansweredQuestion
tagged with: flask
type: Question
score: 0
tagged with: matplotlib

http://stackoverflow.com/a/50303668
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50281842
type: Answer
accepted answer of: http://stackoverflow.com/q/50281842
score: 0
has body: The only way I found was by getting the list Smiles, convert them to Mols and then to Fingerprints. The list of fingerprints and molecules are of the same size and order therefore Fingerprints[0] == Mols[0] in terms of the molecule they are representing. Clustering fingerprints returns the index of the fingerprint in the list, thus the indexes may be used to retrieve the molecule from the Mol list. I do not think that it is the cleanest solution, but works.

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/50307579
tag name: deconvolution

http://stackoverflow.com/q/50322172
favorite count: 0
linked to: http://stackoverflow.com/q/845058
tagged with: stdin
score: 1
tagged with: python
has body: I am writing a python script that takes input from stdin and would like to keep track of the line number of the input from stdin. I could create a counter myself, but I have a feeling that python automatically keeps track of the line number, and thus it would be a waste of computation. I have not found how to get/print that number though. I have read about and tried the .tell() method, but it tracks characters (or bytes) and not lines. Also it seems to fail when input is from stdin. It throws IOError: [Errno 29] Illegal seek My test script "pythonTest.py" looks like: import sys with sys.stdin as file: for line in file: print(line.rstrip()) # Neat way to print the line number Upon executing the one above (as it is now): $ echo 'asdf asdf asdf asdf' | python pythonTest.py adsf asdf asdf asdf I want: $ echo 'asdf asdf asdf asdf' | python pythonTest.py adsf 1 asdf 2 asdf 3 asdf 4 Is there a nice and pythonic way to do this, or is the standard solution to just add your own counter to the for-loop?
tagged with: line-count
type: Question
answer count: 0
type: UnansweredQuestion
has title: Pythonic way to keep track of line number in stdin
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/845058

http://stackoverflow.com/comment/87656677
comment on: http://stackoverflow.com/a/50320464
type: Comment
type: AnswerComment
has text: got an error : return self.attrs[key] KeyError: 'href'
score: 0

http://stackoverflow.com/comment/87634446
type: Comment
comment on: http://stackoverflow.com/a/50306427
type: AnswerComment
score: 1
has text: This is quite an inefficient method of getting the 'minutes' field - 1) format time as a string - HH-MM-SS, 2) retrieve a substring containing only the minutes - why specify the others if you don't want them? 3) parse the string and convert to integer.

http://stackoverflow.com/q/50341598
has comment: http://stackoverflow.com/comment/87699762
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87699347
tagged with: datetime-format
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 3
has body: I have a DataFrame which has dates as string in the form '%m-%d' and I want to convert it to dayofyear format, how do I do that?
favorite count: 0
type: Question
has title: Convert %m-%d to dayofyear format
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50349683
type: UnansweredQuestion

http://stackoverflow.com/q/50345072
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87706226
upvote count: 1
tagged with: scikit-learn
has body: I want to save a keras.wrappers.scikit_learn.KerasClassifier. I used the model.save method as Keras recommends but when I load my model the model is a keras.models.Sequential instead of a keras.wrappers.scikit_learn.KerasClassifier. This is a problem because when I want to make the prediction I have an output with this shape: array([[0.21577413, 0.37268943, 0.13626885, 0.2752676 ], [0.22569732, 0.34428614, 0.15705906, 0.2729574 ], [0.24492404, 0.27987108, 0.21357943, 0.2616254 ], [0.24831992, 0.26592442, 0.22779736, 0.25795835], [0.24938227, 0.26125908, 0.23273101, 0.25662765]], dtype=float32) Instead of this output that I want it array([3, 3, 3, 3, 3], dtype=int64) So my question is, how could I save and load the keras.wrappers.scikit_learn.KerasClassifier? Maybe is there another problem that is changing the output' shape of my predictions? Thanks
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has title: Keras save model and load model changing shape of predictions
has comment: http://stackoverflow.com/comment/87746868
tagged with: python
has comment: http://stackoverflow.com/comment/87705999

http://stackoverflow.com/a/50246356
answers question: http://stackoverflow.com/q/50246268
has comment: http://stackoverflow.com/comment/87510491
has body: To find the overall top 10000 words, the easiest way would be update a global Counter: from collections import Counter global_counter = Counter() # &lt;- create a counter for tokenized_text in corpus: clean_text = [tok.lower() for tok in tokenized_text if tok not in punctuation and tok not in stopwords] global_counter.update(clean_text) # &lt;- update it At this point, you could just use import pandas as pd df = pd.DataFrame(global_counter.most_common(10000)) If you would like to find the count of the words for the specific entries, add now the following code (after the previous one). most_common = set([t[0] for t in global_counter.most_common(10000)]) occurrences = [] for tokenized_text in corpus: clean_text = dict(collections.Counter([tok.lower() for tok in tokenized_text if tok not in punctuation and tok not in stopwords])) occurrences.append({c: clean_text.get(c, 0) for c in most_common}) Now just use pd.DataFrame(occurrences)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87511775
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/87510417
accepted answer of: http://stackoverflow.com/q/50246268
has comment: http://stackoverflow.com/comment/87511694
upvote count: 3

http://stackoverflow.com/comment/87703490
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50343824
has text: But how do i specify euclidean weights for every vertex?
score: 0

http://stackoverflow.com/a/50355776
type: Answer
has body: As stated in https://docs.python.org/3/library/os.html the filenames provided by os.walk() contain no path elements and "To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name)." that's why you get this error.
answers question: http://stackoverflow.com/q/50355334
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87771256
score: 0
comment on: http://stackoverflow.com/q/50377322
has text: Have you checked to ensure your cuda path variables are set up appropriately? I dont remember exactly, but there was some kind of hoop I had to jump through to get tensorflow and cuda to behave with eachother.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87685252
type: Comment
score: 0
has text: Now that the code is smaller it easier to see things. If you want to update the histograms, then you probably want to be [Running a Bokeh Server Application](https://bokeh.pydata.org/en/dev/docs/user_guide/server.html) There's already a complete example of a histogram updating (based on selection in this case) here: https://github.com/bokeh/bokeh/blob/master/examples/app/selection_histogram.py Otherwise, your only options would be to *re-compute the histogram in JavaScript* or *pre-compute all possible histograms* and send their data up front. Is pre-computing everything acceptable?
type: QuestionComment
comment on: http://stackoverflow.com/q/50280177

http://stackoverflow.com/q/50250825
score: 3
tagged with: symbolic-math
has answer: http://stackoverflow.com/a/51763213
tagged with: python
tagged with: jmodelica
type: Question
upvote count: 3
has body: I recently found the paper "MAKING MODELICA MODELS AVAILABLE FOR ANALYSIS IN PYTHON CONTROL SYSTEMS LIBRARY" explaining how to use JModelica in combination with CasADi to get linearized models in Python. This is exactly what I am looking for, but apparently the paper is from 2014 and JModelica 1.12 is used. The described approach is deprecated and used functions are not available anymore. The documentation of JModelica is very limited regarding this topic and I have no idea how to accomplish the described task using the latest version of JModelica. The class CasadiModel is not used anymore and the function compile_fmux throws a compilation error. My final goal involves the modeling of (nonlinear) systems in Modelica. I need a symbolic representation of this model to perform the linearization myself. The linearized model is then used to design a controller in Python. Does anyone have a suggestion?
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: JModelica combined with CasADi to get linearized models in Python
favorite count: 0
tagged with: modelica

http://stackoverflow.com/q/50247602
has title: Setting Python encoding for printing Chinese characters
linked to: http://stackoverflow.com/q/3828723
accepted answer: http://stackoverflow.com/a/50248335
favorite count: 0
type: Question
has body: My code is below. I don't know why can't print Chinese. Please help. When trying to print more than one variable at a time, the words look like ASCII or raw type. How to fix it? # -*- coding: utf-8 -*- import pygoldilocks import sys reload(sys) sys.setdefaultencoding('utf8') rows = ( '已','经激活的区域语言' ) print( rows[0] ) print( rows[1] ) print( rows[0], rows[1] ) print( rows[0].encode('utf8'), rows[1].decode('utf8') ) print( rows[0], 1 ) $ python test.py 已 经激活的区域语言 ('\xe5\xb7\xb2', '\xe7\xbb\x8f\xe6\xbf\x80\xe6\xb4\xbb\xe7\x9a\x84\xe5\x8c\xba\xe5\x9f\x9f\xe8\xaf\xad\xe8\xa8\x80') ('\xe5\xb7\xb2', u'\u7ecf\u6fc0\u6d3b\u7684\u533a\u57df\u8bed\u8a00') ('\xe5\xb7\xb2', 1)
has answer: http://stackoverflow.com/a/50247665
duplicate of: http://stackoverflow.com/q/3828723
tagged with: python
has comment: http://stackoverflow.com/comment/87512535
has answer: http://stackoverflow.com/a/50248335
tagged with: cjk
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/50247665
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/124758954
has answer: http://stackoverflow.com/a/50248331
answer count: 3
tagged with: encoding
downvote count: 0

http://stackoverflow.com/a/50296161
answers question: http://stackoverflow.com/q/50295833
has comment: http://stackoverflow.com/comment/87611278
has comment: http://stackoverflow.com/comment/87611253
has body: If row T requires as input a value calculated in row T-1, then you'll probably want to do an iterative calculation. Typically backtesting is done by iterating through price data in sequence. You can calculate some signals just based on the state of the market, but you won't know the portfolio value, the pnl, or the portfolio positions unless you start at the beginning and work your way forward in time. That's why if you look at a site like Quantopian, the backtests always run from from start date to end date.
type: Answer
has comment: http://stackoverflow.com/comment/87614374
has comment: http://stackoverflow.com/comment/87614218
score: 0
has comment: http://stackoverflow.com/comment/87614136
has comment: http://stackoverflow.com/comment/87615433

http://stackoverflow.com/a/50310299
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50306988
answers question: http://stackoverflow.com/q/50306988
type: Answer
has comment: http://stackoverflow.com/comment/87637130
has comment: http://stackoverflow.com/comment/87637201
score: 1
has body: Note: Read the "Update" section at the end of my answer if you want the true reason. In this scenario, the other two reasons I have mentioned are only valid when the learning rate is set to a low value (less than 1e-3). I put together some code. It is very similar to yours but I just cleaned it a little bit and made it simpler for myself. As you can see, I use a dense layer with one unit with a sigmoid activation function for the last layer and just change the optimizer from adam to rmsprop (it is not important that much, you can use adam if you like): import numpy as np import random # generate random data with two features n_samples = 200 n_feats = 2 cls0 = np.random.uniform(low=0.2, high=0.4, size=(n_samples,n_feats)) cls1 = np.random.uniform(low=0.5, high=0.7, size=(n_samples,n_feats)) x_train = np.concatenate((cls0, cls1)) y_train = np.concatenate((np.zeros((n_samples,)), np.ones((n_samples,)))) # shuffle data because all negatives (i.e. class "0") are first # and then all positives (i.e. class "1") indices = np.arange(x_train.shape[0]) np.random.shuffle(indices) x_train = x_train[indices] y_train = y_train[indices] from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(2, activation='sigmoid', input_shape=(n_feats,))) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.summary() model.fit(x_train, y_train, epochs=5, batch_size=32, verbose=True) Here is the output: Layer (type) Output Shape Param # ================================================================= dense_25 (Dense) (None, 2) 6 _________________________________________________________________ dense_26 (Dense) (None, 1) 3 ================================================================= Total params: 9 Trainable params: 9 Non-trainable params: 0 _________________________________________________________________ Epoch 1/5 400/400 [==============================] - 0s 966us…
type: AcceptedAnswer

http://stackoverflow.com/q/50232639
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50244614
type: AnsweredQuestion
has title: Drag and Drop QLabels with PyQt5
tagged with: drag-and-drop
score: 7
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50244614
downvote count: 0
tagged with: pyqt
upvote count: 7
has body: I'm trying to drag and drop a Qlabel on another Qlabel with PyQt5: from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QHBoxLayout, QVBoxLayout, QGridLayout,QFrame, QComboBox, QLabel, QLineEdit from PyQt5.QtGui import QIcon, QFont, QPixmap, QImage import sys class my_label(QLabel): def __init__(self,title,parent): super().__init__(title,parent) self.setAcceptDrops(True) def dragEnterEvent(self,event): if event.mimeData().hasFormat("text/plain"): event.accept() else: event.ignore() def dropEvent(self,event): self.setText(event.mimeData().text()) class application(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): label = my_label("drop there",self) label.resize(100,100) label.move(190,65) label_to_drag = QLabel("drag this",self) #label_to_drag.setDragEnabled(True) #doesn't work with QLabel self.show() def closeEvent(self,event): message = QMessageBox.question(self,"Message","Quit ?",QMessageBox.Yes | QMessageBox.No,QMessageBox.No) if message == QMessageBox.Yes: event.accept() else: event.ignore() app = QApplication(sys.argv) fenetre = application() sys.exit(app.exec_()) I wanted to make my first label "draggable",by calling the setDragEnabled(True) method (as i was doing for QLineEdit),and drop it on the second label to change his text. Dropping text from another app is working fine,but I can't find how to drag the QLabel inside my own app... What did I miss ? EDIT : modified the code to try to Drag&amp;Drop Images : class DraggableLabel(QLabel): def __init__(self,parent,image): super(QLabel,self).__init__(parent) self.setPixmap(QPixmap(image)) self.show() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.drag_start_position = event.pos() def mouseMoveEvent(self, event): if not (event.buttons() &amp; Qt.LeftButton): return if (event.pos() - self.drag_start_position).manhattanLength() &lt; QApplication.startDragDistance(): return drag = QDrag(self) mimedata = QMimeData() mimedata…
answer count: 1

aggregate
tags question: http://stackoverflow.com/q/50243181
tag name: aggregate
type: Tag
tags question: http://stackoverflow.com/q/50351011

http://stackoverflow.com/q/50263126
accepted answer: http://stackoverflow.com/a/50263277
has answer: http://stackoverflow.com/a/50263323
possible better answer: http://stackoverflow.com/a/50263323
type: Question
has body: I am trying to break a string apart by removing segments that occur between two words. Example: AGCGUGUGAGAGCUCCGA I will remove the parts that occur between: GUGU and AGAG So, the new string will be: AGCCUCCGA I wrote a code that utilises while loop to keep 'splicing' a string over and over till it can't find the GUGU and AGAG in the string. The process works, most of the time. I encountered one case where the 'input' is extremely long and then my code is stuck in an infinite loop and I don't understand why that is the case. I was hoping that someone could review it and help me improve on what I am doing. def splice(strand): while True: initial = strand.find('GUGU') final = strand.find('AGAG') if initial == -1: break if final == -1: break strand = strand[:initial] + strand[final+4:] return strand if __name__ == "__main__": strand = input("Input strand: ") print() spliced = splice(strand) print("Output is {}".format(spliced)) The case where it is failing is: GUGUAGAGGUCACAGUGUAAAAGCUCUAGAGCAGACAGAUGUAGAGGUGUUGUGUAACCCGUAGAGCAAAGGCAACAGUGUGUAAAGAGGUGUAAAGAG Expected result: GUCACACAGACAGAUGUAGAGCAAAGGCAACA I haven't encountered any other cases where the code will not work.
has comment: http://stackoverflow.com/comment/87544383
tagged with: python
has comment: http://stackoverflow.com/comment/87544403
type: AnsweredQuestion
score: 0
has title: Splice a string, multiple times, using a keyword
answer count: 2
has comment: http://stackoverflow.com/comment/87544430
has answer: http://stackoverflow.com/a/50263277

http://stackoverflow.com/q/50343380
has answer: http://stackoverflow.com/a/50343627
has answer: http://stackoverflow.com/a/50343416
has title: Python Django error NoReverseMatch Exception Value: Reverse for 'updatecontact' with no arguments not found
tagged with: django-views
has comment: http://stackoverflow.com/comment/87703267
has comment: http://stackoverflow.com/comment/87703246
type: Question
tagged with: python-3.x
score: 0
answer count: 2
has body: I have a function that update data in the DB. Here is my url: url.py url(r'updatecontact/(?P<id>\d+)/$',views.updatecontact,name="updatecontact"), template.html Update I am getting the error: Exception Type: NoReverseMatch Exception Value: Reverse for 'updatecontact' with no arguments not found. 1 pattern(s) tried: ['updatecontact/(?P<id>\\d+)/$']
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/50386301
has body: You have no reason to convert anything into hex, Python re module can easily search in raw byte strings. But you really should loop with search instead of using findall in order to get the offsets where the strings are found. The code could become: import re infile = "my_file.bin" with open(infile, "rb") as f: data = f.read() matches = [] # initializes the list for the matches curpos = 0 # current search position (starts at beginning) pattern = re.compile(br'\$[A-Z]{3,10}') # the pattern to search while True: m = pattern.search(data[curpos:]) # search next occurence if m is None: break # no more could be found: exit loop matches.append(curpos + m.start(), m.group(0)) # append a pair (pos, string) to matches curpos += m.end() # next search will start after the end of found string
score: 2
has comment: http://stackoverflow.com/comment/87819423
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50363987
accepted answer of: http://stackoverflow.com/q/50363987
type: Answer

http://stackoverflow.com/a/57267330
score: 6
answers question: http://stackoverflow.com/q/50250010
type: Answer
upvote count: 6
has body: With the recently released major version of Plotly 4.0, the steps below work for me with PyCharm 2019.2 on macOs Mojave using iPython notebooks from within PyCharm. I believe that this should work on other operating systems as well with other recent versions of PyCharm supporting Jupyter notebooks. I am using conda for package and environment management but this should work with other tools as well e.g. pip or pipenv (given that orca is installed standalone) Here are my steps: Create and activate conda environment: $ conda create -n pycharm-plotly python $ conda activate pycharm-plotly Install Plotly 4.0 and its dependencies as per the plotly.py's GitHub README for Jupyter Notebook Support $ conda install -c plotly plotly==4.0.0 $ conda install "notebook&gt;=5.3" "ipywidgets&gt;=7.5" In addition, I found that "Plotly Orca" is required for this to work: $ conda install -c plotly plotly-orca psutil requests Please note that the above works with both "Configured Server" and "Managed Server" from within PyCharm for .ipynb file extensions using the following sample code: #%% import plotly.graph_objects as go import plotly.io as pio pio.renderers.default = 'png' fig = go.Figure( data=[go.Bar(y=[2, 1, 3])], layout_title_text="A Figure Displayed with fig.show()" ) fig.show(); Additional Notes: I believe that Plotly's plot rendering doesn't work with "plain" Python files in PyCharm's Scientific mode the same way as it works for Matplotlib or Seaborn.
downvote count: 0

http://stackoverflow.com/a/57223041
score: 0
has body: Go to the cuDNN Archive https://developer.nvidia.com/rdp/cudnn-archive Click on "Download cuDNN v7.6.1 (June 24, 2019), for CUDA 9.0" Click on the version fro your operating system Unzip. Should extract to a directory called cuda Copy the contents of the folder paste it to "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0" All done!!!
type: Answer
answers question: http://stackoverflow.com/q/50296384

http://stackoverflow.com/comment/114165213
comment on: http://stackoverflow.com/a/50340545
type: AnswerComment
has text: Roughly 3 times faster than the dstack + flatten solution with 1000-element arrays on my machine, cheers!
score: 0
type: Comment

http://stackoverflow.com/q/50319570
has comment: http://stackoverflow.com/comment/87654999
has answer: http://stackoverflow.com/a/50331500
score: 0
tagged with: udp
has body: I hope this is not too opinionated because I'm looking for a finite answer. I'm developing a UDP server in Python 3.x that is utilizing asyncio. The server is going to work with a game engine to process pretty much every interaction a player makes in the game. Therefore, I have to authenticate the game client with the game server in some way as well ensure replay attacks do not happen on top of everything else that could harm or spoof the game server. When it comes to authenticating with UDP, I'm at a loss. My plan is to have both the game client and game server authenticate per user and game session. That means having something like a public key on the client end and a private key on the server end where the server can authenticate the client is approved. During that authentication, I am going to generate a symmetric key that the game server makes and passes it down to the game client so every packet sent can be verified with that symmetric key using HMAC. If not, all packets are dropped. My Question Is this the best approach? Creating some type of public key where something like a token is generated per session to ensure packets coming to the UDP server are from authenticated clients? My worry here is the keys are still stored in a Windows EXE file and still likely can be cracked and extracted or am I just too paranoid?
answer count: 1
tagged with: ssl
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87655559
has comment: http://stackoverflow.com/comment/87654962
has comment: http://stackoverflow.com/comment/87654937
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87655027
has comment: http://stackoverflow.com/comment/87655121
has title: What is the best way to secure UDP server with HMAC?

http://stackoverflow.com/comment/87642366
type: Comment
score: 0
has text: Not sure if you've noticed that but there is a [Github issue](https://github.com/tensorflow/tensorflow/issues/18960) which has mentioned this problem. Unfortunately, it hasn't been solved.
type: QuestionComment
comment on: http://stackoverflow.com/q/50312896

http://stackoverflow.com/q/50315954
favorite count: 0
type: Question
has body: I need to do something like (using python): check if a word occurs in json file find a part of that file with that word, that part needs to start and end with other words I don't have problem with first point, but second is trouble. I was trying to using regex startWord.+ foundWord +.endingWord but it doesn't work. What is more, I use basic open() function to open json file. But for the program it is seen as single line. What should I do to be able to find just some lines or part of it? I am rather new in python, hope that question isn't very silly :) Thanks in advance for any help.
has comment: http://stackoverflow.com/comment/87647853
upvote count: 0
accepted answer: http://stackoverflow.com/a/50316131
tagged with: python
score: -1
tagged with: regex
downvote count: 1
has answer: http://stackoverflow.com/a/50316131
type: AnsweredQuestion
answer count: 1
has title: finding part of text containing specific words using regex in python

http://stackoverflow.com/a/50232526
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50230766
answers question: http://stackoverflow.com/q/50230766
type: Answer
has body: It seems you're missing nodejs: try downloading and installing from: https://nodejs.org/en/. This should solve the problem with Jupyterlab. I'm not a user of Anaconda Navigator, but, as far as I can see, it uses enviroments to manage python installations. You should create at least one enviroment from Navigator and select it before trying to run python. More info from Anaconda Navigator documentation here: https://docs.anaconda.com/anaconda/navigator/getting-started
upvote count: 2

http://stackoverflow.com/comment/88311479
comment on: http://stackoverflow.com/q/50326816
has text: "someFunctionPointer" is a `ctypedef` of a C function pointer. e.g. do `ctypedef void (*someFunctionPointer)(char*)` to make `someFunctionPointer` be a pointer to a function that accepts a char* and returns nothing.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87579305
has text: Possible duplicate of [Insert an item into sorted list in Python](https://stackoverflow.com/questions/8024571/insert-an-item-into-sorted-list-in-python)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50281268

http://stackoverflow.com/comment/87528309
type: Comment
has text: what would that flag do ? reversing in integer sum has no effect on result
score: 1
comment on: http://stackoverflow.com/q/50255373
type: QuestionComment

http://stackoverflow.com/comment/87754247
comment on: http://stackoverflow.com/q/50369050
score: 0
type: Comment
type: QuestionComment
has text: Seems relevant: https://xkcd.com/1987/

http://stackoverflow.com/q/50370917
has comment: http://stackoverflow.com/comment/87757772
type: UnansweredQuestion
downvote count: 0
tagged with: lambda
has answer: http://stackoverflow.com/a/50371184
tagged with: docstring
has comment: http://stackoverflow.com/comment/87757767
has title: What is the best way in python to write docstrings for lambda functions?
answer count: 1
tagged with: python
has body: I usually comment my functions using multi-line docstrings with """, as mentioned in : https://www.python.org/dev/peps/pep-0257/ def func1(x): """ This function does ... """ ... But what is the best way to comment a lambda function ? I hesitate between : # This function does ... func2 = lambda x: ... or : func2 = lambda x: ... """ This function does ... """ or else ?
has comment: http://stackoverflow.com/comment/87757709
favorite count: 0
type: Question
score: 9
has comment: http://stackoverflow.com/comment/87757703
has comment: http://stackoverflow.com/comment/87758422
upvote count: 9

http://stackoverflow.com/a/59600403
upvote count: 3
downvote count: 0
score: 3
has body: Simply uninstall the package from your virtual environment and reinstall it. Do migrate if need be. The issue should be solved.
type: Answer
answers question: http://stackoverflow.com/q/50362088

http://stackoverflow.com/a/50367351
has comment: http://stackoverflow.com/comment/87751759
has body: Use values: print(dict_of_ims.values()) Or to unpack the values: for val in dict_of_ims.values(): for item in val: print(item)
has comment: http://stackoverflow.com/comment/87751420
type: Answer
has comment: http://stackoverflow.com/comment/87751815
score: 3
has comment: http://stackoverflow.com/comment/87751237
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50367297

http://stackoverflow.com/q/50307066
has comment: http://stackoverflow.com/comment/87630407
has body: I have a problem, I have 2 lists with x and y values, and I would like to create a function based on these. But the problem is that I would like to build a function like this one: f(x) = a * (x-b)**c I already know scipy.interpolate but I couldn't find anything to return a function like this one. is there a quite easy way to try to create the best function I can by searching which values of a,b and c match the most? thanks for your help! Edit: here is what my current values of x and y look like: I created this function : def problem(values): s = sum((y - values[0]*(x-values[1])**values[2])**2 for x,y in zip(X,Y)) return(s) and I tried to find the best values of a,b and c with scipy.optimize.minimize but I don't know with which values of a,b and c I should start... values = minimize(problem,(a,b,c))
tagged with: function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87630447
upvote count: 1
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50307193
tagged with: math
has title: Python, model a function based on x and y values
has comment: http://stackoverflow.com/comment/87630567
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/18767523
type: Question
tagged with: interpolation
has answer: http://stackoverflow.com/a/50307168
answer count: 2

http://stackoverflow.com/a/50265163
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50264065
downvote count: 0
answers question: http://stackoverflow.com/q/50264065
score: 1
type: Answer
has body: You can use a manually stretched 'tanh'. Alone, 'tanh' returns from -1 to +1. You can stretch it multiplying it by 5 (or maybe just a little more, like 5.1, for instance). model.add(YourLastLayer(..., activation='tanh')) model.add(Lambda(lambda x: x * 5)) The other questions are impossible to answer, we have no idea of what your dataset is about, how data is organized, what it represents and what you want to achieve. It seems, though, that it's a classical Dense (or fully connected) network case.

http://stackoverflow.com/q/50269514
upvote count: 2
has comment: http://stackoverflow.com/comment/87557135
has title: Difficulties with implementing persian calendar rules with Python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87556867
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50269922
score: 1
answer count: 1
downvote count: 1
has body: I am writing a code that somehow resembles the Persian calendar. there are 3 drop down lists for year, month and day. Here are the rules I'd like to include: Months 1 to 6 have 31 days Months 7 to 11 have 30 days Month 12 has 29 days every 4 years 12th month has 30 days (leap year) If the user chooses one of the (1 - 2 - 3 - 4 - 5 - 6) months, the drop down list for days must have 31 days. If the user chooses one of the (7 - 8 - 9 - 10 - 11 ) months, the drop down list for days must have 30 days. If the user chooses the 12th month, the drop down list for days must have 29 days. If the user chooses one of (1375 – 1379 – 1383 – 1387 – 1391 – 1395) year and if he chooses the 12th month, the drop down list for days must have 30 days. Here is the code I have written so far but my code doesn't work, please help me with it. from tkinter import * x=StringVar() def ok(): if months == months[0:5]: x = dayoptions1 if months == months[6:10]: x = dayoptions2 if months == months[11] and years == 1375 or 1379 or 1383 or 1387 or 1391 or 1395: x = dayoptions3 root = Tk() label1 = Label(root, text="year",width=15) label1.grid(row=0, column=0) yearoptions = ["1397", "1396","1395","1394","1393","1392","1391","1390","1389","1388","1387","1386","1385","1384","1383","1382","1381","1380","1379","1378","1377","1376","1375"] yearvariable = StringVar(root) yearvariable.set(yearoptions[0]) years = OptionMenu(root, yearvariable, *yearoptions) years.grid(row=0,column=1,padx=5, pady=5) label2 = Label(root, text="month",width=15) label2.grid(row=0, column=2) monthoptions = ["1", "2","3","4","5","6","7","8","9","10","11","12"] monthvariable = StringVar(root) monthvariable.set(monthoptions[0]) months = OptionMenu(root, monthvariable, *monthoptions) months.grid(row=0,column=3,padx=5, pady=5) label1 = Label(root, text="day",width=15) label1.grid(row=0, column=4) dayoptions1 = ["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"…
favorite count: 0
type: Question

http://stackoverflow.com/comment/87701193
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50342462
has text: (Then what's your algorithm and where are you stuck at while implementing that?)
score: 1

http://stackoverflow.com/q/50281268
favorite count: 0
possible better answer: http://stackoverflow.com/a/50281368
type: Question
has comment: http://stackoverflow.com/comment/87579373
has answer: http://stackoverflow.com/a/50282501
linked to: http://stackoverflow.com/q/8024571
has comment: http://stackoverflow.com/comment/87580616
has comment: http://stackoverflow.com/comment/87579231
has title: fastest way to find insert position for new data into sorted list of dates
has answer: http://stackoverflow.com/a/50281368
has comment: http://stackoverflow.com/comment/87579114
tagged with: python
has comment: http://stackoverflow.com/comment/87579709
has comment: http://stackoverflow.com/comment/87579183
has comment: http://stackoverflow.com/comment/87579576
has comment: http://stackoverflow.com/comment/87579305
tagged with: search
has comment: http://stackoverflow.com/comment/87579145
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87579090
has comment: http://stackoverflow.com/comment/87579176
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/87579149
has body: Let us say I have a list of dates: mydates = [Timestamp('2017-03-31 00:00:00'), Timestamp('2017-06-30 00:00:00') Timestamp('2017-09-30 00:00:00'), Timestamp('2017-12-31 00:00:00'), Timestamp('2018-03-31 00:00:00')] And I get a new date and want to know which position to insert it. If the date is already in the list we assume we will insert it again to the right of existing date. I.e., '2016-12-10' would be inserted in position 0, left to Timestamp('2017-03-31 00:00:00'), etc.
has comment: http://stackoverflow.com/comment/87579415
downvote count: 0
tagged with: insert
upvote count: 1
accepted answer: http://stackoverflow.com/a/50282501
has comment: http://stackoverflow.com/comment/87579161
has comment: http://stackoverflow.com/comment/87579143

http://stackoverflow.com/comment/87665257
type: AnswerComment
has text: Hmm it seems exactly like what i need, i though get an error "No numeric types to aggregate" but i think that maybe has something to do with my pandas version perhaps.
comment on: http://stackoverflow.com/a/50324463
type: Comment
score: 0

http://stackoverflow.com/a/50377806
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50377577
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: effbot is the recommend documentation for the tkinterlibrary. The Label.textvariable attribute should point to a tkinter.StringVar() object: &gt;&gt;&gt; import tkinter as tk &gt;&gt;&gt; root = tk.Tk() &gt;&gt;&gt; test = StringVar() &gt;&gt;&gt; test.set('Hello') &gt;&gt;&gt; pinnarKvar = tk.Label(root, textvariable = test, width = 30) &gt;&gt;&gt; pinnarKvar.pack() HereI am using IDLE so I don't use root.mainloop() since it dynamically updates. To change what you see, after you call pinnarKvar.pack() call text.set() to update.
answers question: http://stackoverflow.com/q/50377577

http://stackoverflow.com/comment/87687332
type: Comment
comment on: http://stackoverflow.com/a/50335524
has text: A suggestion: No need for direct flattening, `a` can be turned directly and efficiently into a `dict` and then you can use `dict.keys()` as the first set.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50349656
has comment: http://stackoverflow.com/comment/87715388
tagged with: python
has body: I am developing a hangman program in Python using Tkinter, and I want to bind the enter key to my submit button I created in Tkinter. I have tried different solutions, but I haven't found one that works quite yet. To download the complete code and a txt file with words used in the program (I haven't packaged it yet) - use this link. When starting the code - press Single-player and then Spela to start the game. The button labled Testa is the one I would like to bind to the enter key. The code is commented in Swedish, but the Testa-button is a part of the function spel_multiplayer() and is created with the following code. testa = Button(root, text="Testa",font=("Helvetica neue",12), command=vinstkontroll) # skapar knapp för att testa gissning testa.pack(fill=X,padx=10) # skapar knapp för att testa gissning Any help is appreciated .
has title: How to connect Enter key to button in Python with Tkinter
type: Question
score: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/50350018
type: UnansweredQuestion
answer count: 1
tagged with: button
upvote count: 1
has comment: http://stackoverflow.com/comment/88883480
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87715345
tagged with: key-bindings
has comment: http://stackoverflow.com/comment/87715092

http://stackoverflow.com/q/50229922
tagged with: python
has title: Unable to run Poincare Embeddings example to get hierarchical representation
has answer: http://stackoverflow.com/a/54664032
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: word-embedding
favorite count: 0
type: Question
has body: I'm trying to replicate Poincaré Embeddings for Learning Hierarchical Representations present on Github by Facebook Research. But I'm unable to run example.sh to embed the mammals subtree in the reconstruction setting. OS: Ubuntu 16.04, Using Anaconda 4.3.30, Python 3.6.5, Pytorch 0.4.0 Command: NHTHREDS=2 ./example.sh Error Log: Using 2 threads slurp: objects=1181, edges=6541 Indexing data json_conf: {"distfn": "poincare", "dim": 5, "lr": 0.3, "batchsize": 10, "negs": 50} Burnin: lr=0.003 'Traceback (most recent call last):\n File "/home/harman/anaconda3/envs/pytorch-venv/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in _worker_loop\n samples = collate_fn([dataset[i] for i in batch_indices])\n File "/home/harman/anaconda3/envs/pytorch-venv/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in &lt;listcomp&gt;\n samples = collate_fn([dataset[i] for i in batch_indices])\n File "/home/harman/harman_workspace/poincare-embeddings/model.py", line 185, in __getitem__\n if n not in self._weights[t]:\nKeyError: tensor(491)\n' Traceback (most recent call last): File "/home/harman/harman_workspace/poincare-embeddings/train.py", line 19, in train_mp train(model, data, optimizer, opt, log, rank, queue) File "/home/harman/harman_workspace/poincare-embeddings/train.py", line 46, in train for inputs, targets in loader: File "/home/harman/anaconda3/envs/pytorch-venv/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 286, in __next__ return self._process_next_batch(batch) File "/home/harman/anaconda3/envs/pytorch-venv/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 307, in _process_next_batch raise batch.exc_type(batch.exc_msg) KeyError: 'Traceback (most recent call last):\n File "/home/harman/anaconda3/envs/pytorch-venv/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in _worker_loop\n samples = collate_fn([dataset[i] for i in batch_indices])\n File "/home/harman/anaconda3/envs/pytorch-…
tagged with: hierarchical-data

http://stackoverflow.com/comment/87540739
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50260132
has text: Sorry but I got an issue running the script , I wrote in my first comment ^^
type: Comment

late-binding
type: Tag
tag name: late-binding
tags question: http://stackoverflow.com/q/50263151

http://stackoverflow.com/a/50339214
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87718275
answers question: http://stackoverflow.com/q/50329184
type: Answer
has body: ibex (which I co-wrote) makes extensive use of Pandas multilevel indexes. Suppose we start with import pandas as pd df = pd.DataFrame({'source': [2, 44], 'class': [0, 1], 'x': [0, 5], 'y': [0, 6], 'z': [0, 8], 'w': 10}) >>> df class source w x y z 0 0 2 10 0 0 0 1 1 44 10 5 6 8 Then the beginning of your pipeline gives >>> (trans(LabelEncoder(), in_cols=['class']) + trans(None, ['source', 'x','y','z'])).fit_transform(df) functiontransformer_0 functiontransformer_1 0 source x y z 0 0 2 0 0 0 1 1 44 5 6 8 This is by design. You can achieve what you want by writing the pipeline as: p = ( trans(LabelEncoder(), in_cols="class") + trans(StandardScaler(), in_cols=["x", "y", "z"]) + trans(None, in_cols="source") ) >>> p.fit_transform(df) functiontransformer_0 functiontransformer_1 functiontransformer_2 0 x y z source 0 0 -1.0 -1.0 -1.0 2 1 1 1.0 1.0 1.0 44
accepted answer of: http://stackoverflow.com/q/50329184
score: 1

http://stackoverflow.com/comment/87530176
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50255630
has text: I'm installing selenium in a virtualenv to see what's really happening.. but i'm not sure why you're getting every element you can as css selectors when you could use `elems = browser.find_elements_by_tag("a")` to get all the links on the page.
type: AnswerComment

http://stackoverflow.com/a/50298369
has body: You have put i18n_patterns inside a patterns list, but this function itself produces a list of urlpatterns, not a single pattern. This is not equivalent to the documentation you found. Use concatenation: urlpatterns = [ re_path(r'^dj-admin/', admin.site.urls), re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^docs/', include(wagtaildocs_urls)), ] + i18n_patterns( path(r'', include(wagtail_urls)), prefix_default_language = False ) or prefix the function call with * to incorporate all elements into the list: urlpatterns = [ re_path(r'^dj-admin/', admin.site.urls), re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^docs/', include(wagtaildocs_urls)), *i18n_patterns( path(r'', include(wagtail_urls)), prefix_default_language = False ) ] This is called iterable unpacking and requires Python 3.5 or newer. The documentation used += augmented assignment to extend the urlpatterns list, which is probably a good pattern for you to just re-use: urlpatterns = [ re_path(r'^dj-admin/', admin.site.urls), re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^docs/', include(wagtaildocs_urls)), ] urlpatterns += i18n_patterns( path(r'', include(wagtail_urls)), prefix_default_language = False )
type: Answer
answers question: http://stackoverflow.com/q/50298335
upvote count: 13
accepted answer of: http://stackoverflow.com/q/50298335
type: AcceptedAnswer
downvote count: 0
score: 13

http://stackoverflow.com/a/57657480
upvote count: 1
answers question: http://stackoverflow.com/q/50338747
score: 1
downvote count: 0
type: Answer
has body: As the documentation says: Note Only LogisticRegression and NaiveBayes are supported now.

http://stackoverflow.com/a/52320299
downvote count: 0
answers question: http://stackoverflow.com/q/50275646
has body: Celery is a fantastic solution to this problem I have used quite successfully in the past to manage millions of jobs per day. The only real downside is the initial learning curve and complexity of debugging when things go sour (it can happen, especially with millions of jobs).
score: 2
type: Answer
upvote count: 2

http://stackoverflow.com/comment/87789337
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50360271
has text: cᴏʟᴅsᴘᴇᴇᴅ Please edit the question if it meant to say "by day" (day-of-week: Monday, Tuesday, or 0..6) rather than "by date". It currently just looks like a duplicate of many others on pandas groupby datetime.

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

http://stackoverflow.com/q/50273461
tagged with: django-forms
has answer: http://stackoverflow.com/a/50273501
type: Question
answer count: 2
tagged with: django
tagged with: python
has title: NameError at /system/invn/create name 'name' is not defined modelForm
has body: I trying to create a form with ModelForm that save it to a database. But got an error. here my models.py class Inventory(models.Model): name = models.CharField(max_length=255) sn = models.DecimalField(max_digits=20, decimal_places=0) desc = models.TextField(blank=True, null=True, default='Tidak ada deskripsi') here my forms.py class InventoryForm(forms.ModelForm): name = forms.CharField(max_length=255) sn = forms.DecimalField(max_digits=20, decimal_places=0) desc = forms.CharField(widget=forms.Textarea) class Meta: model = Inventory fields = ('name', 'sn', 'desc',) here my views.py class InventoryCreateView(TemplateView): template_name ='system/inventory_form.html' def get(self, request): form = InventoryForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = InventoryForm(request.POST) if form.is_valid(): form.save() args = {'form': form, 'name': name, 'sn': sn, 'desc': desc} return render(request, self.template_name, args) its said NameError at /system/invn/create name 'name' is not defined modelForm from args = {'form': form, 'name': name, 'sn': sn, 'desc': desc} what missed here?...
possible better answer: http://stackoverflow.com/a/50273501
accepted answer: http://stackoverflow.com/a/50273528
has answer: http://stackoverflow.com/a/50273528
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50298506
has answer: http://stackoverflow.com/a/50298913
has body: Scipy sparse documentation of csr_matrix says that this kind of matrix is efficient for row slicing. Using this code: import numpy as np from scipy import sparse dok = sparse.dok_matrix((5,1)) dok[1,0] = 1 data = np.array([0,1,2,3,4]) row = np.array([0,1,2,3,4]) col = np.array([0,1,2,3,4]) csr = sparse.csr_matrix((data, (row, col))) csr[:, 0] += dok I get this warning: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient. Why am I getting this warning?
score: 2
tagged with: numpy
type: AnsweredQuestion
upvote count: 2
answer count: 1
downvote count: 0
has title: why do I get warning on scipy sparse column slicing?
tagged with: scipy
tagged with: sparse-matrix
favorite count: 0
type: Question
tagged with: performance
accepted answer: http://stackoverflow.com/a/50298913
tagged with: python

http://stackoverflow.com/comment/87659882
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50321158
type: Comment
has text: Should I add the example as comment or to my original post?

http://stackoverflow.com/q/50297271
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87611917
has comment: http://stackoverflow.com/comment/87611629
has comment: http://stackoverflow.com/comment/87611794
has comment: http://stackoverflow.com/comment/87612348
linked to: http://stackoverflow.com/q/23616507
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87611831
answer count: 1
has comment: http://stackoverflow.com/comment/87611595
has answer: http://stackoverflow.com/a/50297415
favorite count: 0
has body: There is an error in this code... time.sleep(5) print ("Loading Successfull")` When I run this code an error pops up it says: NameError: name 'time' is not defined I think I dont need to define time I've recently have used this command it never said TimeError it's happening first time print ("-----------------Welcome to Digits counter-----------------")#Welcomes the user print ("") print ("Loading...") time.sleep (3) print("Load Sucessfull")
type: Question
has comment: http://stackoverflow.com/comment/87611667
type: UnansweredQuestion
has title: Error in Time Sleep
has comment: http://stackoverflow.com/comment/87611552

http://stackoverflow.com/comment/87623093
type: AnswerComment
has text: okay so i want to convert it into excel file without the index columns and rows?can you guide me on that?
type: Comment
comment on: http://stackoverflow.com/a/50303319
score: 0

anaconda
tags question: http://stackoverflow.com/q/50305634
tags question: http://stackoverflow.com/q/50255346
tags question: http://stackoverflow.com/q/50353508
tags question: http://stackoverflow.com/q/50318518
tags question: http://stackoverflow.com/q/50328929
type: Tag
tags question: http://stackoverflow.com/q/50374292
tag name: anaconda
tags question: http://stackoverflow.com/q/50293427
tags question: http://stackoverflow.com/q/50278398
tags question: http://stackoverflow.com/q/50296720
tags question: http://stackoverflow.com/q/50280144
tags question: http://stackoverflow.com/q/50336562
tags question: http://stackoverflow.com/q/50377905
tags question: http://stackoverflow.com/q/50298826
tags question: http://stackoverflow.com/q/50295889
tags question: http://stackoverflow.com/q/50326084
tags question: http://stackoverflow.com/q/50356636
tags question: http://stackoverflow.com/q/50374950
tags question: http://stackoverflow.com/q/50360460
tags question: http://stackoverflow.com/q/50300010
tags question: http://stackoverflow.com/q/50298011
tags question: http://stackoverflow.com/q/50288006
tags question: http://stackoverflow.com/q/50295684
tags question: http://stackoverflow.com/q/50321283
tags question: http://stackoverflow.com/q/50291225
tags question: http://stackoverflow.com/q/50268442
tags question: http://stackoverflow.com/q/50230766
tags question: http://stackoverflow.com/q/50362389
tags question: http://stackoverflow.com/q/50305725
tags question: http://stackoverflow.com/q/50344058
tags question: http://stackoverflow.com/q/50302827
tags question: http://stackoverflow.com/q/50295907
tags question: http://stackoverflow.com/q/50282464

http://stackoverflow.com/a/50341038
answers question: http://stackoverflow.com/q/50340963
has body: It was just a silly mistake: I changed the name of the field from owner to creator, but I forgot to change it in the perform_create() method: def perform_create(self, serializer): serializer.save(creator=self.request.user)
type: Answer
score: 0

http://stackoverflow.com/comment/87740471
comment on: http://stackoverflow.com/q/50361707
type: Comment
type: QuestionComment
has text: I still cannot get the count of each label and variables. It's not count instance.
score: 0

http://stackoverflow.com/comment/87660558
comment on: http://stackoverflow.com/a/50321643
has text: Is that possible to code in other to make client-side work as server-side too, in order to make a stable two-way communication?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50270576
has answer: http://stackoverflow.com/a/50273296
tagged with: selenium
possible better answer: http://stackoverflow.com/a/50271210
has answer: http://stackoverflow.com/a/50271210
has body: I am using below python code using selenium. click is not working on anchor tag having href = "#" import time import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome("E:\chromedriver.exe") driver.get('file:///E:/Selenium/validateTest.html') driver.find_element_by_xpath("//a[@id='validateData']/i[text()=' Validate Data']").click() Here is the web html code that I am using. Anchor tag Show content Validate Data
has comment: http://stackoverflow.com/comment/87558952
favorite count: 0
has comment: http://stackoverflow.com/comment/87558582
type: Question
tagged with: selenium-chromedriver
tagged with: python-3.x
answer count: 2
has title: click on anchor tag having href = '#'
upvote count: 2
linked to: http://stackoverflow.com/q/44912203
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/50273296
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/44724185
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/50289482
favorite count: 0
has answer: http://stackoverflow.com/a/52733465
type: Question
has body: Struggling with this one... I am trying to use StreamingHttpResponse to output a csv of data. The file itself is constructed fine, but for some reason the filename is being set incorrectly across different browsers. I'm using Django Rest Framework with a custom csv renderer. The CSVRenderer takes the standard data from a Django Rest Framework ReadOnlyModelViewsetand renders it using StreamingHttpResponse. The CSVRenderer was written based on Django docs explaining how to output a csv import csv from rest_framework.renderers import BaseRenderer from django.http import StreamingHttpResponse class Echo(object): '''An object that implements just the write method of the file-like interface. ''' def write(self, value): '''Write the value by returning it, instead of storing in a buffer. ''' return value class CSVRenderer(BaseRenderer): '''Renderer class to generate basic csvs of the data supplied by the serializer ''' media_type = 'text/csv' format = 'csv' def render(self, data, media_type=None, renderer_context=None): rows = [] first_data_row = next(iter(data['results']), None) # Create header rows if data present if first_data_row: rows.append(list(first_data_row.keys())) # print the data to rows for row in data['results']: rows.append(list(row.values())) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in rows), content_type='text/csv') response['Content-Type'] = 'text/csv; name="export.csv"' response['Content-Disposition'] = 'attachment; filename="export.csv"' return response So when I do a GET request to a url e.g. http://example.com/api/mydata?format=csv in IE I get a file containing the correct data named mydata.txt which is the wrong filename and extension! In Firefox I get a file containing the correct data named XuKsgJ.csv which is the right extension but just a random filename! I guess I'm not setting something somewhere, but I can't figure out where. Any suggestions? Running Django 1.10.8, …
has title: Django StreamingHttpResponse not setting correct filename
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52669966
tagged with: django
tagged with: python
score: 2
answer count: 2
upvote count: 2
downvote count: 0
tagged with: django-rest-framework

http://stackoverflow.com/comment/87545731
comment on: http://stackoverflow.com/q/50263862
type: Comment
type: QuestionComment
has text: Your error is unrelated to the 3 lines of code you've posted above. We're going to need to see the rest of the file. The error does explain the issue though - you're using a variable/name `cheese` but it has not been defined
score: 3

http://stackoverflow.com/q/50340548
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87697310
has title: Intersection between dictionary and list?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87697462
accepted answer: http://stackoverflow.com/a/50340600
has comment: http://stackoverflow.com/comment/87697359
has answer: http://stackoverflow.com/a/50340600
tagged with: python
score: -2
tagged with: dictionary
has body: I have a code that receives a response from post requests in format json and there is a list ID (id_s). id_descript = [] id_s=[] for k, d in enumerate(id_descript): answer = requests.post(url,data=json.dumps(data) , headers=headers) response=answer.json() print(response) for i in id_s: print(i) #id_443081 #id_187360 I want to process the results and write them down in one list (result). An example of how this should be displayed:
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87697655
upvote count: 0
has comment: http://stackoverflow.com/comment/87697409

http://stackoverflow.com/comment/87739545
has text: Hi, yes, that is correct. Thanks, I will take a look at that link.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50356224

http://stackoverflow.com/a/72316062
upvote count: 11
downvote count: 0
answers question: http://stackoverflow.com/q/50246304
has body: Production level example import logging import time import functools import traceback LOG_FORMAT = "%(asctime)s - %(levelname)s - %(pathname)s - %(funcName)s - %(lineno)d -msg: %(message)s" logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) def retry(retry_num, retry_sleep_sec): """ retry help decorator. :param retry_num: the retry num; retry sleep sec :return: decorator """ def decorator(func): """decorator""" # preserve information about the original function, or the func name will be "wrapper" not "func" @functools.wraps(func) def wrapper(*args, **kwargs): """wrapper""" for attempt in range(retry_num): try: return func(*args, **kwargs) # should return the raw function's return value except Exception as err: # pylint: disable=broad-except logging.error(err) logging.error(traceback.format_exc()) time.sleep(retry_sleep_sec) logging.error("Trying attempt %s of %s.", attempt + 1, retry_num) logging.error("func %s retry failed", func) raise Exception('Exceed max retry num: {} failed'.format(retry_num)) return wrapper return decorator usage # this means try your function 5 times, each time sleep 60 seconds @retry(5, 60) def your_func(): pass Formal reference: https://peps.python.org/pep-0318/
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/127757715

django-rest-framework
tags question: http://stackoverflow.com/q/50292944
tags question: http://stackoverflow.com/q/50366872
tags question: http://stackoverflow.com/q/50284728
tags question: http://stackoverflow.com/q/50373051
tags question: http://stackoverflow.com/q/50307042
tags question: http://stackoverflow.com/q/50342894
tags question: http://stackoverflow.com/q/50370544
tags question: http://stackoverflow.com/q/50289482
tags question: http://stackoverflow.com/q/50340963
tags question: http://stackoverflow.com/q/50284845
tags question: http://stackoverflow.com/q/50384613
tags question: http://stackoverflow.com/q/50367739
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/50256852
tags question: http://stackoverflow.com/q/50365289
tags question: http://stackoverflow.com/q/50232634
tags question: http://stackoverflow.com/q/50240485
tags question: http://stackoverflow.com/q/50374192
tags question: http://stackoverflow.com/q/50255991
tags question: http://stackoverflow.com/q/50344721
tags question: http://stackoverflow.com/q/50244109
type: Tag
tags question: http://stackoverflow.com/q/50331797
tags question: http://stackoverflow.com/q/50250947
tags question: http://stackoverflow.com/q/50255005
tags question: http://stackoverflow.com/q/50232891
tags question: http://stackoverflow.com/q/50338673
tags question: http://stackoverflow.com/q/50347596
tags question: http://stackoverflow.com/q/50379441
tags question: http://stackoverflow.com/q/50240057
tags question: http://stackoverflow.com/q/50328698
tags question: http://stackoverflow.com/q/50290390
tags question: http://stackoverflow.com/q/50292851
tags question: http://stackoverflow.com/q/50356975
tags question: http://stackoverflow.com/q/50347401
tags question: http://stackoverflow.com/q/50260242

http://stackoverflow.com/q/50282054
type: Question
has comment: http://stackoverflow.com/comment/87606496
has answer: http://stackoverflow.com/a/50282101
accepted answer: http://stackoverflow.com/a/50282101
tagged with: data-visualization
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/4154969
has title: Pyplot / Matplotlib: How to achieve a compressed y-axis
type: AnsweredQuestion
score: 2
upvote count: 3
answer count: 2
tagged with: visualization
has body: I am using pyplot to create a climograph based on the visualization of Walter/Lieth. Climograph Walter/Lieth Another Climograph by Walter/Lieth As you can see on the images (the links above), the right y-axis is compressed starting from the value of 100. Their visual distance gets smaller while their numerical intervals become larger. I can't figure out how to achieve this in pyplot. I know how to set the tick values to create a custom scale but of course they always are equidistant. As you can see in my plot the plotted space on the right y-axis corresponds to the interval of the values: Maybe someone could give a hint on how to achieve the effect shown in the two links above. Cheers!
possible better answer: http://stackoverflow.com/a/50295014
downvote count: 1
has answer: http://stackoverflow.com/a/50295014
favorite count: 0

http://stackoverflow.com/a/50328564
upvote count: 1
has comment: http://stackoverflow.com/comment/87707103
answers question: http://stackoverflow.com/q/50328401
has comment: http://stackoverflow.com/comment/87676065
has comment: http://stackoverflow.com/comment/87703187
has comment: http://stackoverflow.com/comment/87685158
has comment: http://stackoverflow.com/comment/87678511
has body: Here is working version, from bs4 import BeautifulSoup import requests import csv with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results: reader = csv.reader(csvFile, delimiter=';') writer = csv.writer(results) for row in reader: # get the url url = row[0] # fetch content from server html = requests.get(url).content # soup fetched content soup = BeautifulSoup(html, 'html.parser') divTag = soup.find("div", {"class": "productsPicture"}) if divTag: tags = divTag.findAll("a") else: continue for tag in tags: res = tag.get('href') if res != None: writer.writerow([res])
score: 1
has comment: http://stackoverflow.com/comment/87675340
type: Answer
has comment: http://stackoverflow.com/comment/87681946
has comment: http://stackoverflow.com/comment/87677249
has comment: http://stackoverflow.com/comment/87674610
has comment: http://stackoverflow.com/comment/87673684
has comment: http://stackoverflow.com/comment/87680457
accepted answer of: http://stackoverflow.com/q/50328401
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87673527
has comment: http://stackoverflow.com/comment/87673499
has comment: http://stackoverflow.com/comment/87674420

http://stackoverflow.com/a/50337883
has comment: http://stackoverflow.com/comment/87692358
has comment: http://stackoverflow.com/comment/87692177
has body: Many ways to do it for filename in os.listdir(path): if filename.endswith('.csv'): table_list.append(pd.read_csv(filename,sep="|")) new_table_list.append(filename.split(".")[0]) One more for filename in os.listdir(path): if filename.endswith('.csv'): table_list.append(pd.read_csv(filename,sep="|")) new_table_list.append(filename[:-4]) and many more As @barmar pointed out, better to append path as well to the table_list to avoid any issues related to path and location of files and script.
accepted answer of: http://stackoverflow.com/q/50337843
type: Answer
score: 11
answers question: http://stackoverflow.com/q/50337843
upvote count: 11
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87768317
comment on: http://stackoverflow.com/a/50375949
score: 2
type: Comment
type: AnswerComment
has text: No, not again :|

http://stackoverflow.com/a/50349278
score: 8
type: AcceptedAnswer
downvote count: 0
upvote count: 8
accepted answer of: http://stackoverflow.com/q/50349202
type: Answer
has body: You can just use list comprehension: result = [{'description': a, 'sum': int(b)} for a, b in result[0]] But if you don't want to, what's wrong in your code, is that you initialize the dictionary before the loop. You have to redeclare it in each iteration, as in: rows = len(result[0]) all_descriptions_sums = [] for i in range(rows): description_sum = {} description_sum['description'] = result[0][i][0] description_sum['sum'] = int(result[0][i][1]) all_descriptions_sums.append(description_sum) return all_descriptions_sums
answers question: http://stackoverflow.com/q/50349202

http://stackoverflow.com/comment/87650059
has text: could you elaborate more of `m = df[cols].isnull().values & (df['change'] == 0).values[:, None] `? especially `(df['change'] == 0).values[:, None]`
type: AnswerComment
comment on: http://stackoverflow.com/a/50317094
score: 0
type: Comment

http://stackoverflow.com/comment/87497245
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50239885
has text: How can I exclude result {'a': 8} or {'a': 7, 'z': 1}, since I need all product be in machine at least once.

http://stackoverflow.com/q/50289133
has title: How to remove a residual plot in Jupyter output after displaying a matplotlib animation?
has body: I want to display an animation in Jupyter using Matplotlib. Here is some basic example: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() line, = ax.plot(np.random.rand(10)) ax.set_ylim(0, 1) def update(data): line.set_ydata(data) return line, def data_gen(): while True: yield np.random.rand(10) ani = animation.FuncAnimation(fig, update, data_gen, interval=100); from IPython.display import HTML HTML(ani.to_jshtml()) When I run the code for the first time (or after restarting the kernel) I get what I want: However, when I run the very same code for the second time I get a leftover in the left bottom: I noticed that when I add %matplotlib inline at the top, then I got the bad output even after restarting the kernel. Thus my guess is that I have to set the magic command %matplotlib to default at the top each time I create an animation, but I can't even find if %matplotlib have a default value. I use Anaconda. Here are my versions: Conda version: 4.4.10 Python version: Python 3.6.4 :: Anaconda, Inc. IPython version: 6.2.1 Jupyter version: 5.4.0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87594915
has comment: http://stackoverflow.com/comment/87594829
has comment: http://stackoverflow.com/comment/87594556
type: Question
has comment: http://stackoverflow.com/comment/87595022
tagged with: matplotlib
tagged with: animation
has comment: http://stackoverflow.com/comment/87595496
tagged with: python
accepted answer: http://stackoverflow.com/a/50291248
has comment: http://stackoverflow.com/comment/87594618
tagged with: ipython
score: 6
upvote count: 6
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/87595218
has answer: http://stackoverflow.com/a/50291248
has comment: http://stackoverflow.com/comment/87595932
has comment: http://stackoverflow.com/comment/87594916
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87595040
downvote count: 0

http://stackoverflow.com/comment/87665104
comment on: http://stackoverflow.com/q/50324561
has text: @AnjaneyuluBatta I deleted my database and applied it. But another error occured. It said "ValueError: Related model 'recommend.authuser' cannot be resolved" So im trying to delete all the migration files.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50328975
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/87673898
has body: try using:- divElement.find("a", { "title" : "Details" })
accepted answer of: http://stackoverflow.com/q/50328617
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50328617

http://stackoverflow.com/q/50274072
answer count: 1
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87564925
has comment: http://stackoverflow.com/comment/87564858
has body: I have written a code to do matrix multiplication of different range but it takes a lot of time to exexcute the code, code: Program to multiply two matrices using nested loops import time print("Enter the size of matrix A") m = int(input()) n = int(input()) print("Enter the size of matrix A") p = int(input()) q = int(input()) if(n==p): print('enter matrix A') else: print("invalid entry") exit() our_list1 = [] A = [] i = 0 int(i) for i in range(m): for i in range(n): number = int(input('Please enter a element ')) our_list1.append(number) A.append(our_list1) our_list1= [] print(A) print('enter matrix B') our_list1 = [] B = [] for i in range(p): for i in range(q): number = int(input('Please enter a element ')) our_list1.append(number) B.append(our_list1) our_list1= [] print(B) start_time = time.time() # our_list1 = [] R = [] for i in range(m): for i in range(q): number = 0 our_list1.append(number) R.append(our_list1) our_list1= [] print(R) for i in range(len(A)): # iterating by coloum by B for j in range(len(B[0])): # iterating by rows of B for k in range(len(B)): R[i][j] += A[i][k] * B[k][j] print(R) print("--- %s seconds ---" % (time.time() - start_time)) It takes more time to execute this method of matrix multiplication, how can I choose the efficient way of matrix multiplication of huge dimension range? So higher dimension array can be executed smoothly and quickly. Sample output: Matrix A[[3, 3, 3], [3, 3, 3], [3, 3, 3]] Matrix B[[3, 3, 3], [3, 3, 3], [3, 3, 3]] [[0, 0, 0], [0, 0, 0], [0, 0, 0]] [[27, 27, 27], [27, 27, 27], [27, 27, 27]] --- 0.00014400482177734375 seconds --- it takes 0.00014400482177734375 seconds can I improve this timmings when I do for higher dimension multiplication?
tagged with: python
has comment: http://stackoverflow.com/comment/87565288
has comment: http://stackoverflow.com/comment/87565367
has comment: http://stackoverflow.com/comment/87564995
has comment: http://stackoverflow.com/comment/87565340
accepted answer: http://stackoverflow.com/a/50274639
has comment: http://stackoverflow.com/comment/87565056
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50274639
tagged with: list
has title: How can I improve the efficiency of matrix multiplication in python?
has comment: http://stackoverflow.com/comment/87564939

http://stackoverflow.com/q/50230883
has comment: http://stackoverflow.com/comment/87479047
type: UnansweredQuestion
answer count: 1
tagged with: file-writing
type: Question
linked to: http://stackoverflow.com/q/845058
has answer: http://stackoverflow.com/a/50230929
score: 0
has comment: http://stackoverflow.com/comment/87478945
has body: I've been trying to create a text file using python in which I must write around 200 lines. Each line contains the same string but it contains a number that ranges from 1901 to 2100. For example, this_is_the_string_with_a_number_xxxx_in_each_line where xxxx varies from 1901 to 2100 (in the ascending order itself). How do I write these lines to a txt file using python?
has comment: http://stackoverflow.com/comment/87478977
tagged with: python
tagged with: text
has title: How to write multiple lines with a varying number in each line?

http://stackoverflow.com/q/50330959
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87678350
tagged with: python
tagged with: character-encoding
has title: Issues with encoding and decoding UTF-8
has comment: http://stackoverflow.com/comment/87677997
has comment: http://stackoverflow.com/comment/87678730
answer count: 0
score: 0
tagged with: utf-8
has comment: http://stackoverflow.com/comment/87678643
has comment: http://stackoverflow.com/comment/87685443
has body: I'm trying to receive input text, save it to file and call another process that will apply text-to-speech to it. I've been struggling with encoding for days and need some help. At first, I simply took the input text from the POST request as-is and saved it to a file, but I would get errors like this: File "/home/.../merlin/src/run_merlin.py", line 1224, in &lt;module&gt; main_function(cfg) File "/home/.../merlin/src/run_merlin.py", line 572, in main_function label_normaliser.perform_normalisation(in_label_align_file_list, binary_label_file_list, label_type=cfg.label_type) File "/home/.../merlin/src/frontend/linguistic_base.py", line 68, in perform_normalisation self.extract_linguistic_features(ori_file_list[i], output_file_list[i], label_type) File "/home/.../merlin/src/frontend/label_normalisation.py", line 26, in extract_linguistic_features A = self.load_labels_with_state_alignment(in_file_name) File "/home/.../merlin/src/frontend/label_normalisation.py", line 487, in load_labels_with_state_alignment utt_labels = fid.readlines() File "/home/.../merlin/.venv/lib/python3.5/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 0: invalid start byte So I did the following: text = text.encode('utf-8').split() file = codecs.open(filename, 'w+', 'utf-8') file.write(text.decode('utf-8')) file.close() But the same error keeps happening. I tried simply file.write(text), without decoding, but that gave me the following error: Can't convert 'bytes' object to str implicitly If it helps, I'm trying to work with Merlin, but as shown above, the error seems to be thrown by python's codecs.py when reading the file. EDIT: Following Giacomo Catenazzi's suggestion I changed the code to: text = text (not encoded) file = codecs.open(filename, 'w+', 'utf-8') file.write(text) file.close() But the same error happens. I added the full stack trace to the beginning of the question…
linked to: http://stackoverflow.com/q/19699367
type: Question
has comment: http://stackoverflow.com/comment/87678115

http://stackoverflow.com/q/50354155
tagged with: bash
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/50355371
has title: The difference between Python's subprocess.Popen with shell=True and a real shell
has comment: http://stackoverflow.com/comment/87727179
answer count: 1
has answer: http://stackoverflow.com/a/50355371
downvote count: 0
has body: When I open a command line I want it to start in the same working directory where the currently active window is. Therefore I have written a python script which figures out the correct path. It takes as argument a command which opens a terminal. In this argument it replaces a placeholder with the desired directory and executes the command with subprocess.Popen(cmd, stderr=subprocess.PIPE, shell=True) The string cmd is correctly assembled to: xterm -e 'cd '\''/mnt/data/software/computer/tools/i3'\''; /usr/bin/bash' If I execute this command in bash it opens xterm in the correct directory as desired. If I execute this command from the python script xterm does not open. Where is the difference? Additional information: I am using Python 3.6.5. echo $SHELL returns /bin/bash. The keybinding to the script in my i3 config: bindsym $mod+Return exec "/mnt/data/software/computer/tools/i3/i3_launch_cwd.sh \\"xterm -e 'cd %{cwd}; /usr/bin/bash'\\"" (This shell script is just a simple wrapper which redirects stderr to a log file for debugging) After executing the following command in bash xterm does open even from python: xrdb -merge -I$HOME ~/.Xresources The relevant line in Xresources is xterm*faceName: DejaVu Sans Mono Book Why does that make a difference? Solution: Thanks to Charles Duffy's comments I have found the problem. In my python script I am redirecting stderr with stderr=subprocess.PIPE but I forgot to read stderr. Before loading my Xresources file which sets the font xterm prints a warning to stderr that a font can not be loaded. xterm has a very small buffer. Because my program is not reading stderr the buffer is not cleared and xterm is blocked. Replacing subprocess.Popen(cmd, stderr=subprocess.PIPE, shell=True) with p = subprocess.Popen(cmd, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() sys.stderr.write(err) Would solve the problem. But because I am not doing anything with stderr there is no need to redirect it in the first place. So instead I am…
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87727001
has comment: http://stackoverflow.com/comment/87726766
has comment: http://stackoverflow.com/comment/87726681
has comment: http://stackoverflow.com/comment/87810913
tagged with: python
score: 1
type: AnsweredQuestion

http://stackoverflow.com/q/50267256
downvote count: 0
upvote count: 1
has title: Advanced access for `write` on res.partner
favorite count: 0
has comment: http://stackoverflow.com/comment/87674127
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87590383
tagged with: security
accepted answer: http://stackoverflow.com/a/50328924
tagged with: odoo
has answer: http://stackoverflow.com/a/50328924
tagged with: python
type: Question
tagged with: acl
tagged with: odoo-10
score: 1
has comment: http://stackoverflow.com/comment/87667493
has comment: http://stackoverflow.com/comment/87670407
answer count: 1
has body: Is data that was supplied to write() with parameter (vals) accessible from within method check_access_rights? I inherited from res.partner and overriden method check_access_rights with intent to allow a user with no write rights on res.partner to update child_ids (of that partner) if that child was created by that user (create_uid = user.id) . I hope to be able to implement somewhere (in methods write or check_access_rights) this pseudo-code: if `the user belongs to a group "GroupX"` and `user tries to only update field "child_ids" with records that are created by that user` then `allow this write operation on res.partner` else `raise AccessError`

http://stackoverflow.com/a/69227899
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/50263380
has body: I had the same issue. It was the long path. I solved by adding this //?/C at the beginning of the path path = r"//?/C:\Users\Camilo\Proyectos"
type: Answer
upvote count: 4

http://stackoverflow.com/comment/87624999
has text: This does seem like a solution, however, it doesn't seem to work for me. I DO get the whole html part in the response of the call on the webpage when I'm checking the console, however, the download won't happen still.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50282528

http://stackoverflow.com/comment/87620422
score: 0
comment on: http://stackoverflow.com/a/50300501
type: Comment
has text: Great general Answer. I think the problem why `img.makeelement('use', img.attrib)` does not work for me, is that my svg file misses `xmlns:xlink="http://www.w3.org/1999/xlink"`. Is there any way I can add this?
type: AnswerComment

http://stackoverflow.com/q/50381372
upvote count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/43267754
has body: from PIL import Image &gt;&gt;&gt; from PIL import Image Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "D:\appa\Python\miniconda\lib\site-packages\PIL\Image.py", line 60, in &lt;module&gt; from . import _imaging as core ImportError: DLL load failed: The specified module could not be found import image shows that there is no module to import Import PIL PIL.Image &gt;&gt;&gt; import PIL &gt;&gt;&gt; PIL.Image Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'PIL' has no attribute 'Image' Also shows the same error I have used conda install Pillow and it has installed Pillow = 5.1.1, I have also tried downgrading to Pillow = 5.1.0 Any solutions? Do I downgrade it to a lower version for it to work or is there something I have missed during installation.
tagged with: python
has title: PIL 5.1 not working
has answer: http://stackoverflow.com/a/50381513
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/87779002
answer count: 1
score: -1
tagged with: image
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87778848
linked to: http://stackoverflow.com/q/43267754

http://stackoverflow.com/a/50267585
score: 1
type: Answer
has body: You literally don't need to do anything: this functionality is built into the simple_tag decorator. Just use it the way you show in that example. See the last paragraph of the simple_tag section of the docs.
answers question: http://stackoverflow.com/q/50264609
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50264609

http://stackoverflow.com/a/50248675
has body: it is working as expected with the following code now, although I am not sure if this is the most elegant solution for index, row in r.iteritems(): link = row.replace(" ", "") response = requests.get(link).url base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(response)) if base_url=="http://www.sxc.com/": re = urllib.unquote(response.encode("ascii")) item_id = re.rsplit('/', 1) df['links'].loc[index] = re df['item_ids'].loc[index] = item_id[-1]
accepted answer of: http://stackoverflow.com/q/50235946
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50235946

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/50321338
tags question: http://stackoverflow.com/q/50282224
type: Tag

http://stackoverflow.com/a/50247679
has body: MySQL 8.0 made caching_sha2_password the default authentication for new accounts, which requires updated connectors to be able to use it. Alternatively, you can change the account to use the native auth method (but that is less secure).
answers question: http://stackoverflow.com/q/50243506
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50256912
tagged with: python-3.x
has body: I've written a script in python in combination with BeautifulSoup to scrape addresses from some html elements. The addresses are separated by br tags, so I can't get all them using next_sibling. I've tried with two different approaches to reach them. However, the latter one is slightly close. I am still unsure as to what should be the efficient approach to get the addresses like the way I've pasted below in my expected output. Thanks in advance. Elements within which the addresses lies: AK 5200 A St Ste 102 Anchorage, AK 99518 Phone: (907) 563-9333 Website Profile What I've tried so far with: soup = BeautifulSoup(content,"lxml") #here content holding the elements above for items in soup.select(".item-listing"): addr = [item.next_sibling for item in items.select("h4")] # addr = [item.string for item in items.select_one("h4").next_siblings if not item.name=="a"] print(addr) Result of first addr (from the script): ['\n 5200 A St Ste 102'] Result of commented out addr: ['\n 5200 A St Ste 102', None, '\n Anchorage, AK 99518', None, '\n \n Phone: (907) 563-9333\n ', None, '\n', None, '\n', '\n', '\n'] My expected output (or very close to this): 5200 A St Ste 102 Anchorage, AK 99518 Phone: (907) 563-9333
has comment: http://stackoverflow.com/comment/87532550
answer count: 1
downvote count: 0
tagged with: web-scraping
upvote count: 1
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/87541556
type: AnsweredQuestion
has title: Trouble getting items from some messy elements
accepted answer: http://stackoverflow.com/a/50259976
score: 1
has answer: http://stackoverflow.com/a/50259976
tagged with: python
has comment: http://stackoverflow.com/comment/87532660
favorite count: 0
type: Question

http://stackoverflow.com/comment/87481464
type: Comment
comment on: http://stackoverflow.com/a/50231262
score: 0
type: AnswerComment
has text: Thanks for your comment @SeanFrancisN.Ballais. I am using PyCharm so I simply go to PyCharm Community Edition->Preferences->Project Interpreter and I simply add the package after finding it. This is how I did for all packages/libraries like Flask, PyMySQL etc

http://stackoverflow.com/comment/87545462
has text: that image is not from my data, its just an example showing how it connects different points with polyline, which is as mentioned in the following link http://qingkaikong.blogspot.com/2016/06/using-folium-4-draw-lines-plot-san.html
comment on: http://stackoverflow.com/q/50260231
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50258081
type: AnsweredQuestion
tagged with: random
has comment: http://stackoverflow.com/comment/87534185
linked to: http://stackoverflow.com/q/31598562
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87534253
downvote count: 1
has comment: http://stackoverflow.com/comment/87534239
has title: Creating a random number with the usage of set()
has comment: http://stackoverflow.com/comment/87534250
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50258129
score: 0
has answer: http://stackoverflow.com/a/50258129
has comment: http://stackoverflow.com/comment/87534296
has comment: http://stackoverflow.com/comment/87534336
tagged with: python
has comment: http://stackoverflow.com/comment/87534076
has body: Considering the fact that set is an unordered data structure, I began to wonder if it is possible to create a truly "random" number with the usage of it (or with the usage of a dictionary). Lets consider such an input number represented as a string: input = "0123456789" And then we convert the string into a set: input_set = set(input) After printing the result of this operation multiple times, we have following example outputs: {'9', '3', '4', '6', '0', '7', '1', '8', '5', '2'} {'3', '4', '2', '1', '5', '7', '0', '8', '6', '9'} Now we can convert the elements of the set into a string with the usage of: output = ''.join(set_input) And the result of this operation for the sets above would be: 9346071852 3421570869 Would generation of a random number in a following way be considered a good practice? And most of all, do I understand correctly that it would be a "pseudorandom" number, because we could reproduce the result with the usage of some seed value or key?

http://stackoverflow.com/comment/87664518
score: 0
has text: @JeruLuke can you elaborate more on it, on mouse wheel event. I tried to see what mouse wheel output gives. But didnt understand which value to pass!!!
type: QuestionComment
comment on: http://stackoverflow.com/q/50306303
type: Comment

http://stackoverflow.com/q/50345303
answer count: 1
has comment: http://stackoverflow.com/comment/87706767
tagged with: performance
type: Question
has comment: http://stackoverflow.com/comment/87708953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87708895
score: 0
has comment: http://stackoverflow.com/comment/87707040
accepted answer: http://stackoverflow.com/a/50353401
has comment: http://stackoverflow.com/comment/87707226
has comment: http://stackoverflow.com/comment/87707305
has answer: http://stackoverflow.com/a/50353401
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/87711862
has comment: http://stackoverflow.com/comment/87712164
has comment: http://stackoverflow.com/comment/87722513
tagged with: python
has body: I am currently working on implementing multiprocessing on a code segment which takes relatively long to run. It is basically applying a very elaborate function a fair number of times. At the moment I am utilising the following syntax: if (__name__ == '__main__'): pool = Pool(4) results = pool.map(function,data) pool.close() output = pool.join() My CPU consists of 4 cores, hence the Pool(4). I see from my CPU usage that when implementing multiprocessing all 4 pools are using approximately 25% of the available CPU, in contrast to one CPU core using 25% when not using multiprocessing. However, I see that the four CPU cores are using a significantly lower amount of memory: approximately 45k each in contrast to almost 550k when running on one CPU core without multiprocessing (a lack of memory does not seem to be the issue as it remains at approximately 27% utilisation throughout). The computation takes approximately 5 minutes on one CPU core, and stil has not finished for an hour when running on all 4. Could somebody shine some expert views on what may be the root cause of this inefficiency? Happy coding!
has title: Python Multiprocessing Computational Performance Optimisation

http://stackoverflow.com/comment/87603937
has text: @piRSquared thank you sir : -) Both of your guys comment mean a lot to me :-)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50293599
type: AnswerComment

automation
tags question: http://stackoverflow.com/q/50270199
tags question: http://stackoverflow.com/q/50337172
tags question: http://stackoverflow.com/q/50311564
tag name: automation
tags question: http://stackoverflow.com/q/50246844
tags question: http://stackoverflow.com/q/50265439
type: Tag
tags question: http://stackoverflow.com/q/50279442

http://stackoverflow.com/comment/87490952
comment on: http://stackoverflow.com/q/50236792
has text: So what's wrong with it? Is it giving you an error? What's up
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/58969896
upvote count: 0
answers question: http://stackoverflow.com/q/50319617
downvote count: 1
has body: imagine you have a function called preprocessing() that preprocess your images with cv2, if you try to apply it as: data = np.array(list(map(preprocessing,data))) it won't work and that because np.array creates int64and you are trying to assign np.uint8 to it, what you should do instead is adding dtype parameter as follow: data = np.array(list(map(preprocessing,data)), dtype = np.uint8)
type: Answer
score: -1

http://stackoverflow.com/a/50370604
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87757269
accepted answer of: http://stackoverflow.com/q/50370231
has comment: http://stackoverflow.com/comment/87757469
has body: Think of it this way - If web server can generate the files , it can display them also. As for your answer - if you know the path of the file, use the python open built in method to open the file and render the result to a template. data = open('file_path').read().decode('utf-8') render(request, template, context={data:data})
type: Answer
answers question: http://stackoverflow.com/q/50370231

http://stackoverflow.com/q/50280824
has body: After loging in correctly, I want to redirect the user to another page so I use redirect, but I get a NoReverseMatch error. Reverse for 'watchfilms' with arguments '()' and keyword arguments '{}' not found. I don't know what's going wrong so I'm showing you my urls.py and views.py files. Maybe you see something wrong... project's url.py urlpatterns = patterns('', url(r'^films/', include('films.urls')), url(r'^admin/', include(admin.site.urls)), ) app's url.py urlpatterns = patterns('', url(r'^$', 'films.views.index'), url(r'^signup$', 'films.views.signUp'), url(r'^login$', 'films.views.logIn'), url(r'^signedupok$', 'films.views.signedUpOk'), url(r'^watchfilms$', 'films.views.watchFilms'), url(r'^logout$', 'films.views.logout'), ) views.py ... def logIn(request): error = "" username = request.POST.get('username', False) pass = request.POST.get('password', False) user = authenticate(username = username, password = pass) if username or pass: if user is not None: if user.is_active: login(request, user) return redirect('watchfilms') else: error = 'Error while login!' else: errorea = 'Data is not correct!' return render(request, 'films/login.html', {'error': error}) @login_required def watchFilms(request): film_list = Film.objects.all() paginator = Paginator(film_list, 3) page = request.GET.get('page') try: films = paginator.page(page) except PageNotAnInteger: films = paginator.page(1) except EmptyPage: films = paginator.page(paginator.num_pages) return render(request, 'films/watchFilms.html', {'films': films}) ... Once login is OK, watchFilms view should be called but it looks like it cannot be found (I don't get it why, I think urls.py is OK)...
has title: Django NoReverseMatch when redirecting to view
tagged with: http-redirect
has comment: http://stackoverflow.com/comment/87578225
tagged with: django
tagged with: django-urls
tagged with: python
type: AnsweredQuestion
tagged with: view
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50280874
possible better answer: http://stackoverflow.com/a/50280874
has answer: http://stackoverflow.com/a/50280893
accepted answer: http://stackoverflow.com/a/50280893
favorite count: 0
type: Question

http://stackoverflow.com/a/50262817
answers question: http://stackoverflow.com/q/50262722
type: Answer
score: 0
has body: It depends on what you want your code to do. Modules are usually just collections of functions that do different things. For example, the module "random" contains functions for generating random numbers; and "colored" lets you change the font and background of the text you print in your terminal. You can look around on sites like github.com to find cool libraries that may help you, or you may simply google around.

http://stackoverflow.com/comment/87774670
score: 1
has text: @MihaiAlexandru-Ionut Always happy to return good sportsmanship in kind. Your answer is quite nice in its own right.
type: Comment
comment on: http://stackoverflow.com/a/50379052
type: AnswerComment

http://stackoverflow.com/q/50362707
answer count: 0
linked to: http://stackoverflow.com/q/3348460
type: UnansweredQuestion
has title: Python, csv.writer made an empty list every iteration
has body: So i have this 2d array z = [["test","dus"],["dus","ta"]] then i want to write it to an csv files by using this python code: with open('test.csv','w') as out: csv_out=csv.writer(out) csv_out.writerow(['input','output']) for row in z: csv_out.writerow(row) it successfully written it in the csv however i don't get why the results look like this: input output test dus dus ta so it create an empty list after each iteration which doesn't make sense why is this happening ? is it possible to avoid it ?
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87741852
tagged with: python
has comment: http://stackoverflow.com/comment/87741932
duplicate of: http://stackoverflow.com/q/3348460
has comment: http://stackoverflow.com/comment/87741837
tagged with: export-to-csv
score: 0

http://stackoverflow.com/a/50283418
has body: You could use a simple for loop: with open('test.txt', 'r') as f: data = [None]+f.read().split('\n') size = 3 for i in range(len(data)-(size-1)): print(data[i:i+size])
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50283152
type: Answer

http://stackoverflow.com/q/50302730
has comment: http://stackoverflow.com/comment/87621912
has answer: http://stackoverflow.com/a/50302748
has comment: http://stackoverflow.com/comment/87621883
accepted answer: http://stackoverflow.com/a/50302748
tagged with: python
has comment: http://stackoverflow.com/comment/87621863
has answer: http://stackoverflow.com/a/50302763
possible better answer: http://stackoverflow.com/a/50302763
has comment: http://stackoverflow.com/comment/87621873
has comment: http://stackoverflow.com/comment/87621867
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87621875
has title: String Issue in Python
has comment: http://stackoverflow.com/comment/87621909
has comment: http://stackoverflow.com/comment/87621903
has body: I would like to understand why one program of mine is giving error and one not where as I am applying same concept for both of them. The program that is giving error: greeting = "test" age = 24 print( greeting + age) Which is true and it should give error because of incompatible variable types being concatenated. But this same behavior I was expecting from the below code as well where as it is giving proper result. Why is it so? print("Please enter your name: ") myname = input() print("Your name is " + myname) print("Please enter your age: ") myage = input() print("Your age is: " + myage) print("Final Outcome is:") print(myage + " " + myname)
has comment: http://stackoverflow.com/comment/87621858
has comment: http://stackoverflow.com/comment/87621869
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50358327
has answer: http://stackoverflow.com/a/54278757
tagged with: jupyter-notebook
score: 28
upvote count: 30
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/74274910
answer count: 5
tagged with: python
tagged with: pylint
has title: Using Pylint in Ipython (Jupyter-Notebook)
has comment: http://stackoverflow.com/comment/87743462
linked to: http://stackoverflow.com/q/67669843
linked to: http://stackoverflow.com/q/26126853
has answer: http://stackoverflow.com/a/66459252
possible better answer: http://stackoverflow.com/a/66459252
type: AnsweredQuestion
downvote count: 2
tagged with: flake8
accepted answer: http://stackoverflow.com/a/54278757
has body: I want to run Pylint or any equivalent while using Jupyter-Notebook. Is there a way to install and run Pylint this way?
has answer: http://stackoverflow.com/a/71495554
linked to: http://stackoverflow.com/q/37423380
has answer: http://stackoverflow.com/a/62557824

http://stackoverflow.com/a/50287260
score: 0
has body: Found it difficult to repeat given the older version of Python and no access to the original data but your output above suggests whitespace in with the value. Try sample['colval'] = sample['colval'].apply(lambda x: 0 if x.strip()=='N' else 1)
accepted answer of: http://stackoverflow.com/q/50286017
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50286017

http://stackoverflow.com/a/50343789
downvote count: 0
upvote count: 1
has body: You need to use 3rd party service which manually checks the URL by country/region, e.g. asm.ca.com I guess there's no way you can do it for specific IP. So you should determine the country by IP first.
answers question: http://stackoverflow.com/q/50343736
score: 1
type: Answer

http://stackoverflow.com/q/50308620
tagged with: dataframe
tagged with: python
score: -2
linked to: http://stackoverflow.com/q/24216425
has body: I have following data from df proid sku qty 0 p009 SKPK 0.0 1 p009 SKKP 2.0 2 p008 SKPK 0.0 3 p008 SKC1 4.0 4 p008 SKKP 0.0 To qty column i want to add value to 'qty' based on value in 'sku'. the value are present as follows starterkit = {"SKKP":4,'SKP1':3,'SKP1':3,'SKPK':1,'SKC1':1 } want to do something like if df.sku == 'SKKP' df.qty += starterkit['SKKP'] Resulting data frame should be proid sku qty 0 p009 SKPK 1.0 1 p009 SKKP 6.0 2 p008 SKPK 1.0 3 p008 SKC1 5.0 4 p008 SKKP 4.0
tagged with: pandas
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24216425
accepted answer: http://stackoverflow.com/a/50308627
answer count: 2
downvote count: 3
has title: Add a value to a column in data frame all rows at once :Python
upvote count: 1
has answer: http://stackoverflow.com/a/50308627
has answer: http://stackoverflow.com/a/50308626
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50308626

http://stackoverflow.com/a/50378173
has comment: http://stackoverflow.com/comment/87774015
has comment: http://stackoverflow.com/comment/87772533
has comment: http://stackoverflow.com/comment/87773013
answers question: http://stackoverflow.com/q/50377322
has body: I/O nodes such as tf.train.Saver cannot be placed on the GPU. Create them outside your tf.device context after creating your net.
has comment: http://stackoverflow.com/comment/87772616
type: Answer
score: 0

http://stackoverflow.com/a/50363771
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50347596
has body: I finally got it:(This an update of the above code) ##################### HTTP COMMUNICATION WITH PAYROLL ############ # Update Payroll with Employee Relevant Data. # ################################################################### try: url = PAYROLL_IP + "/payroll/employees/" payload = { 'subject_type': 'EMPLOYEE-DETAILS', 'first_name': employee.user.first_name, 'last_name': employee.user.last_name, 'department': employee.department.name, 'company': employee.company.name, 'job_group': employee.job_group.name, 'hr_number': request.data['hr_number'], 'nhif_no': request.data['nhif_no'], 'nssf_no': request.data['nssf_no'], 'tax_id_number': request.data['tax_id_number'], 'joining_date': request.data['joining_date'], } # res = requests.post(url, data=payload) r = requests.post( url, headers={'Content-Type': 'application/json'}, data=json.dumps(payload, cls=DjangoJSONEncoder)) except Exception as e: raise e return Response(data={"Data": "Add Employee Failed", "Error": str(r.status_code)}, status=status.HTTP_201_CREATED) if r.status_code == 201: return Response(data={"Data": "Employee Added Successfull"}, status=status.HTTP_201_CREATED) else: return Response(data={"Answer": "Employee to Payroll Failed", "Error": str(r.status_code)}, status=status.HTTP_201_CREATED)

http://stackoverflow.com/a/50287054
answers question: http://stackoverflow.com/q/50286355
has comment: http://stackoverflow.com/comment/87590363
type: Answer
has comment: http://stackoverflow.com/comment/87590669
has body: I checked your javascript and you are using global window variables that dont exist instead of the local variables you predefined. Firstly I think you should use the local variables you defined. var first_time = 0; var current_count = 0; var total_count = 0; function update(){ if (first_time === 0){ current_count = $('td').length; total_count = current_count; first_time = 1; //var txt = $(" ").text("No new images"); $('body').append(" No new images "); } else { total_count = $('td').length; if (total_count>current_count){ $('.notify').text(total_count-current_count + " images added !"); $('html, body').animate({scrollTop:$(document).height()}, 'slow'); //alert(total_count-current_count + ' images added !'); current_count = total_count; } } } I hope this helps. I'll like you to try using a callback function at the end of the image load since its likely the update function might be called twice because the image load might be taking longer than 2 seconds to load its resource thereby causing setInterval to catch up with it. setInterval(function(){ $('.image-area').load("{{ url_for('image',im=image_date) }}", function() { update(); }); }, 2000);
score: 2
has comment: http://stackoverflow.com/comment/87590159
has comment: http://stackoverflow.com/comment/87590446
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50286355
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87591360
has comment: http://stackoverflow.com/comment/87590701
has comment: http://stackoverflow.com/comment/87590832
has comment: http://stackoverflow.com/comment/87591509

http://stackoverflow.com/comment/87701394
score: 0
type: AnswerComment
type: Comment
has text: That note explains why I was receiving a warning about sorted list. It was erroring on being passed a dict.
comment on: http://stackoverflow.com/a/50342651

http://stackoverflow.com/q/50284728
type: Question
has body: I'm working a project, and use Django REST framework and mongo engine, and I'm confused a question two days, and the detail see below: class Jvv(EmbeddedDocument): unit = fields.StringField() unitValue = fields.IntField() class Meta: db_table = 'imagerecognition' class ImageRecognition(Document): imageUrl = fields.StringField(default='', max_length=100) createTime = fields.DateTimeField(default=datetime.now()) ddPercent = fields.FloatField(required=False, default='') jvv = fields.ListField(fields.EmbeddedDocumentField(Jvv)) def __str__(self): return self.imageUrl class Meta: db_table = 'imagerecognition' then the serializer.p document is : class JvvSerializer(mongoserializers.EmbeddedDocumentSerializer): class Meta: model = Jvv fields = '__all__' class ImageUrlSerializer(mongoserializers.DocumentSerializer): jvv = JvvSerializer(many=True) class Meta: model = ImageRecognition fields = ('imageUrl', 'createTime', 'ddPercent', 'jvv') and the views.py content is below: class ImageUrlSave(views.APIView): def get(self, request, *args, **kwargs): imgs = ImageRecognition.objects(imageUrl='白菜') serializer = ImageUrlSerializer(imgs, many=True) ImageRecognition(imageUrl='土豆', ddPercent=8.22, jvv={'unit':'m', 'unitValue':12}).save() data = serializer.data return Response({ 'msg': 'SUCCESS', 'code_status': 1000, 'result': data }) the question is the mongodatabases have been completed, I want to take some data from it, but when I runserver, it shows raise ValueError("The source SON object needs to be of type 'dict'") ValueError: The source SON object needs to be of type 'dict', how can I handle this problem, and I am Looking forward to get answer. Thank you.
score: 1
tagged with: python
has title: Django REST framwork mongoengine ValueError: The source SON object needs to be of type 'dict'
tagged with: mongoengine
has comment: http://stackoverflow.com/comment/88662639
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87585632
downvote count: 0
tagged with: django
upvote count: 1
tagged with: django-rest-framework
favorite count: 0

http://stackoverflow.com/q/50335057
type: Question
has comment: http://stackoverflow.com/comment/87686344
answer count: 2
has comment: http://stackoverflow.com/comment/87686442
has comment: http://stackoverflow.com/comment/87686751
has comment: http://stackoverflow.com/comment/87686899
has comment: http://stackoverflow.com/comment/87686453
has body: I have a question, I tried to search the forum and see if there is something that can help me but unfortunately I couldn't so here it is: Currently I'm using our AD system and check through that list to see if a user exists and depending on that give them access or not users = [AD user list] for user in users: if user == "user x": print "you are in" else: print "denied" This works great and all but I want to know if I can make this a bit more efficient, so say if the "user x" is the 10th in the list, this code will print "denied" 9 times before it prints "you are in". Is it possible to somehow look into the list first and if the string match is in there give a 1 and if not a 0? This way when I print this I get either a 1 or a 0. Hope my question was clear and I provided enough details. I appreciate all the help.
has title: Loop through a python list and get a 1 or 0 for a match result
has answer: http://stackoverflow.com/a/50335122
tagged with: python
has comment: http://stackoverflow.com/comment/87686343
type: AnsweredQuestion
tagged with: python-2.7
score: 0
possible better answer: http://stackoverflow.com/a/50335125
accepted answer: http://stackoverflow.com/a/50335122
has answer: http://stackoverflow.com/a/50335125
has comment: http://stackoverflow.com/comment/87686427
has comment: http://stackoverflow.com/comment/87686370

http://stackoverflow.com/q/50308750
tagged with: python
has body: I am following the tutorial here to learn Deep Reinforcement Learning (I am very new to the topic). When I try to run the script below on my Macbook it returns me an Import Error (ImportError: sys.meta_path is None, Python is likely shutting down). I tried to run it from the Mac terminal and also in Pycharm with the same result. I tried also with other deep learning scripts and the error is the same (it seems not related to this script in particular). Could you please help me understanding where I am wrong? Script: # Import the gym module import gym # Create a breakout environment env = gym.make('BreakoutDeterministic-v4') # Reset it, returns the starting frame frame = env.reset() # Render env.render() is_done = False while not is_done: # Perform a random action, returns the new frame, reward and whether the game is over frame, reward, is_done, _ = env.step(env.action_space.sample()) # Render env.render() Error below: /usr/local/bin/python3.6 /Users/marcogdepinto/PycharmProjects/PlayPong/pong.py 2018-05-12 18:58:11.915 Python[567:12594] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to (null) Exception ignored in: &lt;bound method SimpleImageViewer.__del__ of &lt;gym.envs.classic_control.rendering.SimpleImageViewer object at 0x10b65bc88&gt;&gt; Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/gym/envs/classic_control/rendering.py", line 347, in __del__ File "/usr/local/lib/python3.6/site-packages/gym/envs/classic_control/rendering.py", line 343, in close File "/usr/local/lib/python3.6/site-packages/pyglet/window/cocoa/__init__.py", line 281, in close File "/usr/local/lib/python3.6/site-packages/pyglet/window/__init__.py", line 770, in close ImportError: sys.meta_path is None, Python is likely shutting down Process finished with exit code 0
type: AnsweredQuestion
score: 3
tagged with: reinforcement-learning
tagged with: deep-learning
upvote count: 3
accepted answer: http://stackoverflow.com/a/50308765
has answer: http://stackoverflow.com/a/50308765
favorite count: 0
type: Question
has title: Python - script made with gym does not work on Mac
answer count: 2
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/51878216
has answer: http://stackoverflow.com/a/51878216
downvote count: 0

multi-index
tags question: http://stackoverflow.com/q/50369334
tag name: multi-index
tags question: http://stackoverflow.com/q/50277263
tags question: http://stackoverflow.com/q/50368090
tags question: http://stackoverflow.com/q/50367703
tags question: http://stackoverflow.com/q/50288315
type: Tag
tags question: http://stackoverflow.com/q/50380093

http://stackoverflow.com/a/50328487
has comment: http://stackoverflow.com/comment/87676896
downvote count: 0
has comment: http://stackoverflow.com/comment/87676817
has comment: http://stackoverflow.com/comment/87674845
has comment: http://stackoverflow.com/comment/87674754
type: Answer
answers question: http://stackoverflow.com/q/50326058
upvote count: 2
score: 2
has body: Either skip parsing in Python: rawKafkaStream.map(lambda rawTweet: rawTweet[1]).foreachRDD(process) or don't use JSON reader: def process(time, rdd): try: sqlContext = getSqlContextInstance(rdd.context) # May or may not work correctly without schema (see below) jsonRDD = sqlContext.createDataFrame(rdd) jsonRDD.registerTempTable("tweets") jsonRDD.printSchema() except: pass In general with both methods you should provide schema: from pyspark.sql.types import * schema = StructType([...]) jsonRDD = sqlContext.read.schema(schema).json(rdd) and jsonRDD = sqlContext.createDataFrame(rdd, schema) respectively.

http://stackoverflow.com/a/50272398
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87591748
score: 1
answers question: http://stackoverflow.com/q/50272397
has comment: http://stackoverflow.com/comment/87572716
type: Answer
has comment: http://stackoverflow.com/comment/87605198
has body: Answer is here below. Please post suggestions to help me improve this code. from PySide2.QtCore import qApp, QTimer from PySide2.QtWidgets import QApplication, QWidget class Widget(QWidget): def __init__(self): super().__init__() self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.timeout.connect(self.single_click) self.double_click_interval = qApp.doubleClickInterval() def mouseReleaseEvent(self, e): if not self.timer.isActive(): self.timer.start(self.double_click_interval) else: self.timer.stop() self.double_click() super().mouseReleaseEvent(e) def single_click(self): print("single") def double_click(self): print("double") if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Widget() w.show() w.raise_() sys.exit(app.exec_())

http://stackoverflow.com/comment/87662472
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50323333
type: Comment
has text: @SCB : I have again verified.In one sessions I always get output 1,in other session I always get output 2

http://stackoverflow.com/comment/87582656
comment on: http://stackoverflow.com/a/50283039
type: AnswerComment
type: Comment
has text: @MateenUlhaq - your solution still didn't remove the quotes
score: 0

http://stackoverflow.com/q/50371690
type: AnsweredQuestion
has title: Unable to find the index in array
score: 0
has comment: http://stackoverflow.com/comment/87760584
type: Question
has answer: http://stackoverflow.com/a/50373787
answer count: 1
accepted answer: http://stackoverflow.com/a/50373787
tagged with: python
has body: Sorry for the very baisc question, but I have an issue on Python (this is my very first python script). I don't understand the root cause Below my code: # On découpe notre dataset en train et en test X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) # On calcule les coefficients est = sm.OLS(Y_train, X_train).fit() # Export les coef dans des variables coefSurface = est.params["surface"] coefArrondissement = est.params["arrondissement"] indices = [i for i, x in enumerate(X_train["surface"]) if x != "whatever"] indices2 = [i for i, x in enumerate(X_train["arrondissement"]) if x != "whatever"] print(indices) print(indices2) #TRAINING predicted_prices = [] for n in range(0, len(Y_train)): print((coefSurface * X_train["surface"][n]) + (coefArrondissement * X_train["arrondissement"][n])) This code display: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,…

http://stackoverflow.com/comment/87654528
has text: your editing doesn't work for one figure but i fixed it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50319233
type: AnswerComment

http://stackoverflow.com/q/50324645
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50325723
has comment: http://stackoverflow.com/comment/87980728
answer count: 1
upvote count: 10
favorite count: 0
accepted answer: http://stackoverflow.com/a/50325723
type: Question
has title: Python web service subscribed to reactive source produces strange behavior in object
tagged with: gunicorn
tagged with: rx-py
tagged with: falconframework
downvote count: 0
score: 10
tagged with: python
has body: I have implemented a web service using Falcon. This service stores a state machine (pytransitions) that is passed to service's resources in the constructor. The service is runs with gunicorn. The web service launches a process on start using RxPy. The event returned in the on_next(event) is used to trigger a transition in the state machine. THE BUG I expect that the state machine has a consistent state both in the service and in the resources but it seems that in the resources the state never changes. We have a test that tries to reproduce this behavior, but surprisingly the test works class TochoLevel(object): def __init__(self, tochine): self.tochine = tochine def on_get(self, req, res): res.status = falcon.HTTP_200 res.body = self.tochine.state def get_machine(): states = ["low", "medium", "high"] transitions = [ {'trigger': 'to_medium', 'source': ['low', 'medium', 'high'], 'dest': 'medium'}, {'trigger': 'to_high', 'source': ['low', 'medium', 'high'], 'dest': 'high'}, {'trigger': 'to_low', 'source': ['low', 'medium', 'high'], 'dest': 'low'} ] locked_factory = MachineFactory.get_predefined(locked=True) return locked_factory( states=states, transitions=transitions, initial='low', auto_transitions=False, queued=False ) def _level_observable(observer): for i in range(1, 21): sleep(0.1) next_val = 'to_low' if 8 &lt;= i &lt;= 15: next_val = 'to_medium' elif i &gt; 15: next_val = 'to_high' observer.on_next(next_val) observer.on_completed() def get_level_observable(): return Observable.create(_level_observable) class NotBlockingService(falcon.API): def __init__(self): super(NotBlockingService, self).__init__() self.tochine = get_machine() self.add_route('/tochez', TochoLevel(self.tochine)) def _run_machine(self, val): self.tochine.trigger(val) print('machine exec: {}, state: {}'.format(val, self.tochine.state)) return self.tochine.state def start(self): source = get_level_observable() (source.subscribe_on(ThreadPoolScheduler(2)) .subscribe(self._run_machine)) def test_ca…

http://stackoverflow.com/a/50379259
has body: Use map and join: df['Multi Name'] = df.groupby('ID')['Name'].transform('unique').map(', '.join) Output: ID Name Multi Name 0 1 John Doe John Doe, Jane Doe 1 1 Jane Doe John Doe, Jane Doe 2 2 John Smith John Smith, Jane Smith 3 2 Jane Smith John Smith, Jane Smith 4 3 Jack Hill Jack Hill 5 4 Jill Hill Jill Hill
answers question: http://stackoverflow.com/q/50379203
downvote count: 0
upvote count: 3
score: 3
type: Answer

http://stackoverflow.com/a/50843997
type: Answer
answers question: http://stackoverflow.com/q/50242232
downvote count: 0
upvote count: 1
has body: Cherrypy is going to recursively serve the files in the index folder. What you are trying to do has more to do with the url path. In your server.py you can attach the handler for /about.html to achieve what you want. @cherrypy.expose def about_html(self): return open('/index/about.html') hope this helps!
score: 1

http://stackoverflow.com/comment/87541598
score: 0
type: Comment
type: AnswerComment
has text: This worked perfectly! Thank you for answering so quickly.
comment on: http://stackoverflow.com/a/50261385

http://stackoverflow.com/comment/87637635
has text: If you're using a dict, then yes, the only option here would be to iterate all the keys, something like `for k, v in d.items(): if s.startswith(k): v.append(s)`. A different data structure, like a search tree or a trie, could make this more efficient (logarithmic rather than linear time), although it won't be much _simpler_ (because the dict is already pretty simple to use).
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50310730

http://stackoverflow.com/comment/87730257
type: Comment
type: QuestionComment
has text: Also, take a look at this similar question: https://stackoverflow.com/q/40951728/2615940. It's not quite a duplicate, but may have some useful info.
comment on: http://stackoverflow.com/q/50356224
score: 0

http://stackoverflow.com/q/50282309
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/87581273
has title: Pass variable from a server web to python?
tagged with: python
linked to: http://stackoverflow.com/q/3434048
score: 0
answer count: 0
has body: I´m running a html page on a server (using Xampp). Now, I would like take a variable from this html and pass it to python but i don´t the way. I don´t know if I can use Flask because I am running the html with Xampp. Thank you!
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87581210
has comment: http://stackoverflow.com/comment/87582684

http://stackoverflow.com/q/50382699
tagged with: python
has comment: http://stackoverflow.com/comment/87786491
has comment: http://stackoverflow.com/comment/87826403
has comment: http://stackoverflow.com/comment/87826663
linked to: http://stackoverflow.com/q/50265501
tagged with: python-3.x
score: 0
has body: I am trying to optimize the hyper-parameters using trust_region_optimizer from scipy. The log-marginal-likelihood optimizer internally needs to be maximized in my case. Scipy least squares minimize the objective function, so I need to minimize the inverse of the objective function. Following is my code: import numpy as np from scipy.optimize import minimize,least_squares from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C from scipy.optimize import least_squares,rosen def trust_region_optimizer(obj_func, initial_theta, bounds): trust_region_method = least_squares(1/obj_func,initial_theta,bounds,method='trf') return (trust_region_method.x,trust_region_method.fun) X=np.random.random((10,4)) y=np.random.random((10,1)) kernel = C(1.0, (1e-5, 1e5)) * RBF(10.0) gp = GaussianProcessRegressor(kernel=kernel, optimizer = trust_region_optimizer(rosen,[10,20,30,40], [0,100]), alpha =1.2, n_restarts_optimizer=10) gp.fit(X, y) While running the above code, I get the following error on console: TypeError: unsupported operand type(s) for /: 'int' and 'function' However, If I remove the kernel, there is no error at all. I tried to replace 1/obj_func with obj_func, I get the following error: ValueError:jac` must be '2-point', '3-point', 'cs' or callable` However, I cannot replace 1/obj_func with obj_func in my work. Any help will be appreciated. Thank you.
answer count: 0
has comment: http://stackoverflow.com/comment/87827615
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87826432
tagged with: scikit-learn
tagged with: scipy
tagged with: hyperparameters
has comment: http://stackoverflow.com/comment/87825842
has comment: http://stackoverflow.com/comment/87828853
type: Question
has title: TypeError while using scipy optimization algorithms with RBF kernel in GaussianProcessRegressor of Scikit-learn

http://stackoverflow.com/comment/87744741
comment on: http://stackoverflow.com/a/50353688
type: Comment
type: AnswerComment
score: 1
has text: Even if it works fine, which code would you rather maintain? Yours or OP's?

http://stackoverflow.com/comment/87626710
has text: perhaps when you are calling bulk_create then you can preprocess the data before calling bulk_create and assign the calculated value to field. list2=[] for e in list: list2.append(Entry(a=e["a"],calc=fn(a)) Entry.objects.bulk_create(list2)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50301795

http://stackoverflow.com/q/50355293
tagged with: python
tagged with: flask
tagged with: matplotlib
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: Return MatplotLib Image from flask service | Does not work with rich format
favorite count: 0
type: Question
has body: I have created an Python application hosted on Flask and publishing some images, it is working fine when I publishing a normal plot using axis.plot functionality but when I want to add rich text, better formatting etc then it is not rendering any image, here the sample reproducible code from flask import Flask, request, send_file, Response, make_response from flask_restful import Resource, Api import matplotlib.pyplot as plt from io import StringIO, BytesIO import numpy as np import json import random from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import pandas as pd app = Flask(__name__) api = Api(app) app.debug = True class Graph(Resource): def get(self): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs] axis.plot(xs, ys) canvas = FigureCanvas(fig) output = BytesIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' return response class PltGraph(Resource): def get(self): fig = Figure() xs = range(100) ys = [random.randint(1, 50) for x in xs] plt.plot(xs,ys) plt.ylabel("Y label") plt.xlabel("X label") plt.title("x and y") canvas = FigureCanvas(fig) output = BytesIO() canvas.print_png(output) response = make_response(output.getvalue()) response.mimetype = 'image/png' print(response) return response api.add_resource(Graph,'/Graph.png') api.add_resource(PltGraph,'/PltGraph.png') app.run(host='0.0.0.0', port= 81) Here the first method 'graph.png' gives result But the second method 'PtgGraph.png' gives blank result, please help
has answer: http://stackoverflow.com/a/50423300
type: UnansweredQuestion

amazon-s3
tags question: http://stackoverflow.com/q/50242188
tags question: http://stackoverflow.com/q/50295964
tags question: http://stackoverflow.com/q/50350844
tags question: http://stackoverflow.com/q/50258562
tags question: http://stackoverflow.com/q/50355996
tags question: http://stackoverflow.com/q/50282981
tags question: http://stackoverflow.com/q/50300879
tags question: http://stackoverflow.com/q/50323705
tag name: amazon-s3
tags question: http://stackoverflow.com/q/50313542
type: Tag
tags question: http://stackoverflow.com/q/50276248
tags question: http://stackoverflow.com/q/50242843
tags question: http://stackoverflow.com/q/50310496
tags question: http://stackoverflow.com/q/50320602
tags question: http://stackoverflow.com/q/50291963
tags question: http://stackoverflow.com/q/50300496
tags question: http://stackoverflow.com/q/50351375
tags question: http://stackoverflow.com/q/50376650
tags question: http://stackoverflow.com/q/50303936
tags question: http://stackoverflow.com/q/50364766
tags question: http://stackoverflow.com/q/50382396
tags question: http://stackoverflow.com/q/50286653
tags question: http://stackoverflow.com/q/50352842

http://stackoverflow.com/comment/87672784
score: 0
type: AnswerComment
has text: Thank you Salman. I am able to read image using your solution.
comment on: http://stackoverflow.com/a/50326506
type: Comment

http://stackoverflow.com/q/50239793
has body: with open('file.txt', 'w') as output: output.write('stuff') output.write('hello there') Output: 5 11 How do I silence the those printed character lengths (5, 11)?
tagged with: python
accepted answer: http://stackoverflow.com/a/50241678
has title: Silence Character Length Print in File Write
has answer: http://stackoverflow.com/a/50241678
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87497026
tagged with: printing
has comment: http://stackoverflow.com/comment/87497242
score: 0
has comment: http://stackoverflow.com/comment/87500036
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/87497115
has comment: http://stackoverflow.com/comment/87497229

http://stackoverflow.com/comment/87734063
comment on: http://stackoverflow.com/a/50358483
has text: I get this error: TypeError: reindex() got an unexpected keyword argument "axis"
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50230195
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50230155
has body: You're almost there, this is the right query that will work: {'query': {'constant_score': {'filter': {'bool': {'must': [ {'range': {'startTime': {'format': "yyyy-MM-dd'T'HH:mm:ss.SSS", 'gte': '2018-01-20T17:19:43.393', 'lte': '2018-04-01T17:19:43.393'} } }, { 'terms': {'id.keyword': ['d42bdc8a-a38b-43fa-9283-13b5e5c08c6e'] } } ] } } } } }
has comment: http://stackoverflow.com/comment/87478106
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50230155

http://stackoverflow.com/comment/87779205
has text: Yes, that will work. I'm confused as to what the purpose of copying and pasting is here however, instead of just calling `split('\n')` on `ogl.read()` You could even use `ogl.read().splitlines()`
comment on: http://stackoverflow.com/q/50381448
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50297639
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/14208256
has answer: http://stackoverflow.com/a/50297733
accepted answer: http://stackoverflow.com/a/50297733
tagged with: python
tagged with: dictionary
tagged with: lambda
has title: python sorting list of dictionary by custom order
upvote count: 14
score: 12
type: AnsweredQuestion
tagged with: list
downvote count: 2
answer count: 1
has body: I have searched that we can sort a list of dictionary by key in alphabetical order using sorted, but is it to sort it in custom order? for example: alist = [ {"id":"A","day":"sun"}, {"id":"B","day":"tue"}, {"id":"C","day":"mon"} ] sort alist according to "day" in custom order i.e. "sun", "mon", "tue"...."sat" sortedalist = [ {"id":"A","day":"sun"}, {"id":"C","day":"mon"} {"id":"B","day":"tue"} ] how can I do this? I think lambda expression is needed to be the key in sorted(), but I am not sure what should be the function
tagged with: sorting
linked to: http://stackoverflow.com/q/14208256

http://stackoverflow.com/a/50256331
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50255366
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50255366
has body: You have a typo in what should be the href attribute of your anchor tag.

http://stackoverflow.com/comment/87710485
score: 0
has text: Each text file has like loads of variables. So I just wanna know how do you select only what you want like loss per inch in this case
type: AnswerComment
comment on: http://stackoverflow.com/a/50347017
type: Comment

http://stackoverflow.com/q/50364049
type: Question
has answer: http://stackoverflow.com/a/70807674
has comment: http://stackoverflow.com/comment/87744332
accepted answer: http://stackoverflow.com/a/50364148
tagged with: python
has answer: http://stackoverflow.com/a/50364148
has body: I'd like to select specific cell values from a Pandas Dataframe. I want to filter out rows with specific values in column A, and then get the values from column B. From what I understand, the correct way to do this is to use df.at, so I've tried df.at(df['Column A' == column_A_value]['Column B']) but this doesn't work. I've also tried, as a hack, str(['Column A' == column_A_value]['Column B']) doesn't work either. What is the right way to do this? Edit: What I'm trying to do is to output the values inside of a bigger loop, something like: while condition: for val in some_column_A_values: print("{},{}".format('stuff', df.at(df['Column A' == val]['Column B'])), file=myfile)
type: AnsweredQuestion
score: 2
answer count: 2
tagged with: pandas
upvote count: 3
has title: Pandas: select cell value using pd.at with condition
possible better answer: http://stackoverflow.com/a/70807674
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87574381
type: Comment
has text: @PM2Ring, `Turtle()` does take args, `__init__(self, shape='classic', undobuffersize=1000, visible=True)`. He's passing the `shape` argument which can be the name of a GIF file if that file is registered as a turtle shape.
type: QuestionComment
comment on: http://stackoverflow.com/q/50275991
score: 0

http://stackoverflow.com/q/50329855
tagged with: pipeline
has answer: http://stackoverflow.com/a/50337385
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-datasets
has comment: http://stackoverflow.com/comment/87686492
has comment: http://stackoverflow.com/comment/87677754
has body: I am training a Recurrent Neural Network in Tensorflow over a dataset of sequence of numbers of varying lengths and have been trying to use the tf.data API to create an efficient pipeline. However I can't seem to get this thing to work My approach My data set is a NumPy array of shape [10000, ?, 32, 2] which is saved on my disk as a file in the .npy format. Here the ? denotes that elements have variable length in the second dimension. 10000 denotes the number of minibatches in the dataset and 32 denotes the size of a mini-batch. I am using np.load to open this data set and I am trying to create a tf.data.Dataset object using the from_tensor_slices method but it seems that this only works if all input Tensors have the same shape! I tried reading the docs but they have only given a very simple example. My code So the numpy files have been generated as follows - dataset = [] for i in xrange(num_items): #add an element of shape [?, 32, 2] to the list where `?` takes # a random value between [1, 40] dataset.append(generate_random_rnn_input()) with open('data.npy', 'w') as f: np.save(f, dataset) The code given below is my attempt to create a tf.data.Dataset object # dataset_list is a list containing `num_items` number of itesm # and each item has shape [?, 32, 2] dataset_list = np.load('data.npy') # error, this doesn't work! dataset = tf.data.Dataset.from_tensor_slices(dataset_list) The error I get is "TypeError: Expected binary or unicode string, got array([[[0.0875, 0. ], ..." Continued, still need help! So I tried @mrry's answer and I am now able to created a Dataset object. However, I am not able to iterate through this dataset using iterators as said in the tutorial. This is what my code looks like now - dataset_list = np.load('data.npy') dataset = tf.data.Dataset.from_generator(lambda: dataset_list, dataset_list[0].dtype, tf.TensorShape([None, 32, 2])) dataset = dataset.map(lambda x : tf.cast(x, tf.float32)) iterator = dataset.make_one_shot_iterator() next_element =…
has title: How to use the Tensorflow Dataset Pipeline for Variable Length Inputs?
upvote count: 8
has comment: http://stackoverflow.com/comment/87687734
tagged with: python
score: 8
accepted answer: http://stackoverflow.com/a/50337385
type: AnsweredQuestion

http://stackoverflow.com/q/50350890
has title: How to ensure only one thread runs at a time, the most recent data?
answer count: 1
has comment: http://stackoverflow.com/comment/87720183
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87717772
tagged with: multithreading
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50351528
score: 0
has body: I have a Flask app with a certain URL route that, when called, invokes a function inside a process via the threading library. This function contains a while True loop that, inside, has a DB query. That same function may be invoked again, but the DB may change, which now results in a different thread. I don't want this however, as it causes a thread to have old data. I want one thread. Here's my current approach: @mod.route('/api/start-zmq-listener') def startZMQListener(): try: thread = threading.Thread(target=enableZMQ, name="enableZMQ", kwargs={ 'username': 'test', 'stopFlag': stopFlag }) thread.start() return success_response('ok') except Exception as e: return error_response(e) def enableZMQ(username, stopFlag): if not stopFlag: context = zmq.Context() listen_on = 'tcp://' + ENGINE_IP sock = context.socket(zmq.SUB) sock.setsockopt(zmq.SUBSCRIBE, b"") sock.connect(listen_on) print ('listening on ' + listen_on) while True: print MONGODB QUERY Let's say the "MONGODB QUERY" is the same each time, but the data it queries is different. How do I make sure there is only one process running at all times that uses the most recent MongoDB query?

xml-namespaces
type: Tag
tags question: http://stackoverflow.com/q/50326271
tag name: xml-namespaces

http://stackoverflow.com/q/50261232
tagged with: fipy
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: According to the FiPy website, you need "at least one of the solvers", and they list SciPy as one possible "solver". I definitely have SciPy installed - I can import it with import scipy. I haven't formally installed FiPy with setup.py or anything like that, I just have the code in a folder called fipy. When I then go into the Python shell and type import fipy, I get: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "fipy/__init__.py", line 44, in &lt;module&gt; from solvers import * File "fipy/solvers/__init__.py", line 68, in &lt;module&gt; raise ImportError, "Could not import any solver package. If you are using Trilinos, make sure you have all of the necessary Trilinos packages installed - Epetra, EpetraExt, AztecOO, Amesos, ML, and IFPACK." ImportError: Could not import any solver package. If you are using Trilinos, make sure you have all of the necessary Trilinos packages installed - Epetra, EpetraExt, AztecOO, Amesos, ML, and IFPACK. I've already tried doing this after formally installing FiPy via setup.py (using pip didn't work, I got some strange error relating to tensorflow). Setting the FIPY_SOLVERS environment variable didn't work either (same error). I'm on Ubuntu with Python 2.7.
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50273989
has title: Fipy doesn't seem to want to use SciPy as a solver
answer count: 1
tagged with: scipy

http://stackoverflow.com/q/50309060
duplicate of: http://stackoverflow.com/q/26262813
has comment: http://stackoverflow.com/comment/87634055
favorite count: 0
type: Question
tagged with: tuples
linked to: http://stackoverflow.com/q/9755990
duplicate of: http://stackoverflow.com/q/9172263
type: UnansweredQuestion
tagged with: python
has title: Why can I change an element of a list within a tuple in Python?
upvote count: 4
duplicate of: http://stackoverflow.com/q/9755990
tagged with: immutability
linked to: http://stackoverflow.com/q/26262813
score: 3
tagged with: list
answer count: 0
downvote count: 1
has body: I am new in Python and I need some clarity on this. I read everywhere that tuples are immutable, so they cannot be changed, however I did this test, and I could change the values inside a list within a tuple, am I doing something wrong? Or why am I able to change this value? Thanks. This is my test code: &gt;tuplelist = ('mouse',[1,2,3]) **('mouse', [1, 2, 3])** &gt;tuplelist[1][0]=999; **('mouse', [999, 2, 3])**

http://stackoverflow.com/q/50271526
score: 2
favorite count: 0
type: Question
tagged with: numpy
has body: I would like to run an operation (e.g. subtracting the median) on rows of a numpy array. One way to do that is using comprehension lists: import numpy as np from statistics import median x = np.array([[1, 2, 3, 4], [5, 6, 7 ,8], [9, 10, 11, 12]]) xm = np.vstack(([x[i,:] - median(x[i,:]) for i in range(x.shape[0])])) Each row is processed, then stacked vertically as numpy array. Is there a more efficient/elegant way to do that?
upvote count: 2
has answer: http://stackoverflow.com/a/50271669
accepted answer: http://stackoverflow.com/a/50271669
tagged with: arrays
answer count: 1
has title: Efficient row operation on numpy arrays
downvote count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87739547
type: Comment
comment on: http://stackoverflow.com/a/50343686
type: AnswerComment
has text: That make sense, I change mx.mod.Module to python list, and construct on there own, and it works. Thank you!
score: 0

http://stackoverflow.com/q/50336251
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87688974
has answer: http://stackoverflow.com/a/50336535
answer count: 2
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/72296068
has body: I have a pandas dataframe, with Start and End datatime. df=pd.DataFrame(data=pd.date_range('20100201', periods=10, freq='5h3min'),columns=['Start']) df.loc[:,'End']=df.loc[:,'Start']+pd.Timedelta(4,'h') Start and End can be expected to be sorted interally, but gaps/overlaps may occur between consecutive rows. I would like to create a new dataframe with the difference that if row contains midnight (e.g. midnight is contained in [Start,End]), the row is then split in two parts before and after midnight ex: Start End 0 2010-02-01 00:00:00 2010-02-01 04:00:00 1 2010-02-01 05:03:00 2010-02-01 09:03:00 2 2010-02-01 10:06:00 2010-02-01 14:06:00 3 2010-02-01 15:09:00 2010-02-01 19:09:00 4 2010-02-01 20:12:00 2010-02-02 00:12:00 5 2010-02-02 01:15:00 2010-02-02 05:15:00 should be Start End 0 2010-02-01 00:00:00 2010-02-01 04:00:00 1 2010-02-01 05:03:00 2010-02-01 09:03:00 2 2010-02-01 10:06:00 2010-02-01 14:06:00 3 2010-02-01 15:09:00 2010-02-01 19:09:00 ----------------------------------------- 4 2010-02-01 20:12:00 2010-02-01 23:59:00 5 2010-02-02 00:00:00 2010-02-02 00:12:00 ----------------------------------------- 6 2010-02-02 01:15:00 2010-02-02 05:15:00
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50336535
tagged with: datetime
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/72296068
score: 4
upvote count: 4
has title: split dataframe entries at midnight
has comment: http://stackoverflow.com/comment/87688939

http://stackoverflow.com/a/50245099
answers question: http://stackoverflow.com/q/50245041
has body: It is not the present working directory that determines your environment. To jump out of the virtual environment, you need to deactivate it. Using the command: deactivate
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50245041
upvote count: 1

http://stackoverflow.com/a/50425385
accepted answer of: http://stackoverflow.com/q/50361720
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50361720
type: Answer
has body: It turns out the path was not correct because it contains \t which was misinterpreted. I ended up using shutil.move + shutil.copy22 for i in os.listdir(staging_folder): if not os.path.exists(final_folder): shutil.move(os.path.join(staging_folder, i), final_folder) else: shutil.copy2(os.path.join(staging_folder, i), final_folder) and then emptify the old folder: def emptify_staging(self, folder): for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) # elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e)
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/50418586
upvote count: 5
type: Answer
has body: You are doing it right. But a faster way is to use TFRecords as shown in the following steps: Use tf.python_io.TFRecordWriter: -- To read the csv file and write it as a tfrecord file as shown here:Tensorflow create a tfrecords file from csv. Reading from the tfrecord : -- def _parse_function(proto): f = { "features": tf.FixedLenSequenceFeature([], tf.float32, default_value=0.0, allow_missing=True), "label": tf.FixedLenSequenceFeature([], tf.float32, default_value=0.0, allow_missing=True) } parsed_features = tf.parse_single_example(proto, f) features = parsed_features["features"] label = parsed_features["label"] return features, label dataset = tf.data.TFRecordDataset(['csv.tfrecords']) dataset = dataset.map(_parse_function) dataset = dataset.shuffle(10000).repeat().batch(128) iterator = dataset.make_one_shot_iterator() features, label = iterator.get_next() I ran both the cases (csv vs tfrecords) on a randomly generated csv. The total time for 10 batches (128 samples each) for a csv direct read was around 204s, while that of tfrecord was around 0.22s.
answers question: http://stackoverflow.com/q/50383963
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50383963
has comment: http://stackoverflow.com/comment/88061011
score: 5

http://stackoverflow.com/comment/87576033
has text: @piRSquared Wow, I'm stealing, er, borrowing that.
comment on: http://stackoverflow.com/a/50279412
score: 3
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87527668
score: 0
has text: Thanks for the answer! Can I send 12 bits at a time using pyserial?@scholi
type: Comment
comment on: http://stackoverflow.com/q/50254997
type: QuestionComment

http://stackoverflow.com/q/50359334
tagged with: python
score: 4
has title: How do you get the geckodriver version from python selenium firefox webdriver?
has answer: http://stackoverflow.com/a/57059486
type: AnsweredQuestion
has body: I'm trying to write in some defensive code to prevent someone from executing a script should they have an older version of geckodriver installed. I cannot for the life of me seem to get the geckodriver version from the webdriver object. The closest I found is driver.capabilities which contains the firefox browser version, but not the geckodriver version. from selenium import webdriver driver = webdriver.Firefox() pprint(driver.capabilities) output: {'acceptInsecureCerts': True, 'browserName': 'firefox', 'browserVersion': '60.0', 'moz:accessibilityChecks': False, 'moz:headless': False, 'moz:processID': 18584, 'moz:profile': '/var/folders/qz/0dsxssjd1133p_y44qbdszn00000gp/T/rust_mozprofile.GsKFWZ9kFgMT', 'moz:useNonSpecCompliantPointerOrigin': False, 'moz:webdriverClick': True, 'pageLoadStrategy': 'normal', 'platformName': 'darwin', 'platformVersion': '17.5.0', 'rotatable': False, 'timeouts': {'implicit': 0, 'pageLoad': 300000, 'script': 30000}} Is it possible the browser version and geckodriver versions are linked directly? if not, how can I check the geckodriver version from within python?
downvote count: 0
tagged with: selenium
favorite count: 0
type: Question
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/50359621
tagged with: selenium-firefoxdriver
tagged with: geckodriver
possible better answer: http://stackoverflow.com/a/57059486
has answer: http://stackoverflow.com/a/50359621

http://stackoverflow.com/comment/87759090
score: 0
comment on: http://stackoverflow.com/q/50363444
type: Comment
has text: What exactly is taking 30 seconds before you connect? Can the result of *that* be saved?
type: QuestionComment

http://stackoverflow.com/q/50309643
has comment: http://stackoverflow.com/comment/87635242
score: 0
has comment: http://stackoverflow.com/comment/87635536
duplicate of: http://stackoverflow.com/q/918154
tagged with: python
has body: How can I read the /billy/var/text.txt into b.py The directory structure is: /billy/b.py /billy/var/text.txt /sally/s.py s.py import sys, os sys.path.append('..') from billy import b print('s.py - ' + os.path.dirname(sys.argv[0])) b.py import sys, os print('b.py - ' + os.path.dirname(sys.argv[0])) ag = open(os.path.dirname(sys.argv[0]) + '//var//text.txt').read()
type: Question
tagged with: python-3.x
answer count: 0
has title: How to use relative imports?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87635711
has comment: http://stackoverflow.com/comment/87636094
has comment: http://stackoverflow.com/comment/87635688
has comment: http://stackoverflow.com/comment/87635704
tagged with: relative-path

http://stackoverflow.com/q/50316869
type: UnansweredQuestion
has body: Try to connect PostgreSQL over ssh, but something went wrong. Could anybody help? from sshtunnel import SSHTunnelForwarder import psycopg2 with SSHTunnelForwarder( "hostname", ssh_username="username", ssh_password="password", remote_bind_address=("127.0.0.1", 5432)) as server: try: conn = psycopg2.connect(host = "127.0.0.1", dbname="db_name", user="db_user", password="db_password") cursor = conn.cursor() cursor.execute("""SELECT * from table""") rows = cursor.fetchall() print(rows) except Exception as e: print("Uh oh, can't connect. Invalid dbname, user or password?") print(e) When run the code - get an error: /usr/local/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) Uh oh, can't connect. Invalid dbname, user or password? could not connect to server: Connection refused Is the server running on host127.0.0.1and accepting **TCP/IP** connections on port5432`? Check db name, user and password many times, but it's now working. Manual connection to db via ssh works good, but I need to do it in python to analyst data.
tagged with: python
tagged with: postgresql
has comment: http://stackoverflow.com/comment/88116890
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has title: Connection to PostgreSQL with python3 over SSH
favorite count: 0
type: Question

http://stackoverflow.com/q/50319869
linked to: http://stackoverflow.com/q/37003421
has comment: http://stackoverflow.com/comment/87673375
score: 0
answer count: 3
tagged with: pandas
tagged with: folium
has answer: http://stackoverflow.com/a/64706134
type: Question
has answer: http://stackoverflow.com/a/56894157
type: UnansweredQuestion
tagged with: python
has title: Issues with Folium Choropleth, pandas: GeoJSON raises AttributeError: 'NoneType'
tagged with: maps
has answer: http://stackoverflow.com/a/50321996
has body: I'm working on a data visualization of a dataframe using Folium but I am stuck to setting the key_on parameter of Choropleth map in Folium. You can view example code snippet on gist here My geojson: { "type":"Topology", "arcs":[...], "transform":{...}, "objects": "Com01012018_g_WGS84":{ "type":"GeometryCollection", "geometries": [ { "arcs":[...], "type":"Polygon", "properties": { "COMUNE": "Borgo Vercelli", "PRO_COM": 2017, ... } }, {...}, ] } } My pandas df: id comune a11y-score 0 Aquila d'Arroscia 65.17 1 Castel del Rio 68.75 2 Castellaneta 71.95 3 Castelvetrano 77.27 4 Montescudo-Monte Colombo 59.65 I want to set the key on "COMUNE" and I am able to loop through geojson very easily: with open('italy-comuni.json', encoding='utf-8') as json_file: data = json.load(json_file) obj = data['objects'] for righe in obj["Com01012018_g_WGS84"]['geometries']: print(righe['properties']['COMUNE']) #print the name of the City As suggested by OP here I checked if both this json and my imported dataframe has the same "comune" value (to avoid raising KeyError ) and alla the values in a11y-score are filled (float values from 0 to 100). Here my Leaflet code: m = folium.Map(location=[42.833333, 12.833333],zoom_start=6,tiles="Mapbox Bright") m.choropleth( geo_data=state_geo, name='choropleth', data=italia_df, columns=['comune', 'a11y-score'], key_on='object.geometry.properties.COMUNE', fill_color='YlOrRd', fill_opacity=0.7, line_opacity=0.2, legend_name='A11y Score' ) folium.LayerControl().add_to(m) Can't figure out how to set key_on properly. Tried these but nothing actually works: object.geometries.properties.COMUNE objects.geometries.properties.comune objects.Com01012018_g_WGS84.geometry.Polygon.properties.COMUNE objects.Com01012018_g_WGS84.geometries.Polygon.properties.COMUNE objects.geometry.Polygon.properties.COMUNE objects.geometries.Polygon.properties.COMUNE object.geometries.Polygon.properties.COMUNE Com01012018_g_WGS84.geometry.properties.COMUNE Errors: ---------------------…

http://stackoverflow.com/a/50338750
has body: Just call it in the subclass' __init__() before calling the super class' __init__()—which works in both Python 2 and 3 as long as the base class is "new-style" (directly or indirectly has object as one of its base classes...the default in Python 3.x). class Base(object): def __init__(self, callback=None): if callback: callback() class Subclass(Base): def __init__(self, callback=None): def another_callback(): print('another_callback') another_callback() # Just call it. super(Subclass, self).__init__(callback) def a_callback(): print('a_callback') x = Subclass(callback=a_callback) Output: another_callback a_callback
score: 0
answers question: http://stackoverflow.com/q/50337827
type: Answer

http://stackoverflow.com/comment/87496586
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50239350
score: 0
has text: i´m using Windows, Does it change something? i made a folder with the app.py and inside other folder "static" with the index.html

http://stackoverflow.com/q/50346020
has comment: http://stackoverflow.com/comment/88024655
tagged with: pyspark
has comment: http://stackoverflow.com/comment/88058194
tagged with: python
has body: Now I am trying to solve a problem of generating items relevance with quantity using association rules in PySpark environment. The raw data is like this: ---------------------------- trans item_code item_qty ---------------------------- 001 A 2 001 B 3 002 A 4 002 B 6 002 C 10 003 D 1 ---------------------------- My aim is to predict the probable additional items for given items. For example, given {A:2,B:3} the probable new set maybe {A:2,B:3,C:5}. So my first step is to generate association rules with quantity coefficient. My method is to use FP-growth algorithm to generate frequent item sets and then find one to one association rules. After filtering the rules by confidence threshold, I can calculate the quantity coefficient. My desired association rules DataFrame is like this (item1->item2): ---------------------------- item1 item2 conf coef ---------------------------- A B 0.8 1.5 B A 1.0 0.67 A C 0.7 2.5 ---------------------------- My spark version is 1.5.1. My code is here: #!/usr/bin/python from pyspark import SparkContext,HiveContext from pyspark.mllib.fpm import FPGrowth import time #read raw data from database def read_data(): sql="""select t.orderno_nosplit, t.prod_code, t.item_code, sum(t.item_qty) as item_qty from ioc_fdm.fdm_dwr_ioc_fcs_pk_spu_item_f_chain t group by t.prod_code, t.orderno_nosplit,t.item_code """ data=sql_context.sql(sql) return data.cache() #calculate quantity coefficient of two items def qty_coef(item1,item2): sql =""" select t1.item, t1.qty from table t1 where t1.trans in (select t2.trans from spu_table t2 where t2.item ='%s' and (select t3.trans from spu_table t3 where t3.item = '%s' """ % (item1,item2) df=sql_context.sql(sql) qty_item1=df.filter(df.item_code==item1).agg({"item_qty":"sum"}).first()[0] qty_item2=df.filter(df.item_code==item2).agg({"item_qty":"sum"}).first()[0] coef=float(qty_item2)/qty_item1 return coef def train(prod): spu=total_spu.filter(total_spu.prod_code == prod) print 'data length',spu.count(),time.strftime…
tagged with: hadoop
score: 0
has title: How to generate association rules with quantity in pyspark?
tagged with: apache-spark
linked to: http://stackoverflow.com/q/50523055
has answer: http://stackoverflow.com/a/55052831
answer count: 1
tagged with: hive
type: Question
has comment: http://stackoverflow.com/comment/87707995
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88039448

http://stackoverflow.com/q/50360125
linked to: http://stackoverflow.com/q/16824004
tagged with: django
linked to: http://stackoverflow.com/q/3842075
answer count: 1
accepted answer: http://stackoverflow.com/a/50360126
has answer: http://stackoverflow.com/a/50360126
type: Question
tagged with: python
has title: Conditionaly redirect users after login
has body: I have looked at both Django -- Conditional Login Redirect and Conditional login redirect in Django and neither address my current issue. What I want to do is check a property of the user after they have successfully logged in. If the property is in a good state send them directly to the page specified by the next URL argument, otherwise send them to fix the property and then forward them to the next page. So far I have succeeded in sending the user on to next after they have fixed the property, but I can't conditionally redirect after login. I know I can set the LOGIN_REDIRECT_URL, but that only applies if there is no value in next.
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50368478
tagged with: list
has title: Why is this giving me "list index out of range"? I'm trying to find names in a list and names can be two words long or more
has comment: http://stackoverflow.com/comment/87753348
score: 0
has comment: http://stackoverflow.com/comment/87753014
answer count: 1
has answer: http://stackoverflow.com/a/50369024
type: Question
tagged with: python
type: UnansweredQuestion
has body: _ID = "000001234" f = open("Players.txt", "r") allLines = f.readlines() nameList = [[] for i in range(1,len(allLines))] for i in range(0,len(allLines)): splitLine = allLines[i].split() l = len(splitLine) for name in range(1,l-3): nameList[i].append(splitLine[name]) #print(nameList[i]) for i in range(0, len(allLines)): splitLine = allLines[i].split() if splitLine[0] == _ID: print(nameList[i]) break f.close() Data: Player ID Player Name Age Height(cm) Weight(kg) 000000001 Aaron Appindangoye 26 183 84.8 000000002 Aaron Cresswell 28 170 66.2 000000003 Aaron Doran 26 170 73.9 000000004 Aaron Galindo 36 183 89.8 000000005 Aaron Hughes 38 183 69.9 000000006 Aaron Hunt 31 183 73.0

dictionary
tags question: http://stackoverflow.com/q/50317280
tags question: http://stackoverflow.com/q/50342428
tags question: http://stackoverflow.com/q/50312458
tags question: http://stackoverflow.com/q/50279889
tags question: http://stackoverflow.com/q/50334255
tags question: http://stackoverflow.com/q/50328246
tags question: http://stackoverflow.com/q/50380529
tags question: http://stackoverflow.com/q/50297639
tags question: http://stackoverflow.com/q/50300869
tags question: http://stackoverflow.com/q/50236770
tags question: http://stackoverflow.com/q/50376287
tags question: http://stackoverflow.com/q/50344999
tags question: http://stackoverflow.com/q/50340463
tags question: http://stackoverflow.com/q/50238635
tags question: http://stackoverflow.com/q/50257201
tags question: http://stackoverflow.com/q/50285193
tags question: http://stackoverflow.com/q/50295913
tags question: http://stackoverflow.com/q/50351606
tags question: http://stackoverflow.com/q/50381203
tags question: http://stackoverflow.com/q/50266925
tags question: http://stackoverflow.com/q/50318190
tags question: http://stackoverflow.com/q/50344376
tags question: http://stackoverflow.com/q/50335782
tags question: http://stackoverflow.com/q/50262594
tags question: http://stackoverflow.com/q/50357395
tags question: http://stackoverflow.com/q/50344027
tags question: http://stackoverflow.com/q/50378928
tags question: http://stackoverflow.com/q/50367297
tags question: http://stackoverflow.com/q/50362074
tags question: http://stackoverflow.com/q/50315964
tags question: http://stackoverflow.com/q/50296097
tags question: http://stackoverflow.com/q/50328443
tags question: http://stackoverflow.com/q/50321335
tags question: http://stackoverflow.com/q/50343137
tags question: http://stackoverflow.com/q/50266770
tags question: http://stackoverflow.com/q/50286676
tags question: http://stackoverflow.com/q/50229993
tags question: http://stackoverflow.com/q/50309540
tags question: http://stackoverflow.com/q/50346370
tags question: http://stackoverflow.com/q/50352855
tags question: http://stackoverflow.com/q/50334763
tags question: http://stackoverflow.com/q/50284174
tags question: http://stackoverflow.com/q/50265304
tags question: http://stackoverflow.com/q/50380164
tags question: http://stackoverflow.com/q/50248633
tags question: http://stackoverflow.com/q/50354360
tags question: http://stackoverflow.com/q/50254839
tags question: http://stackoverflow.com/q/50262652
tags question: http://stackoverflow.com/q/50258047
tags question: http://stackoverflow.com/q/50338391
tags question: http://stackoverflow.com/q/50364221
tags question: http://stackoverflow.com/q/50298896
tags question: http://stackoverflow.com/q/50298644
tags question: http://stackoverflow.com/q/50350456
tags question: http://stackoverflow.com/q/50292184
tags question: http://stackoverflow.com/q/50299060
tags question: http://stackoverflow.com/q/50259411
tags question: http://stackoverflow.com/q/50237664
tags question: http://stackoverflow.com/q/50361188
tags question: http://stackoverflow.com/q/50346347
tags question: http://stackoverflow.com/q/50268093
tags question: http://stackoverflow.com/q/50310730
tags question: http://stackoverflow.com/q/50294019
type: Tag
tags question: http://stackoverflow.com/q/50271762
tags question: http://stackoverflow.com/q/50243740
tags question: http://stackoverflow.com/q/50282387
tags question: http://stackoverflow.com/q/50255732
tags question: http://stackoverflow.com/q/50295884
tags question: http://stackoverflow.com/q/50375640
tags question: http://stackoverflow.com/q/50244973
tags question: http://stackoverflow.com/q/50373835
tags question: http://stackoverflow.com/q/50287479
tags question: http://stackoverflow.com/q/50307306
tags question: http://stackoverflow.com/q/50349202
tags question: http://stackoverflow.com/q/50258928
tags question: http://stackoverflow.com/q/50280590
tags question: http://stackoverflow.com/q/50367030
tags question: http://stackoverflow.com/q/50323656
tags question: http://stackoverflow.com/q/50289773

http://stackoverflow.com/a/50401237
has body: You've messed up your sockets. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((ip, 12345)) sock.listen(1) sock is a socket only used to listen for incoming connections. You cannot read or write to this socket. This while loop is for files larger than 4096 bytes, but each time through, you are waiting for a DIFFERENT connection, so the first chunk is processed for the first connection, the next chunk for the second connection and so on. while True: conn, addr = sock.accept() chunk = file.read(4096) if not chunk: break # EOF sock.send(chunk) Again, you can't send to a listening socket! Perhaps you wanted conn.send(chunk). What you really wanted was a loop more like: conn, addr = sock.accept() while True: chunk = file.read(4096) if not chunk: break conn.send(chunk) conn.close() Unfortunately, the above won't work, because the socket buffer will quickly become full, and stop accepting data no matter how fast the program writes to it. You need to check the return value from conn.send(chunk) to find out how many bytes were sent. If that is less than the length of the chunk, you need to remove that many bytes from the start of the chunk, and try to send the remainder. Repeat until the whole chunk is sent. Or ... simply use conn.sendall(chunk), which blocks until all the data has been accepted into the socket buffer.
type: Answer
answers question: http://stackoverflow.com/q/50281516
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50281516

http://stackoverflow.com/comment/87583972
has text: I only call fetchone once. I was just highlighting the space again where I'm trying to assign it to a variable. Is that what you mean? I'll check if multiple rows satisfy the condition though thank you
comment on: http://stackoverflow.com/q/50283716
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50383715
has comment: http://stackoverflow.com/comment/87895284
has comment: http://stackoverflow.com/comment/87930937
type: Answer
has body: At first I used the following data sets (similar to your case): import numpy as np import keras X = np.random.randint(256, size=(410, 64, 64)) Y = np.random.randint(10, size=(410, 1)) x_train = X[:, :, :, np.newaxis] y_train = keras.utils.to_categorical(Y, num_classes=10) And then modified your code as follows to work: from keras.models import Sequential from keras.layers import Convolution2D, Flatten, Dense classifier = Sequential() # initialize neural network classifier.add(Convolution2D(32, (3, 3), input_shape=(64, 64, 1), activation="relu", data_format="channels_last")) classifier.add(Flatten()) classifier.add(Dense(10, activation='softmax')) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) classifier.fit(x_train, y_train, batch_size=32, epochs=10, verbose=1) Changed the shape of X from 410 x 64 x 64 to 410 x 64 x 64 x 1 (with channel 1). input_shape be the shape of a sample data, that is, 64 x 64 x 1. Changed the shape of Y using keras.utils.to_categorical() (one-hot encoding with num_classes=10). Before compiling, Flatten() and Dense() were applied because you want categorical_crossentropy.
has comment: http://stackoverflow.com/comment/87895198
score: 0
answers question: http://stackoverflow.com/q/50382613

http://stackoverflow.com/comment/87784041
type: QuestionComment
has text: @andrew, looks like these packages where installed `sudo apt-get install libzbar0 libzbar-dev libzbar-dev is already the newest version. libzbar0 is already the newest version.`
score: 0
comment on: http://stackoverflow.com/q/50374464
type: Comment

http://stackoverflow.com/a/50243245
has comment: http://stackoverflow.com/comment/87504215
downvote count: 0
upvote count: 1
has body: You have to pass as argument only the inner object: import json z="""{ "info": [ {"product": "ABC", "email-adr": "abc08@gmail.com", "Gender": "M", "Name": "João", "id": "1069", "mobile": "iOS | 9.1", "client": " " }]}""" &gt;&gt;&gt; pd.DataFrame(json.loads(z)['info']) Gender Name client email-adr id mobile product 0 M João abc08@gmail.com 1069 iOS | 9.1 ABC To load a json file: with open("file.json", "r") as f: data = json.load(f) Then you can do pd.DataFrame(data['info'])
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87504190
answers question: http://stackoverflow.com/q/50243214
type: Answer
accepted answer of: http://stackoverflow.com/q/50243214

http://stackoverflow.com/comment/87661088
comment on: http://stackoverflow.com/q/50321207
type: Comment
score: 0
type: QuestionComment
has text: Please add the stacktrace of this to your question - it'll help.

http://stackoverflow.com/comment/87691692
comment on: http://stackoverflow.com/a/50337566
type: Comment
score: 0
type: AnswerComment
has text: Thanks a ton, @OlivierMelançon my bad. Edited.

http://stackoverflow.com/a/50316743
accepted answer of: http://stackoverflow.com/q/50316400
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50316400
type: Answer
has body: You can do it easily: &gt;&gt;&gt; from openpyxl import Workbook &gt;&gt;&gt; wb = Workbook() &gt;&gt;&gt; ws = wb.active &gt;&gt;&gt; # add a simple formula &gt;&gt;&gt; ws["A1"] = '=IF(C19="John","","X")' &gt;&gt;&gt; wb.save("formula.xlsx") From the doc: https://openpyxl.readthedocs.io/en/2.5/usage.html
score: 0

http://stackoverflow.com/a/68290505
answers question: http://stackoverflow.com/q/50247068
score: 0
has body: The same problem I faced when I renamed my root folder name after creating the virtual environment and installed django. Solution: I created virtual environment again and installed django. The main problem is with the path in django-admin.py in your virtual_environment/Scripts
type: Answer

http://stackoverflow.com/q/50343382
has comment: http://stackoverflow.com/comment/90954142
has comment: http://stackoverflow.com/comment/87708651
has title: Diagnosing Memory leak in boto3
has comment: http://stackoverflow.com/comment/90806568
tagged with: memory
favorite count: 0
type: Question
upvote count: 5
linked to: http://stackoverflow.com/q/1316767
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/51971996
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90964837
answer count: 1
has comment: http://stackoverflow.com/comment/90835192
has body: I have a celery worker running on Elastic Beanstalk that polls a SQS queue, gets messages (containing S3 file names), downloads those files from S3 and processes them. My worker is scheduled to run at every 15 seconds but due to some reason the memory usage keeps on increasing with time. This is the code I'm using to access SQS def get_messages_from_sqs(queue_url, queue_region="us-west-2", number_of_messages=1): client = boto3.client('sqs', region_name=queue_region) sqs_response = client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=number_of_messages) messages = sqs_response.get("Messages", []) cleaned_messages = [] for message in messages: body = json.loads(message["Body"]) data = body["Records"][0] data["receipt_handle"] = message["ReceiptHandle"] cleaned_messages.append(data) return cleaned_messages def download_file_from_s3(bucket_name, filename): s3_client = boto3.client('s3') s3_client.download_file(bucket_name, filename, '/tmp/{}'.format(filename)) Do we need to close client connection in boto3 after we're done with the process ? If so, how can we do it ?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90954119
tagged with: boto3
tagged with: celery

http://stackoverflow.com/q/50342558
tagged with: set
downvote count: 0
has comment: http://stackoverflow.com/comment/87701100
has comment: http://stackoverflow.com/comment/87701044
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87701070
upvote count: 2
accepted answer: http://stackoverflow.com/a/50342651
has answer: http://stackoverflow.com/a/50342686
tagged with: python
has title: python list of sets find symmetric difference in all elements
has answer: http://stackoverflow.com/a/50342651
score: 2
type: AnsweredQuestion
has body: Consider this list of sets my_input_list= [ {1,2,3,4,5}, {2,3,7,4,5}, set(), {1,2,3,4,5,6}, set(),] I want to get the only exclusive elements 6 and 7 as the response, list or set. Set preferred. I tried print reduce(set.symmetric_difference,my_input_list) but that gives {2,3,4,5,6,7} And i tried sorting the list by length, smallest first raises an error due to two empty sets. Largest first gives the same result as unsorted. Any help or ideas please? Thanks :)
tagged with: reduce
answer count: 2
possible better answer: http://stackoverflow.com/a/50342686

http://stackoverflow.com/q/50284208
tagged with: sublimetext3
has comment: http://stackoverflow.com/comment/87585387
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/87636461
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/87636569
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has body: I am Selenium Webdriver Python developer, and I'm using PyCharm, but I would like to move on Sublime, is anyone can help with set up Sublime to run my tests with Pytest framework. When I try to run my test I'm getting in console output something like this &gt;&gt;&gt; and this is it, it doesn't open browser and anything else.
has title: Set up Sublime for Selenium Webdriver, Python, Pytest
has comment: http://stackoverflow.com/comment/87585227
has comment: http://stackoverflow.com/comment/87639749
type: Question
tagged with: pytest
tagged with: python
has comment: http://stackoverflow.com/comment/87585139

http://stackoverflow.com/a/55826136
answers question: http://stackoverflow.com/q/50238523
has body: import turtle ab=turtle.Turtle() ab.speed(0) import turtle def zielscheibe(ringe=10): if ringe&lt;1 or ringe&gt;1000: ab.write('Bitte eine Zahl zwischen 1 und 1000 eingeben') return ab.pu() ab.goto(300,0) ab.seth(90) x=300/ringe for n in range(ringe): ab.pd() if n ==ringe-1: ab.color('black') elif n %2==0: ab.color('red') else: ab.color('white') ab.begin_fill() ab.circle(300-x*n) ab.end_fill() ab.pu() ab.left(90) ab.fd(x) ab.right(90) zielscheibe(10) turtle.mainloop()
downvote count: 1
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/a/50279312
type: Answer
has body: There are a lot of things wrong with your function. Let's go down the list. #Convert string elements in digits[] to ints for n in digits: digits[x] = int(x) x = x + 1 This section is intended to convert the elements of digits into ints, but the elements of digits are already ints. The earlier list comprehension already produced ints: digits = [int(d) for d in str(num)] # ^^^^^^ The whole section is unnecessary. It's not even filling digits with the right ints; instead of calling int on the elements of digits, it calls int on the indices. Also, the loop makes no use of the loop variable n. for n in digits: digits[0] = digits[0] + digits[z] This loop attempts to add all the digits together. However, z is never incremented, so this adds digits[1] to digits[0] every time. Also, even if the loop was changed to increment z, it would most likely go too far and run off the end of the list; z starts at 1, and the loop performs one iteration for each element of digits, so by the last iteration, z would be past the end of the list. Also, again, the n variable is unused. Using digits[0] as a place to hold the sum muddles up the meaning of the digits array during the loop. It'd be better to use a separate variable (and doing so would avoid needing to start z at 1), but since Python already has a sum function, it'd be even simpler to just use sum. #If digits[0] has more than one digit, then run digital_root with digits[0] in the parameters if digits[0] &gt; 9: digital_root(digits[0]) else: return digits[0] This is inside the above loop, but it doesn't look like it's supposed to be; it looks like it was intended to run after digits[0] contains the sum. If so, it should be dedented (delete 4 spaces from each line). Also, since there's no return on the recursive call, the return value of the recursive call is discarded. A corrected version of your function could look like def digital_root(num): if num &gt; 9: digits = [int(d) for d in str(num)] total = 0 for n in digits: total += n …
score: 4
has comment: http://stackoverflow.com/comment/87575398
upvote count: 4
answers question: http://stackoverflow.com/q/50278875
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50278875

http://stackoverflow.com/a/50330672
downvote count: 0
has comment: http://stackoverflow.com/comment/87677659
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87677762
has body: Since memory-views can only be created using a fixed set of strides, you will have to create a copy in your case, where mat.shape[0] &gt; j &gt; i. That means views will only work, if you want to have a view to every x-th element in the array: mat = np.arange(20) view = mat[slice(0, 20, 4)] view # Out[41]: array([ 0, 4, 8, 12, 16]) So this only works for views to equally spaced cells. But if you want to have a view to one contiguous slice(0, i) and another contiguous slice(j, mat.shape[0]), it won't work. You'll have to make a copy.
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50330112
type: Answer
answers question: http://stackoverflow.com/q/50330112

environment-variables
tags question: http://stackoverflow.com/q/50344058
tag name: environment-variables
tags question: http://stackoverflow.com/q/50360320
tags question: http://stackoverflow.com/q/50349585
type: Tag
tags question: http://stackoverflow.com/q/50355487

generator
type: Tag
tag name: generator
tags question: http://stackoverflow.com/q/50353482
tags question: http://stackoverflow.com/q/50338713
tags question: http://stackoverflow.com/q/50366851

http://stackoverflow.com/comment/87510709
score: 0
type: AnswerComment
has text: I believe you first want to filter the group to remove any values of zero, as it is neither positive nor negative. Then use `.gt(0)` to return an array of those that are positive and take the mean to get the percentage of non-zero values that are positive. `lambda x: x[x.ne(0)].gt(0).mean() * 100`
type: Comment
comment on: http://stackoverflow.com/a/50246196

http://stackoverflow.com/comment/87500606
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50240823
has text: what is the template name ,where i have to put this code {% if messages %}
type: Comment

http://stackoverflow.com/q/50340448
has comment: http://stackoverflow.com/comment/87697064
score: 0
tagged with: indentation
has title: Calendar project not indenting and spacing correctly Python 3
has comment: http://stackoverflow.com/comment/87697062
type: Question
has comment: http://stackoverflow.com/comment/87697201
has body: I am currently working on a function that prints a calendar. I'm not using the calendar library. My code isn't starting a new line when it's supposed to. def year_month_calendar(a,b): if b==2: if a%400==0: m=1 elif a%4==0 and a%100!=0: m=1 else: m=0 else: m=0 print("Calendar for", month_str[b-1], ",", a) print('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa') z = 0 y = 0 # y is calculating leap years y += a/4 y -= a/100 y += a/400 z += c z += 365 * (a-1) z += y for l in range(months[b]+1): sys.stdout.flush() if l &gt; 9: sys.stdout.write((' ')*(int(z%7))) else: sys.stdout.write((' ')*(int(z%7))) print(l, end=' ') if (z+l)%7==0: print('\n') This is only a part of my code but can you tell me what I did wrong.
answer count: 0
type: UnansweredQuestion
tagged with: sys
tagged with: newline
tagged with: python
tagged with: calendar

http://stackoverflow.com/q/50365913
has title: Can I write python code that modifies itself during execution?
answer count: 1
has comment: http://stackoverflow.com/comment/87748348
type: Question
has comment: http://stackoverflow.com/comment/87748171
tagged with: python
has comment: http://stackoverflow.com/comment/87748124
accepted answer: http://stackoverflow.com/a/50366022
has answer: http://stackoverflow.com/a/50366022
type: AnsweredQuestion
has body: I mean, target_ZCR_mean = sample_dataframe_summary['ZCR'][1] target_ZCR_std = sample_dataframe_summary['ZCR'][2] lower_ZCR_lim = target_ZCR_mean - target_ZCR_std upper_ZCR_lim = target_ZCR_mean + target_ZCR_std target_RMS_mean = sample_dataframe_summary['RMS'][1] target_RMS_std = sample_dataframe_summary['RMS'][2] lower_RMS_lim = target_RMS_mean - target_RMS_std upper_RMS_lim = target_RMS_mean + target_RMS_std target_TEMPO_mean = sample_dataframe_summary['Tempo'][1] target_TEMPO_std = sample_dataframe_summary['Tempo'][2] lower_TEMPO_lim = target_TEMPO_mean - target_TEMPO_std upper_TEMPO_lim = target_TEMPO_mean + target_TEMPO_std target_BEAT_SPACING_mean = sample_dataframe_summary['Beat Spacing'][1] target_BEAT_SPACING_std = sample_dataframe_summary['Beat Spacing'][2] lower_BEAT_SPACING_lim = target_BEAT_SPACING_mean - target_BEAT_SPACING_std upper_BEAT_SPACING_lim = target_BEAT_SPACING_mean + target_BEAT_SPACING_std each block of four lines of code are very similar to each other except for a few characters. Can I write a function, a class or some other piece of code, such that I can wrap just a template of four lines of code into it and let it modify itself during runtime to get the code do the work of the above code...? By the way, I use python 3.6.
tagged with: self-modifying
score: 0

http://stackoverflow.com/a/50362671
has comment: http://stackoverflow.com/comment/87742303
has comment: http://stackoverflow.com/comment/87741851
score: 2
has comment: http://stackoverflow.com/comment/87741865
has comment: http://stackoverflow.com/comment/87741770
has comment: http://stackoverflow.com/comment/87746071
accepted answer of: http://stackoverflow.com/q/50362479
has comment: http://stackoverflow.com/comment/87741831
upvote count: 2
has comment: http://stackoverflow.com/comment/87742279
has comment: http://stackoverflow.com/comment/87746419
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87747027
has comment: http://stackoverflow.com/comment/87741921
answers question: http://stackoverflow.com/q/50362479
has comment: http://stackoverflow.com/comment/87742362
has comment: http://stackoverflow.com/comment/87742431
has body: We could make use of the sorted nature and hence use np.searchsorted for this task, like so - out = np.empty((len(zbin)-1, len(lst)),dtype=int) for i,l in enumerate(lst): left_idx = np.searchsorted(l, zbin[:-1], 'left') right_idx = np.searchsorted(l, zbin[1:], 'right') out[:,i] = right_idx - left_idx
type: Answer
has comment: http://stackoverflow.com/comment/87745773

http://stackoverflow.com/q/50316132
has comment: http://stackoverflow.com/comment/87648024
tagged with: python
has comment: http://stackoverflow.com/comment/87648053
has answer: http://stackoverflow.com/a/50316170
score: 4
has comment: http://stackoverflow.com/comment/87648041
type: Question
has answer: http://stackoverflow.com/a/50316389
upvote count: 4
has comment: http://stackoverflow.com/comment/87648075
has title: Get all non-unique elements in a list
tagged with: list
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87648035
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I am trying to build a code that returns me a list with non-unique values, such as [1,2,2,3] => [2,2] and the function isn't case-sensitive, such as: ['p','P','a','b',1,5,6] => ['p','P']. This is what I have come up with so far: def non_unique(*data): tempLst = [x for x in data if (data.count(x) &gt; 1 if (ord('a') &lt;= ord(x) &lt;= ord('z') or ord('A') &lt;= ord(x) &lt;= ord('Z')) and (data.count(x.upper()) + data.count(x.lower()) &gt; 1)] return tempLst These are the test examples: if __name__ == "__main__": assert isinstance(non_unique([1]), list) assert non_unique([1, 2, 3, 1, 3]) == [1, 3, 1, 3] assert non_unique([1, 2, 3, 4, 5]) == [] assert non_unique([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] assert non_unique([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9] assert non_unique(['P', 7, 'j', 'A', 'P', 'N', 'Z', 'i', 'A', 'X', 'j', 'L', 'y', 's', 'K', 'g', 'p', 'r', 7, 'b']) == ['P', 7, 'j', 'A', 'P', 'A', 'j', 'p', 7]

http://stackoverflow.com/a/53709602
has body: -U or --upgrade will update listed packages Example: $ pip install -U django-simple-captcha # OR $ pip install --upgrade django-simple-captcha pip3 $ pip3 install -U django-simple-captcha # OR $ pip3 install --upgrade django-simple-captcha pip3 with sudo (to install system-wide, this may be required in some cases) $ sudo pip3 install -U django-simple-captcha # OR $ sudo pip3 install --upgrade django-simple-captcha
answers question: http://stackoverflow.com/q/50316939
type: Answer
downvote count: 0
upvote count: 66
score: 66

http://stackoverflow.com/comment/87758106
type: QuestionComment
has text: Yes I get a CSV file with the "density" variable. The operation `PassArrays()` get the information from the reader, if I understand well. So it is passed correctly as a source to the CSV writer.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50238785

pandas-datareader
tags question: http://stackoverflow.com/q/50283639
tag name: pandas-datareader
type: Tag

http://stackoverflow.com/comment/87658700
type: AnswerComment
has text: Again, `in dict` will only search the keys of that `dict`
type: Comment
comment on: http://stackoverflow.com/a/50321351
score: 0

http://stackoverflow.com/a/50379570
score: 0
has comment: http://stackoverflow.com/comment/87775497
answers question: http://stackoverflow.com/q/50379441
has body: def put(self, request, *args, **kwargs): return self.put(self,request,*kwargs,**kwargs) Change it; def put(self, request, *args, **kwargs): return super(ProductOwnserSingleViewAPIView, self).update(request, *args, **kwargs)
type: Answer

http://stackoverflow.com/q/50336689
tagged with: pandas
has comment: http://stackoverflow.com/comment/87689720
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: indexing
type: UnansweredQuestion
has body: I have a dictionary with a list of dataframes, each with a column that is in datetime format (column name "Datetime Format"). I am attempting to set the index of each dataframe to be that column, and am having difficulty. I've simplified the issue and tried to find a solution, my technique is not sticking: def test_func(dataframe): dataframe = dataframe.set_index('Datetime Format') return dataframe test_dict = {'DF_1': df1, 'DF_2': df2} for k, v in test_dict.items(): v = test_func(v) Upon looking at the resulting test_dict, or each individual dataframe (df1 and df2), I was not successful at setting the indexes to be the 'Datetime Format' column. I know when I do: df1 = df1.set_index('Datetime Format') it works correctly. Please advise as to how to get this to function through a list (or dict in this case). Thank you!
has answer: http://stackoverflow.com/a/50336848
has title: Changing all the indexes of all dataframes in a dict
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/50282540
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50282570
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50282583
has body: I have the following dictionary: d= { '2018-01-01': [[1.0], [2.0], [3.0]], '2018-01-02': [[4.0], [5.0], [6.0]], '2018-01-03': [[7.0], [8.0], [9.0]], '2018-01-04': [[10.0], [11.0], [12.0]], '2018-01-31': [[13.0, 14.0], [15.0, 16.0], [17.0]] } My aim is to count the number of values (floats in this case), assuming some of these 'cells' might contain more than one value (e.g.: values for '2018-01-31'). In other words, I need: result=17 So far, I was able to count the number of 'cells' (sublists), but I can't find out how can I count several values inside a single 'cell'. I tried: cols=len(d[[k for k in d.keys() if d[k]==max(d.values(),key=len)][0]]) cells = [[1 for j in range(cols)] for i in range(len(d))] result = len([item for sublist in cells for item in sublist]) print(str(result)) Output: 15 Thank you very much in advance.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50282749
type: Question
possible better answer: http://stackoverflow.com/a/50282583
upvote count: 2
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50282570
has title: Count number of values in nested lists inside a dictionary
score: 2

http://stackoverflow.com/q/50309626
duplicate of: http://stackoverflow.com/q/50310338
answer count: 0
score: 1
tagged with: sqlite
downvote count: 0
has body: In my Django admin I have a TabularInLine class. In the picture, each element of this class is numbered with it's own ID. How can I delete the text circled by red color on picture? And how I can create a new numbered column (from 1 to amount elements in table)? This TabularInLine class has a foreign key to an other class (class Part). How I can to numerate that for each FK with the numbering (my_id) started from 1 as in the picture below?
upvote count: 1
favorite count: 0
type: Question
has title: Delete object ID and enumerate new column
type: UnansweredQuestion
tagged with: django
tagged with: python

min
type: Tag
tags question: http://stackoverflow.com/q/50298059
tag name: min
tags question: http://stackoverflow.com/q/50281762

http://stackoverflow.com/comment/87658006
type: QuestionComment
type: Comment
has text: if so, Alex's solution may not give you what you want in the capture groups: https://ideone.com/bHdMdx
score: 0
comment on: http://stackoverflow.com/q/50311032

http://stackoverflow.com/a/50381079
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: I'd import the data from your file via pandas: import pandas as pd df = pd.read_table(filename, sep='\s+', index_col=0) Additionally, you can import itertools: import itertools as it With this you can get all combinations of a iterable like this, as an example with the indices of the dataframe here: for i in it.combinations(df.index, 2): print(i) ('A', 'B') ('A', 'C') ('B', 'C') This shows, that you'll get the combinations you want. Now do the same with the data of your dataframe: for i in it.combinations(df.values, 2): print(global_distance(i[0], i[1])) 222.4224400374507 122.66829007875636 342.671447691153 And if you want to have the location names included in the output, you can leave away the index_col=0 when importing, so that A, B and C is also part of the df.values and you could write: for i in it.combinations(df.values, 2): print(i[0][0], '-', i[1][0], global_distance(i[0][1:], i[1][1:])) A - B 222.4224400374507 A - C 122.66829007875636 B - C 342.671447691153
answers question: http://stackoverflow.com/q/50380860

http://stackoverflow.com/a/50321230
has body: You can use re.split: import re s = [['2006/10/18 21:15:51 4.823 -82.592 37.3 SOUTH OF PANAMA'] , ['2006/10/18 10:08:45 32.165 -115.891 7.3 BAJA CALIFORNIA, MEXICO']] new_s = [re.split('(?&lt;=\d)\s(?=[A-Z])', i) for [i] in s] Output: [['2006/10/18 21:15:51 4.823 -82.592 37.3', 'SOUTH OF PANAMA'], ['2006/10/18 10:08:45 32.165 -115.891 7.3', 'BAJA CALIFORNIA, MEXICO']]
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50321160

http://stackoverflow.com/comment/87544026
type: Comment
score: 3
has text: Don't think this is really a duplicate. I presume OP wants to compare them *from* Python. Not using some external regex to DFA tool.
type: QuestionComment
comment on: http://stackoverflow.com/q/50262853

http://stackoverflow.com/comment/87780408
comment on: http://stackoverflow.com/q/50382119
score: 0
has text: Here is the documentation for `Bytes` objects: https://docs.python.org/3/library/stdtypes.html#bytes
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87701070
comment on: http://stackoverflow.com/q/50342558
type: Comment
has text: You mean you only want the elements that are only in 1 set?
score: 0
type: QuestionComment

http://stackoverflow.com/q/50363356
has comment: http://stackoverflow.com/comment/87756519
tagged with: macos
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50380687
has body: When running this command: $ sudo virtualenv ENV --python=python2.7 I'm receiving the following: Running virtualenv with interpreter /usr/local/bin/python2.7 New python executable in /Users/bo3423/git/My-Project/ENV/bin/python2.7 Not overwriting existing python script /Users/bo3423/git/My-Project/ENV/bin/python (you must use /Users/bo3423/git/My-Project/ENV/bin/python2.7) Please make sure you remove any previous custom paths from your /Users/bo3423/.pydistutils.cfg file. Installing setuptools, pip, wheel... Complete output from command /Users/bo3423/git/...ie/ENV/bin/python2.7 - setuptools pip wheel: The directory '/Users/bo3423/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/bo3423/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 setuptools Downloading https://files.pythonhosted.org/packages/8c/10/79282747f9169f21c053c562a0baa21815a8c7879be97abd930dbcf862e8/setuptools-39.1.0-py2.py3-none-any.whl (566kB) Collecting pip Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB) Collecting wheel Downloading https://files.pythonhosted.org/packages/81/30/e935244ca6165187ae8be876b6316ae201b71485538ffac1d718843025a9/wheel-0.31.1-py2.py3-none-any.whl (41kB) Installing collected packages: setuptools, pip, wheel Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/virtualenv_support/pip-8.0.2-py2.py3-none-any.whl/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/virtualenv_support/pip-8.0.2-py2.py3-non…
has answer: http://stackoverflow.com/a/50380687
answer count: 1
tagged with: pip
upvote count: 1
tagged with: python
tagged with: virtualenv
has title: Virtualenv - IOError: [Errno 1] Operation not permitted: '/bin/easy_install'
downvote count: 1
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87761646

http://stackoverflow.com/q/50310979
type: Question
tagged with: python
type: UnansweredQuestion
has title: How to use SQLAlchemy's `one_or_none` query method?
score: 15
upvote count: 15
has answer: http://stackoverflow.com/a/50311355
downvote count: 0
has body: I'm trying to use the one_or_none query method to retrieve a record from my database but when I pass in a kwargs like I normally would with the filter_by method, it says it doesn't expect that keyword. I tried going through the doc, but there's not description of the method's argument or an example.
answer count: 1
tagged with: sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/87638985

http://stackoverflow.com/q/50366257
type: Question
upvote count: 4
type: UnansweredQuestion
has title: Apachi httpd hangs on linux servers
tagged with: apache
tagged with: python
tagged with: php
downvote count: 1
has comment: http://stackoverflow.com/comment/87755003
has answer: http://stackoverflow.com/a/50370377
tagged with: linux
tagged with: mod-wsgi
score: 3
answer count: 1
has body: In the last few months we're experiencing a major issue in our production php servers: The httpd running on our linux servers hangs and not responding to new requests (up to request timeout) until we manually restart it. We've documented this issue quite a bit, and I can point out a few major investigation directions we want to follow, but before starting the research i wanted to ask the community if someone else might be experiencing a similar problem. we are running 4 instances of linux servers, with version: linux- 2.6.32-71, red had 4.4.4-13 and httpd versions: 2.2.15 the php versions we are running are 5.5.15 and 5.5.10 (2 servers on each version). we have detected a few suspicious errors in the logs, but notably couldnt find a specific error near the crashes : Servers seems busy, (you may need to increase StartServers, or Min/MaxSpareServers) spawning X children, there are Y idle and Z total children mod_wsgi Initializing Python mod_wsgi Terminating Python mod_wsgi Cleanup interpeter: '' mod_wsgi: Destroying interpeters KeyError(NUMBER) in ignored this is a php server, why is it throwing python errors? SIGHUP received. Attempting to restart - * glibc detected * /usr/bin/httpd: corrupted double-linked list: ADDRESS *** Connection reset by peer: core_output_filter: writing data to network We noticed that "/var/log/httpd/error_log" and "/var/log/httpd/access_log" removed every time the error occur. We are having a really hard time with this subject, and would really appriciate it if someone can help shed some light on this matter. Thank you very much!
favorite count: 0

http://stackoverflow.com/q/50264831
score: 0
has comment: http://stackoverflow.com/comment/87547761
answer count: 0
has body: I am setting up celery with Flask app. My app folder structure is as follows: app.py in sonip_api/sonip is the entry point: app = factory.flask def main(): app.run(debug=settings.FLASK_DEBUG) if __name__ == "__main__": main() I am following this example to have flask and celery app declared in a factory.py under sonip_api/sonip/api. The actual celery task function is defined in sonip_api/sonip/api/resources/main.py along with these endpoints. I was able to run python sonip/app.py under directory sonip_api. However, I got error running celery -A sonip.api.celery worker in the same directory: File "C:\Users\dxx\WorkSpace\sonip_api\sonip\api\factory.py", line 4, in &lt;module&gt; import settings ModuleNotFoundError: No module named 'settings' It can be fixed by adding sonip in front of settings for the import. But then Flask app won't run. It seems like a path issue, I don't understand why celery's pythonpath is different than flask's. I am sure if I move everything out of sonip to the root directory, both Flask and celery commands would work. But I don't want my app under the same level as env etc.
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/87547747
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87547795
has title: Why does Celery have different Python Path in Flask app
has comment: http://stackoverflow.com/comment/87547724
tagged with: python
tagged with: flask

http://stackoverflow.com/comment/87762199
type: QuestionComment
comment on: http://stackoverflow.com/q/50372759
type: Comment
score: 0
has text: @silgon thanks, I will check it out !

http://stackoverflow.com/a/50354752
accepted answer of: http://stackoverflow.com/q/50352702
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: As soon as you perform a groupby, the original index is lost. This is because, internally, pandas uses the grouper column(s) as an index. What you can do is elevate your index to a column, map counts of product_id via a pre-calculated series, and then set index again. value_counts can be used instead of groupby.size for this task. df = pd.DataFrame({'product_id': [7546, 8278, 6790, 7546, 8278, 6790]}, index=[2103, 2103, 2103, 2104, 2104, 2104]) c = df.product_id.value_counts() res = df.reset_index() res['count'] = res['product_id'].map(c) res = res.set_index('index') print(res) product_id count index 2103 7546 2 2103 8278 2 2103 6790 2 2104 7546 2 2104 8278 2 2104 6790 2
answers question: http://stackoverflow.com/q/50352702
type: Answer

http://stackoverflow.com/comment/87633750
type: QuestionComment
score: 1
has text: That `try: ... except Exception: pass` is hiding useful exception information.
comment on: http://stackoverflow.com/q/50308840
type: Comment

http://stackoverflow.com/comment/87561430
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50272069
has text: @dexter7d anytime ;)

http://stackoverflow.com/a/50325832
type: Answer
has body: Make an empty list of faces. faces = [] Make a copy of the cropped face. face = numpy.copy(img[y:y+h,x:x+w]) Resize face to a fixed thumbnail size. Lets call the fixed size face_width, face_height. Append face in the faces list. faces.append(face). Make sure the cropped face does not already exist in the list. Select a point on the image, i.e px=0, py=0. Copy all the faces from the list to the image starting from px,py. img[py:py+face_height,px:px+face_width] = faces[0] ...
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50325385
score: 0
accepted answer of: http://stackoverflow.com/q/50325385

http://stackoverflow.com/comment/87796834
comment on: http://stackoverflow.com/a/50372000
score: 0
type: AnswerComment
type: Comment
has text: Turns out it was cos the JSON was in a UTC, not ASCI format... annoying.

http://stackoverflow.com/a/50356654
answers question: http://stackoverflow.com/q/50356611
upvote count: 3
score: 3
has body: Make sure that non-numeric values are assigned NaN values: df['colname'] = pd.to_numeric(df['colname'], errors='coerce') n/a looks like it might be a string instead of NaN (which is a floating-point value). Then df = df.dropna(subset=['colname']) should work as expected.
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87729716

http://stackoverflow.com/a/50357827
has body: If genres is a ManyToManyField relation, you can just filter on the field: Film.objects.filter(genres=genre_id) # movies with at least genre_id In that case, Django will perform a JOIN on the many-to-many relation table, and filter that table on the genre_id, hence we obtain the movies where the collection of genres contains at least the genre_id we filter with.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50357383
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50357383

pyad
tag name: pyad
type: Tag
tags question: http://stackoverflow.com/q/50276735

http://stackoverflow.com/a/50288564
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The error is raising because of the __str__() method tries to return self.user.username but, some of the UserProfile instances don't have a related user instance, (because you defined it as null=True in the model) So, change your __str__() method of UserProfile class as below, class UserProfile(models.Model): # your fields def __str__(self): if self.user: return self.user.username return "no user related to this profile" Or, change your UserProfile model as below and do migration, class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # &lt;&lt;&lt; change is here description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') phone = models.IntegerField(default=0) def __str__(self): return self.user.username
has comment: http://stackoverflow.com/comment/87594015
type: Answer
answers question: http://stackoverflow.com/q/50287816
score: 2
accepted answer of: http://stackoverflow.com/q/50287816
has comment: http://stackoverflow.com/comment/87593867

http://stackoverflow.com/comment/87697360
comment on: http://stackoverflow.com/a/50332395
score: 0
type: AnswerComment
type: Comment
has text: I tried it before but that is bad about sorting then (e.g. 11, 115, 178, 25, 278,...)

http://stackoverflow.com/comment/87724176
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50352077
has text: ive read both of those three times at least, its quite confusing for a novice but from what I understood I thought my script was ok, and when it worked I assume thus. im not sure I have any blocking operations in there. a blocking operation anything that takes longer than 50ms? is that right? and if I have one of those it should be run in an executor?

http://stackoverflow.com/comment/87764297
type: AnswerComment
has text: (Note, this is not the the most efficient way to fetch multiple messages)
type: Comment
comment on: http://stackoverflow.com/a/50374001
score: 0

http://stackoverflow.com/a/50324864
score: 2
has comment: http://stackoverflow.com/comment/87666352
has comment: http://stackoverflow.com/comment/87828080
answers question: http://stackoverflow.com/q/50324600
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87827978
has body: I think need combine_first for match by No. column: #filter only `MN` rows if necessary df22 = df2[df2['Type'] == 'MN'].set_index('No.') df1 = df22.combine_first(df1.set_index('No.')).reset_index().reindex(columns=df1.columns) print (df1) No. col1 col2 col3 Type col 0 123 24.0 57.0 22.0 MN ... 1 146 7.0 9.0 4.0 AA ... 2 175 21.0 43.0 37.0 MN ... 3 453 41.0 39.0 15.0 MN ... 4 643 0.0 0.0 0.0 NAN ...
has comment: http://stackoverflow.com/comment/87827720
has comment: http://stackoverflow.com/comment/87666620
has comment: http://stackoverflow.com/comment/87666657
has comment: http://stackoverflow.com/comment/87666374
has comment: http://stackoverflow.com/comment/87827778
type: Answer
accepted answer of: http://stackoverflow.com/q/50324600
has comment: http://stackoverflow.com/comment/87666544

http://stackoverflow.com/q/50234722
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87490841
tagged with: django-views
linked to: http://stackoverflow.com/q/9899113
has answer: http://stackoverflow.com/a/50234748
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/9899113
accepted answer: http://stackoverflow.com/a/50234748
answer count: 1
tagged with: django
has title: Django NameError name 'request' is not defined
has body: got an error Django NameError name 'request' is not defined. my views.py class ShiftCreateView(CreateView): fields = ('name', 'timein', 'timeout', 'desc') model = models.Shift def form_valid(self, form): self.object = form.save(commit=False) self.object.timein = request.POST.get("timein", "") self.object.timeout = request.POST.get("timeout", "") self.object.save() return super(ModelFormMixin, self).form_valid(form)

http://stackoverflow.com/comment/87775570
has text: @Metropolis Thanks for all the help, I inspected both data sets and the issue was that my original dataframe had a Index column, It all worked fine after I resetted the index.
type: AnswerComment
comment on: http://stackoverflow.com/a/50360132
type: Comment
score: 0

http://stackoverflow.com/q/50263155
accepted answer: http://stackoverflow.com/a/50309636
tagged with: tkinter-canvas
tagged with: python
has title: How do I display an extremly long image in Tkinter? (how to get around canvas max limit)
has answer: http://stackoverflow.com/a/50263364
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50263364
has answer: http://stackoverflow.com/a/50309636
tagged with: image
has body: I've tried multiple ways of displaying large images with tkinterreally long image No matter what I've tried, there doesn't seem to be any code that works. The main issue is that Canvas has a maximum height limit of around 30,000 pixels. Is there a way to display this whole image? increase, or get around the canvas limit? See the example image below.
tagged with: tkinter
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/87606000
comment on: http://stackoverflow.com/q/50294533
has text: Hi and thanks for the answer. Then, is there a way to get the same result in my script then in my manually made request ?
score: 0
type: Comment
type: QuestionComment

xcode
tag name: xcode
type: Tag
tags question: http://stackoverflow.com/q/50310658
tags question: http://stackoverflow.com/q/50380468

http://stackoverflow.com/q/50284233
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/87584786
has answer: http://stackoverflow.com/a/50284336
has comment: http://stackoverflow.com/comment/87584873
has comment: http://stackoverflow.com/comment/87584731
tagged with: printing
has answer: http://stackoverflow.com/a/50284699
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87584830
linked to: http://stackoverflow.com/q/14789930
has comment: http://stackoverflow.com/comment/87587350
favorite count: 0
has title: Python: deleting the nth acharcter in console
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87584780
has comment: http://stackoverflow.com/comment/87584842
has body: example output estimate of pi: 3.13658765 then a new better estimate comes along. Say, 3.1416232. So I find the first character in the old estimate that doesn't match the new. In this case, it is the 4th character. Question: Is there a way to delete the 4th character in console(and then repeat this until all characters after 3.1 are gone) so that I can then print the new, better values for each of those characters? Note: I don't want to delete everything and console and then reprint, as this would get considerably slower as the number of digits increases.
type: UnansweredQuestion

http://stackoverflow.com/a/50567812
downvote count: 0
has body: You are only mutating 5% of the population, not 5% of the "genome". This means your population will be fixed incredibly quickly - https://en.wikipedia.org/wiki/Fixation_(population_genetics) . This makes sense why the population isn't doing very well, because you are only exploring a very small area of the fitness landscape ( https://en.wikipedia.org/wiki/Fitness_landscape ) . You should change the mutate function to mutate 5% of the genome (ie weights between nodes). Feel free to play around with the mutation rate as well - different problems perform better at different mutational rates. If you are worried about loosing the current "best genome", a typical approach in evolutionary computation is to copy the individual with the highest fitness over to the next generation without mutation. (Sorry, this probably should have been a comment but I don't have enough reputation).
answers question: http://stackoverflow.com/q/50309918
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/87572489
has text: @Lirum I'm not sure if it's possible, but this looks like a promising place to start: http://docs.sqlalchemy.org/en/latest/orm/mapping_columns.html
comment on: http://stackoverflow.com/a/50277707
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50329853
has comment: http://stackoverflow.com/comment/87675626
has comment: http://stackoverflow.com/comment/87675693
has comment: http://stackoverflow.com/comment/87675619
has body: Input: X Y Hyderabad 1 1 Bangalore 0 1 Goa 1 1 Chennai 0 1 Hyderabad 0 1 Goa 0 0 Chennai 0 1 Goa 0 0 Hyderabad 1 0 Chennai 0 1 Chennai 1 1 Goa 0 1 Bangalore 0 0 Bangalore 0 1 expected output: X 0 1 Y 0 3 1 1 7 3
favorite count: 0
type: Question
tagged with: counter
tagged with: python
score: -8
possible better answer: http://stackoverflow.com/a/50329983
has title: find number of 1 and 0 combinations in two columns
accepted answer: http://stackoverflow.com/a/50330014
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50329983
downvote count: 11
has answer: http://stackoverflow.com/a/50330014
answer count: 2
has comment: http://stackoverflow.com/comment/87675666
tagged with: pandas
upvote count: 3

http://stackoverflow.com/comment/116631921
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50293746
has text: What is **b** here? did you attempt to run this before posting? I have tried to run this code and this is what I get _NameError: name 'b' is not defined_

http://stackoverflow.com/comment/87764978
has text: It has to do with the collation of your database. You need to ensure that the collation of the database is the same as that one of the field.
comment on: http://stackoverflow.com/q/50374375
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50328971
upvote count: 5
has title: Celery: Disable heartbeat between workers
tagged with: python
has comment: http://stackoverflow.com/comment/87754051
linked to: http://stackoverflow.com/q/21132240
accepted answer: http://stackoverflow.com/a/51093045
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51093045
answer count: 1
downvote count: 0
has body: I'm working on a data processing routine in Celery with a Redis backend and broker. Many workers (~200) interact with a broker to get tasks and execute those tasks. However, my workers are all sending heartbeat signals to one another, which populates their logs with all sorts of cruft like this: [2018-05-13 15:38:00,737: INFO/MainProcess] missed heartbeat from celery@d12chas387.crc.nd.edu [2018-05-13 15:38:00,737: INFO/MainProcess] missed heartbeat from celery@d12chas530.crc.nd.edu [2018-05-13 15:38:00,737: INFO/MainProcess] missed heartbeat from celery@d12chas531.crc.nd.edu [2018-05-13 15:38:00,738: INFO/MainProcess] missed heartbeat from celery@d12chas351.crc.nd.edu [2018-05-13 15:38:00,738: INFO/MainProcess] missed heartbeat from celery@d12chas515.crc.nd.edu [2018-05-13 15:38:00,739: INFO/MainProcess] missed heartbeat from celery@d12chas492.crc.nd.edu The workers should never interface with each other directly, they should all get the information they need from the broker. Is it possible to disable heartbeats between worker nodes? If so, is this a bad idea for some reason I'm not yet seeing?
favorite count: 0
tagged with: celery
type: Question
score: 5
tagged with: redis
tagged with: message-passing

http://stackoverflow.com/a/50276765
downvote count: 0
upvote count: 1
has body: print(f"hello from {self.__class__}")
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50276731

http://stackoverflow.com/comment/87593841
type: QuestionComment
has text: You have to be specific, "does not help" is quite vague. Are you getting error messages? Wrong values? Include any error messages in your question.
comment on: http://stackoverflow.com/q/50288258
score: 1
type: Comment

http://stackoverflow.com/comment/87592515
comment on: http://stackoverflow.com/a/50287683
type: AnswerComment
has text: year value `2018` how if i want `18`
score: 0
type: Comment

http://stackoverflow.com/comment/87607118
type: Comment
has text: Elegant solution!
type: AnswerComment
comment on: http://stackoverflow.com/a/50295089
score: 1

http://stackoverflow.com/q/50317825
accepted answer: http://stackoverflow.com/a/50319190
has comment: http://stackoverflow.com/comment/87651366
has body: see below the following code I have at the moment and the error that is coming with it. companynames = [] for x in urls: website_nametext = requests.get(x) all_text = website_nametext.text all_soup = BeautifulSoup(all_text, 'html.parser') companynames.append(all_soup.h1.get_text()) overall_data = pd.DataFrame(data=[companynames], columns=['Company Name']) I receive the following error AssertionError: 1 columns passed, passed data had 3 columns If I was to change the code to put three columns then it allows the dataframe to be created. See below the code. companynames = [] for x in urls: website_nametext = requests.get(x) all_text = website_nametext.text all_soup = BeautifulSoup(all_text, 'html.parser') companynames.append(all_soup.h1.get_text()) overall_data = pd.DataFrame(data=[companynames], columns=['Company Name', 'Company Name', 'Company Name']) However I want the results 'x' , 'y' and 'z' to be in one column and each name on a separate row. rather than there being three separate columns as per my initial code however obviously that is creating an error. How do I do so?
has answer: http://stackoverflow.com/a/50319190
type: AnsweredQuestion
score: 0
tagged with: for-loop
tagged with: pandas
answer count: 1
has title: Python For Loop DataFrame
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87651718
has comment: http://stackoverflow.com/comment/87651362
tagged with: python

http://stackoverflow.com/q/50357138
has title: get Button to subtract value mulitple times tkinter
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/50357200
score: 0
has body: I'm trying to create a button that'll decrease the value of an integer. It works once (going from 10 to 9), but I cannot get it to go from 9 to 8. from tkinter import * w = Tk() w.geometry('500x500') integer = 10 def subtract(): new_integer = integer - 1 l1.config(text=new_integer) l1 = Label(w, text=integer, bg='white', fg='black') l1.config(height=2, width=7) l1.grid(row=1, column=1) b1 = Button(w, text='&lt;&lt;&lt; 1', bg='black', fg='white', command=subtract) b1.config(height=2, width=7) b1.grid(row=1, column=0) w.mainloop()
accepted answer: http://stackoverflow.com/a/50357165
type: Question
possible better answer: http://stackoverflow.com/a/50357200
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50357165

http://stackoverflow.com/q/50240427
accepted answer: http://stackoverflow.com/a/50240590
tagged with: python
has answer: http://stackoverflow.com/a/50240590
has body: When searching my db all special characters work aside from the "+" - it thinks its a space. Looking on the backend which is python, there is no issues with it receiving special chars which I believe it is the frontend which is Javascript what i need to do is replace "+" == "%2b". Is there a way for me to use create this so it has this value going forth?
tagged with: replace
type: Question
has comment: http://stackoverflow.com/comment/87498360
score: 0
answer count: 1
tagged with: javascript
has title: Replace character with a absolute value
type: AnsweredQuestion
tagged with: syntax

http://stackoverflow.com/comment/87717449
has text: Well that's another question then.. but the answer to your "maybe I am using the wrong tool" question is obviously "yes" - pdb is a step debugger, not a tool to pass arguments to a script.
comment on: http://stackoverflow.com/q/50348914
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/50281242
has comment: http://stackoverflow.com/comment/87584268
answers question: http://stackoverflow.com/q/50280953
has body: I don't know if you can get around using loops. This seems pretty similar to how you would calculate a correlation matrix, which uses loops in the pandas documentation. At least it's symmetric so you only have to compare half of them. Instead of calculating a correlation, you want to find the number of elements that are shared between two lists lst1 and lst2 which is len(set(lst1) &amp; set(lst2)) import pandas as pd import numpy as np df = pd.DataFrame({'subreddit': ['sub1', 'sub2', 'sub3', 'sub4'], 'user': [['A', 'B', 'C'], ['A', 'F', 'C'], ['F', 'E', 'D'], ['X', 'Y', 'Z']]}) mat = df.user cols = df.subreddit idx = cols.copy() K = len(cols) correl = np.empty((K, K), dtype=int) for i, ac in enumerate(mat): for j, bc in enumerate(mat): if i &gt; j: continue c = len(set(ac) &amp; set(bc)) correl[i, j] = c correl[j, i] = c overlap_df = pd.DataFrame(correl, index=idx, columns=cols) #subreddit sub1 sub2 sub3 sub4 #subreddit #sub1 3 2 0 0 #sub2 2 3 1 0 #sub3 0 1 3 0 #sub4 0 0 0 3 And if you want to get those smaller DataFrames then you just need a little bit of manipulation. For example: overlap_df.index.name='subreddit_1' overlap_df'sub1'.stack().reset_index().rename(columns={0: 'shared_users'}) subreddit_1 subreddit shared_users 0 sub1 sub1 3 1 sub2 sub1 2 2 sub3 sub1 0 3 sub4 sub1 1
type: Answer
has comment: http://stackoverflow.com/comment/87584192
has comment: http://stackoverflow.com/comment/87584171
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87579366
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50280953
has comment: http://stackoverflow.com/comment/87584145

http://stackoverflow.com/comment/87602827
has text: sobra = autores_atuais.loc[m1 & m2, 'Ementa']
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50292745

http://stackoverflow.com/a/50335430
answers question: http://stackoverflow.com/q/50335402
accepted answer of: http://stackoverflow.com/q/50335402
type: Answer
has body: IIUC, you can just pass the argument as_index=False to your groupby. You can then access it as you would any other dataframe vetor_valores = df.groupby(['mes','clif_cod'], as_index=False).sum() &gt;&gt;&gt; vetor_valores mes clif_cod ano peds_val_fat 0 1 1 2016 10.20 1 2 2 2016 15.20 2 4 3 2016 30.90 3 5 3 2016 14.80 4 5 4 2016 10.99 5 6 4 2016 39.90 6 12 4 2016 54.90 To access values, you can now use iloc or loc as you would any dataframe: # Select first row: vetor_valores.iloc[0] ... Alternatively, if you've already created your groupby and don't want to go back and re-make it, you can reset the index, the result is identical. vetor_valores.reset_index()
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

top-n
type: Tag
tag name: top-n
tags question: http://stackoverflow.com/q/50304103

http://stackoverflow.com/a/50238556
has body: I have since figured I was making life difficult for myself. import numpy as np from numpy.linalg import inv from scipy.stats import gmean for n in range(20,21,1): X=np.random.uniform(-0.3,0.3,(n)) Y=np.random.uniform(-0.3,0.3,(n)) a,b=np.ogrid[-1:n-1:1,-1:n-1:1] def f(n, x, y): D=np.array(np.exp(1j*(5*np.pi/6)*np.abs((a+x)-(b+y)))) D[diag,diag]=1-1j/np.sqrt(3) #this diag line is just to choose the diagonal elements specifically as they never change. return D Ddiff = np.abs(np.dstack(inv([f(n, x, y) for x,y in zip(X,Y)]))) D2diff = gmean(Ddiff,axis=-1) I've moved the X and Y arrays inside the function so each time it's called, a new X and Y are called too. I also specified the element to call just using a and b seeing as they are integers anyway. Then I just use a dummy index to call the function 500 times. def f(n): X=np.random.uniform(-0.3,0.3,(n)) Y=np.random.uniform(-0.3,0.3,(n)) D=np.array(np.exp(1j*(5*np.pi/6)*np.abs((a+X[a])-(b+Y[b])))) D[diag,diag]=1-1j/np.sqrt(3) return D Ddiff = np.abs( np.dstack( inv( [f(n) for _ in range(500)] ) ) ) D2diff = gmean(Ddiff,axis=-1)
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50236942
score: 0
accepted answer of: http://stackoverflow.com/q/50236942

http://stackoverflow.com/q/50252083
favorite count: 0
tagged with: jit
has comment: http://stackoverflow.com/comment/87666629
type: Question
has answer: http://stackoverflow.com/a/50260501
tagged with: numba
has title: Making four nested for loops even faster with Numba
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87521378
upvote count: 3
score: 3
linked to: http://stackoverflow.com/q/49389068
has comment: http://stackoverflow.com/comment/87531641
downvote count: 0
tagged with: loops
has body: I'm a bit new to work with Numba, but I got the gist of it. I wonder if there any more advanced tricks to make four nested for loops even faster that what I have now. In particular, I need to calculate the following integral: Where B is a 2D array, and S0 and E are certain parameters. My code is the following: import numpy as np from numba import njit, double def calc_gb_gauss_2d(b,s0,e,dx): n,m=b.shape norm = 1.0/(2*np.pi*s0**2) gb = np.zeros((n,m)) for i in range(n): for j in range(m): for ii in range(n): for jj in range(m): gb[i,j]+=np.exp(-(((i-ii)*dx)**2+((j-jj)*dx)**2)/(2.0*(s0*(1.0+e*b[i,j]))**2)) gb[i,j]*=norm return gb calc_gb_gauss_2d_nb = njit(double[:, :](double[:, :],double,double,double))(calc_gb_gauss_2d) For and input array of size 256x256 the calculation speed is: In [4]: a=random.random((256,256)) In [5]: %timeit calc_gb_gauss_2d_nb(a,0.1,1.0,0.5) The slowest run took 8.46 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 1min 1s per loop Comparison between pure Python and Numba calculation speed give me this picture: Is there any way to optimize my code for better performance?
has comment: http://stackoverflow.com/comment/87521402
has comment: http://stackoverflow.com/comment/87531760
has comment: http://stackoverflow.com/comment/87531573
answer count: 1
tagged with: iteration

http://stackoverflow.com/q/50281187
has comment: http://stackoverflow.com/comment/87684547
has comment: http://stackoverflow.com/comment/87581563
has comment: http://stackoverflow.com/comment/87583973
has comment: http://stackoverflow.com/comment/87581756
has comment: http://stackoverflow.com/comment/87612372
has comment: http://stackoverflow.com/comment/87581436
has comment: http://stackoverflow.com/comment/87686297
has comment: http://stackoverflow.com/comment/87686230
has body: I've modified some code that takes a .wav file and turns it into a .png. The original source for the .wav to .png conversion is from: https://github.com/bobvanluijt/audio-convolutional-neural-network/blob/master/convertWavToPng.py I've edited it so that instead the colors are sorted in a gradient fashion so that it looks like: https://i.sstatic.net/p4njd.jpg Here: from PIL import Image import wave, struct, sys, math ## # Collect input ## if sys.argv[1][-4:] != '.wav': sys.exit("First argument should be a .wav file") if sys.argv[2][-4:] != '.png': sys.exit("Second argument should be a .png file") ## # Conversion: ## # Wave file needs to be 16 bit mono waveFile = wave.open(sys.argv[1], 'r') if waveFile.getnchannels() != 1: sys.exit("ERROR: The wave file should be single channel (mono)") imageRgbArray = list() waveLength = waveFile.getnframes() # Create the image size (based on the length) imageSize = math.ceil(math.sqrt(waveLength)) # Loop through the wave file for i in range(waveLength): # Try to read frame, if not possible fill with 0x0 try: waveData = waveFile.readframes(1) data = struct.unpack("&lt;h", waveData) # This loads the wave bit convertedData = int(data[0]) + 32768 except: convertedData = 0 pass bits = 5 rgbData = tuple([(convertedData&gt;&gt;bits*i)&amp;(2**bits-1) for i in range(3)]) rgbData = tuple(map(lambda x: x&lt;&lt;3, rgbData)) # Add the RGB value to the image array imageRgbArray.append(rgbData) # Create new image im = Image.new('RGB', (int(imageSize), int(imageSize))) # Add image data im.putdata(list(sorted(imageRgbArray))) # Save image im.save(sys.argv[2]) But now I need to be able to convert the sorted .png back into a .wav file. Luckily, I already have this to work with: https://github.com/bobvanluijt/audio-convolutional-neural-network/blob/master/convertPngToWav.py from PIL import Image import wave, struct, sys, soundfile as Sndfile, numpy as np, math ## # Collect input ## if sys.argv[1][-4:] != '.png': sys.exit("First argument should be a .…
type: Question
has comment: http://stackoverflow.com/comment/87605348
has title: Convert png back to wav
has comment: http://stackoverflow.com/comment/87580502
linked to: http://stackoverflow.com/q/50195130
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87583470
has comment: http://stackoverflow.com/comment/87580583
has comment: http://stackoverflow.com/comment/87580804
has comment: http://stackoverflow.com/comment/87605949
score: 0
has comment: http://stackoverflow.com/comment/87582087

http://stackoverflow.com/a/50354588
downvote count: 0
has body: It's workable using: df1.rename(columns={'old_name':'new_name'}) Although, it doesn't look good as I have 10 columns to rename.
type: Answer
answers question: http://stackoverflow.com/q/50353740
score: 4
upvote count: 4

http://stackoverflow.com/q/50280946
possible better answer: http://stackoverflow.com/a/50283626
has answer: http://stackoverflow.com/a/50281590
has comment: http://stackoverflow.com/comment/87578565
has comment: http://stackoverflow.com/comment/87578571
has answer: http://stackoverflow.com/a/50283626
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87579562
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87579049
score: 1
tagged with: python
tagged with: regex
has title: RegEx looking both backwards and forward
has comment: http://stackoverflow.com/comment/87580235
type: Question
accepted answer: http://stackoverflow.com/a/50281590
answer count: 2
has body: I'd like to get all the strings when it has a given term not followed by a set of given terms either preceded by the same terms using regular expressions, something like this: (?&lt;!(term1|term2)[\w\- ]{1,25})my_term(?![\w\- ]{1,25}(term1|term2)) Visualisation but it seems it doesn't work with any of the following texts: my_term good example. Another good my_term example. This one term1 shouldn't my_term work. Neither my_term do term2 it. Any idea?

http://stackoverflow.com/comment/87716801
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50347401
has text: I am very new to Django rest framework. i can pass queryset to serializers and get the output. but in this project there are join query with sub query for Services and Addon services. i dont know how to write such complex code using serializers.
type: Comment

http://stackoverflow.com/q/50295889
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Python 3.6 IPython console can't find ipykernel or cloudpickle after adding new conda environment for Python 2.7
has answer: http://stackoverflow.com/a/50301504
tagged with: anaconda
score: 1
has body: I'm working on a project where I need to switch between Python 2.7 and Python 3.6 occasionally. So I recently set up a Python 2.7 environment in Anaconda using the following command. conda create -n py27 python=2.7 anaconda By default, Anaconda uses a Python 3.6 environment and Spyder (and the IPython console) had been working perfectly prior to the creation of the Python 2.7 environment. However, after creating the new environment, I can no longer use the IPython console in Spyder when I launch in the Python 3.6 environment (works fine for my new Python 2.7 environment) because for some reason it doesn't recognize the ipykernel and cloudpickle modules (even though I've checked and re-installed these modules for my Python 3.6 environment). Below is the error continue to get. An error ocurred while starting the kernel Your Python environment or installation doesn't have the ipykernel and cloudpickle modules installed on it. Without these modules is not possible for Spyder to create a console for you. You can install them by running in a system terminal: pip install ipykernel cloudpickle or conda install ipykernel cloudpickle If anyone has any ideas how I can fix this, let me know. Thank you!
tagged with: spyder
tagged with: ipython

http://stackoverflow.com/q/50375933
has body: from pyparsing import * class AParseActionHolder(object): def __call__(self, string, index, t): f(info_from_outer_parse_results,t[0]) expr = operatorPrecedence( Word(nums),[ (Literal('A'), 1, opAssoc.RIGHT,AParseActionHolder()), (Literal('B'), 2, opAssoc.LEFT), (Literal('C'), 2, opAssoc.LEFT)]) print(expr.parseString("3B1C2BA1")[0])#[['3','B','1'],'C',['2','B',"nested in B and C"]] print(expr.parseString("A1B3")[0])#["nested in B", 'B', '3'] print(expr.parseString("A(1B3)")[0])#["not nested", ['1', 'B', '3']] How can I access info from outer parsing result in which the argument of parseaction is nested? Can I do it with parseaction? If not is there some other Pyparsing tool for it or I should define recursive function that takes pyparsing.ParseResults as argument?
accepted answer: http://stackoverflow.com/a/50382430
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50382430
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: pyparsing
favorite count: 0
has title: Pyparsing: access outer ParseResults in parseaction
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50321744
type: Answer
has comment: http://stackoverflow.com/comment/87659408
answers question: http://stackoverflow.com/q/50321308
has comment: http://stackoverflow.com/comment/87659433
upvote count: 3
score: 3
downvote count: 0
has body: Extract the urls from the text file first. Then use urllib to access each url. You can find details of reading and writing files from the official documentation. Here for simplicity, I assume you want to store the retrieved data in a list import urllib with open(path-to-url-files) as fh: urls = fh.readlines() retrieved_pages = [] for url in urls: retrieved_pages.append(urllib.request.urlopen(url).read()) Now you can print the lines of each retrieved url if you want to. for page in retrieved_pages: for line in page: print(line) print("\n\n")
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87659447
accepted answer of: http://stackoverflow.com/q/50321308

http://stackoverflow.com/comment/87586598
comment on: http://stackoverflow.com/q/50284691
type: Comment
type: QuestionComment
has text: Do you need SQL? If so, sqlite3 makes sense. I've used in-memory sqlite3 as a cache in front of on-disk sqlite3, because it's dead simple to move queries back and forth between the two, and it works pretty well at the small-to-medium scale (as in the kind of scale where sqlite3 makes sense for your persistent storage…). On the other hand, if you just need a key-value store, wrapping it in a relational database and generating and parsing SQL is just unnecessary complexity in your code and overhead in your runtime.
score: 0

http://stackoverflow.com/a/50347366
answers question: http://stackoverflow.com/q/50347080
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87711438
downvote count: 0
has comment: http://stackoverflow.com/comment/87715812
has body: You can change your model and form as below models.py class CVSS(models.Model): AV_CHOICES = AV = [ (u'N', u'Network'), (u'A', u'Adjacent'), (u'L', u'Local'), (u'P', u'Physical'), ] av = models.CharField( choices=AV_CHOICES max_length=1, null=True, ) forms.py class CVSSForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CVSSForm, self).__init__(*args, **kwargs) self.fields['av'].widget = forms.RadioSelect() class Meta: model = CVSS fields = ['av',] views.py def edit(request, fid): cvss = get_object_or_404(CVSS, finding_id=fid) cvss_form = CVSSForm(instance=cvss) if request.method == 'POST': cvss_form = CVSSForm(instance=cvss, data=request.POST) if cvss_form.is_valid(): cvss_form.save() template.html {{ form }}
type: Answer

http://stackoverflow.com/q/50373813
favorite count: 0
tagged with: excel
type: Question
type: AnsweredQuestion
upvote count: 3
tagged with: http://stackoverflow.com/tag/xlsx
has answer: http://stackoverflow.com/a/50373885
tagged with: python
score: 2
has title: Aggregate columns with same date (sum)
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50373885
tagged with: xlsxwriter
answer count: 1
downvote count: 1
has body: So, i need to aggregate rows where the date is the same. My code, as of now, returns the following: date value source 0 2018-04-08 15:52:26.110 1 ANAPRO 1 2018-04-22 12:14:38.807 1 ANAPRO 2 2018-04-22 12:34:18.403 1 ANAPRO 3 2018-04-22 12:40:35.877 1 ANAPRO 4 2018-04-22 12:53:57.897 1 ANAPRO 5 2018-04-22 13:02:45.180 1 ANAPRO 6 2018-05-04 17:41:15.840 1 ANAPRO 7 2018-04-22 15:03:54.353 1 ANAPRO 8 2018-04-22 15:24:27.030 1 ANAPRO 9 2018-04-22 15:27:56.813 1 ANAPRO I don't think I can aggregate the columns while I have HH:MM:SS.ms being showed alongside the date (I only need the date) I've tried this : df['date'] = pandas.to_datetime(df['date'], format='%b %d %Y.%f').astype(str) But to no avail, I still got the same return. The code is: Reads the my excel file (user input). df = pandas.read_excel(var + '.xlsx') Selects the columns I need, and create a new .xlsx to contain it. df = df.iloc[:, 36].to_excel(var + '_.xlsx', index=False) Opens the new .xlsx file. df = pandas.read_excel(var + '_.xlsx') Renames the column df = df.rename(columns={'Prospect Dt. Cadastro': 'date'}) Adds the other columns I need. df['value'] = 1 df['source'] = 'ANAPRO' Tries to format the date. df['date'] = pandas.to_datetime(df['date'], format='%b %d` %Y.%f').astype(str) Creates the final xlsx, with all the formatted data. df = df.to_excel('payload.xlsx') Reads the final xlsx. df = pandas.read_excel('payload.xlsx', names=['date', 'value', 'source']) Prints the first 10 rows. print(df.head(10)) I'm new to python, so sorry if I'm doing something awkward, thank you!

nested
tags question: http://stackoverflow.com/q/50362074
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/50287479
tags question: http://stackoverflow.com/q/50343734
tags question: http://stackoverflow.com/q/50239582
tags question: http://stackoverflow.com/q/50363050

http://stackoverflow.com/q/50286820
tagged with: flask
type: Question
has title: Printing value next to text box from a function in flask html
type: UnansweredQuestion
has body: I am having below code from flask import Flask, render_template, request app = Flask(__name__) import logging @app.route("/") def hello(): return "Hello csdfwe!" @app.route('/test/') def check(): return render_template('template.html') @app.route('/result/', methods = ['GET', 'POST']) def result(): print "*****", request.form, "******" return render_template('template1.html') @app.route('/result1/', methods = ['GET', 'POST']) def result1(): return "Pressed OK" if __name__ == "__main__": app.run() template1.html is Value1 Value2 Charging Duration Query : In html file, as you can see I am having different text box for Value1 and Value2. I want to print the existing value of value1 that is already there after the text box. It means template will show the already existing value and user can set any new value. I don't know how to get the value from a function in html. Please guide
tagged with: python
has answer: http://stackoverflow.com/a/50290774
score: 0
answer count: 1

http://stackoverflow.com/comment/87599992
comment on: http://stackoverflow.com/q/50289773
has text: What makes you think breaking out of a loop is not best practice, out of curiosity?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50348710
type: UnansweredQuestion
has body: Which Python Libraries are best to match test strings? I have a list of suburbs from the city of Auckland, NZ I also have several million rows of data where the address has a suburb field, but these have all been free form typed in. This means they have spelling mistakes, and all sorts of weird problems. (Like using MT instead of Mount and other things like that where the data entry operator used a non-standard convention) I am wanting to use python to find a way to work out which suburb each entry relates to. But I'm not even sure where to begin. (I'm still at a fairly basic Python level) I had thought of possibly assigning numbers to each letter and then trying to build some functions around a kNN match, somebody else has suggested using a Jaccard similarity in some way. The list of suburbs I want to match to: ['ABBOTSFORD', 'ACACIA BAY', 'ADDISON', 'AHUROA', 'AIRPORT OAKS', 'ALBANY', 'ALBANY HEIGHTS', 'ALBANY NORTH', 'ALBANY SOUTH', 'ALBANY WEST', 'ALEXANDRA', 'ALFRISTON', 'ALGIES BAY', 'AOTEA', 'ARARIMU', 'ARCH HILL', 'ARDMORE', 'ARKLES BAY', 'ARKLES BAY', 'ARMY BAY', 'AUCKLAND CENTRAL', 'AVONDALE', 'AVONDALE NORTH', 'AVONDALE SOUTH', 'AVONDALE WEST', 'AWANUI', 'AWHITU', 'BALMORAL', 'BAYSWATER', 'BAYVIEW', 'BEACH HAVEN', 'BEACH HAVEN NORTH', 'BEACH HAVEN SOUTH', 'BEACHLANDS', 'BELLEVUE', 'BELMONT', 'BETHELLS BEACH', 'BIRKDALE', 'BIRKDALE NORTH', 'BIRKDALE SOUTH', 'BIRKENHEAD', 'BIRKENHEAD POINT', 'BLOCKHOUSE BAY', 'BOMBAY', 'BOTANY', 'BOTANY DOWNS', 'BROOKBY', 'BROWNS BAY', 'BUCKLANDS BEACH', 'BURSWOOD', 'CAMPBELLS BAY', 'CASTOR BAY', 'CHAPEL DOWNS', 'CHATSWOOD', 'CHELTENHAM', 'CLAUDELANDS', 'CLENDON PARK', 'CLEVEDON', 'CLOVER PARK', 'COATESVILLE', 'COCKLE BAY', 'CONIFER GROVE', 'CROWN HILL', 'DAIRY FLAT', 'DANNEMORA', 'DARGAVILLE', 'DEVONPORT', 'DOME FOREST', 'EAST TAMAKI', 'EASTERN BEACH', 'EDEN TERRACE', 'ELLERSLIE', 'EPSOM', 'EPSOM NORTH', 'EPSOM SOUTH', 'FAIRVIEW HEIGHTS', 'FARM COVE', 'FAVONA', 'FLAT BUSH', 'FORREST HILL', 'FREEMANS BAY', 'GLEN EDEN', 'GLE…
downvote count: 2
answer count: 1
favorite count: 0
tagged with: pattern-matching
type: Question
score: 0
has title: Which Python Libraries are best to match test strings
tagged with: python
has comment: http://stackoverflow.com/comment/87714416
tagged with: text
has answer: http://stackoverflow.com/a/50348851
tagged with: list
has comment: http://stackoverflow.com/comment/87713115
upvote count: 2

http://stackoverflow.com/comment/87721771
type: QuestionComment
comment on: http://stackoverflow.com/q/50339418
score: 0
has text: They aren't being *converted* to ASCII, they already *are* ASCII.
type: Comment

http://stackoverflow.com/q/50271715
type: Question
has answer: http://stackoverflow.com/a/50271858
has answer: http://stackoverflow.com/a/50272329
has title: Can't run Python file via Command Prompt, File is not defined error
has body: I am new to Python and currently doing a basic python course to learn. I have been running code all day via the Command Prompt and it has been working fine. For some reason though it has stopped working and python files I try to run are returning the following error: Traceback (most recent call last): File "", line 1, in NameError: name 'hello' is not defined As per the screen shot and the numbers on it, I performed the following steps in an attempt to run the file: change to the folder where file is saved run 'dir' to list all files. I am trying to run 'hello.py'. This contains the code: print('hello simon!') I can run the file by just typing hello.py into the command prompt, this works ok I can also run with: python hello.py - this works ok when I activate Python by typing Python --> Enter, this starts the interpreter ok. However if I then try to run by typing hello.py I get the error message. This has worked ok all day, I have not changed anything on my PC (to the best of my knowledge!) but just started to get this error a few hours ago. I have looked all over the internet for solution but found nothing. I have uninstalled and re-installed Python, restarted etc... all to no avail. I am running Python 3.6.5 on a Windows 7 64 bit PC. It won't let me attach a picture so here is link to screenshot of Command Prompt and error: https://i.sstatic.net/BBUe5.jpg I hope someone can help me with this please Thankyou
tagged with: python
possible better answer: http://stackoverflow.com/a/50271858
answer count: 4
accepted answer: http://stackoverflow.com/a/50271818
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50271818
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50271825
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87630285
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50307124
type: QuestionComment
has text: can you send a sample code?

http://stackoverflow.com/comment/87587755
comment on: http://stackoverflow.com/a/50285463
score: 0
type: AnswerComment
type: Comment
has text: Thanks a lot! this works. Now when i concatenate its coming in only one row.If i have to repeat for all rows of system-infos how can i do that

http://stackoverflow.com/q/50315688
has answer: http://stackoverflow.com/a/50315798
has answer: http://stackoverflow.com/a/50315992
has comment: http://stackoverflow.com/comment/87647322
favorite count: 0
has body: This is what I have so far: import random list1 = [] list2 = [] for i in range(5): for j in range(3): list1.append(random.randrange(1,101)) list2.append(list1) list1=[] for i in list2: for j in i: print(j, end=",") print(" (Sum: ", sum(i), " Average: ", (sum(i)/len(i)), ")", sep="") print() I want to be able to find the largest and smallest number on each column. So for example, the output would be: 1,91,46, (Sum: 138 Average: 46.0) 82,62,21, (Sum: 165 Average: 55.0) 39,52,41, (Sum: 132 Average: 44.0) 60,69,45, (Sum: 174 Average: 58.0) 20,21,7, (Sum: 48 Average: 16.0) Largest number of first column: 82 Smallest number of first column: 1 Largest number of second column: 91 Smallest number of second column: 21 Largest number of third column: 46 Smallest number of third column: 7 I know of min/max, is there some way I can use those to get these results? Or do I have to use a different method? Any help appreciated!
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: How can I find the min and max of a specific position in a loop of lists?
has comment: http://stackoverflow.com/comment/87647396
score: 2

http://stackoverflow.com/a/50241932
score: 3
accepted answer of: http://stackoverflow.com/q/50241441
type: Answer
answers question: http://stackoverflow.com/q/50241441
has comment: http://stackoverflow.com/comment/87501692
has body: The line Company = forms.ModelChoiceField() is evaluated when the module is loaded. You don't have access to self.username at that point. Instead, you should set the queryset in the form's __init__ method: class DepartmentForm(forms.Form): company = forms.ModelChoiceField( queryset=Company.objects.none(), # use empty queryset now, we'll set the real queryset when the form is initialised widget=forms.Select(...), ) def __init__(self, *args, **kwargs): self.username = kwargs.pop('username', None) super(DepartmentForm, self).__init__(*args, **kwargs) self.fields['company'].queryset = Company.objects.raw(...)
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50376528
has comment: http://stackoverflow.com/comment/87769787
answer count: 3
has answer: http://stackoverflow.com/a/50377003
has body: I have a basic question regarding working with arrays: a= ([ c b a a b b c a a b b c a a b a c b]) b= ([ 0 1 0 1 0 0 0 0 2 0 1 0 2 0 0 1 0 1]) I) Is there a short way, to count the number of time 'c' in a corresponds to 0, 1, and 2 in b and 'b' in a corresponds to 0, 1, 2 and so on II) How do I create a new array c (subset of a) and d(subset of b) such that it only contains those elements if the corresponding element in a is 'c' ?
has comment: http://stackoverflow.com/comment/87769498
downvote count: 1
favorite count: 0
has title: Creating a subset of array from another array : Python
has comment: http://stackoverflow.com/comment/87769538
type: Question
upvote count: 0
score: -1
tagged with: arrays
has answer: http://stackoverflow.com/a/50377363
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87769550
has comment: http://stackoverflow.com/comment/87769399
has answer: http://stackoverflow.com/a/50377296
has comment: http://stackoverflow.com/comment/87769346

http://stackoverflow.com/comment/87518125
score: 0
comment on: http://stackoverflow.com/q/50250345
has text: `ConnectTimeoutError(, 'Connection to pypi.python.org timed out. (connect timeout=15)')` looks like you can't connect to `pypi` can you install direct from https://github.com/django/django/releases/tag/2.0.5 ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87499268
type: AnswerComment
has text: because of this line in my code `print('Credentials invalids')` that's because username or password is invalid
comment on: http://stackoverflow.com/a/50240823
type: Comment
score: 0

http://stackoverflow.com/q/50256571
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87531010
tagged with: python
has answer: http://stackoverflow.com/a/50256601
score: 2
has title: Column Names in Pandas (Python)
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: Python : Pandas : Data Frame : Column Names I have large number of columns and column names are also very large. I would like to see few columns and rows but view becoming restricted to size of column names. How can I temporarily see dataframe in Python without column names (just display data )

http://stackoverflow.com/q/50335016
tagged with: class
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50335296
score: 1
has comment: http://stackoverflow.com/comment/87686233
has title: Re-assigning Instance Variables to Local Method Variables
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50335246
answer count: 2
has body: I have seen the following many times, where the instance variables (ex. obj_foo and obj_bar) are re-assigned to be local method variables (ex. within call): class Example: def __init__(self, obj_foo, obj_bar): self.obj_foo = obj_foo self.obj_bar = obj_bar def call(self): obj_foo, obj_bar = self.obj_foo, self.obj_bar obj_foo.do_something() obj_bar.do_something_else() I am not sure if this is convention (easy to read) or if there is a more significant purpose? Is this bad practice? Does this effect performance?
has comment: http://stackoverflow.com/comment/87687334
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50335246
tagged with: namespaces
accepted answer: http://stackoverflow.com/a/50335296

http://stackoverflow.com/q/50308403
has comment: http://stackoverflow.com/comment/87632815
has comment: http://stackoverflow.com/comment/87632793
upvote count: 0
has title: Find the Parent Attributes of a div class in Python BeautifulSoup
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/50308606
has comment: http://stackoverflow.com/comment/87632832
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87632801
has body: soup = BeautifulSoup(code below, "html.parser") &lt;item class="info" data="findthisinfo" example="exa1"&gt; &lt;div class="exampleclass"&gt; EXAMPLE INFO &lt;/div&gt; &lt;item class="info" data="findthisinfo1" example="exa0"&gt; &lt;div class="exampleclass"&gt; EXAMPLE INFO 2 &lt;/div&gt; &lt;item class="info" data="findthisinfo2" example="exa2"&gt; &lt;div class="exampleclass"&gt; SOME TEXT &lt;/div&gt; for example in soup.find_all('item', attrs={'class': 'info'}): examp2 = example.find_all('div', attrs={'class': 'exampleclass'}) examp3 = soup('div', text=re.compile("EXAMPLE")) This gives me output of: [EXAMPLE] [EXAMPLE] [] I would now like to find the parent class for the two particular output, so for example I need the parent values of data="findthisinfo" and data="findthisinfo1" How would I go about in doing this?
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/87632859
tagged with: python
has comment: http://stackoverflow.com/comment/87632773

http://stackoverflow.com/comment/87504492
has text: It's a little overkill in this situation, but I'm not sure if I'd say it's way more work. It's literally just using "literal_eval" instead of "int" and adding an import. I mainly included it as an alternative to int.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50241321
type: Comment

http://stackoverflow.com/comment/87521832
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50244613
has text: Thank you very musch @DanMašek. playback FPS was 5 and now is 16. However it should be 24 at least but i think parallelization could increase the speed of this code. I'll be looking forward for your reply about parallelization
type: AnswerComment

http://stackoverflow.com/q/50249025
has answer: http://stackoverflow.com/a/50249204
downvote count: 0
tagged with: directory
upvote count: 1
has body: Given two directory e.g., dirA=getTrainingDir() dirB=getTestingDir() now I want to loop through the two directories if they are not None and not empty string what I am doing now is: data_directories=[] if dirA: data_directories.append(dirA) if dirB: data_directories.append(dirB) for data_directory in data_directories: ... Any more elegant syntax for this purpose?
has answer: http://stackoverflow.com/a/50249147
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87515519
tagged with: python
has title: Loop through not None and not empty directories
has comment: http://stackoverflow.com/comment/87515542
tagged with: list
answer count: 2
score: 1

http://stackoverflow.com/q/50264277
downvote count: 0
has answer: http://stackoverflow.com/a/50264373
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87546741
type: AnsweredQuestion
has body: Im getting an error when using pythons inbuild function "open" and don't know how to get it to work for png files. Examplecode: img =open('here.png').read() Error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 101: character maps to &lt;undefined&gt;
has answer: http://stackoverflow.com/a/50264316
has answer: http://stackoverflow.com/a/50264399
tagged with: python
accepted answer: http://stackoverflow.com/a/50264316
has comment: http://stackoverflow.com/comment/87546771
score: 2
possible better answer: http://stackoverflow.com/a/50264399
answer count: 3
has comment: http://stackoverflow.com/comment/87546634
upvote count: 2
has title: Using pythons open function for .png Image
has comment: http://stackoverflow.com/comment/87546637

http://stackoverflow.com/q/50248434
has title: Inserting a python time object to a MySQL table
has answer: http://stackoverflow.com/a/50249122
type: Question
has body: I have a MySQL database. I use python mysqldb module to access this database. I have a table which has a column with mysql data type time. Which python data type should I use to insert a time value into this column? What should I be using in the execute statement?
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 1
tagged with: mysql-python
tagged with: mysql

http://stackoverflow.com/comment/87567967
type: AnswerComment
has text: now problem on line 62 final = final() float object is not callable
type: Comment
comment on: http://stackoverflow.com/a/50275259
score: 0

http://stackoverflow.com/comment/87722935
type: QuestionComment
comment on: http://stackoverflow.com/q/50352493
has text: Your tests import `setup.py`, which uses `input`. Maybe your setup.py sile shouldn't be using `input`? Without you posting the contents of all your file,s it's not 100% clear to me what exactly you are doing and what you are intending/wanting to do.
score: 0
type: Comment

http://stackoverflow.com/comment/87665605
type: AnswerComment
score: 0
has text: Can you explain what is i[0] is doing. I am just a beginner and not good at list comprehensions
type: Comment
comment on: http://stackoverflow.com/a/50324810

http://stackoverflow.com/a/50374889
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50374348
has body: import re list_to_keep=[] pattern= re.compile(r'[0-9 ]+[e.\-+][0-9]*',re.IGNORECASE) with open(f, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter='\n') for row in reader: if(pattern.match(str(row))): list_to_keep.append(row) Can use regex to find your row and keep it in list.
accepted answer of: http://stackoverflow.com/q/50374348
type: AcceptedAnswer

http://stackoverflow.com/a/50295182
score: 0
answers question: http://stackoverflow.com/q/50295085
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50295085
upvote count: 1
downvote count: 1
has body: You need to remove the space before the - in " -regex". Try this: subprocess.run(["find" , dirPath, "-regex", '".*\.odt"', "-type", "f", "-maxdepth", "1" ])
type: Answer
has comment: http://stackoverflow.com/comment/87607117

http://stackoverflow.com/q/50233237
downvote count: 0
answer count: 1
upvote count: 1
has body: I have a dict with finance data that I want to convert to pd.DataFrame. The data looks like: {u'candles': [{u'complete': True, u'mid': {u'c': u'1.19228', u'h': u'1.19784', u'l': u'1.18972', u'o': u'1.19581'}, u'time': u'2018-05-06T21:00:00.000000000Z', u'volume': 119139}, {u'complete': False, u'mid': {u'c': u'1.18706', u'h': u'1.19388', u'l': u'1.18614', u'o': u'1.19239'}, u'time': u'2018-05-07T21:00:00.000000000Z', u'volume': 83259}], u'granularity': u'D', u'instrument': u'EUR_USD'} It's a bit tricky since I want to have a dataframe that has these fields: c h l o time volume 1.19228 1.19784 1.18972 1.19581 2018-05-06T21:00:00.000000000Z 119139 1.18706 1.19388 1.18614 1.19239 2018-05-07T21:00:00.000000000Z 83259 I have tried various combos like: pd.DataFrame(dict['candles']) pd.DataFrame([dict['candles']]) but it does not seem possible to convert to desired format without transforming the dict
favorite count: 0
duplicate of: http://stackoverflow.com/q/21104592
type: Question
has comment: http://stackoverflow.com/comment/87484821
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50233768
has comment: http://stackoverflow.com/comment/87484772
tagged with: pandas
linked to: http://stackoverflow.com/q/21104592
has answer: http://stackoverflow.com/a/50233768
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: Import JSON dict with list into Dataframe

http://stackoverflow.com/q/50259135
type: Question
has comment: http://stackoverflow.com/comment/87536221
upvote count: 9
tagged with: bytecode
tagged with: python
has answer: http://stackoverflow.com/a/50264759
score: 9
answer count: 2
type: UnansweredQuestion
tagged with: cpython
downvote count: 0
has answer: http://stackoverflow.com/a/50259382
has body: What's the purpose of keeping track of blocks in Python bytecode? The documentation here mentions: ... Per frame, there is a stack of blocks, denoting nested loops, try statements, and such. But they don't actually seem necessary to actually perform loops. For instance, playing around with the REPL I see: &gt;&gt;&gt; def foo(): ... while True: ... print('hi') ... &gt;&gt;&gt; for inst in list(dis.get_instructions(foo)): print(inst) ... Instruction(opname='SETUP_LOOP', opcode=120, arg=12, argval=14, argrepr='to 14', offset=0, starts_line=2, is_jump_target=False) Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=2, starts_line=3, is_jump_target=True) Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval='hi', argrepr="'hi'", offset=4, starts_line=None, is_jump_target=False) Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=6, starts_line=None, is_jump_target=False) Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=8, starts_line=None, is_jump_target=False) Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=2, argval=2, argrepr='', offset=10, starts_line=None, is_jump_target=False) Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=12, starts_line=None, is_jump_target=False) Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=14, starts_line=None, is_jump_target=True) Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False) The JUMP_ABSOLUTE instruction listed jumps to the LOAD_GLOBAL instruction listed. From just looking at the instructions, it seems like SETUP_LOOP and POP_BLOCK opcodes could be no-ops. From what I understand, in Python there are no block scoped variables, so that doesn't like it would be the reason either.
has title: Why does CPython have a "POP_BLOCK" opcode?
favorite count: 0

http://stackoverflow.com/comment/87491847
comment on: http://stackoverflow.com/a/50237158
score: 0
type: AnswerComment
has text: @SkillerDz I used return because it was mentioned in the question, but it's not necessary.
type: Comment

http://stackoverflow.com/comment/87728344
type: Comment
has text: @MisterMiyagi Would you like to say something on my above comment.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50348347

http://stackoverflow.com/comment/87697171
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50340495
has text: You can add some `print` functions before calling `sys.exit()`. Remember that when you call `exit` the 'control' goes back to the shell, so it has to be the last instruction you want to execute inside your script.
score: 1

http://stackoverflow.com/comment/109203772
type: Comment
score: 2
type: AnswerComment
has text: Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided.
comment on: http://stackoverflow.com/a/61737261

http://stackoverflow.com/comment/87609661
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50296090
has text: @AntonvBR Fair call. I'd normally use a list for something like this. Indexing is faster than dict lookup, and a list consumes less RAM than a dict. OTOH, a dict can be handy if you want to implement a sparse array, or even if you want a contiguous array with the first index being > 0. Also, if you want to create a bunch of points, and then drop the ones that fail some test it can be more efficient to do that with a dict.

http://stackoverflow.com/a/50349683
downvote count: 0
has body: If you have a df like this: df = {'date': ['12-31','01-01','07-02', '12-04','06-05'], 'col1': [5,10,20,30,20]} df = pd.DataFrame(data=df) col1 date 0 5 12-31 1 10 01-01 2 20 07-02 3 30 12-04 4 20 06-05 You can convert the column date to dayofyear format in this way(non leap year): df["date"]= pd.to_datetime(df.date, format="%m-%d").dt.dayofyear Output: col1 date 0 5 365 1 10 1 2 20 183 3 30 338 4 20 156
answers question: http://stackoverflow.com/q/50341598
has comment: http://stackoverflow.com/comment/87715259
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87715031

http://stackoverflow.com/q/50232685
has answer: http://stackoverflow.com/a/53583595
has comment: http://stackoverflow.com/comment/87490215
score: 4
has title: Keras ImageDataGenerator flow directory with 3D CNN data format error?
upvote count: 4
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/55009774
answer count: 3
linked to: http://stackoverflow.com/q/42699956
tagged with: keras
tagged with: tensorflow
has answer: http://stackoverflow.com/a/50238699
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has body: I am new in Keras, I have a dataset with multiple folders each indicates to a specific class. I used ImageDataGenerator to read the data from the subfolders. I am trying to use 16 consecutive frames with size 80x100 so the input_shape is (16, 80, 100, 1). When I do the training there is an error about the input of the network, I know that the input should 5d tensor for 3D CNN but I am not sure if I doing this correctly. I am using spyder to write and implement the code: from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, Conv3D, MaxPooling3D from keras.layers.advanced_activations import LeakyReLU from keras.optimizers import SGD, RMSprop from keras.utils import np_utils, generic_utils from keras.losses import categorical_crossentropy from keras.optimizers import Adam import os import matplotlib import matplotlib.pyplot as plt import numpy as np import cv2 from sklearn.cross_validation import train_test_split from sklearn import cross_validation from sklearn import preprocessing datagen = ImageDataGenerator() train_data=datagen.flow_from_directory('C:\\Users\\AA\\Data\\Training', target_size=(80, 100), color_mode='grayscale', classes=None, class_mode='categorical', batch_size=32, interpolation='nearest') test_data=datagen.flow_from_directory('C:\\Users\\AA\\Data\\Testing', target_size=(80, 100), color_mode='grayscale', classes=None, class_mode='categorical', batch_size=32, interpolation='nearest') ins = (16, 80, 100, 1) model = Sequential() model.add(Conv3D(32, kernel_size=(3, 3, 3), input_shape=ins, border_mode='same')) model.add(Activation('relu')) model.add(Conv3D(32, kernel_size=(3, 3, 3), border_mode='same')) model.add(Activation('softmax')) model.add(MaxPooling3D(pool_size=(3, 3, 3), border_mode='same')) model.add(Dropout(0.25)) model.add(Conv3D(64, kernel_size=(3, 3, 3), border_mode='same')) model.add(Activation('relu')) model.add(Conv3D(64, kernel_size=(3, 3…
tagged with: python

http://stackoverflow.com/a/52782257
type: Answer
score: 17
answers question: http://stackoverflow.com/q/50316275
has comment: http://stackoverflow.com/comment/112389398
has comment: http://stackoverflow.com/comment/112248895
downvote count: 0
upvote count: 17
has body: I can't duplicate your exact problem, but I can't get pipenv to automatically recognise the requirements either. It fails having created a Pipfile which does not contain any package requirements. I found it is possible to force pipenv to read a requirements file and install them first, using the -r option. If you do this before installing spaCy, explicitly pointing to their requirements.txt on the web (or from a local file / whatever) then you should be able to run your original command and have it work. pipenv install -r https://raw.githubusercontent.com/explosion/spaCy/master/requirements.txt pipenv install -e git+https://github.com/explosion/spaCy#egg=spacy Edit: I reported this to pipenv and spaCy. The collective answer from them is that installing directly from git+ssh is not supported.

http://stackoverflow.com/comment/87622795
has text: So if I built a pyinstall script that generates folders or txt files I would need to add the path to those files and folders to the spec file that is generated with pyinstaller?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50302455
type: Comment

http://stackoverflow.com/comment/117065405
score: 1
comment on: http://stackoverflow.com/a/65777342
type: Comment
has text: Thanks! For weird reason it worked. Any idea why this might be an issue?
type: AnswerComment

http://stackoverflow.com/a/50337280
answers question: http://stackoverflow.com/q/50337244
type: Answer
has comment: http://stackoverflow.com/comment/87691154
has comment: http://stackoverflow.com/comment/87690921
has comment: http://stackoverflow.com/comment/87691074
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Form is located inside an iframe, so to be able to handle input fields you need to switch to that iframe: WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("signin-iframe")) username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//input[@aria-label="Email" and @placeholder="Email *"]'))) username.send_keys("my_user_name") password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//input[@aria-label="Password" and @placeholder="Password *"]'))) password.send_keys("my_password") username.submit()
accepted answer of: http://stackoverflow.com/q/50337244
has comment: http://stackoverflow.com/comment/87691362
has comment: http://stackoverflow.com/comment/87691180
has comment: http://stackoverflow.com/comment/87690780

http://stackoverflow.com/q/50372057
tagged with: database
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
score: 0
has title: How to get and store 2 values in one column in database? Python Flask SQLAlchemy
tagged with: flask
tagged with: sqlalchemy
answer count: 1
has answer: http://stackoverflow.com/a/50373382
has comment: http://stackoverflow.com/comment/87762307
type: Question
has body: I am trying to store 2 values in one column and I do not know if it's even possible. It looks like that. I get data from HTML form like below. It works. Choose Language {% for language in languages %} {{ language }} " {% endfor %} Cancel But it only stored one value in database. class Book(Base): __tablename__ = 'Book' language = Column(String(30)) # how change that? This is how I get this one value. languages = ['Polish', 'English'] @app.route('/books/new/', methods=['GET', 'POST']) def newBook(): if request.method == 'POST': newBook = Book(language = request.form['language']) # how change that? session.add(newBook) session.commit() flash("New Book Added!") return redirect(url_for('showBooks')) else: return render_template('newBook.html', languages=languages) That code works but I get only English or Polish value. But I want that I can store sometimes both values. I know that is possible to use request.form.getlist but I didn't find a working example and how to store it in a database.

http://stackoverflow.com/comment/87770529
type: QuestionComment
has text: ... and rerun your script in a new session, because you have clobbered the function by assigning an integer to the name.
comment on: http://stackoverflow.com/q/50376948
score: 0
type: Comment

http://stackoverflow.com/comment/87767873
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50374255
has text: Sorry. Basically every LP solver returns duals. Scipy linprog seems to be the exception.

dataframe
tags question: http://stackoverflow.com/q/50347808
tags question: http://stackoverflow.com/q/50383910
tags question: http://stackoverflow.com/q/50346992
tags question: http://stackoverflow.com/q/50254331
tags question: http://stackoverflow.com/q/50233237
tags question: http://stackoverflow.com/q/50251408
tags question: http://stackoverflow.com/q/50317196
tags question: http://stackoverflow.com/q/50379490
tags question: http://stackoverflow.com/q/50379203
tags question: http://stackoverflow.com/q/50379541
tags question: http://stackoverflow.com/q/50318879
tags question: http://stackoverflow.com/q/50246976
tags question: http://stackoverflow.com/q/50337526
tags question: http://stackoverflow.com/q/50343100
tags question: http://stackoverflow.com/q/50230233
tags question: http://stackoverflow.com/q/50269588
tags question: http://stackoverflow.com/q/50353592
tags question: http://stackoverflow.com/q/50332270
tags question: http://stackoverflow.com/q/50356255
tags question: http://stackoverflow.com/q/50328246
tags question: http://stackoverflow.com/q/50328057
tags question: http://stackoverflow.com/q/50347027
tags question: http://stackoverflow.com/q/50319733
tags question: http://stackoverflow.com/q/50307707
tags question: http://stackoverflow.com/q/50297291
tags question: http://stackoverflow.com/q/50270181
tags question: http://stackoverflow.com/q/50321326
tags question: http://stackoverflow.com/q/50283639
tags question: http://stackoverflow.com/q/50322378
tags question: http://stackoverflow.com/q/50329427
tags question: http://stackoverflow.com/q/50248701
tags question: http://stackoverflow.com/q/50242598
tags question: http://stackoverflow.com/q/50320709
tags question: http://stackoverflow.com/q/50366424
tags question: http://stackoverflow.com/q/50316927
tags question: http://stackoverflow.com/q/50253527
tags question: http://stackoverflow.com/q/50302228
tags question: http://stackoverflow.com/q/50375985
tags question: http://stackoverflow.com/q/50336735
tags question: http://stackoverflow.com/q/50321673
tags question: http://stackoverflow.com/q/50232280
tags question: http://stackoverflow.com/q/50335429
tags question: http://stackoverflow.com/q/50376298
tags question: http://stackoverflow.com/q/50293496
tags question: http://stackoverflow.com/q/50364266
tags question: http://stackoverflow.com/q/50300813
tags question: http://stackoverflow.com/q/50291125
tags question: http://stackoverflow.com/q/50351914
tags question: http://stackoverflow.com/q/50363115
tags question: http://stackoverflow.com/q/50343650
tags question: http://stackoverflow.com/q/50335626
tags question: http://stackoverflow.com/q/50261070
tags question: http://stackoverflow.com/q/50297174
tags question: http://stackoverflow.com/q/50280612
tags question: http://stackoverflow.com/q/50310454
tags question: http://stackoverflow.com/q/50296997
tags question: http://stackoverflow.com/q/50375640
tags question: http://stackoverflow.com/q/50297439
tags question: http://stackoverflow.com/q/50256748
tags question: http://stackoverflow.com/q/50350539
tags question: http://stackoverflow.com/q/50371245
tags question: http://stackoverflow.com/q/50363545
tags question: http://stackoverflow.com/q/50335857
tags question: http://stackoverflow.com/q/50369334
tags question: http://stackoverflow.com/q/50367656
tags question: http://stackoverflow.com/q/50375913
tags question: http://stackoverflow.com/q/50259791
tags question: http://stackoverflow.com/q/50318574
tags question: http://stackoverflow.com/q/50283422
tags question: http://stackoverflow.com/q/50241548
tags question: http://stackoverflow.com/q/50312018
tags question: http://stackoverflow.com/q/50307793
tags question: http://stackoverflow.com/q/50292274
tags question: http://stackoverflow.com/q/50229942
tags question: http://stackoverflow.com/q/50334294
tags question: http://stackoverflow.com/q/50242968
tags question: http://stackoverflow.com/q/50243600
tags question: http://stackoverflow.com/q/50375422
tags question: http://stackoverflow.com/q/50376247
tags question: http://stackoverflow.com/q/50382104

http://stackoverflow.com/comment/87702808
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50343406
has text: If you're on Python 3.5+, one liner like so glob.glob(path, recursive=True) would do the trick. For more complete answer and older Python versions, see here: https://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
score: 1

http://stackoverflow.com/q/50311704
tagged with: cartopy
has answer: http://stackoverflow.com/a/50394345
has title: Cartopy figsize does not change the actual size of the map
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87702211
score: 1
has body: How to change the figure width and height when using cartoopy. figsize change only the white space around the figure, yet not the figure itself. Any ideas. import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt def main(): fig = plt.figure(figsize=(10,10)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent([-20, 60, -40, 45], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS, linestyle=':') ax.add_feature(cfeature.LAKES, alpha=0.5) ax.add_feature(cfeature.RIVERS) plt.show() if __name__ == '__main__': main() this code is found here
upvote count: 5
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/87692542
has comment: http://stackoverflow.com/comment/87666559
favorite count: 0
accepted answer: http://stackoverflow.com/a/50394345
type: Question
tagged with: python-3.x
downvote count: 4

http://stackoverflow.com/comment/87497176
has text: @P.Rodoreda please add your view, not the one of `home`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50239611

http://stackoverflow.com/comment/87541518
type: Comment
type: QuestionComment
score: 0
has text: You already have a dictionary which is inside an array. I don't really understand what's you want...
comment on: http://stackoverflow.com/q/50261659

http://stackoverflow.com/q/50282224
score: 1
type: Question
tagged with: twilio
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Flask - Gevent - Pushbullet - Twilio - This operation would block forever
tagged with: flask
tagged with: pushbullet
favorite count: 0
has body: so I have the following app that I'm working on https://github.com/SimplySynced/simplyfishy/tree/master and i'm running into this error when I trigger my float switch and try to send a message via twilio and pushbullet. File "/home/pi/simplyfishy/simplyfishyenv/local/lib/python3.5/site- packages/gevent/hub.py", line 630, in switch return RawGreenlet.switch(self) gevent.hub.LoopExit: ('This operation would block forever', &lt;Hub at 0x7451b210 epoll pending=0 ref=0 fileno=17&gt;) Full Traceback https://pastebin.com/E0FJm8ZW. I've tried using gevent.spawn when I call the functions as well and this still provided the same issue. I have made sure that my monkey patch line is at the top of the files. Now this error will only occur on the first trigger, if I continue to trigger the float switch both message go through with no issues. No errors at all going forward.

http://stackoverflow.com/comment/87668178
type: AnswerComment
comment on: http://stackoverflow.com/a/50324950
type: Comment
score: 0
has text: Thanks. lxml was included with my Anaconda Python install. So i'm good. Anaconda Python 3.6.5. But I create conda environments so...

http://stackoverflow.com/comment/87727314
comment on: http://stackoverflow.com/q/50355365
has text: It looks like you took your `saver` code directly from the tensorflow documentation. They also demonstrate how to use [`tf.train.Saver.restore`](https://www.tensorflow.org/api_docs/python/tf/train/Saver#restore) to restore a saved session.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87603447
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50285824
has text: I think you shouldn't use Relu at the end of the last layer.

http://stackoverflow.com/q/50294263
downvote count: 0
possible better answer: http://stackoverflow.com/a/50294517
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50294517
has title: Python : multithread doesn't improve run time
has answer: http://stackoverflow.com/a/50294504
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/50294480
linked to: http://stackoverflow.com/q/17241663
has body: I'm trying to write simple multi-threaded python script: from multiprocessing.dummy import Pool as ThreadPool def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread): images = glob.glob(img_fldr_src+'/*.'+img_file_extension) pool = ThreadPool(max_num_of_thread) pool.starmap(resize_img,zip(images,itertools.repeat(img_fldr_dst))) # close the pool and wait for the work to finish pool.close() pool.join() def resize_img(img_path_src,img_fldr_dest): #print("about to resize image=",img_path_src) image = io.imread(img_path_src) image = transform.resize(image, [300,300]) io.imsave(os.path.join(img_fldr_dest,os.path.basename(img_path_src)),image) label = img_path_src[:-4] + '.xml' if copyLabels is True and os.path.exists(label) is True : copyfile(label,os.path.join(img_fldr_dest,os.path.basename(label))) setting the argument max_num_of_thread to any number in [1...10] doesn't improve my run time at all (for 60 images it stays around 30 sec) , the max_num_of_thread=10 my PC got stuck my question is : what is the bottle neck in my code , why can't I see any improvement? some data about my PC : python -V Python 3.6.4 :: Anaconda, Inc. cat /proc/cpuinfo | grep 'processor' | wc -l 4 cat /proc/meminfo MemTotal: 8075960 kB MemFree: 3943796 kB MemAvailable: 4560308 kB cat /etc/*release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=17.10
tagged with: python
has answer: http://stackoverflow.com/a/50294480
score: 4
tagged with: image
has comment: http://stackoverflow.com/comment/87605050
upvote count: 4
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/87939786
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50371857
has text: This means that you are probably making too many requests/connections. What does the elasticsearch log say?
type: Comment

http://stackoverflow.com/q/50328380
tagged with: python
has comment: http://stackoverflow.com/comment/87708284
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87739396
upvote count: 1
downvote count: 1
has body: I have an array that needs to be partially incremented with the values of another (smaller) array. However, even if the smaller array does start inside the bounds of bigger array, it can overflow in some cases like shown below. In this case I still want the values to be incremented/modified with a manner that clips the overflowing indices and uses what remains inside the bounds. Here is how I do it at the moment h = big_image.shape[0] w = big_image.shape[1] small_image = make_small_image(c) # c is the edge length if (x+c) &gt; w: small_image = small_image[:(w - x), :] if (y+c) &gt; h: small_image = small_image[:, :(h - y)] big_image[y:y + c, x: x + c] += small_image.T I wonder if there is a easier and faster way to do it (an API or a better technique etc.)
answer count: 1
has answer: http://stackoverflow.com/a/50329472
favorite count: 0
type: Question
tagged with: numpy
has title: Incrementing the value of a ROI that (possibly) partially is out of bounds in Python
has comment: http://stackoverflow.com/comment/87743790
has comment: http://stackoverflow.com/comment/87699946
accepted answer: http://stackoverflow.com/a/50329472

http://stackoverflow.com/comment/87691130
score: 0
type: Comment
has text: Your data is in wide format. Consider reshaping to long format and have indicators *female, male, etc.* in their own columns apart from numeric value then plot by categories.
type: QuestionComment
comment on: http://stackoverflow.com/q/50337237

http://stackoverflow.com/a/50379052
answers question: http://stackoverflow.com/q/50378928
score: 4
has comment: http://stackoverflow.com/comment/87774670
upvote count: 4
has comment: http://stackoverflow.com/comment/87774863
has comment: http://stackoverflow.com/comment/87774750
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87774718
has body: Not much changes, just flatten your values in advance. itertools.chain from itertools import chain xs, ys = zip(*chain.from_iterable(test.values())) Of course, this returns tuples. If you want lists instead, I recommend adding a map call— xs, ys = map(list, zip(*chain.from_iterable(test.values()))) print(xs) [81, 78, 80, 65, 88, 81] print(ys) [90, 90, 80, 78, 81, 88] Comprehension-based This is the alternative, squash nested loops into a single line (i.e., a nested list comprehension)— xs, ys = map(list, zip(*[j for i in test.values() for j in i])) print(xs) [81, 78, 80, 65, 88, 81] print(ys) [90, 90, 80, 78, 81, 88] However, I recommend itertools.chain because it has been shown to outperform nested list comprehensions, comprehensively (...hah).
has comment: http://stackoverflow.com/comment/87774941
has comment: http://stackoverflow.com/comment/87774930
accepted answer of: http://stackoverflow.com/q/50378928
has comment: http://stackoverflow.com/comment/87774657
type: Answer

http://stackoverflow.com/comment/87756307
type: Comment
comment on: http://stackoverflow.com/a/50351074
type: AnswerComment
has text: I attempted to freeze your OpenDFT project and I am getting the exact same error, so it is probably an environment issue. I had to go through a few extra steps as well to get it to this point that I had to do for mine as well, showing again that my environment isn't correct.
score: 0

http://stackoverflow.com/comment/87748540
type: Comment
type: QuestionComment
has text: @PM2Ring i need to check if a in range of x and y or not.
comment on: http://stackoverflow.com/q/50366029
score: 0

http://stackoverflow.com/a/50306758
score: 4
type: AcceptedAnswer
downvote count: 0
has body: No, GAE does not record write frequency of entities. It is easy enough to implement yourself by adding a property to record the number of times an entity has been put and increment it on each write.
accepted answer of: http://stackoverflow.com/q/50303675
type: Answer
answers question: http://stackoverflow.com/q/50303675
upvote count: 4

http://stackoverflow.com/a/50239807
has body: You can use numpy stack functions to speed up: aa = [a0, a1, a2] np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50239640
type: Answer
accepted answer of: http://stackoverflow.com/q/50239640
has comment: http://stackoverflow.com/comment/87497384
score: 2

http://stackoverflow.com/comment/87528362
type: AnswerComment
comment on: http://stackoverflow.com/a/50254444
type: Comment
has text: I should have said `object` (or even more specifically, `function`), rather than object.
score: 0

http://stackoverflow.com/comment/87659960
type: AnswerComment
score: 1
has text: @DanielMöller `axis` was [introduced as an argument on November 22, 2017](https://github.com/tensorflow/tensorflow/commit/b1d8c59e9b014b527fb2fbef9ce9afc14dbc4938#diff-7e066e8d1b9eff5c683b33517b35ae13) in TensorFlow's `softmax()` so yes, if the TensorFlow version is 1.4.0 or less, that would cause this error.
comment on: http://stackoverflow.com/a/50321847
type: Comment

http://stackoverflow.com/a/50377964
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50376895
has body: Using pdfminer.six successfully read from left to right with spaces in between.

http://stackoverflow.com/a/50256666
has comment: http://stackoverflow.com/comment/87531987
has comment: http://stackoverflow.com/comment/87532116
has comment: http://stackoverflow.com/comment/87531773
has comment: http://stackoverflow.com/comment/87532332
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87532293
upvote count: 1
has comment: http://stackoverflow.com/comment/87532073
has comment: http://stackoverflow.com/comment/87531570
score: 1
answers question: http://stackoverflow.com/q/50255240
has comment: http://stackoverflow.com/comment/87531727
has body: Here's a solution for the first part of your loop: You should try this on a disposable local copy of your database and check that everything works well before running these in production: from django.db.models import Count # get a list of all categories which have no products empty_categories = Category.objects.annotate(product_count=Count('products')).filter(product_count=0).values_list('id', flat=True) # delete association of empty categories in all brands Brand.categories.through.objects.filter(category_id__in=list(empty_categories)).delete() For the second part, perhaps you can do something like this, though I'm not convinced if it's any faster (or even correct as it is): for brand in Brand.objects.all(): # get a list of categories of all products in the brand brand_product_categories = brand.products.all().value_list('category__id', flat=True).distinct() # get the brand's categories brand_categories = Category.objects.filter(category__brand=brand).value_list('id', flat=True) # get elements from a not in b categories_to_add = set(brand_product_categories) - set(brand_categories) for category_id in categories_to_add: brand.categories.add(category_id)
has comment: http://stackoverflow.com/comment/87531935

http://stackoverflow.com/q/50274211
score: 2
has comment: http://stackoverflow.com/comment/87565221
has comment: http://stackoverflow.com/comment/87619674
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87565420
type: UnansweredQuestion
downvote count: 0
favorite count: 0
has title: better method for python3 if elif else db update script
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87565579
has body: my code works as expected below, but I will be using this as a 'template' moving forward and before I make a giant file I wanted to make it 'cleaner' as I think I am doing it wrong even though it works. at the top of my script can I specify the database connections and then just reference them in functions below? def db_update(x): if x &lt; 30: connection = MySQLdb.connect (host= "localhost", REDACTED) cursor = connection.cursor() sqlcommand = """REDACTED""" cursor.execute(sqlcommand) cursor.fetchone() connection.commit() cursor.close() connection.close() elif x &gt; 270 : connection = MySQLdb.connect (host= "localhost", REDACTED) cursor = connection.cursor() sqlcommand = """REDACTED""" cursor.execute(sqlcommand) cursor.fetchone() connection.commit() cursor.close() connection.close() else: connection = MySQLdb.connect (host= "localhost", REDACTED) cursor = connection.cursor() sqlcommand = """REDACTED""" cursor.execute(sqlcommand) cursor.fetchone() connection.commit() cursor.close() connection.close() I am wondering if I could make it look like this. def db_update(x): connection = MySQLdb.connect (host= "localhost", REDACTED) cursor = connection.cursor() if x &lt; 30: sqlcommand = """REDACTED""" elif x &gt; 270 : sqlcommand = """REDACTED""" else: sqlcommand = """REDACTED""" cursor.execute(sqlcommand) cursor.fetchone() connection.commit() cursor.close() connection.close() or even better would be reference it from a global or an import script like so def run_sql(): connection = MySQLdb.connect (host= "localhost", REDACTED) cursor = connection.cursor() cursor.execute(sqlcommand) cursor.fetchone() connection.commit() cursor.close() connection.close() def db_update(run_sql, x): if x &lt; 30: sqlcommand = """REDACTED""" elif x &gt; 270 : sqlcommand = """REDACTED""" else: sqlcommand = """REDACTED""" runsql() I am very new to this so please be gentle and if there are good learning links please feel free to share
tagged with: python
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/q/50368906
has answer: http://stackoverflow.com/a/50383255
accepted answer: http://stackoverflow.com/a/50383255
tagged with: queue
favorite count: 0
type: Question
upvote count: 2
score: 2
has body: I am trying to run a code where I am working with Queue and threads. Below is the code snippet: import threading from Queue import Queue def function(): results = [] for i in range(68): return_list = function2(i) results.append(return_list) if return_list: print("True returned") else: print("Returned false") return results def function2(i): print("In function 2 with: " + str(i)) results = [] working_queue = Queue() for _ in range(25): worker = threading.Thread(target=function3, args=(working_queue, results)) worker.setDaemon(True) worker.start() for p in range(150): working_queue.put(p) working_queue.join() return results def function3(working_queue, results): while True: try: current_item = working_queue.get() print("Processing:" + str(current_item)) results.append("True") except Exception as e: print("An exception in function 3: " + str(e)) finally: working_queue.task_done() if __name__ == "__main__": results = function() print(str(results)) The code raises the following exception: Traceback (most recent call last): File "C:/pythonErrors/stackoverflow.py", line 45, in &lt;module&gt; function() File "C:/pythonErrors/stackoverflow.py", line 8, in function return_list = function2(i) File "C:/pythonErrors/stackoverflow.py", line 24, in function2 worker.start() File "C:\Python27\lib\threading.py", line 736, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread How can we delete the previously created and completed threads. So that with each for loop execution in function2() new threads are not created. The requirement is to create only 25 threads for the whole process (currently total 68x25 threads are being created)
downvote count: 0
has title: Python Exception in threading: can't start new thread
tagged with: multithreading
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/50355715
answers question: http://stackoverflow.com/q/50296719
has body: What version of MySQL are you using? I was not able to use PyMySQL with MySQL 8, so I had to downgrade to 5.4. EDIT: Here's my thread on troubleshooting and ultimately resolving: PyMySQL Access Denied "using password (no") but using password
type: Answer
score: 0

http://stackoverflow.com/a/50329735
answers question: http://stackoverflow.com/q/50321452
type: Answer
has comment: http://stackoverflow.com/comment/87691449
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50321452
upvote count: 1
has body: Are you using your own model or some existing code? If you're using your own implementation the low GPU utilization might be due to your specific implementation. Often, the data pipeline is to blame for this. Check out the performance guide for TF (https://www.tensorflow.org/performance/performance_guide) as well as how to efficiently import data using tf.data.Dataset (https://www.tensorflow.org/programmers_guide/datasets). If it is not the data pipeline then some of your code is probably executed on the CPU, which results in a lot of copying from GPU to CPU and vice versa. Maybe you perform some of the operations with Numpy or something similar, which only runs on CPU?! Also, other common guidelines apply, e.g. try not to use placeholders and feed_dict, etc... Overall it would be more helpful if we can see your code or if we knew which model you are using if you are using existing code. Without seeing your code it's hard to know what the problem is. Try downloading the MNIST-CNN example from Tensorflow directly and run it on your computer. It should have a GPU-Util of at least 80%. If this is not the case then mos

http://stackoverflow.com/a/50374404
downvote count: 0
has body: Since the Laplacian is an integer matrix, let us use integers: L = Matrix([[ 1, 0, 0, 0, -1, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, -1, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, -1, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, -1, 0], [-1, 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, -1, 0, 0, 0, 3, 0, 0, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 1, 0, -1], [ 0, 0, -1, -1, 0, -1, 0, 0, 3, 0], [ 0, 0, 0, 0, 0, -1, 0, -1, 0, 2]]) Computing the eigenvalues: &gt;&gt;&gt; L.eigenvals() {0: 3, 1: 1, 2: 1} This is very strange, as the matrix is 10-by-10, not 5-by-5. I tried to compute the Jordan normal form, but could not do it, as function jordan_form produced the error message IndexError: list index out of range. Computing the characteristic polynomial: &gt;&gt;&gt; s = Symbol('s') &gt;&gt;&gt; p = (s * eye(10) - L).det() &gt;&gt;&gt; p s**10 - 14*s**9 + 77*s**8 - 214*s**7 + 321*s**6 - 256*s**5 + 99*s**4 - 14*s**3 Note that the monomial of lowest degree is cubic. This allows us to conclude that the multiplicity of eigenvalue 0 is 3 and, thus, the graph is not connected. Let us try to find the roots of the characteristic polynomial: &gt;&gt;&gt; solve(p,s) [0, 0, 0, 1, 2, CRootOf(s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7, 0), CRootOf(s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7, 1), CRootOf(s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7, 2), CRootOf(s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7, 3), CRootOf(s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7, 4)] Note that only 5 roots were actually found (eigenvals produced only 5 eigenvalues, too). The 5 missing roots are the roots of the quintic s**5 - 11*s**4 + 42*s**3 - 66*s**2 + 39*s - 7. It has been known since the 19th century that not all polynomials of degree 5 (or higher) have roots that can be expressed using arithmetic operations and radicals. Hence, we may be asking SymPy to do the impossible. Better use NumPy to compute approximate values of the 10 eigenvalues.
answers question: http://stackoverflow.com/q/50356594
score: 3
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50356594
type: AcceptedAnswer

http://stackoverflow.com/q/50307050
favorite count: 0
has title: Speeding up row-by-row loop with if-condition in Python
type: Question
score: 3
tagged with: performance
tagged with: python
type: AnsweredQuestion
upvote count: 3
has body: I have a dataset of 6 milion rows, the columns are: symbol, timeStamp, open price and close price. I run the following loop, which takes very long, though being very simple (if open price is nan, take close price from the previous row): for i in range(0,len(price2)): print(i) if np.isnan(price3.iloc[i,2]): price3.iloc[i,2]=price3.iloc[i-1,3] How can I speed this loop up? As far as I know, I can change to apply(), but how can I include the if-condition to it?
has answer: http://stackoverflow.com/a/50307309
downvote count: 0
accepted answer: http://stackoverflow.com/a/50307309
tagged with: pandas
answer count: 1
tagged with: loops

mod-wsgi
tags question: http://stackoverflow.com/q/50366257
tags question: http://stackoverflow.com/q/50379323
type: Tag
tag name: mod-wsgi

http://stackoverflow.com/comment/87525202
type: Comment
has text: This can also be problematic but seems unrelated. In generell if you just do one weight update it should not destroy your accuracy even if the data is wrongly scaled. For the the scaler problem: Can you pickle the scaler object and call it without fit in the scond run?
comment on: http://stackoverflow.com/a/50253540
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87929956
type: Comment
comment on: http://stackoverflow.com/q/50378906
type: QuestionComment
score: 0
has text: I am guessing this question might not be answered...

http://stackoverflow.com/comment/87598659
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50291028
score: 0
has text: `variable_list = ['ABC','DEF']` `df = pd.read_csv(csvfile,delimiter='#',engine='python',header=None)` `df.columns = ['ID1','ID2','var_name','var_value']` `f=df.set_index(['ID1','ID2','var_name'])['var_value'].unstack(fill_value='').fillna('')[variable_list].reset_index()` `L1 = [f.columns.tolist()] + f.values.tolist()`

http://stackoverflow.com/q/50380066
tagged with: mocking
type: UnansweredQuestion
has body: The test for the following method checks that the stdout in prompt is correct. When 'input()' gets called it waits for the user to press enter and interrupt. The test is passing by auto keypress-ing 'enter'. This is hacky and there must be a better way of testing this method. METHOD: class GameDisplay: @staticmethod def prompt(text): input_value = input(text) return input_value TEST: from pynput.keyboard import Key, Controller class TestGameDisplay(unittest.TestCase): @patch('sys.stdout', new_callable=StringIO) def test_prompt_output(self, mock_stdout): keyboard = Controller() keyboard.press(Key.enter) self.gameDisplay.prompt('Choose 0: ') keyboard.release(Key.enter) self.assertEqual( mock_stdout.getvalue(), 'Choose 0: ') if __name__ == '__main__': unittest.main() OUTPUT: Breaks line as a result of pressing enter. ................................... ............................................ ---------------------------------------------------------------------- Ran 79 tests in 0.113s OK TEST FIX ATTEMPT: @patch('sys.stdout', new_callable=StringIO) @patch('builtins.input', return_value='0') def test_prompt_output(self, mock_stdout, input): self.gameDisplay.prompt('Choose 0: ') self.assertEqual( mock_stdout.getvalue(), 'Choose 0: ') OUTPUT: FAIL: test_prompt_output (tests.test_game_display.TestGameDisplay) self.assertEqual( mock_stdout.getvalue(), 'Choose 0: ') AssertionError: &lt;MagicMock name='input.getvalue()' id='4675607744'&gt; != 'Choose 0: ' ---------------------------------------------------------------------- Ran 79 tests in 0.015s FAILED (failures=1)
tagged with: python
has comment: http://stackoverflow.com/comment/87776588
has answer: http://stackoverflow.com/a/50380962
has comment: http://stackoverflow.com/comment/87776469
score: 3
has comment: http://stackoverflow.com/comment/87786323
upvote count: 3
has title: Testing python stdout on input prompt
answer count: 1
downvote count: 0
tagged with: stdout
has comment: http://stackoverflow.com/comment/87776646
tagged with: pynput
has comment: http://stackoverflow.com/comment/87815393
favorite count: 0
tagged with: unit-testing
type: Question

http://stackoverflow.com/comment/87570311
has text: Check https://docs.python.org/3/library/functions.html for details about `str`. As for the question itself, I'd recommend a *Python* beginner's tutorial.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50276843

http://stackoverflow.com/a/50249073
upvote count: 1
answers question: http://stackoverflow.com/q/50248876
downvote count: 1
has comment: http://stackoverflow.com/comment/87516183
has comment: http://stackoverflow.com/comment/87517947
has body: To locate the element with text as Invoice Detail Report and invoke click() on it you can use either of the following strategies : Using XPATH with text : WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(.,'Invoice Detail Report')]"))).click() Using XPATH with attributes : WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='c_library_element_name rc_actionable ia-inline-block' and contains(@href,'reporteditor.phtml')]"))).click() XPATH using all the attributes : WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='c_library_element_name rc_actionable ia-inline-block' and contains(@href,'reporteditor.phtml') and contains(.,'Invoice Detail Report')]"))).click()
has comment: http://stackoverflow.com/comment/87520547
type: Answer
has comment: http://stackoverflow.com/comment/87517941
has comment: http://stackoverflow.com/comment/87516059
has comment: http://stackoverflow.com/comment/87516442
has comment: http://stackoverflow.com/comment/87516623
score: 0
has comment: http://stackoverflow.com/comment/87516467
has comment: http://stackoverflow.com/comment/87520632
has comment: http://stackoverflow.com/comment/87516535

http://stackoverflow.com/comment/87828351
type: Comment
type: QuestionComment
has text: Sorry for not posting earlier. Yes I managed to achieve what I wanted but not exactly with your answer. The main idea was to generate batches of tensor image data in form of ==> x, [y1, y2, y3, y4, y5]. I will post my working answer below. Thanks
comment on: http://stackoverflow.com/q/50333532
score: 0

http://stackoverflow.com/q/50364413
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/50365826
has title: Run command only once after Django app startup
score: 1
has body: I have a django-based function that needs to be run only once in Django, when the app boots up. The tricky part is that: The code in question heavily uses django ORM, so apps have to be ready at that point, The code should run only once - e.g. not once per every worker, but exactly once per "website" (regardless of whether it's deployed via gunicorn with a dozen of workers, or run locally via the built-in development web-server), The code should only run once the app boots, but NOT by running other management commands. The code can take a while to complete, and I don't want it to trigger each time I run makemigrations or shell. I could, theoretically, just introduce a locking mechanism and let it run somewhere in AppConfig.ready() method, but that would still run in all management commands as well. Since the app is packaged in Docker, I've been also thinking about simply wrapping the code in a separate management command and running it in the entry point, just before the app is being started. That seems to do the trick, but it will be done automatically only in that particular container - if somebody runs a local development server to work on the app on his own, he might not be aware that an additional command should be run. I've searched through the documentation and it doesn't look like Django has a way to do this natively on its own. Perhaps there's a better approach that I can't think of?
answer count: 1
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/87668199
type: AnswerComment
comment on: http://stackoverflow.com/a/50325697
score: 0
type: Comment
has text: This isn't *strictly* true – it won't work for generators, for instance. For that you would need to get an iterator over y via `it = y.__iter__()`, then do `try: x = it.next()` and catch `StopIteration`, per the [iterator protocol](https://stackoverflow.com/a/16301581/5951320).

http://stackoverflow.com/a/50365202
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/50346580
has comment: http://stackoverflow.com/comment/87753279
score: 0
has comment: http://stackoverflow.com/comment/87846282
has body: Just to get this working and as you have already embraced a global variable, just make logger a global variable, rather than self.logger. Note self.logger.AppendText(IncrementMe) will have to become logger.AppendText(str(IncrementMe)) as appending an int will give you grief. Ideally, you should rewite this to have the thread as a Class, then you can use a wx.PostEvent to trigger actions in your MyWin by binding to the Event. See: https://wxpython.org/Phoenix/docs/html/events_overview.html https://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/ Edit: Here is a pubsub script which, hopefully, will point you in the right direction. from threading import Thread import wx from wx.lib.pubsub import pub import time class WorkThread(Thread): def __init__(self): """Init Worker Thread Class.""" Thread.__init__(self) self.stop_work_thread = 0 self.start() # start the thread self.val = 0 def run(self): while True: if self.stop_work_thread == 1: break time.sleep(1) self.val += 1 wx.CallAfter(pub.sendMessage, "update", step=self.val) wx.CallAfter(pub.sendMessage, "finish") return def stop(self): self.stop_work_thread = 1 class Progress(wx.Frame): def __init__(self, parent, title): super(Progress, self).__init__(parent, title = title,size = (500,300)) self.panel = wx.Panel(self) self.start_btn = wx.Button(self.panel, label="Start", pos=(20,50)) self.start_btn.Bind(wx.EVT_BUTTON, self.onStart) self.stop_btn =wx.ToggleButton(self.panel, label="Stop", pos=(20, 90)) self.stop_btn.Bind(wx.EVT_TOGGLEBUTTON, self.onCancel) self.logger = wx.TextCtrl(self.panel, pos=(150,0), size=(200,200), style=wx.TE_MULTILINE | wx.TE_READONLY) self.stop_btn.Disable() self.Bind(wx.EVT_CLOSE, self.onExit) def onUpdate(self, step): step = str(step)+'\n' self.logger.AppendText(step) def onStart(self, event): self.logger.Clear() pub.subscribe(self.onUpdate, "update") pub.subscribe(self.onFinish, "finish") btn = event.GetEventObject() self.start_btn.Disable() self.work = WorkThread() Progress(self…
accepted answer of: http://stackoverflow.com/q/50346580

encoding
tags question: http://stackoverflow.com/q/50247602
tags question: http://stackoverflow.com/q/50358785
tags question: http://stackoverflow.com/q/50231447
tag name: encoding
tags question: http://stackoverflow.com/q/50310493
type: Tag
tags question: http://stackoverflow.com/q/50272801
tags question: http://stackoverflow.com/q/50258127
tags question: http://stackoverflow.com/q/50369637

http://stackoverflow.com/comment/87520167
score: 0
type: Comment
type: QuestionComment
has text: Okay, well, it's a function. You can't subscript that.
comment on: http://stackoverflow.com/q/50251410

http://stackoverflow.com/comment/87810200
type: Comment
type: AnswerComment
has text: Thank you so much for help. I am nearly reaching the result. But is there any way to sort the key by value in dictionary without importing modules? And in the first update: for word, count in v.items(): it has the AttributeError: 'str' object has no attribute 'items' then how can I display every word and its count in the same sentence of target word? I have update my question and code for you to have a look
comment on: http://stackoverflow.com/a/50342605
score: 0

http://stackoverflow.com/q/50288127
tagged with: archive
has body: My zip file contains a lot of smaller zip files. I want to iterate through all those files, reading and printing each of their comments. I've found out that zipfile file.zip or unzip -z file.zipcan do this to a file in separate, but I'm looking for a way to go through all of them. Couldn't find anything perfect yet, but this post. However, the code is too advanced for me, and I need something very basic, to begin with :) Any ideas or information would be great, thanks!
possible better answer: http://stackoverflow.com/a/50488185
type: Question
tagged with: http://stackoverflow.com/tag/zip
has answer: http://stackoverflow.com/a/74509749
accepted answer: http://stackoverflow.com/a/50288556
tagged with: python
has answer: http://stackoverflow.com/a/50288556
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50488185
score: 0
answer count: 3
has title: Reading multiple zip archive comments with python
linked to: http://stackoverflow.com/q/38273849

min-heap
tags question: http://stackoverflow.com/q/50234921
tag name: min-heap
type: Tag

http://stackoverflow.com/q/50328202
favorite count: 0
tagged with: python-2.7
tagged with: python
score: 1
has body: How can I modify QAction icon size in PyQt4? I tried doing this: Custom class: class MyStyle(QCommonStyle): def pixelMetric(self, QStyle_PixelMetric, QStyleOption_option=None, QWidget_widget=None): if QStyle_PixelMetric == QStyle.PM_SmallIconSize: return 30 return QCommonStyle.pixelMetric(self, QStyle_PixelMetric, QStyleOption_option, QWidget_widget) rest of the code: self.popMenu = QMenu(parent) self.popMenu.setStyle(MyStyle())
has comment: http://stackoverflow.com/comment/87688863
has title: QAction icon size
type: Question
has comment: http://stackoverflow.com/comment/87688948
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87690546
type: UnansweredQuestion
tagged with: pyqt4
downvote count: 1

http://stackoverflow.com/a/50356263
has body: You were correct about the issue with your code, it is found in the line: a = [x[0],x[-5:]] This creates nested items that look like this: ['F37', ['1', '0', '0', '0', '1']] Here are two ways to fix this: Option 1 - Use the splat* operator: a = [x[0],*x[-5:]] Option 2 - Concatenate two slices of your list: a = x[:1] + x[-5:] Both of these will remove the nesting of your lists, and instead give you lines looking like: ['F37', '1', '0', '0', '0', '1'] Which you can then write to your output file.
type: Answer
answers question: http://stackoverflow.com/q/50356124
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50356124
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/134233796
score: 0
has text: Does this answer your question? [Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library?](https://stackoverflow.com/questions/76105218/why-does-tkinter-or-turtle-seem-to-be-missing-or-broken-shouldnt-it-be-part)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50327906

http://stackoverflow.com/a/50318697
downvote count: 0
has comment: http://stackoverflow.com/comment/87654333
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50318132
has body: So what you want to do, like what skrx said, is a while loop to continuously keep the code inside the while loop and the pygame window running, and as well as a for event loop, in order to be able to shut down the window. Here's how you can do it: import pygame pygame.init() pygame.display.set_mode((640, 480)) # opens the display while True: # the while loop that will keep your display up and running! for event in pygame.event.get(): # the for event loop, keeping track of events, if event.type == pygame.QUIT: # and in this case, it will be keeping track of pygame.QUIT, which is the X or the top right pygame.quit() # stops pygame There are other ways of stopping the while loop, and you could do this: running = True while running: # the while loop that will keep your display up and running! for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() Hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/50318132

http://stackoverflow.com/a/50271836
score: 0
answers question: http://stackoverflow.com/q/50271726
type: AcceptedAnswer
has body: Use all Ex: l = (5,range(10,15)) check = (5,12) if all([check[0] == l[0] and check[1] in l[1]]): print("Ok") Output: Ok
accepted answer of: http://stackoverflow.com/q/50271726
type: Answer

pymysql
tags question: http://stackoverflow.com/q/50296719
tags question: http://stackoverflow.com/q/50272352
tags question: http://stackoverflow.com/q/50383580
tag name: pymysql
tags question: http://stackoverflow.com/q/50298281
type: Tag
tags question: http://stackoverflow.com/q/50261847
tags question: http://stackoverflow.com/q/50270618
tags question: http://stackoverflow.com/q/50336458

http://stackoverflow.com/comment/87646293
comment on: http://stackoverflow.com/q/50313790
type: Comment
type: QuestionComment
has text: I've added the full exception, also trying the print statement results in File "./AtomParse", line 12, in <module> print(lxml.etree.tostring(tree)) NameError: name 'lxml' is not defined
score: 0

http://stackoverflow.com/q/50238914
tagged with: python
has body: How can I compile solidity files which perform relative imports through py-solc? Here's a minimal example: Directory structure my-project - main.py - bar.sol - baz.sol main.py: from solc import compile_source def get_contract_source(file_name): with open(file_name) as f: return f.read() contract_source_code = get_contract_source("bar.sol") compiled_sol = compile_source(contract_source_code) # Compiled source code baz.sol: pragma solidity ^0.4.0; contract baz { function baz(){ } } bar.sol: pragma solidity ^0.4.0; import "./baz" as baz; contract bar { function bar(){ } } When I try to run the python file I get the following error: solc.exceptions.SolcError: An error occurred during execution > command: `solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc` > return code: `1` > stderr: > stdout: :17:1: Error: Source "baz" not found: File outside of allowed directories. import "./baz" as baz; ^----------------------^ I'm still not 100% clear on how imports work. I've reviewed the docs and it seems like I need to pass some extra arguments to the compile_source command. I've found some potentially useful docs here and I think I need to play around with allow_paths or compile_files which I will. If I find a solution before I get an answer I will post what I find.
accepted answer: http://stackoverflow.com/a/50239031
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/50239031
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/72668956
favorite count: 0
tagged with: web3py
has title: Py-solc and solidity imports
type: Question
tagged with: solidity
possible better answer: http://stackoverflow.com/a/72668956
score: 3

clr
type: Tag
tag name: clr
tags question: http://stackoverflow.com/q/50255983

http://stackoverflow.com/a/50266709
has body: If you want setC in the same format as setA and setB. I think this workaround will do. Entering values directly as tuple is not possible as tuples are immutable and hence we append the new tuples as list and then convert it to a tuple. ` setC = [] i=0 while setA[0][i][0]== setB[0][i][0] and (i &lt; min(len(setA[0]), len(setB[0]))-1): setC.append((setA[0][i][1],setA[0][i][0], setB[0][i][1])) i+=1 setC = [tuple(setC)] `
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50266240

http://stackoverflow.com/comment/87660526
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50312962
has text: Sorry, I set them the main loop restriction to be 1 so i can debug it faster. But the problem isn't there. It is in the "count_word_occurences" loop.
type: Comment

http://stackoverflow.com/comment/87565340
comment on: http://stackoverflow.com/q/50274072
has text: [[3, 3, 3], [3, 3, 3], [3, 3, 3]][[3, 3, 3], [3, 3, 3], [3, 3, 3]] [[27 27 27] [27 27 27] [27 27 27]] --- 0.0005307197570800781 seconds ---
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88037347
has text: thanks for your help with this, I think ive finally made a working script however have been stumped by celery in this question (https://stackoverflow.com/questions/50512302/django-celery-asyncio-daemonic-process-are-not-allowed-to-have-children) shall I delete this question you've assited with or would you like to post answer?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50352077

http://stackoverflow.com/a/50355201
has comment: http://stackoverflow.com/comment/87793505
type: Answer
has body: You're right, the first answer is pretty straightforward. The problem is that the variable output which you try to read in StreamingHandler is not in scope when your code that defines it is inside a function called main. output = 5 def test(): print(output) # the following statement runs fine, output is in scope because it # was defined in the top-level scope test() def test_2(): print(output_2) def main(): output_2 = 6 test_2() # error! test_2 doesn't know the value of output_2 because the # output_2 variable was declared within main() main() So, you need to work out a way to pass the output variable to the server. My approach is to declare output as a class variable in StreamingHandler, and add output as an argument when instantiating a new StreamingServer as follows: import io import picamera import logging import socketserver from threading import Condition from http import server PAGE="""\ &lt;html&gt; description of webpage &lt;/html&gt; """ class StreamingOutput(object): def __init__(self): self.frame = None self.buffer = io.BytesIO() self.condition = Condition() def write(self, buf): if buf.startswith(b'\xff\xd8'): # New frame, copy the existing buffer's content and notify all # clients it's available self.buffer.truncate() with self.condition: self.frame = self.buffer.getvalue() self.condition.notify_all() self.buffer.seek(0) return self.buffer.write(buf) class StreamingHandler(server.BaseHTTPRequestHandler): output = None def do_GET(self): if self.path == '/': self.send_response(301) self.send_header('Location', '/index.html') self.end_headers() elif self.path == '/index.html': content = PAGE.encode('utf-8') self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(content)) self.end_headers() self.wfile.write(content) elif self.path == '/stream.mjpg': self.send_response(200) self.send_header('Age', 0) self.send_header('Cache-Control', 'no-cache, private') self.send_header('Pragma', 'no-cache') self.send_h…
has comment: http://stackoverflow.com/comment/87793204
score: 2
answers question: http://stackoverflow.com/q/50354034
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87777938
has text: The Notebook has these specifications: Screen: 12.3” PixelSense Display | Resolution: 2736 x 1824 (267 PPI) | Aspect ratio: 3:2 .
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50378653
score: 0

http://stackoverflow.com/a/50237436
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87507926
accepted answer of: http://stackoverflow.com/q/50233156
has comment: http://stackoverflow.com/comment/87504807
has body: See @ekhumoro's explanation of why, but using the decorated method in the slot is causing your problem due to an incorrect signature. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def LogInfos(func): def wrapper(*s, **gs): print('log') ret = func(*s, **gs) return ret return wrapper class Window(QWidget): def __init__(self): super(Window, self).__init__() layout = QHBoxLayout(self) btn = QPushButton('test') layout.addWidget(btn) btn.clicked.connect(self.testSlot) @LogInfos def testSlot(self, checked=False): print('test slot') @LogInfos def testLog(): print('test log') if __name__ == '__main__': testLog() app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/87498138
answers question: http://stackoverflow.com/q/50233156
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50242498
has comment: http://stackoverflow.com/comment/87503449
answers question: http://stackoverflow.com/q/50242278
has comment: http://stackoverflow.com/comment/87503862
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87504051
has comment: http://stackoverflow.com/comment/87504019
has comment: http://stackoverflow.com/comment/87504108
has comment: http://stackoverflow.com/comment/87503892
has comment: http://stackoverflow.com/comment/87503783
type: Answer
has body: You can add a ManyToManyField in your Course Model, named: class Course(models.Model): # other fields students = models.ManyToManyField('Profile',blank=True)` So when you have a profile instance, this query profile_instance.course_set.all() will display all the courses that this profile/student has attended In your view, don't override get_queryset() {% if user.is_authenticated %} welcome {{ user.first_name }} -- {% for course in user.profile.course_set.all %} {{ course.Course_Name }}{% if not forloop.last %},{% endif %} {% empty %} No course {% endfor %} {% endif %} Logout ...
has comment: http://stackoverflow.com/comment/87504065
has comment: http://stackoverflow.com/comment/87504088
has comment: http://stackoverflow.com/comment/87503254
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50242278
has comment: http://stackoverflow.com/comment/87503477
has comment: http://stackoverflow.com/comment/87503571
downvote count: 0
has comment: http://stackoverflow.com/comment/87503920
has comment: http://stackoverflow.com/comment/87503515

http://stackoverflow.com/a/50274956
has comment: http://stackoverflow.com/comment/87569262
answers question: http://stackoverflow.com/q/50273897
downvote count: 1
upvote count: 0
type: Answer
score: -1
has body: Although this doesn't actually provide an answer to the actual question, it's an alternative that goes around the scenario that was brought up, and achieves the same (final) goal (it's more elegant, but slower - especially for large lists). It works on both Python 2 and Python 3 (where reduce could also be replaced by itertools.accumulate), and makes use of: [Python 2.Docs]: Built-in Functions (max, reduce) [Python 2.Docs]: operator - Standard operators as functions (mul) [Python 2.Docs]: itertools - Functions creating iterators for efficient looping (combinations) &gt;&gt;&gt; import itertools &gt;&gt;&gt; import operator &gt;&gt;&gt; &gt;&gt;&gt; l = [1, 9, 0, -5, 7, 2, 4] &gt;&gt;&gt; &gt;&gt;&gt; def max_prod(seq, count=3): ... return max(reduce(operator.mul, item) for item in itertools.combinations(seq, count)) ... &gt;&gt;&gt; max_prod(l) 252 which is: 9 * 7 * 4.

http://stackoverflow.com/a/50268654
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87554976
answers question: http://stackoverflow.com/q/50268576
upvote count: 2
has body: You can do it like this: import requests j = requests.get('https://api.bitfinex.com/v2/tickers?symbols=ALL').json() mydict = {} for i in j: mydict[i[0]] = i[1:] Or using dictionary comprehension: mydict = {i[0]: i[1:] for i in j} Then access it as: mydict['tZRXETH']
type: Answer

http://stackoverflow.com/comment/87776430
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50375905
has text: Divakar: As like all times, this is a great answer! Many thanks :)

http://stackoverflow.com/comment/87666307
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50234770
has text: One more way is to take an object oriented approach and transform your existing python codes into classes and directly import them :)

http://stackoverflow.com/a/50378202
answers question: http://stackoverflow.com/q/50378153
score: 6
has body: Use: df['order'] = df.groupby('user1')['quantity'].rank(ascending=False).astype(int) Output: user1 user2 quantity order 0 Alice Carol 10 1 1 Alice Bob 5 2 2 Bob Dan 2 1 3 Carol Eve 7 2 4 Carol Dan 100 1 Details. df.groupby('user1')['quantity'].rank(ascending=False) Output: 0 1.0 1 2.0 2 1.0 3 2.0 4 1.0 Name: quantity, dtype: float64
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/87772857
accepted answer of: http://stackoverflow.com/q/50378153
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87772895

http://stackoverflow.com/comment/87706804
type: Comment
score: 0
type: QuestionComment
has text: is data is the last item of the line?
comment on: http://stackoverflow.com/q/50345470

http://stackoverflow.com/comment/87751195
type: AnswerComment
has text: Oh I see. So `len(r)` raises the error, while `r.__len__()` won't.
comment on: http://stackoverflow.com/a/50367338
type: Comment
score: 0

http://stackoverflow.com/q/50352569
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50352721
has body: I have an excel sheet where one column contains a time field, where the values are the time of day entered as four digits: i.e. 0845, 1630, 1000. I've read this into a pandas dataframe for analysis, one piece of which is labeling each time as day or evening. To do this, I first changed the datatype and format: # Get start time as time df['START_TIME'] = pd.to_datetime(df['START_TIME'],format='%H%M').dt.time Which gets the values looking like: 08:45:00 16:30:00 10:00:00 The new dtype is object. When I try to perform a logical test on that field, i.e. # Create indicator of whether course begins before or after 4:00 PM df['DAY COURSE INDICATOR'] = df['START_TIME'] &lt; '16:00:00' I get a Type Error: TypeError: '&lt;' not supported between instances of >'datetime.time' and 'str' or syntax error if I remove the quotes. What is the best way to create that indicator; how do I work with stand-alone time values? Or am I better off just leaving them as integers.
has title: How to perform logical tests on time values in a pandas dataframe
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/50352703
possible better answer: http://stackoverflow.com/a/50352721
accepted answer: http://stackoverflow.com/a/50352703

http://stackoverflow.com/comment/87555892
has text: thank you.i think i have the answers i need
type: Comment
comment on: http://stackoverflow.com/q/50265916
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87598224
type: AnswerComment
score: 0
type: Comment
has text: The data are coming from a database which first will be open if the URL will be invoked. At the moment I have the _undefined name df_ error and I'm sure if can do this globally and when.
comment on: http://stackoverflow.com/a/50289930

http://stackoverflow.com/comment/87784742
type: QuestionComment
has text: Actually, the problem _does_ happen with your sample input if I leave those `.` lines in. Are those actually in your real file?
comment on: http://stackoverflow.com/q/50383910
score: 0
type: Comment

http://stackoverflow.com/q/50358413
upvote count: 2
tagged with: gpio
downvote count: 0
has body: (Warning! I am not educated on this topic) Hey folks. I'm posting here because I have a friend who desperately needs help with her project. I'm familiar with scripting, but not too much with programming. I do work in IT, so I'll do my best to provide the necessary information. She's trying to program a Raspberry Pi Zero to control a stepper motor using Python 3. Simple as that. She followed these tutorials. Looks like she used the parts and wiring from #1 and the code from #2: https://tutorials-raspberrypi.com/how-to-control-a-stepper-motor-with-raspberry-pi-and-l293d-uln2003a/ https://www.raspberrypi.org/forums/viewtopic.php?f=49&amp;t=55580 Helpful pictures here. This is her actual setup: https://photos.app.goo.gl/WJbCo4UU3wAdo8913 Helpful notes: She mentioned she is not using a resistor between the power source and the L293D Driver IC. Parts Used: -Raspberry Pi Zero (Pi 2 or 3 was recommended, but the Zero has the same pin-out as the 2 &amp; 3. She just had to solder on her own double-header) -12V DC Power Bank -Nema 17 Stepper Motor (https://www.amazon.com/STEPPERONLINE-17HS13-0404S1-Stepper-Motor-Printer/dp/B00PNEQ9T4) -L293D Motor Driver IC (https://www.amazon.com/NDRTJM-SHOMPFL1045-L293D-Stepper-Driver/dp/B008XCGLNM) -Breadboard w/ jumper cables (Duh!) The code that she's using is below. When she attempts to run it, the motor just vibrates. Seems like it's repeatedly taking a step forward and a step back. No error codes are received. She also tried using another Nema 17 Stepper Motor that drawed 2A, but dropped down to the Nema 17 that draws .4A and gets the same result. import RPi.GPIO as GPIO import time #variables delay = 0.05 steps = 500 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #Enable GPIO pins for ENA and ENB for stepper enable_a = 18 enable_b = 22 #Enable pins for IN1-3 to control step sequence coil_A_1_pin = 17 #black coil_A_2_pin = 4 #green coil_B_1_pin = 24 #red coil_B_2_pin = 23 #blue #Set pin states GPIO.setup(enable_a, GPIO.OUT) GPIO.setup(…
favorite count: 0
possible better answer: http://stackoverflow.com/a/50361427
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53442586
tagged with: motordriver
tagged with: python
has title: Programming in Python: Controlling Stepper Motor + Raspberry Pi Zero + L293D IC
has answer: http://stackoverflow.com/a/53401543
answer count: 4
has answer: http://stackoverflow.com/a/50361427
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50358907
tagged with: raspberry-pi
accepted answer: http://stackoverflow.com/a/50358907

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/50368024

http://stackoverflow.com/q/50250302
tagged with: jaydebeapi
tagged with: sql-server
score: 0
possible better answer: http://stackoverflow.com/a/50250390
has comment: http://stackoverflow.com/comment/87517938
tagged with: python
accepted answer: http://stackoverflow.com/a/50253178
has body: Problem I am connecting with JayDeBeApi to SQL Server 2017 and running a script like: SELECT ... INTO #a-temp-table DELETE FROM a-table INSERT INTO a-table SELECT FROM #a-temp-table DELETE #a-temp-table During step 3 i get the following error: Cannot insert duplicate key row in object 'dbo.a-table' with unique index 'UQ_a-table'. The duplicate key value is (11, 0001, 3751191, T70206CAT, 0000). Instead of ~360k records, only ~180k get inserted. So step 3 aborts. The temp table however gets deleted. So step 4 completes. I am able to fix the error. But with JayDeBeApi, I am not seeing the error. It seems like everything went fine from the Python point of view. My goal is to capture those errors to handle them appropriately. Any idea how to achieve that? What I've tried My Python code looks like. try: localCursor = dbConnection.cursor() x = localCursor.execute(query) logInfo("Run script %s... done" % (scriptNameAndPath), "run script", diagnosticLog) except Exception as e: logError("Error running sql statement " + scriptNameAndPath + ". Skipping rest of row.", "run script", e, diagnosticLog) myrow = skipRowAndLogRecord(startRowTime, cursor, recordLog) continue x = localCursor.execute(myqrystm) completes successfully, so no exception is thrown. x is None and while inspecting localCursor, I see no sign of any error message(s)/code(s)
has answer: http://stackoverflow.com/a/50253178
type: AnsweredQuestion
answer count: 2
has title: Error swallowed
has answer: http://stackoverflow.com/a/50250390
type: Question

http://stackoverflow.com/comment/87726971
type: QuestionComment
comment on: http://stackoverflow.com/q/50355080
score: 0
type: Comment
has text: Then I'd try `pip install numpy=1.11.0 pandas==0.18.0 --force-reinstall --upgrade` based on https://github.com/pandas-dev/pandas/issues/18442

http://stackoverflow.com/comment/87543726
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50262705
type: Comment
has text: @AdamSmithI wanted to add you to my above question but I couldn't hence mention in the new comment.

http://stackoverflow.com/comment/87581838
comment on: http://stackoverflow.com/a/50282583
has text: Cheers, I appreciate your understanding... if OP decides to use this answer, I hope they accept yours. Good luck!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/97694961
type: QuestionComment
comment on: http://stackoverflow.com/q/50337569
score: 0
has text: @MartijnPieters Wow, nice transcription!
type: Comment

http://stackoverflow.com/comment/87500426
comment on: http://stackoverflow.com/a/50241246
type: Comment
has text: indentation error means that you missed a space when you copied/pasted. Integer are included in float, so it should be good :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/50242232
tagged with: cherrypy
type: Question
has title: How to get cherrypy to serve static files from the index and a static directory, with custom paths as well?
linked to: http://stackoverflow.com/q/759627
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87502529
tagged with: static-content
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87502158
has body: I have a directory structure that looks like this: project/ index/ about.html index.html forum.html profile.html settings.html apple-touch-icon.png static/ main.css forum.css main.js forum.js load-image.min.js server.py metaclass.py mailing.py errors.log I'd like to be able to make cherrypy serve all of these files from index/. However, I also want about.html, index.html, forum.html, profile.html, etc. to be accessible via /about, /, /forum, /profile, etc., so this is not the same as just simple static file serving. Also, I want to have some custom methods, like /login, which needs a GET and POST, and pre-templated user profile pages. How can this be done?
tagged with: python
has answer: http://stackoverflow.com/a/50843997
favorite count: 0

http://stackoverflow.com/q/50352511
linked to: http://stackoverflow.com/q/58441974
has comment: http://stackoverflow.com/comment/87833097
has comment: http://stackoverflow.com/comment/87747143
has body: I have two vectors (r1 and r2) both of length 3500 and I want to compare them. The problem is that when I use plt.bar I get two different kind of plot for r2. How is it possible? Can anyone tell me what is wrong in my code? def compare_representations(r1, r1title, r2, r2title, image, k): ka = np.asarray(range(k)) #ka =3500 plt.figure(figsize=(13,10)) #histogram Query hiq = plt.subplot(2,2,1) hiq.set_title("Histogram for " + r1title) hiq.set_xlabel("Visual words") hiq.set_ylabel("Frequency") #hist1 = plt.plot(r1, color='orangered') hist1 = plt.bar(ka,r1,width=1.0,color="orangered") #histogram Image his = plt.subplot(2,2,2) his.set_title("Histogram for "+ r2title) his.set_xlabel("Visual words") his.set_ylabel("Frequency") #hist2 = plt.plot(r2, color='mediumslateblue') hist2 = plt.bar(ka,r2,width=1.0,color='mediumslateblue') #histograms compared comp = plt.subplot(2,2,3) comp.set_title("Compare Histograms: ") comp.set_xlabel("Visual words") comp.set_ylabel("Frequency") #plt.plot(r1, color ='orangered') #plt.plot(r2, color = 'mediumslateblue') plt.bar(ka,r1,width=1.0,color ='orangered') plt.bar(ka,r2,width=1.0,color = 'mediumslateblue') #plot founded image ax = plt.subplot(2,2,4) ax.grid(False) img = mpimg.imread(image, format='jpeg') # Turn off tick labels and show just name of founded image ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_xlabel(os.path.basename(image)) imgplot = plt.imshow(img) plt.show() return(hist1, hist2, imgplot)
has comment: http://stackoverflow.com/comment/87747116
tagged with: matplotlib
has answer: http://stackoverflow.com/a/61317633
has title: matplotlib pyplot compare two bar diagrams by overlapping them
tagged with: python
has comment: http://stackoverflow.com/comment/87729733
answer count: 2
downvote count: 0
type: UnansweredQuestion
tagged with: bar-chart
has comment: http://stackoverflow.com/comment/87723525
has answer: http://stackoverflow.com/a/50409846
favorite count: 0
has comment: http://stackoverflow.com/comment/87721430
type: Question
has comment: http://stackoverflow.com/comment/87764810
upvote count: 3
score: 3

http://stackoverflow.com/a/50360803
accepted answer of: http://stackoverflow.com/q/50360698
score: 0
has body: I can't figure out how to target that third &lt;dd&gt;&lt;/dd&gt; for each respective &lt;div class="row"&gt; find_all will return a list of all occurrences, so you could just take the third element of the result. Although you may want to wrap the whole thing with try catch to prevent IndexError https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all I'd make a function out of this code to reuse it for different pages: soup = BeautifulSoup(html.read(), "html.parser") result = [] for meta in soup.find_all('div', {'class': 'course-meta'}): try: institution = meta.find_all('dd')[2].text.strip() result.append(institution) # or whatever you like to store it except IndexError: pass
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87738246
answers question: http://stackoverflow.com/q/50360698
type: Answer

http://stackoverflow.com/comment/87539846
has text: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
score: 0
comment on: http://stackoverflow.com/q/50260840
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87672387
type: QuestionComment
score: 0
has text: It is possible to do with a custom postgres function. It's not built in to django querysets, unfortunately. Postgres does support python scripting, if you are willing to experiment with that. There's not a bunch of examples available in the docs, but it is possible. https://www.postgresql.org/docs/10/static/plpython.html
comment on: http://stackoverflow.com/q/50327518
type: Comment

http://stackoverflow.com/comment/87493430
type: AnswerComment
has text: Hi Man, I really appreciate your help .. I got your code but I got this error `mask = cv2.addWeighted(out_resized, 0.7, out_resized_clipped,0.3,0) cv2.error: /Users/travis/build/skvark/opencv-python/opencv/modules/core/src/arithm.cpp:659: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function arithm_op` I don't understand what's that?
comment on: http://stackoverflow.com/a/50235435
type: Comment
score: 0

http://stackoverflow.com/a/50244588
has body: Your Form is not a view. It's just making inputs inside your form. I.e., basic forms.Form from Django documentation from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) is rendered to HTML like this: Your name: That's all. What you need is View, not Form. I think you should try FBV(Function-Based View), not using form. So I highly recommend to follow Django tutorials - it's very good - and take a step from basic request/response. Here is official Django documentation. It's easy to follow and well-organized. I also recommend Django girls tutorial. It supports many languages and is good for beginners.
has comment: http://stackoverflow.com/comment/97006297
type: Answer
accepted answer of: http://stackoverflow.com/q/50242919
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50242919
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/53815323
answers question: http://stackoverflow.com/q/50319617
has body: It may be easier to initialize new numpy array with initial image as source and dtype=np.uint8: import numpy as np img = cv2.imread('path//to//image//file') img = np.array(img, dtype=np.uint8) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
has comment: http://stackoverflow.com/comment/123377670
type: Answer
downvote count: 0
score: 7
upvote count: 7

http://stackoverflow.com/q/50371158
has title: test ansible roles with molecule and boto3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50662905
tagged with: aws-sdk
has body: I have ansible roles that creates servers, S3 buckets, security groups ... and I want to establish some unit testing using Molecule. After some researches, I found out that Molecule is using Testinfra to run some assert commands on the remote/local host. That can work for my roles that create some servers like apache2, nginx.. but how about the other roles that are just creating some other aws resources like load balancers, autoscaling groups, security groups, or just s3 buckets? in this case, there will be no host nor instances. It would be easy to make tests by Unittest and boto3 and call the AWS API, but my question is can I use molecule only and fire up an EC2 instance everytime I want to test my role of security group and then do something like this : def test_security_group_has_80_open(host): cmd = host.run('aws ec2 describe-security-groups --group-names MySecurityGroup') return_code = cmd.rc output = cmd.stdout assert output.contains('"ToPort": 80') That EC2 instance would have AWSCLI installed. Is this a correct way ? Is it possible to test all type of roles by Molecule by firing an EC2 that runs awscli calls ?
tagged with: aws-cli
tagged with: python
score: 0
tagged with: molecule
tagged with: ansible
has comment: http://stackoverflow.com/comment/87758544
answer count: 1
type: Question

http://stackoverflow.com/comment/87584438
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50283742
has text: You're welcome! From your code it looks like you want to iteratively add one row's `tpv` value to the sum of all the previous rows of `tpv`, to keep track of a progressive summation (`sumTpv`). That's what `cumsum` does.

http://stackoverflow.com/a/50264278
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50264230
has body: Maybe this will help you https://github.com/dbader/schedule import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) while True: schedule.run_pending() time.sleep(1)
type: Answer
answers question: http://stackoverflow.com/q/50264230
has comment: http://stackoverflow.com/comment/87550339

http://stackoverflow.com/q/50256012
possible better answer: http://stackoverflow.com/a/50259986
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/50259986
downvote count: 0
accepted answer: http://stackoverflow.com/a/50256391
has title: Drop rows with masked elements in astropy Table
has body: Consider an astropy Table() object. from astropy.io import ascii weather_data = """ day,precip,type ,1.5,rain Tues, 9., Wed,1.1,snow ed,,aaa Wd,1.1,snow """ dat = ascii.read(weather_data) print(dat) day precip type ---- ------ ---- -- 1.5 rain Tues 9.0 -- Wed 1.1 snow ed -- aaa Wd 1.1 snow I need to drop all rows that contain at least one masked element. The final table should then look like: day precip type ---- ------ ---- Wed 1.1 snow Wd 1.1 snow This seems like a simple task, but I could not find a way t do it in the docs. Add I know that I could use .to_pandas() to convert the table to a pandas object and then use something like .dropna(), but this forces me to have pandas installed which I don't want.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50256391
score: 3
linked to: http://stackoverflow.com/q/13413590
tagged with: python
tagged with: astropy
type: AnsweredQuestion

http://stackoverflow.com/comment/116125256
comment on: http://stackoverflow.com/a/50245954
has text: @agent18, I have updated the links. Thanks for notifying
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87558956
type: Comment
comment on: http://stackoverflow.com/a/50270701
score: 0
type: AnswerComment
has text: hi Rohan! may i know which part of my code do i change to yours?

http://stackoverflow.com/comment/87628722
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50306006
has text: @VTT I tried that
score: 0

http://stackoverflow.com/a/50391359
has body: here is the complete code how you will do it import boto3 from botocore.exceptions import ClientError s3 = boto3.client('s3') s3_re = boto3.resource('s3') for bucket in s3_re.buckets.all(): s3_bucket = bucket s3_bucket_name = s3_bucket.name bucket_tagging = s3_re.BucketTagging(s3_bucket_name) try: response = s3.get_bucket_tagging(Bucket=s3_bucket_name) except ClientError: print (bucket+ ",does not have tags, add tag") print("give key : ") inp_key = input() print("give value : ") inp_val = input() response = bucket_tagging.put( Tagging={ 'TagSet': [ { 'Key': inp_key, 'Value': inp_val }, ] } )
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50376650
score: 1
upvote count: 1

http://stackoverflow.com/comment/87704602
type: AnswerComment
score: 0
has text: Where would i put this? Replace the `btn = Button()` part with this one?
type: Comment
comment on: http://stackoverflow.com/a/50344387

http://stackoverflow.com/q/50384085
has comment: http://stackoverflow.com/comment/87784155
has title: Why does subprocess command print 0 instead of path?
tagged with: python
has body: I'm beginner in python I have tried following code. When I run code it doesn't give error, however expected output must be in file, instead it prints output on console. In actual test.txt file it make entries as 0. Why does it print 0 and not the path returned by pwd command? from subprocess import call path = call('pwd') with open('test.txt', "w") as f : f.seek(0) f.write(str(path)) f.close()
score: 0
has answer: http://stackoverflow.com/a/50384500
answer count: 1
has comment: http://stackoverflow.com/comment/87783976
type: Question
has comment: http://stackoverflow.com/comment/87783891
has comment: http://stackoverflow.com/comment/87783839
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87783768

http://stackoverflow.com/q/50258275
linked to: http://stackoverflow.com/q/252703
tagged with: python-2.7
answer count: 2
score: 1
has body: I'm trying to write a Google Document script and it's going terribly. I am appending all of the information from specific rows to a list and I want to print out a certain item in that list. eg The second thing it adds to the list. However that would be easy right? But I'm having to append the list to a list. So I have a list of lists. And Now I don't know how to get the script to just print out the 2nd item of each list inside of the list. This is my code- if not spreadsheet_key: print &gt;&gt;sys.stderr, 'No Spreadsheet Key given' sys.exit() worksheet_id = 'od6' storage = Storage(r'P:\Bureau Schedule\auto_drive_creds') credentials = storage.get() if credentials.access_token_expired: credentials.refresh(httplib2.Http()) spr_client = gdata.spreadsheet.service.SpreadsheetsService( additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token} ) q = gdata.spreadsheet.service.CellQuery() q.return_empty = 'true' cells = spr_client.GetCellsFeed( spreadsheet_key, worksheet_id, query=q ) batchRequest = gdata.spreadsheet.SpreadsheetsCellsFeed() lst_a = [] for i, cell in enumerate(cells.entry): lst_b = [] if cell.title.text.startswith('AG'): if cell.content.text == '2': lst_b.append([cells.entry[i-30].cell.inputValue, cells.entry[i-29].cell.inputValue, cells.entry[i-25].cell.inputValue]) lst_a.append(lst_b) print lst_a[0] I'm expecting quite an easy answer but I'm unsure and I've been stuck for a quite awhile so I thought I may as well ask.
has title: Printing Certain Items In A List
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50258441
has answer: http://stackoverflow.com/a/50258448
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50258247
has body: I'm trying to create my own corpus out of a set of text files. However, I want to do some preprocessing on the text files before they get corpus-ized and I can't figure out how to do that, short of creating a script to run through every single text file first, do the text preprocessing, save a new text file, and then make the corpus on the new, post-processed files. (This seems inefficient now, because I have ~200 mb of files that I would need to read through twice, and is not really scalable if I had a much larger corpus.) The preprocessing that I want to do is very basic text manipulation: Make every word as listed in the corpus lower case Remove any items entirely enclosed in brackets, e.g., [coughing] Remove digits at the start of each line (they're line numbers from the original transcriptions) which are the first four characters of each line Critically, I want to do this preprocessing BEFORE the words enter the corpus - I don't want, e.g., "[coughing]" or "0001" as an entry in my corpus, and instead of "TREE" I want "tree." I've got the basic corpus reader code, but the problem is that I can't figure out how to modify pattern matching as it reads in the files and builds the corpus. Is there a good way to do this? corpusdir = "C:/corpus/" newcorpus = PlaintextCorpusReader(corpusdir, '.*') corpus_words = newcorpus.words() # get words in the corpus fdist = nltk.FreqDist(corpus_words) # make frequency distribution of the words in the corpus This answer seems sort of on the right track, but the relevant words are already in the corpus and the poster wants to ignore/strip punctuation before tokenizing the corpus. I want to affect which types of words are even entered (i.e., counted) in the corpus at all. Thanks in advance!
type: UnansweredQuestion
tagged with: nltk
tagged with: python
has title: Create a new corpus with NLTK that ignores certain strings in input files and does not enter them into the corpus
linked to: http://stackoverflow.com/q/26411779
linked to: http://stackoverflow.com/q/4951751
score: 0
answer count: 1
tagged with: corpus
has answer: http://stackoverflow.com/a/50279508
type: Question

http://stackoverflow.com/q/50346213
type: AnsweredQuestion
score: 2
tagged with: apache-spark
downvote count: 0
tagged with: k-means
answer count: 1
accepted answer: http://stackoverflow.com/a/50347124
favorite count: 0
type: Question
has title: PySpark: accessing vector elements in sql
has body: I have spark dataframe that has a column named features that holds vectors of data. This column is the output of pyspark's StandardScaler object. I am creating a dataset here similar to the one I have. # create sample data arr = [[1,2,3], [4,5,6]] df_example = spark.createDataFrame(arr, ['A','B','C']) assembler = VectorAssembler(inputCols=[x for x in df_example.columns],outputCol='features') df_vector = assembler.transform(df_example).select('features') &gt;&gt;&gt; df_vector.show() +-------------+ | features| +-------------+ |[1.0,2.0,3.0]| |[4.0,5.0,6.0]| +-------------+ I want to find the Euclidean distance between each vector and a particular cluster center(an array of same length). Assume the cluster center is: cluster_center_0 = np.array([0.6, 0.7, 0.8]) How do I achieve this? I tried creating a SQL query hoping that I could get access to the elements inside the vector using OFFSET and from there it would be easy to calculate the distances. But that didn't work out. This is the query I used. Unfortunately it doesn't work and I have very limited knowledge of sql SELECT aml_cluster_inpt_features aml_cluster_inpt_features[OFFSET(0)] AS offset_0, aml_cluster_inpt_features[OFFSET(1)] AS offset_1, aml_cluster_inpt_features[OFFSET(2)] AS offset_2, aml_cluster_inpt_features[OFFSET(3)] AS offset_3, FROM event_rate_holder Is there a simpler way of doing this? If not, am I headed in the right direction with the sql query above?
tagged with: pyspark
linked to: http://stackoverflow.com/q/38384347
tagged with: python
has answer: http://stackoverflow.com/a/50347124
upvote count: 2

geopandas
tags question: http://stackoverflow.com/q/50236408
tag name: geopandas
type: Tag
tags question: http://stackoverflow.com/q/50378688
tags question: http://stackoverflow.com/q/50332273

http://stackoverflow.com/comment/87628406
has text: @Kasramvd: That's because types are ignored at runtime. This has nothing to do with Python 3.7: all versions of Python 3 (starting from 3.0) will run OP's code (assuming the `typing` module backport is installed when necessary). However, type checking tools like mypy will reject OP's code regardless of what version of Python he or she is trying to run. For more details see [this post](https://stackoverflow.com/q/41356784/646543).
comment on: http://stackoverflow.com/a/50305711
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87768740
comment on: http://stackoverflow.com/q/50376214
score: 0
type: Comment
type: QuestionComment
has text: whenever i used to run command for scrapy version it gives me error of same as above

http://stackoverflow.com/q/50335794
has comment: http://stackoverflow.com/comment/87687848
has comment: http://stackoverflow.com/comment/87687840
has comment: http://stackoverflow.com/comment/87688504
tagged with: python
duplicate of: http://stackoverflow.com/q/952914
has comment: http://stackoverflow.com/comment/87687774
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50336099
upvote count: 1
has title: Remove outer list from list of lists of lists
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
type: Question
linked to: http://stackoverflow.com/q/952914
tagged with: python-3.x
has body: How can I remove the outer layer of this? [[['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH']], [['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]] There are plenty of posts detailing how to flatten a list of lists (essentially the same as removing the outer layer), but I could not find anything for a list of lists of lists Thanks!

http://stackoverflow.com/comment/87679792
type: QuestionComment
comment on: http://stackoverflow.com/q/50331895
type: Comment
has text: Also, you really shouldn't name dictionaries `dict` as that overrides a builtin name.
score: 0

http://stackoverflow.com/q/50249653
type: Question
has answer: http://stackoverflow.com/a/50249842
possible better answer: http://stackoverflow.com/a/50249842
has body: I have two dataframes, which in both I happened to set 'timeStamp' as the index. df_1.set_index('timeStamp', inplace=True). df_1 value timeStamp 2016-11-23 20:00:00 37.21 2016-11-23 21:00:00 37.79 2016-11-23 22:00:00 33.99 2016-11-23 23:00:00 32.66 2016-11-24 00:00:00 31.61 df_2 value timeStamp 2016-11-23 23:00:00 32.92 2016-11-24 00:00:00 31.54 2016-11-24 01:00:00 29.14 I wanted to make a dataframe comparing both values when the time is shared. I tried combined_df= pd.merge(df_real, df_fc, on='timeStamp', how='inner') and got a key error. So instead of merging two dataframes on an index, I kept the dataframes without 'timeStamp' as their index. For example. df I used instead for merging timeStamp value 0 2016-11-23 20:00:00 37.21 1 2016-11-23 21:00:00 37.79 2 2016-11-23 22:00:00 33.99 3 2016-11-23 23:00:00 32.66 13 2016-11-24 00:00:00 31.61 Then I was able to merge and my new df was set(shown below). I also then set the index to timestamp, later on. timeStamp value_x value_y 0 2016-11-23 23:00:00 32.66 32.92 my question Why couldn't I merge on the column name that was specified as an index? I wanted to set that merge to a new dataframe...
tagged with: dataframe
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50250243
has answer: http://stackoverflow.com/a/50250218
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50249732
accepted answer: http://stackoverflow.com/a/50249732
favorite count: 0
has title: Pandas merging 2 dataframes on their similar columns(which is the index)

http://stackoverflow.com/a/50342119
upvote count: 1
score: 1
has body: diff df.assign(Key=df.range.diff().lt(0).cumsum().add(1)) time range Key 0 2018-03-04 00:00:06.520 0 1 1 2018-03-04 00:00:07.130 0 1 2 2018-03-04 00:00:07.850 1 1 3 2018-03-04 00:00:08.420 1 1 4 2018-03-04 00:00:09.210 2 1 5 2018-03-04 00:00:10.070 2 1 6 2018-03-04 00:00:10.840 3 1 7 2018-03-04 00:00:11.230 3 1 8 2018-03-04 00:00:11.980 4 1 9 2018-03-04 00:00:12.560 4 1 10 2018-03-04 00:00:13.120 0 2 11 2018-03-04 00:00:13.790 0 2 12 2018-03-04 00:00:14.330 1 2 13 2018-03-04 00:00:15.280 1 2 14 2018-03-04 00:00:15.960 2 2 15 2018-03-04 00:00:16.420 2 2 16 2018-03-04 00:00:17.090 3 2 flatnonzero and repeat a = np.diff(np.flatnonzero(np.concatenate( [[True], np.diff(df.range.values) &lt; 0, [True]] ))) df.assign(Key=np.arange(a.size).repeat(a) + 1) time range Key 0 2018-03-04 00:00:06.520 0 1 1 2018-03-04 00:00:07.130 0 1 2 2018-03-04 00:00:07.850 1 1 3 2018-03-04 00:00:08.420 1 1 4 2018-03-04 00:00:09.210 2 1 5 2018-03-04 00:00:10.070 2 1 6 2018-03-04 00:00:10.840 3 1 7 2018-03-04 00:00:11.230 3 1 8 2018-03-04 00:00:11.980 4 1 9 2018-03-04 00:00:12.560 4 1 10 2018-03-04 00:00:13.120 0 2 11 2018-03-04 00:00:13.790 0 2 12 2018-03-04 00:00:14.330 1 2 13 2018-03-04 00:00:15.280 1 2 14 2018-03-04 00:00:15.960 2 2 15 2018-03-04 00:00:16.420 2 2 16 2018-03-04 00:00:17.090 3 2
type: Answer
answers question: http://stackoverflow.com/q/50341199
downvote count: 0

http://stackoverflow.com/q/50263061
tagged with: python
has comment: http://stackoverflow.com/comment/87544290
has answer: http://stackoverflow.com/a/50263362
score: 0
tagged with: math
tagged with: probability
answer count: 1
tagged with: probability-density
type: Question
tagged with: python-3.x
has body: I recently watched a video about the Monty Hall Problem and was interested in the fact that the contestant had a 2/3 chance of winning when switching. So, I decided to write a simulation for it to see it for myself. However, my simulation gave the answer to be 50%. Could somebody point out why? Note: the number of doors can be adjusted by changing num_of_doors. from random import randint num_of_doors = 3 num_of_simulations = 0 wins = 0 while True: num_of_simulations += 1 doors = {k: "Donkey" for k in range(1, num_of_doors + 1)} car = randint(1, num_of_doors) doors[car] = "Car" choice = randint(1, num_of_doors) while len(doors) &gt; 2: reveal = randint(1, num_of_doors) if reveal in doors: if reveal != choice and doors[reveal] != "Car": del doors[reveal] for k in doors: if k != choice: choice = k if doors[choice] == "Car": wins += 1 print(100 * wins / num_of_simulations)
type: UnansweredQuestion
has title: Why does this implementation of the Monty Hall give the probability to be 50%?

http://stackoverflow.com/a/50343460
answers question: http://stackoverflow.com/q/50343406
accepted answer of: http://stackoverflow.com/q/50343406
type: AcceptedAnswer
downvote count: 0
score: 5
upvote count: 5
type: Answer
has body: Looks like btcusd is a bottom-level directory. That means that when you call os.walk with the r'/data/realtimedata/trades/bitfinex/btcusd/' path, the dirs variable will be an empty list [], so the inner loop for d in dirs: does not execute at all. My advice would be to re-write your function to iterate over the files directly, and not the directories... don't worry, you'll get there eventually, that's the nature of a directory tree. def scan_for_files(path): file_list = [] for path, _, files in os.walk(path): for f in files: file_list.extend(glob.iglob(os.path.join(path, f, '*.csv')) return file_list However, on more recent versions of python (3.5+), you can use recursive glob: def scan_for_files(path): return glob.glob(os.path.join(path, '**', '*.csv'), recursive=True) Source.

http://stackoverflow.com/comment/87565767
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50274484
has text: Increment `n` (and update your filename) at the end of your loop instead of at the beginning.
score: 0

http://stackoverflow.com/a/70017474
has body: I`m working with .dwg file and Python 2.7, this works for me: import os import base64 # Open the file infile = open(input_file, 'r') # 'r' says we are opening the file to read, infile is the opened file object that we will read from # encode file to base64 base64EncodedStr = base64.b64encode(infile.read())
type: Answer
answers question: http://stackoverflow.com/q/50369637
score: 0

http://stackoverflow.com/a/50289093
downvote count: 1
has body: There is no such syntax in Python. The closest to one line you can get is two lines: lst = [1, 1, 2, 2, 2, 3, 3] uniq = [] for i in lst: if i not in uniq: uniq.append(i) # &lt;---- else: continue # &lt;---- print(str(i)) # other useful code Trying to put everything on one line (if i not in uniq: uniq.append(i); else: continue) would give you a syntax error). The syntax you mentioned (uniq.append(i) if i not in uniq else continue) is a ternary expression, and as an expression, it cannot contain continue, which is a statement.
type: Answer
score: -1
answers question: http://stackoverflow.com/q/50288459
accepted answer of: http://stackoverflow.com/q/50288459
upvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87635382
type: AnswerComment
comment on: http://stackoverflow.com/a/50309639
score: 1
type: Comment
has text: @WaterInTheButtle Please see my recent edit. That can be accomplished by using `filter`.

http://stackoverflow.com/a/50305711
answers question: http://stackoverflow.com/q/50305636
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/87627629
has comment: http://stackoverflow.com/comment/87627729
upvote count: 10
has comment: http://stackoverflow.com/comment/87627722
has comment: http://stackoverflow.com/comment/87627658
has comment: http://stackoverflow.com/comment/87628618
has comment: http://stackoverflow.com/comment/87628208
has comment: http://stackoverflow.com/comment/87628406
has comment: http://stackoverflow.com/comment/87627711
has comment: http://stackoverflow.com/comment/87627749
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87627857
accepted answer of: http://stackoverflow.com/q/50305636
has comment: http://stackoverflow.com/comment/87627964
has body: Imagine that this would be possible: arr3: List[Animal] = arr1 Now you think you have list of animals, but this is actually a list of dogs (note that arr3 is not a copy of arr1, they are the same list). And because you think this is the list of animals you can add a Cat to it. However, because this is actually list of dogs, you cannot add a Cat to it. Otherwise you will fail on AttributeError after trying to use dog-specific attribute. More generally, list is invariant - List[Animal] cannot be assigned to List[Dog] (because it can already contain cats) and List[Dog] cannot be assigned to List[Animal] (because you can add cat later) This might not be obvious in Python, but you can make simple test: arr3: List[Animal] = arr1 arr3.append(Cat()) for dog in arr1: print(dog.bark()) Mypy does not allow this because this assignment might break your code logic

http://stackoverflow.com/q/50248527
tagged with: python
type: AnsweredQuestion
has title: Remove tag inside another tag beautifulsoup
downvote count: 0
has answer: http://stackoverflow.com/a/50248606
score: 1
upvote count: 1
answer count: 1
has body: uHow can I extract text inside a tag like this: Find me<\p> Not me<\p> Not me too<\p> And I want to get : Find me With python and beautifulsoup
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/50248606

ipywidgets
tags question: http://stackoverflow.com/q/50287990
type: Tag
tags question: http://stackoverflow.com/q/50376408
tag name: ipywidgets
tags question: http://stackoverflow.com/q/50274978
tags question: http://stackoverflow.com/q/50320535

http://stackoverflow.com/comment/89089291
has text: I am sorry I did not respond to this until now.I will try to take a peak here soon. I ended up working around the code by doing the additional filtering in the code post response.
comment on: http://stackoverflow.com/a/50314157
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50345331
answer count: 0
has body: So, I want to find every contours of an image and store them in a special format so that the image can be reconstructed in another context. Currently, I'm retrieving contours with the RETR_CCOMP option to get external and internal ones, and when I want to show the shapes, I give these contours to fillPoly. My problem is about holes. When there is a hole in a shape, I want to keep track of them to redraw them. But since I am getting internal contours of the outer shape, when I redraw the hole, it is larger by one pixel. Here is an explanation of what i would like to have: in the image one is a sample image. The image two is what findcontours gives me (externals in yellow and internals in green). But I would like to get the contours from the image 3, so that I can redraw the exact same shapes later. Thanks for your answers
has comment: http://stackoverflow.com/comment/87706563
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87707030
type: Question
has title: Opencv - external contours of holes
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87707237
tagged with: opencv
has comment: http://stackoverflow.com/comment/87706746
score: 0
has comment: http://stackoverflow.com/comment/87706694

http://stackoverflow.com/q/50378166
tagged with: python
score: 4
has body: I've dug through SO posts, I've dug through random obscure blogs and I can't seem to fix my issue here. This is how I went about all this: I created a nice fresh new virtual environment: virtualenv venv I installed all my requirements: pip install -r requirements.txt Per the LocalFlavor Documentation I pip installed django-localflavor But when I try to run coverage on my application per the django docs: coverage run --source='.' manage.py test visitor_check_in I get the error 'No module named 'localflavor'... My installed apps looks like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', 'localflavor', 'visitor_check_in', 'django_extensions', ] Just last week I had this running, but I must have goofed something up during a conference recently when I was running through some tutorials or something - but I was in other virtual environments for those tutorials - so I'm stumped. If I move the order of my installed apps like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', 'visitor_check_in', 'django_extensions', 'localflavor', ] It gives me the same no module found error - except it says it cannot find the module django_extensions The traceback looks like this: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup…
has comment: http://stackoverflow.com/comment/87773632
has comment: http://stackoverflow.com/comment/87773208
has comment: http://stackoverflow.com/comment/87772849
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87772863
tagged with: code-coverage
has comment: http://stackoverflow.com/comment/87774479
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50379137
has comment: http://stackoverflow.com/comment/87773884
linked to: http://stackoverflow.com/q/18959072
has answer: http://stackoverflow.com/a/50379137
has comment: http://stackoverflow.com/comment/87773321
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: coverage.py
has comment: http://stackoverflow.com/comment/87773124
has title: Django Coverage ModuleNotFoundError: No module named 'django_extensions'
tagged with: django

http://stackoverflow.com/comment/87831733
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50383529
type: Comment
has text: Testing with size = 1000000 gives me (9.3 ms for your version, 5.1 ms with declaring contigous arrays, 4.4ms with contigous arrays and march=native)

http://stackoverflow.com/comment/87739909
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50359600
has text: Are you using bot.commands or on_message?
score: 0

http://stackoverflow.com/q/50363545
type: Question
type: UnansweredQuestion
has body: In C++, when I can't find a keyword in a table, it will return NULL or in database it will return a empty table, so the program continues to run. But in python, it throws an exception, and interrupts my program. Can I avoid that? for example, I have such a DataFrame named datevar : (datetimeIndex) value 2001-01-01 1 2001-01-02 1 2001-01-03 3 .... v = datevar.xs('2000-01-01', level='date') # of course "keyError" v = datevar.loc['2000-01-01' , :] # of course "keyError"
tagged with: dataframe
tagged with: python
has title: python: pandas.DataFrame，how to avoid keyerror?
has comment: http://stackoverflow.com/comment/87743339
score: 9
answer count: 1
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/87743300
upvote count: 10
downvote count: 1
favorite count: 0
tagged with: keyerror
has answer: http://stackoverflow.com/a/50365378

http://stackoverflow.com/q/50269401
score: 0
has answer: http://stackoverflow.com/a/57196855
has comment: http://stackoverflow.com/comment/87556455
tagged with: raspberry-pi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87587272
answer count: 1
has comment: http://stackoverflow.com/comment/87660328
has comment: http://stackoverflow.com/comment/87624306
tagged with: opencv
has comment: http://stackoverflow.com/comment/87562483
has body: How to scan barcode using Raspberry pi camera module V2 This is the link to my previously asked question about barcode scanning. To be more specific: Hardware : Raspberry pi and Raspberry pi camera module v2 : https://www.amazon.in/Raspberry-Camera-Board-Module- V2/dp/B071P2S8LG/ref=sr_1_5?s=computers&amp;ie=UTF8&amp;qid=1525942832&amp;sr=1-5&amp;keywords=raspberry+pi+camera+module I have tried to scan bar code using 1) pyzbar library 2) SimpleCV 3) OpenCV and zbar Using Pyzbar : from PIL import Image import pyzbar.pyzbar as pyzbar file_path = 'image.png' with open(file_path, 'rb') as image_file: image = Image.open(image_file) image.load() codes = pyzbar.decode(Image.open('image.png')) print('QR codes: %s' % codes) Using SimpleCV : from SimpleCV import Color,Camera,Display cam = Camera() #starts the camera display = Display() while(display.isNotDone()): img = cam.getImage() #gets image from the camera barcode = img.findBarcode() #finds barcode data from image if(barcode is not None): #if there is some data processed barcode = barcode[0] result = str(barcode.data) print result #prints result of barcode in python shell barcode = [] #reset barcode data to empty set img.save(display) #shows the image on the screen Using OpenCV : https://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/ I have tried all three ways to scan barcode but none of them is working. Using the last code, I am able to detect the barcode location in the image but cannot scan barcode. Thanks in advance
has title: Scan bar code using raspberry pi camera module v2
tagged with: python
has comment: http://stackoverflow.com/comment/87562628
type: Question
tagged with: barcode-scanner

http://stackoverflow.com/comment/87688334
comment on: http://stackoverflow.com/a/50333170
type: AnswerComment
has text: is `nyctaxi` you project name? it looks more like possible dataset name to me
score: 0
type: Comment

scrapy
tags question: http://stackoverflow.com/q/50328482
tags question: http://stackoverflow.com/q/50321111
tags question: http://stackoverflow.com/q/50302209
tags question: http://stackoverflow.com/q/50268266
tags question: http://stackoverflow.com/q/50251719
tags question: http://stackoverflow.com/q/50294318
tags question: http://stackoverflow.com/q/50239979
tags question: http://stackoverflow.com/q/50370707
tags question: http://stackoverflow.com/q/50319579
tags question: http://stackoverflow.com/q/50318606
tags question: http://stackoverflow.com/q/50363321
tags question: http://stackoverflow.com/q/50281108
tag name: scrapy
tags question: http://stackoverflow.com/q/50377269
tags question: http://stackoverflow.com/q/50351869
tags question: http://stackoverflow.com/q/50351890
tags question: http://stackoverflow.com/q/50371551
tags question: http://stackoverflow.com/q/50324329
tags question: http://stackoverflow.com/q/50382306
tags question: http://stackoverflow.com/q/50381189
tags question: http://stackoverflow.com/q/50249514
tags question: http://stackoverflow.com/q/50236117
tags question: http://stackoverflow.com/q/50303654
tags question: http://stackoverflow.com/q/50285793
tags question: http://stackoverflow.com/q/50376214
tags question: http://stackoverflow.com/q/50379817
tags question: http://stackoverflow.com/q/50341847
tags question: http://stackoverflow.com/q/50278818
type: Tag
tags question: http://stackoverflow.com/q/50306562
tags question: http://stackoverflow.com/q/50358131
tags question: http://stackoverflow.com/q/50313185
tags question: http://stackoverflow.com/q/50360392
tags question: http://stackoverflow.com/q/50289353
tags question: http://stackoverflow.com/q/50258604
tags question: http://stackoverflow.com/q/50309021

http://stackoverflow.com/a/50301924
type: Answer
has body: For it not to be an empty separator, you should insert a comma inside the two quotes, or else it will technically be empty. In fact, you don't even need the sep because you could just do .split(",")
score: 0
answers question: http://stackoverflow.com/q/50301912

http://stackoverflow.com/comment/87570581
has text: This is what is asking: Instead of putting the integer value for each card in a list, you will create an object of type Card, invoke the deal() method, then append it to your list. There is a good example to refer to on page 516. Your deal hand function will pass the list of objects to the display hand function and the hand stats function, so you will need to modify the code in each of those functions so they reference the data attributes in the object rather than just an integer value in a list like it currently does.
comment on: http://stackoverflow.com/q/50276799
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50285324
has comment: http://stackoverflow.com/comment/87588002
has comment: http://stackoverflow.com/comment/87588865
has body: Use: L = ['ABC','GHI'] df1 = df.pivot('ID', 'var_name', 'var_value').fillna('')[L].reset_index() print (df1) var_name ID ABC GHI 0 1 This is abc1 1 2 This is abc2 This is ghi2 2 3 This is abc3 3 4 This is abc4 L1 = [df1.columns.tolist()] + df1.values.tolist() print (L1) [['ID', 'ABC', 'GHI'], [1, 'This is abc1', ''], [2, 'This is abc2', 'This is ghi2'], [3, 'This is abc3', ''], [4, 'This is abc4', '']] Explanation: First pivot, replace NaNs by fillna, convert subset for filtering columns and create column from index by reset_index Last create nested list and last insert columns names EDIT: I try change order of values in list: L = ['GHI', 'ABC'] df1 = df.pivot('ID', 'var_name', 'var_value').fillna('')[L].reset_index() print (df1) var_name ID GHI ABC 0 1 This is abc1 1 2 This is ghi2 This is abc2 2 3 This is abc3 3 4 This is abc4 L1 = [df1.columns.tolist()] + df1.values.tolist() print (L1) [['ID', 'GHI', 'ABC'], [1, '', 'This is abc1'], [2, 'This is ghi2', 'This is abc2'], [3, '', 'This is abc3'], [4, '', 'This is abc4']]
has comment: http://stackoverflow.com/comment/87596881
has comment: http://stackoverflow.com/comment/87596987
type: Answer
has comment: http://stackoverflow.com/comment/87588054
has comment: http://stackoverflow.com/comment/87587394
has comment: http://stackoverflow.com/comment/87592151
has comment: http://stackoverflow.com/comment/87588149
answers question: http://stackoverflow.com/q/50285171
has comment: http://stackoverflow.com/comment/87586968
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87588732
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50285171
has comment: http://stackoverflow.com/comment/87590409
downvote count: 0
has comment: http://stackoverflow.com/comment/87592442

http://stackoverflow.com/comment/87679332
type: QuestionComment
comment on: http://stackoverflow.com/q/50331102
score: 0
has text: Might be worth looking at something like https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html that shows you how to add additional info to the existing User model, which would allow you to store the users gmail credentials as part of the user model.
type: Comment

http://stackoverflow.com/a/50316933
downvote count: 0
upvote count: 1
score: 1
has body: There are couple of ways you can do this: either use vectorised functions to combine series, or use a lambda function with pd.Series.apply. Vectorised solution Don't forget to cast non-numeric types as str. df['HostAffected'] = df['Host'] + '/' + df['Protocol'] + '/' + df['Port'].map(str) Performance note: Converting a series of ints to strings - Why is apply much faster than astype? Apply lambda function df['HostsAffected'] = df.apply(lambda x: '/'.join(list(map(str, x))), axis=1) With both solutions, you can simply filter by this column to remove all others: df = df'HostsAffected' Complete example from io import StringIO import pandas as pd mystr = StringIO("""Host,Protocol,Port 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,49707 10.0.0.10,tcp,49672 10.0.0.10,tcp,49670""") # replace mystr with 'file.csv' df = pd.read_csv(mystr) # combine columns df['HostsAffected'] = df['Host'] + '/' + df['Protocol'] + '/' + df['Port'].map(str) # include only new columns df = df'HostsAffected' Result: print(df) HostsAffected 0 10.0.0.10/tcp/445 1 10.0.0.10/tcp/445 2 10.0.0.10/tcp/445 3 10.0.0.10/tcp/445 4 10.0.0.10/tcp/445 5 10.0.0.10/tcp/445 6 10.0.0.10/tcp/445 7 10.0.0.10/tcp/49707 8 10.0.0.10/tcp/49672 9 10.0.0.10/tcp/49670
has comment: http://stackoverflow.com/comment/87649901
answers question: http://stackoverflow.com/q/50316797
type: Answer

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/50248724
type: Tag

http://stackoverflow.com/a/50384500
has body: If you want to get output from an external command, use subprocess.check_output as noted by @Paul Rooney. You may change your program as follows to print the output of pwd to file: from subprocess import check_output path_bytes = check_output('pwd', shell=True) path_str = path_bytes.decode('utf-8') with open('test.txt', 'w') as f: f.write(path_str)
type: Answer
answers question: http://stackoverflow.com/q/50384085
score: 0

http://stackoverflow.com/a/50369019
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Does something like this work or you want to keep f = x + y + z? w = torch.cat([x, y, z]) f = w[0] + w[1] + w[2] print (ag.grad(f, w, retain_graph=True, create_graph=True)) # output (tensor([[ 1.],[ 1.],[ 1.]]),)
answers question: http://stackoverflow.com/q/50361177

split
tags question: http://stackoverflow.com/q/50253985
tags question: http://stackoverflow.com/q/50381760
tags question: http://stackoverflow.com/q/50347808
tags question: http://stackoverflow.com/q/50355741
tags question: http://stackoverflow.com/q/50357767
tags question: http://stackoverflow.com/q/50276911
tags question: http://stackoverflow.com/q/50263776
tags question: http://stackoverflow.com/q/50289016
tag name: split
tags question: http://stackoverflow.com/q/50372601
tags question: http://stackoverflow.com/q/50306386
tags question: http://stackoverflow.com/q/50282499
tags question: http://stackoverflow.com/q/50271546
tags question: http://stackoverflow.com/q/50278746
tags question: http://stackoverflow.com/q/50380632
type: Tag
tags question: http://stackoverflow.com/q/50383545
tags question: http://stackoverflow.com/q/50360724
tags question: http://stackoverflow.com/q/50289743
tags question: http://stackoverflow.com/q/50322454
tags question: http://stackoverflow.com/q/50321160
tags question: http://stackoverflow.com/q/50323656
tags question: http://stackoverflow.com/q/50327590

http://stackoverflow.com/a/50379137
upvote count: 7
downvote count: 0
score: 7
type: AcceptedAnswer
has body: Since you mention that it is only happening when you run coverage it is quite possible that it is happening because coverage is not using your virtualenv, but your global python installation instead. A question with similar issue has been posted here before - Running coverage inside virtualenv Apparently, you need to install coverage in your virtualenv as well for it work as expected.
has comment: http://stackoverflow.com/comment/102407011
type: Answer
accepted answer of: http://stackoverflow.com/q/50378166
answers question: http://stackoverflow.com/q/50378166

http://stackoverflow.com/comment/87677016
has text: I am still learning python and I need to conform my dataset according to the particular algorithm which takes images as input. I am though trying to workaround and use numpy arrays instead of images as my dataset.
comment on: http://stackoverflow.com/q/50317614
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50275675
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/50282528
has body: I'm sending a file from a webpage to a Flask server, perform some transformations on it, and then I want to return the transformed document so that the user can download it. I have one button, this will send the POST request: fileUpload: function(file) { var formData = new FormData(); formData.append('file',file); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", () => { console.log("asdf"); }); xhr.open("POST", "http://localhost:7733/receivedoc"); xhr.send(formData); } Then on the server, I do the transformation and want to return a file: ... #Transformations, save file to the file system return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) However, I don't get any file downloads in my browser. There are no errors, the request seems to go through OK. The request headers are Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,hu;q=0.7,cs;q=0.6,sk;q=0.5,de;q=0.4 Connection: keep-alive Content-Length: 114906 Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycEQwQtGAXe1ysM9b DNT: 1 Host: localhost:7733 Origin: http://localhost:5000 Referer: http://localhost:5000/ And the request payload: ------WebKitFormBoundarycEQwQtGAXe1ysM9b Content-Disposition: form-data; name="file"; filename="response.xls" Content-Type: application/octet-stream ------WebKitFormBoundarycEQwQtGAXe1ysM9b-- response.xls is exactly the file I'd want to download. How can I download it? UPDATE - trying to implement Joost's solution. I do: @app.route('/receivedoc', methods=['POST', 'GET', 'OPTIONS']) @crossdomain(origin='*') def upload_file(): if request.method == 'POST': #TRANSFORMING FILE, then saving below: writer = pd.ExcelWriter(filename) df_output.to_excel(writer,'Pacing', index=False) writer.save() return send_from_directory(directory=app.config['UPLOAD_FOLDER'], filename=filename) if request.method == 'GET': prefixed = [filename for filename in os.listdir(app.config['UPLOAD_FOLDER']) if filename.sta…
score: 0
answer count: 1
has title: Download file from API
type: Question
tagged with: download
tagged with: rest
type: UnansweredQuestion

http://stackoverflow.com/comment/87799536
comment on: http://stackoverflow.com/a/50379950
type: Comment
has text: That worked! And I think I see why the code is that way, but lemme ask just in case. Why do we need to have mutex=None at the top even though it is declared in the initializer function? Also, why is the initializer function not a part of the Pool object?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87606508
type: Comment
has text: sorry about that--i just added all of the information above after UPDATE--hope this helps you understand me a bit better
type: AnswerComment
comment on: http://stackoverflow.com/a/50294143
score: 0

http://stackoverflow.com/a/50354212
score: 0
has body: you can go with s = file_name dict = App.get_running_app().get_widget_contents() with open(s, 'w') as f: writer = csv.writer(f) for key in dict: writer.writerow([key, dict[key]])
type: Answer
answers question: http://stackoverflow.com/q/50354041

http://stackoverflow.com/q/50316797
has comment: http://stackoverflow.com/comment/87649411
type: AnsweredQuestion
has body: Hi I'm trying to combine several existing columns into 1 new column then delete the three original ones in a CSV file. I have been trying to do this with pandas however not having much luck. I'm fairly new to python. My code first combines several CSV files in the same directory an then attempts to manipulates the columns. The first combine works and I get an output.csv with the combined data, however the combine of columns does not. import glob import pandas as pd interesting_files = glob.glob("*.csv") header_saved = False with open('output.csv','wb') as fout: for filename in interesting_files: with open(filename) as fin: header = next(fin) if not header_saved: fout.write(header) header_saved = True for line in fin: fout.write(line) df = pd.read_csv("output.csv") df['HostAffected']=df['Host'] + "/" + df['Protocol'] + "/" + df['Port'] df.to_csv("newoutput.csv") Effectively turning this: Host,Protocol,Port 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,445 10.0.0.10,tcp,49707 10.0.0.10,tcp,49672 10.0.0.10,tcp,49670 into something like this: HostsAffected 10.0.0.10/tcp/445 10.0.0.10/tcp/445 10.0.0.10/tcp/445 10.0.0.10/tcp/445 10.0.0.10/tcp/445 10.0.0.10/tcp/445 10.0.0.11/tcp/445 10.0.0.11/tcp/49707 10.0.0.11/tcp/49672 10.0.0.11/tcp/49670 10.0.0.11/tcp/49668 10.0.0.11/tcp/49667 There are other columns in the csv however. I'm not a coder, I'm just trying to solve a problem, any help much appreciated.
answer count: 3
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/50316933
linked to: http://stackoverflow.com/q/19377969
accepted answer: http://stackoverflow.com/a/50316945
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87649723
has answer: http://stackoverflow.com/a/50316945
possible better answer: http://stackoverflow.com/a/50316933
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/49371629
has title: Combine three columns into one in CSV file with python and pandas
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50316877

amazon-web-services
tags question: http://stackoverflow.com/q/50258562
tags question: http://stackoverflow.com/q/50306675
tags question: http://stackoverflow.com/q/50382930
tags question: http://stackoverflow.com/q/50278679
tags question: http://stackoverflow.com/q/50286653
tags question: http://stackoverflow.com/q/50260854
tags question: http://stackoverflow.com/q/50379463
tags question: http://stackoverflow.com/q/50256995
tags question: http://stackoverflow.com/q/50242843
tags question: http://stackoverflow.com/q/50289221
tags question: http://stackoverflow.com/q/50320602
tags question: http://stackoverflow.com/q/50371705
tags question: http://stackoverflow.com/q/50359668
tags question: http://stackoverflow.com/q/50297189
tags question: http://stackoverflow.com/q/50291963
tags question: http://stackoverflow.com/q/50240486
tags question: http://stackoverflow.com/q/50233013
tags question: http://stackoverflow.com/q/50351375
tags question: http://stackoverflow.com/q/50364540
tags question: http://stackoverflow.com/q/50376650
type: Tag
tags question: http://stackoverflow.com/q/50303936
tags question: http://stackoverflow.com/q/50319337
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/50295437
tags question: http://stackoverflow.com/q/50352842
tags question: http://stackoverflow.com/q/50358354
tags question: http://stackoverflow.com/q/50295964
tags question: http://stackoverflow.com/q/50279057

http://stackoverflow.com/comment/87746376
comment on: http://stackoverflow.com/a/50362209
score: 0
type: Comment
has text: @David Then you could just do the same thing but replace True with the value you want to compare it to and else with another comparison and maybe a default value just in case at the end? Example: if accessResult == 1: then do something
type: AnswerComment

http://stackoverflow.com/q/50261760
answer count: 1
tagged with: django
type: Question
score: 0
has title: Submitting two forms at once in Django
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/50335562
has body: I'm working on a ListView which includes two forms, a search form and a filter form. Both of the forms ultimately change the view's queryset through its get_queryset method. I would like to make it such that when you search for something, the filters are persisted, and vice versa. It is more-or-less working, but there is still one bug: whenever I search for something, a 'CLEAR FILTERS' button appears which should not be there: In the template, the search form is included like so: {% block search_form %} {% with action='dashboard:families' placeholder='Search Families' %} {% include '_search.html' %} {% endwith %} {% endblock %} where _search.html is {% load get %} search close {% if filter_form %} {% for field in filter_form %} {% endfor %} {% endif %} and the custom filter get simply implements the dict.get method: from django import template register = template.Library() @register.filter def get(dictionary, key): return dictionary.get(key) In short, the search form includes a hidden filter_form which gets submitted with the search query. The part of the template which contains the filter form reads as follows: {{ filter_form.guide }} Guide {% if filter_form.is_guide_filled %} clear {% endif %} {{ filter_form.status }} Status {% if filter_form.is_status_filled %} clear {% endif %} {{ filter_form.package }} Company / Package {% if filter_form.is_package_filled %} clear {% endif %} {{ filter_form.next_outreach }} Outreach {% if filter_form.is_next_outreach_filled %} clear {% endif %} {{ filter_form.country }} Country {% if filter_form.is_country_filled %} clear {% endif %} {{ filter_form.vip }} VIP {% if filter_form.is_vip_filled %} clear {% endif %} {{ filter_form.app }} App {% if filter_form.is_app_filled %} clear {% endif %} closeClear Filters Note that the filter form also contains a hidden field named q with the search query. Since this is a CharField, it makes sense to set the value as request.GET.q.strip. The problem is that if I drop into the debugger in the …
has comment: http://stackoverflow.com/comment/87546048
tagged with: django-templates
type: UnansweredQuestion

http://stackoverflow.com/comment/87687334
type: QuestionComment
comment on: http://stackoverflow.com/q/50335016
has text: As for good or bad, there may be some justification for micro-optimizations in fairly extreme cases. But if its just to make it look more like C++ or to avoid writer's cramp, its a bad idea. First, its unclear that you are referring to an instance object, and second, if it is reassigned (`obj_foo = other_thing`) its also unclear whether the writer intended this to be local only or whether its a bug. This reduces maintainability, IMHO.
score: 1
type: Comment

http://stackoverflow.com/comment/92264594
type: Comment
comment on: http://stackoverflow.com/a/50320784
score: 0
type: AnswerComment
has text: I am solving this problem using normalizing input1 and input2 as (xi-min(xi))/ (max(x)-min(x)). Should I normalize Y also in same way. Then how can I bring value of Y back to real value.

http://stackoverflow.com/comment/87560510
type: Comment
type: QuestionComment
score: 0
has text: @Speketwome: you don't know how to code in python a comparison between two timestamps and/or adding/subtracting two times? I don't either. I could google it, but my googling is as good as yours.
comment on: http://stackoverflow.com/q/50271245

http://stackoverflow.com/comment/87502308
comment on: http://stackoverflow.com/q/50242065
score: 0
has text: In your for loop, you can remove other statements and try `df = df.append(dict([item.split(":")]), ignore_index=True)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87613697
type: QuestionComment
comment on: http://stackoverflow.com/q/50298061
has text: Could you add some more details about your question instead of just posting the code.
type: Comment
score: 1

http://stackoverflow.com/q/50351258
downvote count: 0
answer count: 1
tagged with: selenium
tagged with: google-chrome
has answer: http://stackoverflow.com/a/50351480
linked to: http://stackoverflow.com/q/11520341
favorite count: 0
type: Question
has body: The automation task involves the use of Chrome Keyboard shortcuts like Ctrl+t, Ctrl+Tab using Selenium driver with Python. I have used multiple methods that have been defined for using keyboard shortcuts driver.find_element_by_tag_name('html').send_keys(Keys.CONTROL + 't') driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') ActionChains(driver) \ .key_down(Keys.CONTROL).send_keys('t') \ .key_up(Keys.CONTROL).perform() ActionChains(driver).key_down(Keys.CONTROL).key_down('t').key_up(Keys.CONTROL).key_up('t').perform() But none of these seems to work. I have tried this on Chrome, Firefox and Opera. Have used Chromedriver, Geckodriver and Operadriver for the three browsers. Has anyone been able to successfully implement shortcut keys using selenium webdriver and python? To be more explicit, I want to cycle through the open tabs on Chrome using the "Ctrl+t" shortcut. I do not want to access tabs using the switch_to_window method
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87718536
has comment: http://stackoverflow.com/comment/87722413
tagged with: selenium-webdriver
score: 2
upvote count: 2
has title: Automate Google Chrome keyboard shortcuts using Selenium

http://stackoverflow.com/comment/87763391
type: QuestionComment
score: 0
has text: Are you sure that the newly modified subroutine is actually being called?
type: Comment
comment on: http://stackoverflow.com/q/50372481

http://stackoverflow.com/comment/87569436
score: 0
has text: @BryanOakley could you please tell me what tk version you have? I have 8.5.18
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50276202

http://stackoverflow.com/q/50297608
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: sprite
has answer: http://stackoverflow.com/a/50298978
favorite count: 0
type: Question
has body: I am trying to remove the black background from this sprite taken from a sprite sheet. As you'll see in the following is the code and suggested by this post (Transparent spritesheet has black background), I've tried to use the pygame.SRCALPHA flag but this does not seem to work. I've even tried to use the same sprite sheet after converting it with a transparent background and I get the same black border around the Mario sprite. import pygame pygame.init() def imgcolorkey(image, colorkey): if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) return image class SpriteSheet(object): sprite_sheet = None def __init__(self, file_name): #self.sprite_sheet = pygame.image.load(file_name).convert() self.sprite_sheet = pygame.image.load(file_name,pygame.SRCALPHA) #self.sheet = load_image(filename) def imgat(self, rect, colorkey = None): rect = pygame.Rect(rect) #image = pygame.Surface(rect.size).convert() #image = pygame.Surface(rect.size, pygame.SRCALPHA ).convert() image = pygame.Surface(rect.size, pygame.SRCALPHA) #image.fill(transColor) image.blit(self.sprite_sheet, (0, 0), rect) return imgcolorkey(image, colorkey) def imgsat(self, rects, colorkey = None): imgs = [] for rect in rects: imgs.append(self.imgat(rect, colorkey)) return imgs
has title: How to remove black background from sprite in sprite sheet in pygame
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/48119295

http://stackoverflow.com/q/50296004
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87609005
has comment: http://stackoverflow.com/comment/87609171
accepted answer: http://stackoverflow.com/a/50296198
has answer: http://stackoverflow.com/a/50296198
tagged with: python
has answer: http://stackoverflow.com/a/50298208
has body: Python pyLint complains xlsxwriter's worksheet.merge_range() method has error: "No value for argument 'last_col' in method call" and "No value for argument 'data' in method call" When xlsxwriter's documentation gives example worksheet.merge_range('B3:D4', 'Merged Cells', merge_format). With method details: merge_range(first_row, first_col, last_row, last_col, data[, cell_format]) Here is my code that is causing this problem. worksheet.merge_range('C1:E1', 'DATE', format4) Is there any workaround or fix for this problem? I am using xlsxwiter version: &gt;&gt;&gt; print(xlsxwriter.__version__) 0.9.6 and python version: Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32. Thank you in advance
has title: PyLint, XLSXWriter Error: No value for argument 'last_col' in method call merge_range()
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87609398
score: 1
possible better answer: http://stackoverflow.com/a/50298208
tagged with: xlsxwriter
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/50407236
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87935644
has body: You can use the same strategy that the standard random module uses. All the functions in that module are actually methods of a "private" instance of the Random class. That's convenient for most common uses of the module, although sometimes it's useful to create your own instances of Random so that you can have multiple independent random streams. I've adapted your code to illustrate that technique. I named the class and its instance with a single leading underscore, since that's the usual convention in Python to signify a private name, but bear in mind it's simply a convention, Python doesn't do anything to enforce this privacy. mymodule.py class _MyClass: """ This is my custom class """ def my_method(self): return "myValue" _myclass = _MyClass() my_method = _myclass.my_method main_to_be.py from mymodule import my_method print(my_method()) output myValue BTW, the from mymodule import method1, method2 syntax is ok if you only import a small number of names, or it's clear from the name which module it's from (like math module functions and constants), and you don't import from many modules. Otherwise it's better to use this sort of syntax import mymodule as mm # Call a method from the module mm.method1() That way it's obvious which names are local, and which ones are imported and where they're imported from. Sure, it's a little more typing, but it makes the code a whole lot more readable. And it eliminates the possibility of name collisions. FWIW, here's a way to automate adding all of the _myclass methods without explicitly listing them (but remember "explicit is better than implicit"). At the end of "mymodule.py", in place of my_method = _myclass.my_method, add this: globals().update({k: getattr(_myclass, k) for k in _MyClass.__dict__ if not k.startswith('__')}) I'm not comfortable with recommending this, since it directly injects items into the globals() dict. Note that that code will add all class attributes, not just methods. In your question you talk about singl…
has comment: http://stackoverflow.com/comment/87936833
has comment: http://stackoverflow.com/comment/87947071
accepted answer of: http://stackoverflow.com/q/50370744
has comment: http://stackoverflow.com/comment/87936779
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87937085
answers question: http://stackoverflow.com/q/50370744
upvote count: 4
has comment: http://stackoverflow.com/comment/87936961
has comment: http://stackoverflow.com/comment/87936400
has comment: http://stackoverflow.com/comment/87936808
score: 3
has comment: http://stackoverflow.com/comment/87935555
has comment: http://stackoverflow.com/comment/87937214

http://stackoverflow.com/comment/87586520
has text: Related https://stackoverflow.com/questions/1781617/to-understand-from-php-array-to-python
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50285203
type: QuestionComment

http://stackoverflow.com/q/50368024
type: Question
has body: I have a subset of ℕ5, five dimensional vectors whose elements lie in the natural numbers. This subset is defined as the product of intervals [a1, a2]×[b1, b2]×...×[f1, f2], and I would like to enumerate the subsets of size 1, that is the vectors (x1, x2, x3, x4, x5) where x1 is in [a1, a2], x2 is in [b1, b2] etc. What is the best way to do this?
upvote count: 2
accepted answer: http://stackoverflow.com/a/50368130
tagged with: python
tagged with: enumeration
type: AnsweredQuestion
score: 2
answer count: 1
downvote count: 0
has title: Iterate/Enumerate over a subset of N^5 in Python
has answer: http://stackoverflow.com/a/50368130
favorite count: 0
tagged with: iteration

http://stackoverflow.com/comment/87557777
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50246440
has text: I use #2, that is `cv2.convertScaleAbs` to avoid `underflow/overflow`, range in [0, 255] .
type: Comment

http://stackoverflow.com/q/50328482
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50328605
accepted answer: http://stackoverflow.com/a/50328605
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: scrapy
has title: Xpath selecting data after the tag
favorite count: 0
type: Question
has body: I have this html: Full-time 1 year Part-time 2 years I want to get the value of Part-time(After Part-time), which is: 2 years My Xpath code is : //div[@class="sys_key-facts"]/p[strong[contains(text(), "Part-time")]][preceding-sibling::br]/text() but this is returning empty. Please let me know where I am mistaking. Thanks
tagged with: python

http://stackoverflow.com/a/50341222
has comment: http://stackoverflow.com/comment/87698676
has comment: http://stackoverflow.com/comment/87698606
accepted answer of: http://stackoverflow.com/q/50341158
has comment: http://stackoverflow.com/comment/87698649
answers question: http://stackoverflow.com/q/50341158
type: AcceptedAnswer
has body: Because you are returning from the function at the wrong place. What you are currently doing is making the first item in the list Uppercase, appending it to the new list and returning. Hence the result ends up with just one element. Change the return location as below and you'll have the desired output. t = ['a','b','c'] def capitalize_all(t): res = [] for s in t: res.append(s.capitalize()) return res print(capitalize_all(t))
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/87698856
has text: i am using python
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50341291
type: Comment

http://stackoverflow.com/a/50422629
upvote count: 3
downvote count: 0
has body: Here an example of how to achieve what you want. I basically followed the Basemap example how to deal with shapefiles and added a bit of shapely magic to restrict the outlines to the map boundaries. Note that I first tried to extract the map outline from ax.patches, but that somehow didn't work, so I defined a circle which has a radius of boundinglat and transformed it using the Basemap coordinate transformation functionality. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon import shapely from shapely.geometry import Polygon as sPolygon boundinglat = -40 lats = np.arange(-90,boundinglat+1,1) lons = np.arange(0,361,1) X, Y = np.meshgrid(lons, lats) data = np.random.rand(len(lats),len(lons)) fig, ax = plt.subplots(nrows=1, ncols=1, dpi=150) m = Basemap( ax = ax, projection='spstere',boundinglat=boundinglat,lon_0=180, resolution='i',round=True ) xi, yi = m(X,Y) cf = m.contourf(xi,yi,data) #adjust the path to the shapefile here: result = m.readshapefile( 'shapefiles/AntarcticaWGS84_contorno', 'antarctica', zorder = 10, color = 'k', drawbounds = False) #defining the outline of the map as shapely Polygon: rim = [np.linspace(0,360,100),np.ones(100)*boundinglat,] outline = sPolygon(np.asarray(m(rim[0],rim[1])).T) #following Basemap tutorial for shapefiles patches = [] for info, shape in zip(m.antarctica_info, m.antarctica): #instead of a matplotlib Polygon, create first a shapely Polygon poly = sPolygon(shape) #check if the Polygon, or parts of it are inside the map: if poly.intersects(outline): #if yes, cut and insert intersect = poly.intersection(outline) verts = np.array(intersect.exterior.coords.xy) patches.append(Polygon(verts.T, True)) ax.add_collection(PatchCollection( patches, facecolor= 'w', edgecolor='k', linewidths=1., zorder=2 )) plt.show() The result looks like this: Hope this helps.
answers question: http://stackoverflow.com/q/50378688
type: AcceptedAnswer
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/50378688

http://stackoverflow.com/comment/87504495
type: QuestionComment
comment on: http://stackoverflow.com/q/50242948
score: 0
type: Comment
has text: Did you try setting the encoding attribute on the FileField? https://docs.djangoproject.com/en/2.0/ref/files/file/ It's your read method that is failing to decode on the FileField not the TextField.

http://stackoverflow.com/a/70596970
upvote count: 1
has body: Try this, if you have a new version of pip and you just want the result of get_supported function call: python -c "from pip._internal.utils.compatibility_tags import get_supported; print(get_supported())" # output: [<cp310-cp310-win_amd64 @ 2517399109376>, <cp310-abi3-win_amd64 @ 2517399104384>, <cp310-none-win_amd64 @ 2517399161408>, <cp39-abi3-win_amd64 @ 2517399103040>, <cp38-abi3-win_amd64 @ 2517399294208>, <cp37-abi3-win_amd64 @ 2517399294464>, <cp36-abi3-win_amd64 @ 2517399294720>, <cp35-abi3-win_amd64 @ 2517399294976>, <cp34-abi3-win_amd64 @ 2517399295232>, <cp33-abi3-win_amd64 @ 2517399295488>, <cp32-abi3-win_amd64 @ 2517399104000>, <py310-none-win_amd64 @ 2517399296320>, <py3-none-win_amd64 @ 2517398433664>, <py39-none-win_amd64 @ 2517399296512>, <py38-none-win_amd64 @ 2517399296704>, <py37-none-win_amd64 @ 2517399296960>, <py36-none-win_amd64 @ 2517399297216>, <py35-none-win_amd64 @ 2517399297472>, <py34-none-win_amd64 @ 2517399297728>, <py33-none-win_amd64 @ 2517399297984>, <py32-none-win_amd64 @ 2517399298240>, <py31-none-win_amd64 @ 2517399298496>, <py30-none-win_amd64 @ 2517399298752>, <cp310-none-any @ 2517399299264>, <py310-none-any @ 2517399299008>, <py3-none-any @ 2517399299520>, <py39-none-any @ 2517399299840>, <py38-none-any @ 2517399300032>, <py37-none-any @ 2517399300288>, <py36-none-any @ 2517399300544>, <py35-none-any @ 2517399300800>, <py34-none-any @ 2517399301056>, <py33-none-any @ 2517399301312>, <py32-none-any @ 2517399301568>, <py31-none-any @ 2517399301824>, <py30-none-any @ 2517399302080>]
has comment: http://stackoverflow.com/comment/126659860
has comment: http://stackoverflow.com/comment/130922720
answers question: http://stackoverflow.com/q/50248524
type: Answer
score: -1
downvote count: 2
has comment: http://stackoverflow.com/comment/133436005

http://stackoverflow.com/a/50500850
type: Answer
has body: You should define an options_array. Then use that array to populate the dropdown options and value parameters. Once the array is defined you can select a default value by index from the pre-defined array (options_array). options_array = BuildOptions(data.TASKPROVINCE,1) html.Div([ dcc.Dropdown( id='Prov_DD', options=options_array, value=options_array[0], multi=True) ], className='two columns' ), You won't be able to grab a value from dcc.Dropdown(options=...), because it's not actually instantiated yet. Plus, at this time I think the only other way to pragmatically update dcc.Dropdown is by using callbacks. Just define the array first.
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/50334425
score: 7

http://stackoverflow.com/a/50272069
type: Answer
has comment: http://stackoverflow.com/comment/87561430
answers question: http://stackoverflow.com/q/50271719
has comment: http://stackoverflow.com/comment/87561350
score: 0
has body: It was a indentation error in code: x = 25 epsilon = 0.01 numGuesses = 0 low = 0.0 high = max(1.0, x) ans = (high + low)/2.0 while abs(ans**2 - x) &gt;= epsilon: print('low =', low, 'high =', high, 'ans =', ans) numGuesses += 1 if ans**2 &lt; x: low = ans else: high = ans ans = (high + low)/2.0 print ('numGuesses =', numGuesses) print (ans, 'is close to square root of', x) output: ('low =', 0.0, 'high =', 25, 'ans =', 12.5) ('numGuesses =', 1) (6.25, 'is close to square root of', 25) ('low =', 0.0, 'high =', 12.5, 'ans =', 6.25) ('numGuesses =', 2) (3.125, 'is close to square root of', 25) ('low =', 0.0, 'high =', 6.25, 'ans =', 3.125) ('numGuesses =', 3) (4.6875, 'is close to square root of', 25) ('low =', 3.125, 'high =', 6.25, 'ans =', 4.6875) ('numGuesses =', 4) (5.46875, 'is close to square root of', 25) ('low =', 4.6875, 'high =', 6.25, 'ans =', 5.46875) ('numGuesses =', 5) (5.078125, 'is close to square root of', 25) ('low =', 4.6875, 'high =', 5.46875, 'ans =', 5.078125) ('numGuesses =', 6) (4.8828125, 'is close to square root of', 25) ('low =', 4.6875, 'high =', 5.078125, 'ans =', 4.8828125) ('numGuesses =', 7) (4.98046875, 'is close to square root of', 25) ('low =', 4.8828125, 'high =', 5.078125, 'ans =', 4.98046875) ('numGuesses =', 8) (5.029296875, 'is close to square root of', 25) ('low =', 4.98046875, 'high =', 5.078125, 'ans =', 5.029296875) ('numGuesses =', 9) (5.0048828125, 'is close to square root of', 25) ('low =', 4.98046875, 'high =', 5.029296875, 'ans =', 5.0048828125) ('numGuesses =', 10) (4.99267578125, 'is close to square root of', 25) ('low =', 4.98046875, 'high =', 5.0048828125, 'ans =', 4.99267578125) ('numGuesses =', 11) (4.998779296875, 'is close to square root of', 25) ('low =', 4.99267578125, 'high =', 5.0048828125, 'ans =', 4.998779296875) ('numGuesses =', 12) (5.0018310546875, 'is close to square root of', 25) ('low =', 4.998779296875, 'high =', 5.0048828125, 'ans =', 5.0018310546875) ('numGuesses =', 13) (5.00030517578125, 'is clos…

http://stackoverflow.com/q/50351664
answer count: 1
tagged with: keyword
has comment: http://stackoverflow.com/comment/87719324
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/471546
downvote count: 1
has body: I couldn't find the official glossary of python operators but at least it seems that operator library of python doesn't include and or or keyword. They do have operator.and_, but it's for bitwise and operator(&amp;). What makes me more confused is that they do include is or not keywords as operators. In short, isn't and(and or) an operator? If it isn't, what is the standard of being an operator in Python? I though I'm pretty familiar with python but this problem confuses me a lot at the moment.
score: 0
tagged with: syntax
duplicate of: http://stackoverflow.com/q/19186564
tagged with: operator-keyword
has comment: http://stackoverflow.com/comment/87719232
has answer: http://stackoverflow.com/a/50351699
linked to: http://stackoverflow.com/q/19186564
favorite count: 0
type: Question
has title: Isn't the keyword "and" an operator in python? Why?
tagged with: grammar
type: UnansweredQuestion

http://stackoverflow.com/a/50342690
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50342606
has body: You can use send_email with to. class ContactForm(forms.Form): title = forms.CharField() email = forms.EmailField() contents = forms.CharField(widget=forms.Textarea) def send_email(self, to): subject = self.cleaned_data['title'] from_email = self.cleaned_data['email'] contents = self.cleaned_data['contents'] message = '\n\ncontens:\n' + contents + '\n\nfrom to:\n' + from_email send_mail(subject, message, settings.EMAIL_HOST_USER, to) And pass to list from form_valid() in view. ... def form_valid(self, form): # set to email list for your model # maybe you want to this? to = [self.object.mailAddress] form.send_email(to) return super().form_valid(form)
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/87702254
answers question: http://stackoverflow.com/q/50342606

http://stackoverflow.com/a/50341028
has body: I don't feel terribly good about this.. but oh well. d = pd.Series( df.ImpactRate.values, [list(zip(df.Date, df.Category)), df.Location], name='Impact Rate' ) s = d.sum(level=0) t = d.div(s, level=0).rename('Break Down') f = lambda t: ' '.join(f'{l} ({v*100:0.2f}%)' for (_, l), v in t.items()) pd.DataFrame(pd.concat( [s, t.groupby(level=0).apply(f)], axis=1 ).to_dict()).rename_axis(['Date', 'Category']).reset_index() Date Category Break Down Impact Rate 0 2018-04-22 Outage MT (29.33%) ND (14.41%) SD (56.26%) 0.17708 1 2018-04-24 Transport TX (100.00%) 0.03111
answers question: http://stackoverflow.com/q/50340717
upvote count: 1
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/50235218
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/50235365
has body: I have the following code: import xlrd import xlwt import xlsxwriter import openpyxl import sys import os string0="Username" stringhost="Host" string1="Last password change" string2="Password expires" string3="Password inactive" string4="Account expires" string5="Minimum number of days between password change" string6="Maximum number of days between password change" string7="Number of days of warning before password expires" hostid="---" workbook=xlsxwriter.Workbook('/media/sf_vboxshared/sample.xlsx') worksheet1=workbook.add_worksheet('Sheet1') worksheet1.write(0,0,string0) worksheet1.write(0,1,stringhost) worksheet1.write(0,2,string1) worksheet1.write(0,3,string2) worksheet1.write(0,4,string3) worksheet1.write(0,5,string4) worksheet1.write(0,6,string5) worksheet1.write(0,7,string6) worksheet1.write(0,8,string7) num1=1 num2=1 num3=1 num4=1 num5=1 num6=1 num7=1 num8=1 num9=1 contenttail=[] with open("users.log",'r') as dump: for num, line in enumerate(dump): if string1 in line: tail=line.split(string1)[1] tail=tail.strip() tail=tail.lstrip(":") worksheet1.write(num1,2,tail) num1=num1+1 elif string2 in line: tail2=line.split(string2)[1] tail2=tail2.strip() tail2=tail2.lstrip(":") worksheet1.write(num2,3,tail2) num2=num2+1 elif string3 in line: tail=line.split(string3)[1] tail=tail.strip() tail=tail.lstrip(":") worksheet1.write(num3,4,tail) num3=num3+1 elif string4 in line: tail=line.split(string4)[1] tail=tail.strip() tail=tail.lstrip(":") worksheet1.write(num4,5,tail) num4=num4+1 elif string5 in line: tail=line.split(string5)[1] tail=tail.strip() tail=tail.lstrip(":") worksheet1.write(num5,6,tail) num5=num5+1 elif string6 in line: tail=line.split(string6)[1] tail=tail.strip() tail=tail.lstrip(":") worksheet1.write(num6,7,tail) num6=num6+1 elif string7 in line: tail=line.split(string7)[1] tail=tail.strip() tail=tail.lstrip(":") contenttail.append(tail) worksheet1.write(num7,8,tail) num7=num7+1 elif hostid in line: words=line.split(hostid)[1] print words contenthost=[]…
score: 0
answer count: 1
type: Question
type: UnansweredQuestion
has title: Python script overwrite rows in Excel

http://stackoverflow.com/comment/87638296
has text: I've tried reuploading files as well as adding new ones with the same result. :/ This is driving me nuts haha it should be so simple
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50310995

http://stackoverflow.com/q/50372759
tagged with: keras
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87762199
has title: Executing CTNK algorithm in Weka. Reproducibility issues
has body: I want to execute a python script in Weka that is using Keras + CTNK as backend and so, build a neural network. The script works finem but every time that I want to execute it, I have a different output. How could I keep the reproducibility in each execution? Thanks
linked to: http://stackoverflow.com/q/32419510
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87761664
tagged with: neural-network
tagged with: python

http://stackoverflow.com/comment/87481597
type: Comment
type: QuestionComment
has text: Will you be trying to access the PI behind the same firewall?
comment on: http://stackoverflow.com/q/50232079
score: 0

gmail
type: Tag
tags question: http://stackoverflow.com/q/50238184
tag name: gmail
tags question: http://stackoverflow.com/q/50298042
tags question: http://stackoverflow.com/q/50257795

http://stackoverflow.com/comment/87627639
type: QuestionComment
has text: @ninesalt yes, it could be also spaces or something like that
type: Comment
comment on: http://stackoverflow.com/q/50305682
score: 0

http://stackoverflow.com/q/50264247
tagged with: python-3.x
tagged with: python-import
has comment: http://stackoverflow.com/comment/87551070
duplicate of: http://stackoverflow.com/q/5128845
answer count: 0
type: UnansweredQuestion
downvote count: 0
favorite count: 0
has body: I installed python 3.6 from source. Python seems working fine but I'm unable to import openssl 1.1.1 (a pre-release that I need to use). I think that there is a path issue but not sure. When I try to import ssl from python, this is the output I get: ~/Downloads/Python-3.6.5$ python3 Python 3.6.5 (default, May 9 2018, 15:43:39) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ssl Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/ssl.py", line 101, in &lt;module&gt; import _ssl # if we can't import it, let the error propagate ModuleNotFoundError: No module named '_ssl' Any suggestions? When I installed openssl, I grabbed the source code then: ./config sudo make sudo make install It seems that openssl has been installed correctly. The output is mostly similar to this path: /usr/local/share/man/man5/config.5 I then Then uncommented these two lines in Python-3.6.5/Module/Setup.dist _socket socketmodule.c And # Socket module helper for SSL support; you must comment out the other # socket line above, and possibly edit the SSL variable: SSL=/usr/local/ssl _ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto Then, When I try to import ssl in python, I get this error: Python 3.6.5 (default, May 9 2018, 15:43:39) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ssl Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/ssl.py", line 101, in &lt;module&gt; import _ssl # if we can't import it, let the error propagate ModuleNotFoundError: No module named '_ssl' Can you please help? What can be the cause of the problem?
tagged with: ssl
linked to: http://stackoverflow.com/q/5128845
tagged with: python
upvote count: 6
score: 6
has title: Can't import ssl in python3.6: ModuleNotFoundError: No module named '_ssl'
type: Question
tagged with: openssl

http://stackoverflow.com/comment/87729733
has text: Using my own (reduced) variable values (r1, r1title, r2, r2title,) the code worked properly for me
comment on: http://stackoverflow.com/q/50352511
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50295008
linked to: http://stackoverflow.com/q/12837811
has body: I issue this statement: db = cx_Oracle.connect("user/pass@IP/BKTDW") and I get this error: Traceback (most recent call last): File "", line 1, in cx_Oracle.DatabaseError: Error while trying to retrieve text for error ORA-01804 It seems that connect method doen't work at all. I have installed the Oracle Client and I am connecting normally via Toad or Sql Developer. Please Help!
tagged with: python
has answer: http://stackoverflow.com/a/62171520
accepted answer: http://stackoverflow.com/a/50345205
type: AnsweredQuestion
score: 0
answer count: 2
has title: Can't connect with cx_Oracle of Python to oracle remote database
has answer: http://stackoverflow.com/a/50345205
tagged with: cx-oracle
possible better answer: http://stackoverflow.com/a/62171520
has comment: http://stackoverflow.com/comment/87607859
type: Question
tagged with: oracle-database

http://stackoverflow.com/comment/87662702
comment on: http://stackoverflow.com/a/50323470
score: 0
type: Comment
type: AnswerComment
has text: Still fails for `"/* fake comment *** */"`.

http://stackoverflow.com/a/50356351
type: Answer
has body: You can't have two programs use the same serial port. Close the serial monitor in the Arduino IDE. PS: You are also trying to read lines in Python, but you aren't sending them from the Arduino. Print the numbers as lines with Serial.println(rand);.
has comment: http://stackoverflow.com/comment/87739398
upvote count: 6
has comment: http://stackoverflow.com/comment/87729728
has comment: http://stackoverflow.com/comment/87730797
has comment: http://stackoverflow.com/comment/87739526
has comment: http://stackoverflow.com/comment/87763977
downvote count: 0
has comment: http://stackoverflow.com/comment/87730544
answers question: http://stackoverflow.com/q/50356224
has comment: http://stackoverflow.com/comment/87737667
score: 6

http://stackoverflow.com/a/50281435
has comment: http://stackoverflow.com/comment/87579591
has body: If you want the longest word, the key function should make use of len(): max_word = max(word_dict, key=len) which would be the same as: max_word = max(word_dict, key=lambda x: len(x)) The way you are using max() would give you the last word in lexicographic order.
type: Answer
has comment: http://stackoverflow.com/comment/87579786
answers question: http://stackoverflow.com/q/50281383
has comment: http://stackoverflow.com/comment/87579891
has comment: http://stackoverflow.com/comment/87579692
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87747431
has text: i just happened to find out. Anyway. Thanks a lot @jpp
type: AnswerComment
comment on: http://stackoverflow.com/a/50365615
score: 1
type: Comment

http://stackoverflow.com/comment/87572093
score: 0
comment on: http://stackoverflow.com/q/50277509
type: QuestionComment
type: Comment
has text: @ThierryLathuille It should keep every list in the list where the second value of the inside list is different to either the one before it or the one after it. Also the very large numbers are just Unix time stamps, they don't affect the rule, the rule is only about the second number

excel
tags question: http://stackoverflow.com/q/50353740
tags question: http://stackoverflow.com/q/50247438
tags question: http://stackoverflow.com/q/50364847
tags question: http://stackoverflow.com/q/50280796
tags question: http://stackoverflow.com/q/50307124
tags question: http://stackoverflow.com/q/50346449
tags question: http://stackoverflow.com/q/50233709
tags question: http://stackoverflow.com/q/50306355
tags question: http://stackoverflow.com/q/50254018
tags question: http://stackoverflow.com/q/50290349
tags question: http://stackoverflow.com/q/50348405
tag name: excel
tags question: http://stackoverflow.com/q/50235218
tags question: http://stackoverflow.com/q/50286206
tags question: http://stackoverflow.com/q/50277478
tags question: http://stackoverflow.com/q/50287024
tags question: http://stackoverflow.com/q/50274270
tags question: http://stackoverflow.com/q/50358812
tags question: http://stackoverflow.com/q/50245208
type: Tag
tags question: http://stackoverflow.com/q/50236928
tags question: http://stackoverflow.com/q/50309364
tags question: http://stackoverflow.com/q/50331329
tags question: http://stackoverflow.com/q/50298244
tags question: http://stackoverflow.com/q/50235529
tags question: http://stackoverflow.com/q/50351011
tags question: http://stackoverflow.com/q/50332735
tags question: http://stackoverflow.com/q/50307145
tags question: http://stackoverflow.com/q/50335837
tags question: http://stackoverflow.com/q/50282961
tags question: http://stackoverflow.com/q/50334591
tags question: http://stackoverflow.com/q/50304867
tags question: http://stackoverflow.com/q/50248467
tags question: http://stackoverflow.com/q/50345819
tags question: http://stackoverflow.com/q/50347906
tags question: http://stackoverflow.com/q/50283461
tags question: http://stackoverflow.com/q/50373813
tags question: http://stackoverflow.com/q/50291709
tags question: http://stackoverflow.com/q/50281305
tags question: http://stackoverflow.com/q/50275306
tags question: http://stackoverflow.com/q/50237603
tags question: http://stackoverflow.com/q/50376540

http://stackoverflow.com/q/50358310
possible better answer: http://stackoverflow.com/a/50373919
has comment: http://stackoverflow.com/comment/115866204
downvote count: 1
favorite count: 0
type: Question
tagged with: lapack
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50381112
has answer: http://stackoverflow.com/a/50381112
has comment: http://stackoverflow.com/comment/87784205
has title: how does numpy.linalg.eigh vs numpy.linalg.svd?
score: 5
tagged with: python
has answer: http://stackoverflow.com/a/50373919
upvote count: 6
linked to: http://stackoverflow.com/q/41109122
tagged with: numerical
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/115853792
answer count: 2
has body: problem description For a square matrix, one can obtain the SVD X= USV' decomposition, by using simply numpy.linalg.svd u,s,vh = numpy.linalg.svd(X) routine or numpy.linalg.eigh, to compute the eig decomposition on Hermitian matrix X'X and XX' Are they using the same algorithm? Calling the same Lapack routine? Is there any difference in terms of speed? and stability?
has comment: http://stackoverflow.com/comment/87784113

http://stackoverflow.com/comment/87757709
comment on: http://stackoverflow.com/q/50370917
has text: isn't the whole point of lambda functions to have something quick and disposable? put a comment after it with a `#` maybe?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50329426
answer count: 1
downvote count: 1
favorite count: 0
has body: I have a problem using the MinMaxScaler from scikit-learn and cannot interpret the error message correctly, nor can I find information about it. TypeError: ufunc 'subtract' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind'' For the fit I used a matrix with the following formats: (275, 821), numpy.ndarray, numpy.float64 The correctly transformed output was: (275, 821), numpy.ndarray, numpy.float64 My input for the "way back" with inverse_transform: (206, 821), numpy.ndarray, numpy.float64 I have done this before and it worked without any problems. Obviously something about my data is different now, which I can't see and is not related to the format? I would be happy if someone could explain the error message or give me another hint about what went wrong. numpy 1.13.1, pandas 0.20.3, scikit-learn 0.19.0, python 2.7.6 Thank you very much! I discovered that the MinMaxScalers attributes have been saved separately by joblib. The min_ attribute appears to be: joblib.numpy_pickle.NDArrayWrapper at 0x7fbc302253d0 For clarification: I save the scaler with joblib and load it before inverse_transform. ### X and Y are two matrices with values between 0-6000 X_frame = pd.DataFrame(X) Y_frame= pd.DataFrame(Y) XYdata = pd.concat([X_frame, Y_frame], axis=1) XYdata = XYdata.as_matrix() mm = MinMaxScaler((0,1)) XY_new = mm.fit_transform(XYdata) np.save('data',XY_new) filename_scaler = 'scaler.sav' joblib.dump(mm, filename_scaler) ### There's a prediction algorithm in between I can't add because of company restrictions, the code returns the matrix data scaler = joblib.load('scaler.sav') new_data1 = scaler.inverse_transform(data)
score: -1
has comment: http://stackoverflow.com/comment/87676041
has answer: http://stackoverflow.com/a/50330294
tagged with: numpy
type: Question
has comment: http://stackoverflow.com/comment/87675315
has title: scikit-learn - MinMaxScaler: TypeError: ufunc 'subtract'
tagged with: python
has comment: http://stackoverflow.com/comment/87675743
type: AnsweredQuestion
upvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/50330294

http://stackoverflow.com/comment/87572760
type: Comment
has text: @Rob pass the column over which you want to evaluate duplicity. `drop_duplicates('ind')`
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50277625

http://stackoverflow.com/q/50245888
has comment: http://stackoverflow.com/comment/87509515
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/50246124
has body: Can somebody please point out the error in the code below? The last line keeps throwing an error: tmp = img1[coords] IndexError: index 409 is out of bounds for axis 0 with size 352 I'm only shifting the indices by 10 so I don't understand how I'm suddenly out of bounds in img1 img1 = np.random.randint(0,256, (352,870, 3), dtype=np.uint8) img2 = np.random.randint(0,256, (44,853, 3), dtype=np.uint8) coords = np.where(img2[:, :, 2] &gt;= 250) coords = np.transpose(np.transpose(coords)+(10, 10)) tmp = img1[coords]
has comment: http://stackoverflow.com/comment/87509563
downvote count: 2
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87509430
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50246057
possible better answer: http://stackoverflow.com/a/50246057
tagged with: numpy-indexing
accepted answer: http://stackoverflow.com/a/50246124
has title: numpy index array throws out of bounds exception

http://stackoverflow.com/comment/87580415
has text: See https://ideone.com/hBMEP9
comment on: http://stackoverflow.com/q/50281898
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50233034
upvote count: 1
has body: Have a look here. It says that input_formats should be: A list of strings representing the input formats which may be used to parse the date Try passing input_formats=['YYYY-MM-DDThh:mm:ssZ'] or ['iso-8601'] Also you may want to try and set format as well.
has comment: http://stackoverflow.com/comment/87483772
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87483522
answers question: http://stackoverflow.com/q/50232634
has comment: http://stackoverflow.com/comment/87484362
type: Answer

http://stackoverflow.com/comment/87691997
type: Comment
score: 1
has text: The first argument to `read_csv` needs to be a filename, not a list of filenames.
type: QuestionComment
comment on: http://stackoverflow.com/q/50337843

http://stackoverflow.com/q/50241077
has body: I want to blend a video on top of another one using an alpha video. This is my code. It works perfectly but the problem is that this code isn't efficient at all and that's because of /255 parts. It is slow and has lagging probelm. Is there a standard and efficient way for doing this? I want results be real-time. Thanks import cv2 import numpy as np def main(): foreground = cv2.VideoCapture('circle.mp4') background = cv2.VideoCapture('video.MP4') alpha = cv2.VideoCapture('circle_alpha.mp4') while foreground.isOpened(): fr_foreground = foreground.read()[1]/255 fr_background = background.read()[1]/255 fr_alpha = alpha.read()[1]/255 cv2.imshow('My Image',cmb(fr_foreground,fr_background,fr_alpha)) if cv2.waitKey(1) == ord('q'): break cv2.destroyAllWindows def cmb(fg,bg,a): return fg * a + bg * (1-a) if __name__ == '__main__': main()
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87504114
has answer: http://stackoverflow.com/a/50252768
tagged with: python
possible better answer: http://stackoverflow.com/a/50246440
tagged with: opencv
type: AnsweredQuestion
tagged with: lag
has answer: http://stackoverflow.com/a/50246440
accepted answer: http://stackoverflow.com/a/50244613
has title: Alpha Blending using OpenCV for videos
answer count: 3
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/50244613
tagged with: alphablending
has comment: http://stackoverflow.com/comment/87500848
downvote count: 0

http://stackoverflow.com/a/50259161
upvote count: 1
answers question: http://stackoverflow.com/q/50259042
has body: Use this if coffee price cannot be zero coffee = 1 # or any other positive number while coffee &gt; 0: coffee = int(input("Enter price of coffee or a negative value to stop: ")) if coffee &gt; 0: if coffee price can be zero, use this coffee = 0 while coffee &gt;= 0: coffee = int(input("Enter price of coffee or a negative value to stop: ")) if coffee &gt;= 0:
accepted answer of: http://stackoverflow.com/q/50259042
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50241771
tagged with: mxnet
tagged with: python
has title: Getting error while infering sagemaker endpoint
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: amazon-sagemaker
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87571370
has answer: http://stackoverflow.com/a/50242110
has body: I created training job in sagemaker with my own training and inference code using MXNet framework. I am able to train the model successfully and created endpoint as well. But while inferring the model, I am getting the following error: ‘ClientError: An error occurred (413) when calling the InvokeEndpoint operation: HTTP content length exceeded 5246976 bytes.’ What I understood from my research is the error is due to the size of the image. The image shape is (480, 512, 3). I trained the model with images of same shape (480, 512, 3). When I resized the image to (240, 256), the error was gone. But producing another error 'shape inconsistent in convolution' as I the trained the model with images of size (480, 512). I didn’t understand why I am getting this error while inferring. Can't we use images of larger size to infer the model? Any suggestions will be helpful Thanks, Harathi
type: UnansweredQuestion

http://stackoverflow.com/comment/87527229
comment on: http://stackoverflow.com/a/50254160
has text: How does the `D=df.stack()` part work if your column has a name such as `There are spaces in this header`? Also, how do you apply this to a selection of an existing dataframe, e.g. without creating a new one?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87504366
type: QuestionComment
has text: @generalhenry this has been taken care in the prod code, forgot to add here. Thanks for that I've updated now.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50241000

http://stackoverflow.com/a/50307890
has comment: http://stackoverflow.com/comment/87632067
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50307871
has comment: http://stackoverflow.com/comment/87632091
answers question: http://stackoverflow.com/q/50307871
has comment: http://stackoverflow.com/comment/87632260
has comment: http://stackoverflow.com/comment/87632315
type: Answer
has comment: http://stackoverflow.com/comment/87632163
has comment: http://stackoverflow.com/comment/87632480
has comment: http://stackoverflow.com/comment/87632556
has comment: http://stackoverflow.com/comment/87632400
has body: i is only the filename. you should give the full path to the program. example: let first file be stackoverflow.json you try to open with filename such as: open('stackoverflow.json', 'r') what you should do is: open('C:/Users/new/stackoverflow.json', 'r') so the code should do it: files = [] base_path = 'C:/Users/new' for i in os.listdir(base_path): if i.endswith('.json'): full_path = '%s/%s' % (base_path, i) files.append(open(full_path, 'r', encoding='utf-8').read()) print("starting to print json documents...") for single_file in files: print(single_file) print("printing done") EDIT: as @khelwood states, you should also replace read with read().
has comment: http://stackoverflow.com/comment/87632122
has comment: http://stackoverflow.com/comment/87632361
score: 1
has comment: http://stackoverflow.com/comment/87632461
has comment: http://stackoverflow.com/comment/87632419
has comment: http://stackoverflow.com/comment/87631872
has comment: http://stackoverflow.com/comment/87632492
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87632377

http://stackoverflow.com/a/50245586
type: Answer
answers question: http://stackoverflow.com/q/50245522
has body: Try this: with open('file.txt') as file: l=[] for line in file.readlines(): line_array = line.split(' ') l.append=(line_array[0], line_array[4], line_array[7]) after this the l will be : [ ('Loss', '2.500000e+00', '-0.578') ] tell me if you need those values in different structure not a list of tuples.
downvote count: 0
upvote count: 1
score: 1

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/50310374

http://stackoverflow.com/q/50283008
accepted answer: http://stackoverflow.com/a/50283242
tagged with: numpy
type: AnsweredQuestion
score: 0
tagged with: arrays
tagged with: python
has body: I read in numpy.delete documentation that given an array arr: mask = np.ones(len(arr), dtype=bool) mask[[0,2,4]] = False result = arr[mask,...] Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask. From this I can see what arr[mask,...] does, and I have tested how it works and am able to use this to mask arrays. But I'm just curious, what exactly is this arr[mask,...] syntax? i.e. How do I use this syntax generally?
answer count: 1
has title: how does numpy masking using arr[mask, ...] work?
has answer: http://stackoverflow.com/a/50283242
type: Question
tagged with: mask

http://stackoverflow.com/q/50277438
accepted answer: http://stackoverflow.com/a/50277906
downvote count: 0
tagged with: file
upvote count: 1
favorite count: 0
has body: I have to read and store a data file composed of 3 columns and N row *Number of block .. here a simple example: z=3 1 2 3 2 5 6 1 5 7 z=2 1 3 9 2 5 7 which is the best way to read this file and store several block of z row using python ? EDIT: I have to store them into a separate blocks (indexed) for example in the above example I should have block[0]=[[1 2 3],[2 5 6],[1 5 7]] block[1] = [[1 3 9],[2 57]] @shahaf e come lo indicizzo ? scusa ma sono un noob in python :) could some body explain me how to indicize the several blocks ? and in particular I wrote z= N but in reality it's ZONE I= 41 F=POINT TIME T= 0.0000715363 I have to catch 41 .. and read and store the follow 41 line, than after a couple of white line I encounter another ZONE section .. I don't know how many zone I there are in the file ..
type: Question
has title: Python : read a data set file
tagged with: database
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/50277906
possible better answer: http://stackoverflow.com/a/50277721
has answer: http://stackoverflow.com/a/50277721
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/50232725
tagged with: loops
type: Question
accepted answer: http://stackoverflow.com/a/50233603
tagged with: algorithm
tagged with: python
has body: I have a python code that gets all the rows from a table and inserts it into another in blocks of 1000. allRows = db.getAllRows() #12.345 elements package = [] for idx, pr in enumerate(allRows): package.append(pr) if (idx + 1) % 1000 == 0: db.inserPackage(package) package = [] this code works and inserts the package of 1000 rows, but if the length of the list is, for example 12.345, I'm losing the rest of the list after 12.000 (345) elements. How could I get the remain of the list and insert it?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50233603
has title: Get remainder of a list
answer count: 2
has answer: http://stackoverflow.com/a/50232758
possible better answer: http://stackoverflow.com/a/50232758

http://stackoverflow.com/comment/87660868
score: 0
has text: I did not mention or imply any benefit, but it _is_ an option.
comment on: http://stackoverflow.com/a/50322491
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87737228
comment on: http://stackoverflow.com/a/50360280
score: 0
type: AnswerComment
type: Comment
has text: i'm pretty new to python so i will need some time to digest the details but this looks incredbly elegant (+1)

http://stackoverflow.com/q/50320813
has body: Can someone please explain what's happening me or am I missing something really obvious? import pandas as pd df = pd.DataFrame([[0.0094909865]]) df = df.round(9) print(df) This gives me 0.009490986. I was expecting a rounded value of 0.009490987 Can someone help me understand? I am using Pandas '0.20.3'
tagged with: pandas
has title: Pandas rounding decimals not working
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50320846
score: 5
has answer: http://stackoverflow.com/a/50320846
tagged with: rounding
upvote count: 5
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/50321308
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87659422
has title: How to read a txt.file with urllib
type: Question
has comment: http://stackoverflow.com/comment/87659486
has answer: http://stackoverflow.com/a/50321744
has comment: http://stackoverflow.com/comment/87658948
tagged with: python
score: -1
has body: I am trying to read the contents of a .txt file. Contained within the file is a URLs list. I need to open each of the URLs with urllib. I get the error shown below. Can someone explain me how to fix it? data =(urllib.request.urlopen(r"C:\Users\diese\OneDrive\Documentos\GitHub\MCPP_diego_ramirez\Proyectof\urlsDow.txt") for line in data: print (line) URLError: &lt;urlopen error unknown url type: c&gt;
accepted answer: http://stackoverflow.com/a/50321744
type: AnsweredQuestion
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87658612
tagged with: url
has comment: http://stackoverflow.com/comment/87658663

http://stackoverflow.com/comment/87580594
has text: The photon keeps moving in the same direction until it undergoes a collision. Only when it collides do you randomly set a new direction, otherwise you compute its new position based on the previous direction. There is no distribution of distances since the photon always moves the same distance during each step.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50281548
type: Comment

http://stackoverflow.com/comment/87502529
score: 0
comment on: http://stackoverflow.com/q/50242232
type: QuestionComment
has text: @WillianVieira If you read the post, you will see that I need to access `index.html` as `/` and `about.html` as `/about`.
type: Comment

http://stackoverflow.com/comment/87854321
type: QuestionComment
comment on: http://stackoverflow.com/q/50332699
score: 0
has text: Trying to use both of them actually doesn't work very well at the moment - slot descriptors will conflict with defaults or field objects.
type: Comment

http://stackoverflow.com/a/50381707
score: 0
type: Answer
has body: It looks like showMaximized() was only applied to the displayed figure and not to the saved one, so the only solution I found is to get rid of showMaximized(), find the size of the screen with tkinter, and use these dimensions to specify the size of the figure: import tkinter as tk root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() returns the height and width of the screen in pixels mydpi = 100 fig, ax = plt.subplots(figsize=(width/mydpi, height/mydpi), dpi=mydpi) sets the dpi of the figure and uses the dimensions found previously to set the size of the figure as full screen. Finally, the full code is: import numpy as np import matplotlib.pyplot as plt import tkinter as tk root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() mydpi = 100 x = np.arange(0,10,0.01) y1 = np.sin(x) y2 = np.sin(3*x) y3 = np.sin(5*x) fig, ax = plt.subplots(figsize=(width/mydpi, height/mydpi), dpi=mydpi) plt.subplots_adjust(bottom=0.09, top=0.96, right=0.97, left=0.07) plt.plot(x,y1, 'C0', linewidth = 2) plt.plot(x,y2, 'C1', linewidth = 2) plt.plot(x,y3, 'C2', linewidth = 2) plt.xlabel('x label', fontsize=18) plt.ylabel('y label', fontsize=18) plt.xticks(color='k', size=16) plt.yticks(color='k', size=16) plt.grid() plt.legend(['blue', 'red', 'green'], fontsize=16) fig.savefig('coco_gcf-dpi.png', dpi=plt.gcf().dpi, bbox_inches = 'tight') plt.show() And now, I finally have my plot saved exactly as I see it displayed on my screen!
answers question: http://stackoverflow.com/q/50341684

greatest-n-per-group
tag name: greatest-n-per-group
tags question: http://stackoverflow.com/q/50381064
type: Tag

http://stackoverflow.com/q/50292316
tagged with: python
has comment: http://stackoverflow.com/comment/87601152
downvote count: 6
tagged with: bash
has title: How to export bash scripts to python?
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/50292511
has comment: http://stackoverflow.com/comment/87601014
favorite count: 0
type: Question
has body: I want to export this code in Python: #!/usr/bin/env bash export LANG="en_US.UTF-8" LC_ALL="en_US.UTF-8" echo Starting carddav sync at $(date) mkdir -p carddav cat vdirsyncer.config.template | sed "s/VDIRSYNC_USER/$VDIRSYNC_USER/; s/VDIRSYNC_PASS/$VDIRSYNC_PASS/" &gt; vdirsyncer.config yes | vdirsyncer -c vdirsyncer.config discover vdirsyncer -c vdirsyncer.config sync rm vdirsyncer.config echo Carddav sync done, starting carddavsync I tried to take advantage of bash2py, but did not succeed.
tagged with: python-3.x
score: -6
has answer: http://stackoverflow.com/a/50292521
has comment: http://stackoverflow.com/comment/87601159
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50292579

http://stackoverflow.com/comment/87716229
comment on: http://stackoverflow.com/q/50350051
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest well you need to make an azimuthal selection/projection because the cross section has a direction and a width
score: 0

http://stackoverflow.com/q/50238052
tagged with: python
tagged with: python-2.7
has answer: http://stackoverflow.com/a/50240551
type: AnsweredQuestion
has title: Writing an error function to feed scipy.optimize.least_squares in python
has comment: http://stackoverflow.com/comment/87494319
downvote count: 0
upvote count: 1
score: 1
has body: I am trying to fit some data to a non-linear function, and wanted to play with the model function to see if I could get a better fitting than the one I already have. As I was trying to figure things out, I came up with more questions. I have: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import least_squares from scipy.optimize import curve_fit temperature = [ 38., 40., 42., 44., 46., 48., 50., 52., 54., 56., 58., 60., 62., 64., 66., 68., 70., 71.9, 73.81, 75.69, 77.6, 79.49, 81.38, 83.29, 85.19, 87.11, 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 100. ] exp_rate = [ 8.71171203e-01, 1.15342914e+00, 1.39178845e+00, 1.66700007e+00, 1.96267002e+00, 2.32390602e+00, 2.68542886e+00, 3.13116448e+00, 3.60152705e+00, 4.12575295e+00, 4.67617489e+00, 5.29745193e+00, 6.06796117e+00, 6.99056274e+00, 8.40124338e+00, 1.04449551e+01, 1.38236107e+01, 1.96811651e+01, 2.91545190e+01, 4.67945718e+01, 7.36377025e+01, 1.19474313e+02, 1.91938580e+02, 3.07692308e+02, 4.92610837e+02, 7.87401575e+02, 1.20738388e+03, 1.51773627e+03, 1.89049140e+03, 2.33880380e+03, 2.90892166e+03, 3.53003887e+03, 4.28065700e+03, 5.15251443e+03, 6.18043152e+03, 7.49720729e+03, 9.57524225e+03, 1.17175325e+04] def Orbach_Raman(temperature, pre_1, U_1, C, n): # This is my model function return np.array( (1./pre_1)*np.exp(-U_1/(temperature)) + C*(temperature**n) ) pre_1, U_1, C, n = np.array([1.17E-12, 1815, 1E-6, 3.77]) # Define the starting guess guess = pre_1, U_1, C, n popt_stret, pcov = curve_fit(Orbach_Raman, temperature, exp_rate, p0=guess) But curve_fit() cannot find the optimal parameters and it raises File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 680, in curve_fit raise RuntimeError("Optimal parameters not found: " + errmsg) RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000. which is very weird as the starting guess already provides a very good fit of the data plt.loglog(temperature, exp_rate, '-o'…
answer count: 1
tagged with: scipy
favorite count: 0
accepted answer: http://stackoverflow.com/a/50240551
tagged with: numpy
type: Question
tagged with: curve-fitting

http://stackoverflow.com/a/50275224
type: Answer
has comment: http://stackoverflow.com/comment/87754007
has body: Based on your error message: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "'C:\\Users\\NAME\\Desktop'" I guess you entered 'C:\Users\NAME\Desktop' into the input prompt. Omit quotes ('') and then you should be good to go. Otherwise you will end up passing this string to os.chdir: "'C:\Users\NAME\Desktop'" which is not a valid path.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50275028
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50275028

http://stackoverflow.com/q/50297863
type: Question
tagged with: python-3.x
has body: I'm trying to create a polar projection using matplotlib.pyplot.subplots() but I get the error projection is not defined when I try to pass a dictionary to matplotlib.pyplot.subplots() My code: import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=1, ncols=2, subplot_kw={projection:'polar'}) However plt.subplot(1,1,1, projection='polar') works as expected. The documentation for plt.subplots() says that the dictionary in subplot_kw will be passed to add.subplot() which takes projection as a optional parameter so I'm not sure what my mistake is.
score: 3
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50298046
has answer: http://stackoverflow.com/a/76723467
possible better answer: http://stackoverflow.com/a/76723467
tagged with: python
has title: Using subplot_kw in matplotlib to create a polar projection in subplots
type: AnsweredQuestion
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/50298046
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50263840
tagged with: spss-files
has title: Read SPSS Viewer files (.spv) with Python
type: Question
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
favorite count: 0
score: 3
has body: There seems to be a million questions on reading SPSS .sav files via Python but nothing on reading SPSS .spv files, aka Viewer Files. See image below, highlighted in yellow. My aim is to read the information within it (usually frequencies, tables, charts etc) and do something fun with it. I know you can export the same information in excel but I want to know if I can work directly with the .spv file. Is this possible?
tagged with: python

http://stackoverflow.com/q/50273301
tagged with: python-3.x
has title: Text added to New window is not visible in Curses
tagged with: python
tagged with: curses
score: 2
type: AnsweredQuestion
has body: I am trying to add a window and a text in this window with curses using this and this: window.addstr("This is a text in a window") Code: class View: def __init__(self, ): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(True) # ----------------- self.add_window_and_str() self.add_str() # ----------------- self.stdscr.getkey() curses.endwin() def add_str(self): #just text in standart screen self.stdscr.addstr("test") self.stdscr.refresh() def add_window_and_str(self): scr_limits = self.stdscr.getmaxyx() win = curses.newwin(scr_limits[0] - 10, scr_limits[1] - 10, 5, 5) win.addstr("Example String") win.refresh() self.stdscr.refresh() The text added with self.add_str is visible but the "Example String" is not. How can i manipulate windows to make that text visible?
upvote count: 2
has answer: http://stackoverflow.com/a/50282474
accepted answer: http://stackoverflow.com/a/50282474
tagged with: python-curses
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/50348970
has body: I found a solution with regex. import re def b(a): while '\b' in a: a = re.sub('[^\b]\b', '', a) return a b('Test..\b\b! 12344\b5') # Out: 'Test! 12345'
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50348303
type: AcceptedAnswer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50348303

http://stackoverflow.com/a/50320948
has comment: http://stackoverflow.com/comment/87658225
score: 0
has comment: http://stackoverflow.com/comment/87657936
type: Answer
answers question: http://stackoverflow.com/q/50320773
has body: To access the filenames you printed, store the filenames in a list for processing later: import os filenames = [] for r, d, f in os.walk(thisdir): for file in f: if not file.startswith('.'): filename = os.path.join(r, file) print(filename) filenames.append(filename) for filename in filenames: with open(filename, 'r') as f: Alternatively use your validation function directly after you construct the filename: for r, d, f in os.walk(thisdir): for file in f: if not file.startswith('.'): filename = os.path.join(r, file) print(filename) # perform validation within the loop with open(filename, 'r') as f:
has comment: http://stackoverflow.com/comment/87657960

http://stackoverflow.com/comment/122997528
type: AnswerComment
score: 0
has text: This is the easiest and safer way IMO.
comment on: http://stackoverflow.com/a/51240725
type: Comment

http://stackoverflow.com/comment/88020782
type: AnswerComment
comment on: http://stackoverflow.com/a/50385360
score: 0
type: Comment
has text: Have you seen the new question I asked right below here? Don't wanted to create a new ticket for the same problem.

http://stackoverflow.com/q/50294552
has title: How do i add the `pip install --user` bin to my PATH?
downvote count: 1
tagged with: python
favorite count: 0
type: Question
answer count: 2
upvote count: 5
has comment: http://stackoverflow.com/comment/87606493
has answer: http://stackoverflow.com/a/75613368
has body: When I install a binary by using pip install --user &lt;package&gt;, it gets installed to ~/Library/Python/3.6/bin, but this path isn't on my PATH. Obviously I could add PATH=$PATH:~/Library/Python/3.6/bin to my bashrc/zshrc, but when I upgrade to python 3.7 I'd have to modify this. It seems like when I installed pip, it should have done something to add that directory to my PATH. Is there a recommended way to install pip so that it automatically manages adding the appropriate bin to my path? Thanks in advance!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87605596
tagged with: pip
score: 4
has answer: http://stackoverflow.com/a/50306442

http://stackoverflow.com/a/50337805
type: Answer
answers question: http://stackoverflow.com/q/50337743
downvote count: 0
upvote count: 1
has body: There are two problems: if args.date: will always be true, because it'll be the default value or the user-entered value, neither of which is false-y (datetime objects and non-empty strings never are). store_true is the wrong action to use, because that tells argparse that this switch takes no value (it'll set args.past to True when the user uses the switch, anything following --date is not seen as part of this argument). Leave it to the default 'store'. Also, str is the default type, and the wrong type if you want to parse the user input into a datetime instance. This works: parser.add_argument( '--past', default=datetime.now() - timedelta(days=5)) But now args.past is going to be either a string (user input), or a datetime instance (the default value). You probably want to use a type= argument that converts user input to a datetime object too. Such as: def to_datetime(s): return datetime.strptime(s, '%Y%m%d') parser.add_argument( '--past', type=to_datetime, default=datetime.now() - timedelta(days=5)) to accept dates in your prescribed YYYYMMDD format. Demo: &gt;&gt;&gt; from argparse import ArgumentParser &gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; def to_datetime(s): ... return datetime.strptime(s, '%Y%m%d') ... &gt;&gt;&gt; parser = ArgumentParser(prog='demo') &gt;&gt;&gt; parser.add_argument( ... '--past', ... type=to_datetime, ... default=datetime.now() - timedelta(days=5)) _StoreAction(option_strings=['--past'], dest='past', nargs=None, const=None, default=datetime.datetime(2018, 5, 9, 20, 42, 34, 806341), type=&lt;function to_datetime at 0x10bf422f0&gt;, choices=None, help=None, metavar=None) &gt;&gt;&gt; args = parser.parse_args() &gt;&gt;&gt; args.past datetime.datetime(2018, 5, 9, 20, 42, 34, 806341) &gt;&gt;&gt; args = parser.parse_args(['--past', '20180514']) &gt;&gt;&gt; args.past datetime.datetime(2018, 5, 14, 0, 0)
score: 1

http://stackoverflow.com/q/50353972
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50354058
score: 0
tagged with: eval
tagged with: python
has comment: http://stackoverflow.com/comment/87724199
has title: Time Complexity - BigO Notation of Python's eval
tagged with: big-o
upvote count: 2
has answer: http://stackoverflow.com/a/50354058
downvote count: 2
has body: What is the time complexity of Python's eval for evaluating mathematical expressions? I cannot find any sources that state it. My assumption is that it is O(n) where n is the amount of operators in the expression. If anyone has a reference to a site where this is stated, it would be much appreciated if you could share.
tagged with: time-complexity
answer count: 1
has comment: http://stackoverflow.com/comment/87724286
favorite count: 0

http://stackoverflow.com/q/50270540
has body: I created a new Colaboratory notebook and wanted to simply authenticate myself to have access to files on my Drive. However when I'm running script below from google.colab import auth auth.authenticate_user() from oauth2client.client import GoogleCredentials creds = GoogleCredentials.get_application_default() import getpass !google-drive-ocamlfuse --headless -id={creds.client_id} -secret={creds.client_secret} &lt; /dev/null 2&gt;&amp;1 | grep URL vcode = getpass.getpass() !echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} The only thing I can see is the text input, without any link, nothing. When I type just anything then I receive /bin/sh: 1: google-drive-ocamlfuse: not found. This happens to me quite often recently, what am I doing wrong?
favorite count: 0
type: Question
tagged with: google-drive-api
has comment: http://stackoverflow.com/comment/87598899
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51904152
has title: Google Colaboratory not displaying link during authorisation
tagged with: python
tagged with: google-colaboratory
score: 2
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87747461
type: QuestionComment
has text: Can you upload and share your image here?
comment on: http://stackoverflow.com/q/50364235
score: 0
type: Comment

http://stackoverflow.com/q/50328615
has comment: http://stackoverflow.com/comment/87675785
type: Question
has title: Plotly offline charts with dropdown in flask
has comment: http://stackoverflow.com/comment/87681102
upvote count: 2
tagged with: plotly
accepted answer: http://stackoverflow.com/a/50339679
answer count: 1
has body: I am trying to render a plotly chart in flask. Everything works fine when I use a normal chart. The issue arises when trying to use charts with drop-down menus. In that case I get a blank webpage. My code is below. from flask import Flask,render_template,url_for import plotly.graph_objs as go import pandas as pd import plotly import json app = Flask(__name__) @app.route('/') def dashboards(): # Read in the Data via Pandas df = pd.read_csv('raw.githubusercontent.com/plotly/datasets/master/volcano.csv') data = [go.Surface(z=df.values.tolist(), colorscale='Viridis')] layout = go.Layout( width=800, height=900, autosize=False, margin=dict(t=0, b=0, l=0, r=0), scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230, 230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), aspectratio=dict(x=1, y=1, z=0.7), aspectmode='manual' ) ) updatemenus = list([ dict( buttons=list([ dict( args=['type', 'surface'], label='3D Surface', method='restyle' ), dict( args=['type', 'heatmap'], label='Heatmap', method='restyle' ) ]), direction='down', pad={'r': 10, 't': 10}, showactive=True, x=0.1, xanchor='left', y=1.1, yanchor='top' ), ]) annotations = list([ dict(text='Trace type:', x=0, y=1.085, yref='paper', align='left', showarrow=False) ]) layout['updatemenus'] = updatemenus layout['annotations'] = annotations fig = dict(data=data, layout=layout) # Convert the figures to JSON graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) # Render the Template return render_template('dashboard.html', graphJSON=graphJSON) if __name__ == '__main__': app.run() HTML template is Fruit Plot I get a blank page. can anyone pls help?
has answer: http://stackoverflow.com/a/50339679
score: 1
tagged with: flask
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87680008
tagged with: python

http://stackoverflow.com/comment/87695434
type: QuestionComment
comment on: http://stackoverflow.com/q/50339462
score: 0
has text: Thanks. That is a helpful post. I did a lot of googling and for some reason that post did not come up!
type: Comment

http://stackoverflow.com/comment/87541485
type: QuestionComment
comment on: http://stackoverflow.com/q/50261638
has text: df.Date.diff().dt.days.cumsum() ?
score: 0
type: Comment

http://stackoverflow.com/a/50247318
has body: As metatoaster stated, you need define the global Spanish array outside of the if statement. global Spanish Spanish = [] if message.content.upper().startswith("P$LANG"): lang = message.content[7:] """ user1 = { "Language" : lang = message.content[7:], "ID" : user == message.author.id, } """ if lang.upper() == "SPANISH" or lang.upper() == "SPAIN" or lang.upper() == "ESPAÑOL": xcm = "&lt;@!" + message.author.id + "&gt; Ahora Phantom está en Español. Ten en cuenta que los comandos seguiran siendo en Inglés, solo que la respuesta será en Español." Spanish.append(message.author.id) await client.send_message(channel, xcm) if message.content.upper().startswith('P$POLLHELP'): # await client.add_reaction(message, ":radio_button:") if message.author.id in Spanish: await client.send_message( channel, "**Uso:** P$~&lt;x&gt;poll &lt;pregunta&gt; | reemplaza &lt;x&gt; con el número, min - 1 || máx - 5 |-|-| reemplaza &lt;pregunta&gt; con tu pregunta.*" ) else: await client.send_message( channel, "**Usage:** P$~&lt;x&gt;poll &lt;question&gt; | replace the &lt;x&gt; with the number, min - 1 || max - 5 |-|-| replace &lt;question&gt; with your question.*" ) print("P$pollhelp was used by " + str(author.name))
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50246752
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50246752

http://stackoverflow.com/comment/136121366
comment on: http://stackoverflow.com/a/53310545
has text: i have mac pro m1 2020 and it's correctly work for me thanks
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/50339050
has comment: http://stackoverflow.com/comment/87694592
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50339020
has comment: http://stackoverflow.com/comment/87725939
has body: You have to import the module for regex in Django 2.0 like: from django.urls import path, re_path from . import views urlpatterns = [ path('articles/2003/', views.special_case_2003), re_path(r'^articles/(?P&lt;year&gt;[0-9]{4})/$', views.year_archive), re_path(r'^articles/(?P&lt;year&gt;[0-9]{4})/(?P&lt;month&gt;[0-9]{2})/$', views.month_archive), re_path(r'^articles/(?P&lt;year&gt;[0-9]{4})/(?P&lt;month&gt;[0-9]{2})/(?P&lt;slug&gt;[\w-]+)/$', views.article_detail), ] More info The new address will be the name of the functions or class you assign, in your case path('details/[-\w]', details), details is the function and you can get the parameters with the name assigned to the regex group re_path(r'^articles/(?P&lt;year&gt;[0-9]{4})/$', views.year_archive), in this example the regex group name is ?P&lt;year&gt;
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/87694506
accepted answer of: http://stackoverflow.com/q/50339020

http://stackoverflow.com/q/50311010
downvote count: 1
linked to: http://stackoverflow.com/q/10147455
favorite count: 0
type: Question
upvote count: 2
has title: Got an error by sending emails using python 2 and smtplib
tagged with: smtplib
has answer: http://stackoverflow.com/a/50311034
accepted answer: http://stackoverflow.com/a/50311034
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87638212
type: AnsweredQuestion
tagged with: python-2.7
has body: EDIT: The main error is when this script runs from different IP / Wifi or whatever. It will just cancel it like skip over it or whatever. I'm trying to send an email with text that says something. (or I can insert a variable for example: score = 32 and I would put 'score' in body without the ' '.) The following code is what I'm using: import smtplib gmail_user = 'name@gmail.com' gmail_password = 'password' sent_from = gmail_user to = 'me@gmail.com' subject = 'OMG Super Important Message' body = 'blah blah blah this is a message' email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print 'Email sent!' except: print 'Something went wrong...' So where it says 'body' I can put like a variable not just a text and it would send. But now, when I send a program to someone and they go through the steps until this and the script will just skip it because the print 'loaded successful' one won't print meaning it didn't work. Any help on how to fix?
score: 1

http://stackoverflow.com/q/50289628
tagged with: multiprocessing
possible better answer: http://stackoverflow.com/a/55660094
type: Question
has body: This is basically a duplicate of: Keras + Tensorflow and Multiprocessing in Python But my setup is a bit different, and their solution doesn't work for me. I need to train a keras model against predictions made from another model. The predictions are connected to some CPU heavy code, so I would like to parallelize them and have the code run in worker processes. Here is the code I would like to execute: import numpy as np from keras.layers import Input, Dense from keras.models import Model from keras.optimizers import Adam def create_model(): input_layer = Input((10,)) dense = Dense(10)(input_layer) return Model(inputs=input_layer, outputs=dense) model_outside = create_model() model_outside.compile(Adam(1e-3), "mse") def subprocess_routine(weights): model_inside = create_model() model_inside.set_weights(weights) while True: # lots of CPU batch = np.random.rand(10, 10) prediction = model_inside.predict(batch) yield batch, prediction weights = model_outside.get_weights() model_outside.fit_generator(subprocess_routine(weights), epochs=10, steps_per_epoch=100, use_multiprocessing=True, workers=1) This produces an error E tensorflow/core/grappler/clusters/utils.cc:81] Failed to get device properties, error code: 3 I found the above question, the answer is to move keras imports into the subprocess. I have added all imports into the subprocess_routine. But that doesn't change the error. It would probably be necessary to eliminate keras imports altogether from the main process, but in my setup, that would mean huge refactorings. Keras + multithreading seems to work. In this issue, scroll down to the very last comment: https://github.com/keras-team/keras/issues/5640 In my code, it looks like this: model_inside = create_model() model_inside._make_predict_function() graph = tf.get_default_graph() def subprocess_routine(model_inside, graph): while True: batch = np.random.rand(10, 10) with graph.as_default(): prediction = model_inside.predict(batch) yield batch, prediction model_…
tagged with: python
accepted answer: http://stackoverflow.com/a/50895406
has title: Use keras in multiprocessing
linked to: http://stackoverflow.com/q/38694111
has answer: http://stackoverflow.com/a/50895406
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55660094
answer count: 2
linked to: http://stackoverflow.com/q/42504669
downvote count: 0
score: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/50290969
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50290872
type: Answer
has body: You can simply do this: Employee = dict(EmpName="Peter", Empid="456", Designation="Country Head") ... Employee = dict(EmpName="Suresh", Empid="585", Designation="Director") And, if you want to have an update() method, then create a class Employee which contains the update() method. Anyway, as the fields seems to be fixed, I would advise you to use an object Employee with the fields EmpName, Empid and Designation in it. One of the major benefit of using an object (in place of several dictionaries objects), is that you will be able to type (and, then, trust the content of each element) of a collection of Employee's objects. Where, manipulating a collection of dictionaries may just lead you to have missing fields or different labels for each fields.

http://stackoverflow.com/comment/87711113
comment on: http://stackoverflow.com/q/50347502
type: Comment
has text: In cases like this, it's best to include *OS* and *Python* version / architecture (seems to be *Python2*).
type: QuestionComment
score: 0

http://stackoverflow.com/a/50372897
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50371456
type: Answer
has body: You don't need all the getters. You can simply use object accessor methods, e.g. tree_a.left_child. Secondly, you didn't create a BinaryTree out of your children, meaning that it doesn't make sense to run sum_tree on them. Read through the following code, and make sure that you understand what's going on. Pretty sure that what you actually want, is this class BinaryTree: def __init__(self, root, left_child=None, right_child=None): self.root = root self.left_child = None if not left_child else BinaryTree(*left_child) self.right_child = None if not right_child else BinaryTree(*right_child) self.node = [root, left_child, right_child] def set_root(self, root): self.root = root def sum_tree(self): tree_sum = 0 if self.left_child: tree_sum += self.left_child.sum_tree() if self.right_child: tree_sum += self.right_child.sum_tree() return tree_sum + self.root tree_a = BinaryTree(8) tree_b = BinaryTree(9, [6, [], []], [65, [], []]) print(tree_a.sum_tree()) # 8 print(tree_b.sum_tree()) # 80 print(tree_b.left_child.node) # [6, [], []]
upvote count: 2

http://stackoverflow.com/q/50377322
has title: How can I get my tensorflow script to run on my GPU?
has comment: http://stackoverflow.com/comment/87771091
has body: I'm trying to train a DNN using the following script: import numpy as np import os, sys import argparse from PIL import Image from freeze_graph import freeze_graph import tensorflow as tf import time from net import * sys.path.append(os.path.join(os.path.dirname(sys.path[0]), "./")) from custom_vgg16 import * # gram matrix per layer def gram_matrix(x): assert isinstance(x, tf.Tensor) b, h, w, ch = x.get_shape().as_list() features = tf.reshape(x, [b, h*w, ch]) # gram = tf.batch_matmul(features, features, adj_x=True)/tf.constant(ch*w*h, tf.float32) gram = tf.matmul(features, features, adjoint_a=True)/tf.constant(ch*w*h, tf.float32) return gram # total variation denoising def total_variation_regularization(x, beta=1): assert isinstance(x, tf.Tensor) wh = tf.constant([[[[ 1], [ 1], [ 1]]], [[[-1], [-1], [-1]]]], tf.float32) ww = tf.constant([[[[ 1], [ 1], [ 1]], [[-1], [-1], [-1]]]], tf.float32) tvh = lambda x: conv2d(x, wh, p='SAME') tvw = lambda x: conv2d(x, ww, p='SAME') dh = tvh(x) dw = tvw(x) tv = (tf.add(tf.reduce_sum(dh**2, [1, 2, 3]), tf.reduce_sum(dw**2, [1, 2, 3]))) ** (beta / 2.) return tv parser = argparse.ArgumentParser(description='Real-time style transfer') parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)') parser.add_argument('--dataset', '-d', default='dataset', type=str, help='dataset directory path (according to the paper, use MSCOCO 80k images)') parser.add_argument('--style_image', '-s', type=str, required=True, help='style image path') parser.add_argument('--batchsize', '-b', type=int, default=1, help='batch size (default value is 1)') parser.add_argument('--ckpt', '-c', default=None, type=int, help='the global step of checkpoint file desired to restore.') parser.add_argument('--lambda_tv', '-l_tv', default=10e-4, type=float, help='weight of total variation regularization according to the paper to be set between 10e-4 and 10e-6.') parser.add_argument('--lambda_feat', '-l_feat', default=1e0, type=f…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87771006
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87770804
tagged with: deep-learning
downvote count: 0
has comment: http://stackoverflow.com/comment/87770921
has comment: http://stackoverflow.com/comment/87770848
has comment: http://stackoverflow.com/comment/87771256
tagged with: gpu
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87771388
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50378173

http://stackoverflow.com/q/50232527
tagged with: python
has comment: http://stackoverflow.com/comment/87482523
has answer: http://stackoverflow.com/a/50232719
score: 0
has body: We are building a school information system using Python/Django. The production server runs Ubuntu, Apache2 with mod_wsgi. Recently strange things happen to our server. When we test our code locally everything works well. After deployment the application works, but sometimes returns 'Page not found' or 'Division by zero' errors. Why is this happen, from attack or server configuration, please help us!
answer count: 1
has title: Django application behaves strangely, sometimes works, sometimes doesn't
linked to: http://stackoverflow.com/q/32308335
type: Question
tagged with: django
type: UnansweredQuestion

http://stackoverflow.com/q/50281305
has body: I have a bunch of excel files which I am merging into a csv file. Once the files are merged, I need to add a few more columns in the beginning of the csv file (I am planning to populate those columns using parameters e.g. GLB_DM_VER to populate Global_DM_Version column). The following script gives me an error: AttributeError: 'NoneType' object has no attribute 'to_csv' I am new to Python and would really appreciate any help on this issue.Thanks. import glob path= input("Enter the location of files ") GLB_DM_VER = input("Enter global DM version") file_list = glob.glob(path+"\*.xls") excels = [pd.ExcelFile(name) for name in file_list] frames = [x.parse(x.sheet_names[2], header=0,index_col=None) for x in excels] combined = pd.concat(frames) combined = combined.insert(loc=1, column = 'Global_DM_Version', value = GLB_DM_VER ) combined.to_csv("STAND_2.csv", header=['TARGET_DOMAIN','SOURCE_DOMAIN','DOMAIN_LABEL','SOURCE_VARIABLE','RAVE_LABEL','TYPE','VARIABLE_LENGTH','CONTROL_TYPE','CODELIST_OID','TARGET_VARIABLE','MANDATORY','RAVE_ORIGIN'], index=False)
upvote count: 1
tagged with: python
downvote count: 1
tagged with: excel
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: Merging excel files using pandas and adding a custom column gives error
accepted answer: http://stackoverflow.com/a/50281405
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50281405

http://stackoverflow.com/comment/87812489
has text: The edit you made removed the portion of the code that caused the error: http://paste.debian.net/1025113/
comment on: http://stackoverflow.com/q/50350632
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/50356028
has answer: http://stackoverflow.com/a/50356125
has answer: http://stackoverflow.com/a/50356230
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/2122385
favorite count: 0
tagged with: python-3.x
has body: In Python how could I accomplish printing out the time in realtime in a Terminal? while(True): print("[ " + "Time: " + datetime.date.today().strftime("%Y-%m-%d") + " ]") The code above will just print out the line infinite amount of times. How can I do a "static" line of text and refresh the time every second without doing print statements on every line? Hope this wasn't too confusing :) Wasn't sure what to search for, it didn't give me the result I was looking for.
type: Question
linked to: http://stackoverflow.com/q/6169217
answer count: 2
has title: Print out text with dynamic pieces in Python to the Terminal
duplicate of: http://stackoverflow.com/q/2122385
tagged with: python
possible better answer: http://stackoverflow.com/a/50356125
accepted answer: http://stackoverflow.com/a/50356230
type: AnsweredQuestion

http://stackoverflow.com/comment/94443949
score: 0
type: AnswerComment
has text: Thanks, this is a very nice solution. I just found a bug in it. When a level has only one variant, you do not include it in the output. I have fixed it and posted a new answer. If you would like you can update your answer with mine and I'd remove it.
type: Comment
comment on: http://stackoverflow.com/a/53154393

http://stackoverflow.com/q/50284343
tagged with: linux
has body: I'm trying to make a python script which is going run a bash script on a remote machine via ssh and then parse its output. The bash script outputs lot of data (like 5 megabytes of text / 50k lines) in stdout and here is a problem - I'm getting all the data only in ~10% cases. In other 90% cases I'm getting about 97% of what i expect and it looks like it always trims at the end. This is how my script looks like: import subprocess import re import sys import paramiko def run_ssh_command(ip, port, username, password, command): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password) stdin, stdout, stderr = ssh.exec_command(command) output = '' while not stdout.channel.exit_status_ready(): solo_line = '' # Print stdout data when available if stdout.channel.recv_ready(): # Retrieve the first 1024 bytes solo_line = stdout.channel.recv(2048). output += solo_line ssh.close() return output result = run_ssh_command(server_ip, server_port, login, password, 'cat /var/log/somefile') print "result size: ", len(result) I'm pretty sure that problem is in overflowing of some internal buffer, but which one and how to fix it? Thank you very much for any tip!
accepted answer: http://stackoverflow.com/a/50295830
tagged with: ssh
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50294962
answer count: 2
tagged with: bash
has title: Losing stdout data in python
score: 1
has answer: http://stackoverflow.com/a/50295830
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50294962

http://stackoverflow.com/comment/87526315
comment on: http://stackoverflow.com/a/50254268
has text: ok thanks guys (answer and comments) ... A last clarification : `itertools.islice` use is equivalent to loop in a range and then access by index ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87609530
comment on: http://stackoverflow.com/q/50296210
type: QuestionComment
score: 0
has text: what's the the name of the app containing your `api/get_teacher`
type: Comment

http://stackoverflow.com/comment/87723960
score: 0
type: Comment
type: QuestionComment
has text: Stats show the current team statistics and game is one specific game, hence game['gp'] = 1. Therefore, after game is added to stats, the news stats will update stats['gp'] by 1. This will give me the current statistics after they were udpate by 1 game. I hope this makes sense.
comment on: http://stackoverflow.com/q/50353592

http://stackoverflow.com/comment/87785061
score: 0
has text: I think you need provide more information such as your directories structure, where do you run your cmd, what is your cmd... and so on.
type: Comment
comment on: http://stackoverflow.com/q/50384348
type: QuestionComment

http://stackoverflow.com/q/50289308
favorite count: 0
has comment: http://stackoverflow.com/comment/87594717
has answer: http://stackoverflow.com/a/50289523
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87594886
tagged with: python
has comment: http://stackoverflow.com/comment/87595177
type: Question
has comment: http://stackoverflow.com/comment/87594700
has title: Python Take raw input and search for it in a line with multiple characters
answer count: 1
has body: I'm trying to search for a specific set of characters, user defined, in a string at a specific point. This is my code so far: # -*- coding: utf-8 -*- f = open("text.txt", 'r') linelist = f.readlines() f.close User_number = raw_input('What number would you like to single out from your text?') anum1 = User_number[0] anum2 = User_number[1] f4 = open("Modded_text.txt", "w") for line in linelist: i =0; if anum1 in line[10] and anum2 in line[11]: f4.write(line) f4.close() The problem I have is that this gives me "IndexError: string index out of range". It also seems to be a messy way of doing what I want even if it did work. Can anyone advise me on how I can get this working and improve my code?
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50289523

http://stackoverflow.com/q/50321139
downvote count: 0
upvote count: 7
score: 7
tagged with: keras
linked to: http://stackoverflow.com/q/50339622
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/87668328
has answer: http://stackoverflow.com/a/50321998
tagged with: metrics
type: Question
accepted answer: http://stackoverflow.com/a/50321980
linked to: http://stackoverflow.com/q/10580676
has body: I have simple seq2seq model: import seq2seq import numpy as np import keras.backend as K from seq2seq.models import Seq2Seq from keras.models import Model from keras.models import Sequential from keras.layers import Embedding, Input, TimeDistributed, Activation BLOCK_LEN = 60 EVENTS_CNT = 462 input = Input((BLOCK_LEN,)) embedded = Embedding(input_dim=EVENTS_CNT+1, output_dim=200)(input) emb_model = Model(input, embedded) seq_model = Seq2Seq(batch_input_shape=(None, BLOCK_LEN, 200), hidden_dim=200, output_length=BLOCK_LEN, output_dim=EVENTS_CNT) model = Sequential() model.add(emb_model) model.add(seq_model) model.add(TimeDistributed(Activation('softmax'))) model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= model_1 (Model) (None, 60, 200) 92600 _________________________________________________________________ model_12 (Model) (None, 60, 462) 1077124 _________________________________________________________________ time_distributed_2 (TimeDist (None, 60, 462) 0 ================================================================= Total params: 1,169,724 Trainable params: 1,169,724 Non-trainable params: 0 _________________________________________________________________ And I'm trying to create my own metric: def symbol_acc(true, predicted): np_y_true = K.get_value(true) np_y_pred = K.get_value(predicted) return K.mean(np_y_true == np_y_pred) And if I try to compile model with this metric I get an error "You must feed a value for placeholder tensor" with the following message: InvalidArgumentError Traceback (most recent call last) C:\Users\Anna\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1322 try: -&gt; 1323 return fn(*args) 1324 except errors.OpError as e: C:\Users\Anna\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options,…
tagged with: neural-network
has answer: http://stackoverflow.com/a/50321980
has comment: http://stackoverflow.com/comment/87658608
tagged with: python
has title: Keras error "You must feed a value for placeholder tensor"
possible better answer: http://stackoverflow.com/a/50321998
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/50271043
tagged with: pyqt4
tagged with: python
has body: So I managed to write a PyQt4 Widget, which can run a loop in a thread. 2 Things are done in the thread. A loop is started and a signal is emitted to a progress bar to give info about progress. (I know this could be done better but for my task is sufficient) After the loop is done running, a pandas.DataFrame is emitted from inside the thread to matplotlib, which is outside the thread and in the main Widget class. Everything works fine, you can move the Widget while the loop is processed. The only Problem is that when the Widget is moved at the same time as the plot is popped up (or the processing is done), everything freezes. Not only the Widget and the plot but also my windows desktop. I can get out of it with task manager. Any Advice how to circumvent this? I am using Python 3.6 (32 bit) code: import sys from PyQt4.QtGui import * from PyQt4.QtCore import * import matplotlib.pyplot as plt import pandas as pd class App(QMainWindow): def __init__(self): super(App, self).__init__() self.setGeometry(500, 300, 820, 350) self.setWindowTitle("Program") self.initUI() def initUI(self): #Buttons btnposx = 30 btnposy = 50 self.btn4 = QPushButton('Load', self) self.btn4.move(btnposx,btnposy+220) self.btn4.released.connect(self.thread) #ProgressBar self.pb = QProgressBar(self) self.pb.move(btnposx+150,btnposy+220) self.pb.resize(470,27) self.show() @pyqtSlot(float) def load(self, val): self.pb.setValue(val) @pyqtSlot(object) def plot(self, pq): pq.plot(grid = 1) plt.show() def thread(self): self.thread_ = Thread() self.thread_.pb_signal.connect(self.load, Qt.QueuedConnection) self.thread_.plot_signal.connect(self.plot, Qt.QueuedConnection) self.thread_.start() class Thread(QThread): pb_signal = pyqtSignal(float) plot_signal = pyqtSignal(object) def __init__(self, *args, **kwargs): QThread.__init__(self, *args, **kwargs) def __del__(self): self.wait() @pyqtSlot() def run(self): val = 0 self.pb_signal.emit(20) l = range(50000000) for i in l: val += 1 self.pb_signal.emit(60) self.…
has comment: http://stackoverflow.com/comment/87567808
has title: Troubleshooting PyQt4 Matplotlib
score: 0
linked to: http://stackoverflow.com/q/19390622
tagged with: pandas
has comment: http://stackoverflow.com/comment/87559545
has comment: http://stackoverflow.com/comment/87567566
tagged with: matplotlib
type: Question
duplicate of: http://stackoverflow.com/q/47972386
answer count: 0
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/comment/87888710
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50336667
has text: @Josh thank you! I already tried that one too. :)
type: Comment

http://stackoverflow.com/comment/88417499
type: Comment
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/50352614
has text: can you please post some sample Python code that produces the plot in question?

http://stackoverflow.com/q/50358908
downvote count: 0
has answer: http://stackoverflow.com/a/50359282
has answer: http://stackoverflow.com/a/50362685
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/11011756
has body: As a follow-on to this question which was resolved using Counter(), I've run into a new problem that seems easy enough to fix - except I can't get it to work. I'm trying to use Counter() to sum a series of dict entries which works if the sum is a positive integer, BUT returns an empty element if the sum is a negative integer. I was able to find this answer which is right on point in explaining that Counter() is designed to count and not sum, per se. I can recreate the example and get it to work, but with a django queryset, when coupled with the Counter() method, generates a more complex dictionary that looks like this. totals = { 'sumthing_a': Counter({'total': 48000}), 'sumthing_b': Counter({'total': 39050}), 'sumthing_c': Counter({'total': 8950}), 'sumthing_d': Counter({'total': 10000}), 'sumthing_e': Counter({'total': 17200}), 'sumthing_f': Counter({'total': 17750}), 'sumthing_g': Counter({'total': 30450}), } I've tried variations of: totals.update({'sumthing_e': Counter({'total': 300})}) which replaces the original 17200 with 300 rather than adding them. I've also tried: totals['sumthing_e'].update({'sumthing_e': Counter({'total': 300})}) which throws: unsupported operand type(s) for +: 'Counter' and 'int' The documentation for .update() states: Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs. And there is a docs note that states: For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs. This leads me to believe that what I'm trying to do is possible, if it is coded correctly. The final result should be the ability to have a negat…
accepted answer: http://stackoverflow.com/a/50359282
has title: Using collections.Counter() with a Django queryset that has negative integers
possible better answer: http://stackoverflow.com/a/50362685
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50341867
score: 1

http://stackoverflow.com/a/50276690
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87570023
has body: Dictionary key should be either an immutable value, or a variable that contains an immutable value (like a string or a number). name isn't a string and isn't defined as a variable in the current scope. One way of fixing this would be def createCategory(): utils.clear() category = { 'name': 'test' } utils.insertCategory(category)
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/50276640

plot
tags question: http://stackoverflow.com/q/50327665
tags question: http://stackoverflow.com/q/50346498
tags question: http://stackoverflow.com/q/50277856
type: Tag
tags question: http://stackoverflow.com/q/50242754
tags question: http://stackoverflow.com/q/50378543
tags question: http://stackoverflow.com/q/50356795
tags question: http://stackoverflow.com/q/50338284
tags question: http://stackoverflow.com/q/50289947
tags question: http://stackoverflow.com/q/50369623
tag name: plot
tags question: http://stackoverflow.com/q/50293846
tags question: http://stackoverflow.com/q/50234543
tags question: http://stackoverflow.com/q/50302614
tags question: http://stackoverflow.com/q/50315792
tags question: http://stackoverflow.com/q/50314924
tags question: http://stackoverflow.com/q/50361356
tags question: http://stackoverflow.com/q/50288933
tags question: http://stackoverflow.com/q/50344802
tags question: http://stackoverflow.com/q/50317308
tags question: http://stackoverflow.com/q/50278360
tags question: http://stackoverflow.com/q/50341684
tags question: http://stackoverflow.com/q/50247596
tags question: http://stackoverflow.com/q/50352335
tags question: http://stackoverflow.com/q/50324921
tags question: http://stackoverflow.com/q/50366368

optimization
tags question: http://stackoverflow.com/q/50364217
tags question: http://stackoverflow.com/q/50353421
tags question: http://stackoverflow.com/q/50356245
tag name: optimization
tags question: http://stackoverflow.com/q/50361464
tags question: http://stackoverflow.com/q/50256850
tags question: http://stackoverflow.com/q/50352689
tags question: http://stackoverflow.com/q/50353176
tags question: http://stackoverflow.com/q/50340056
tags question: http://stackoverflow.com/q/50265501
tags question: http://stackoverflow.com/q/50298570
tags question: http://stackoverflow.com/q/50247772
tags question: http://stackoverflow.com/q/50310730
type: Tag

http://stackoverflow.com/a/50306875
has body: Did you try to use prefetch_related in the view/viewset which uses SomeModelSerializer? Something like from rest_framework import viewsets from myapp.models import SomeModel from myapp.api.v1.serializers import SomeModelSerializer class SomeModelViewSet(viewsets.ModelViewSet): serializer_class = SomeModelSerializer queryset = SomeModel.objects.prefetch_related( 'related_table1', 'related_table1__related_table2', 'related_table3', )
type: Answer
has comment: http://stackoverflow.com/comment/87670469
answers question: http://stackoverflow.com/q/50292851
score: 0

http://stackoverflow.com/a/50334621
score: 0
has body: thanks guys, I've been testing with this and the re.sub function just seems to print out the below string in a loop : CUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTBCUSTB . I have amended the code snippet above to : for word in subnet_list: line = re.sub(r'\b5.6.7.8\b', 'CUST_B', '5.6.7.88') Ideally I would like the string element to be replaced in all of the list occurrences along with preserving the list structure ?
answers question: http://stackoverflow.com/q/50316649
type: Answer

http://stackoverflow.com/q/50289692
tagged with: tweepy
has answer: http://stackoverflow.com/a/50302901
has title: Handle 420 response code returned by Tweepy api
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: error-handling
upvote count: 1
downvote count: 1
tagged with: twitter-streaming-api
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50294919
has body: Whenever a user logs in to my application and searches I have to start a streaming API for fetching data required by him. Here is my stream API class import tweepy import json import sys class TweetListener(tweepy.StreamListener): def on_connect(self): # Called initially to connect to the Streaming API print("You are now connected to the streaming API.") def on_error(self, status_code): # On error - if an error occurs, display the error / status code print('An Error has occured: ' + repr(status_code)) return False def on_data(self, data): json_data = json.loads(data) print(json_data) Here is my python code file which calls class above to start Twitter Streaming import tweepy from APIs.StreamKafkaApi1 import TweetListener consumer_key = "***********" consumer_secret = "*********" access_token = "***********" access_secret = "********" hashtags = ["#ipl"] def callStream(): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth,wait_on_rate_limit=True) tweetListener = TweetListener(userid,projectid) streamer = tweepy.Stream(api.auth, tweetListener) streamer.filter(track=hashtags, async=True) if __name__ == "__main__": callStream() But if I hit more than twice my application return error code 420. I thought to change API(using multiple keys) used to fetch data whenever Error 420 occurs. How to get error raised by the on_error method of TweetListener class in def callStream()
tagged with: python
tagged with: twitter

http://stackoverflow.com/q/50301358
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has title: Python string template substitution with dict of regex groups?
favorite count: 0
has body: I'm new to python/programing in general and trying to build a statsd to opentsdb proxy based off prometheus' statsd proxy in go. I'm trying to have a string template like the following: label_name = "${1}_${2}_${3}_${6}" Then using the above label = string template format, replace the contents of 1,2,3, and 7 with the re.match.groups of a different string. I thought I could do this with strings Template.safe_substitute and a small for loop to turn the groups into a dictionary: ...: label_match_dict = {} ...: for i in range(len(input_match.groups())): ...: label_match_dict[str(i+1)] = input_match.groups()[i] Yet I am having trouble because it looks like string.Template() is looking for [_a-z][_a-zA-Z0-9] which will not match my dict of {1: "blue", 2: "green", 3: "red", 4: "yellow"}. Now I'm completely lost and feel like there must be a clean way to do this instead of my garden path. So say I have a statsd metric like: connstats_by.vip.nested._Common_Domain.89.44.250.117.conncount:40|g and a regex string like so: re.compile('connstats_by\\.vip\\.nested\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^\:]*)(?:\:)([^\|]*)(?:\|)([^\n]*)') Which after the above for loop gives me: { 1: "_Primary_Domain", 2: "192", 3: "168", 4: "1", 5: "117", 6: "conncount", 7: "40", 8: "g" } I just can't seem to wrap my brain around substituting the members of the template with the members of the dict without a really gross looking nested for loop. I feel like I am going down the wrong path. I am hoping someone here can point me toward a more pythonic direction that I can understand 3 months down the road. Thanks in advance for any help.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50304696
score: 1
tagged with: regex
accepted answer: http://stackoverflow.com/a/50304696
type: Question
tagged with: substitution
has comment: http://stackoverflow.com/comment/87620486

http://stackoverflow.com/q/50317196
has title: What is the best way to write a function to compute row-wise elements in panda?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87755671
answer count: 2
tagged with: function
downvote count: 0
possible better answer: http://stackoverflow.com/a/50317293
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50317273
has answer: http://stackoverflow.com/a/50317293
has comment: http://stackoverflow.com/comment/87761572
has answer: http://stackoverflow.com/a/50317273
has comment: http://stackoverflow.com/comment/87650171
type: AnsweredQuestion
score: 3
tagged with: pandas
upvote count: 3
has body: I have a base table like: col1 is a column of independent values, col2 is an aggregate based on Country and Type combo. I want to compute columns col3 through col5 with the following logic: col3: ratio of an element in col1 to the total of col1 col4: ratio of an element in col1 to the corresponding element in col2 col5: the natural exponent of the product of row-wise elements in col3 and col4 I wrote a function like the below to achieve this: def calculate(df): for i in range(len(df)): df['col3'].loc[i] = df['col1'].loc[i]/sum(df['col1']) df['col4'].loc[i] = df['col1'].loc[i]/df['col2'].loc[i] df['col5'].loc[i] = np.exp(df['col3'].loc[i]*df['col4'].loc[i]) return df This function executes, and gives me the expected results, but the notebook also throws a warning: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy I'm not sure if I'm writing the best function here. Any help would be appreciated! Thanks.

http://stackoverflow.com/q/50369957
score: 17
has answer: http://stackoverflow.com/a/64585424
tagged with: ipython
has comment: http://stackoverflow.com/comment/87982629
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/87912847
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50484801
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/50484801
has answer: http://stackoverflow.com/a/61134742
upvote count: 17
has comment: http://stackoverflow.com/comment/87846255
favorite count: 0
linked to: http://stackoverflow.com/q/35986087
has body: For some time I am getting the following error (warning?): ERROR! Session/line number was not unique in database. History logging moved to new session when working with Jupyter notebook (<XXXX> is a number, e.g. 9149). As the same error has been reported for Spyder (Spyder's Warning: "Session/line number not unique in database") my guess is that there is some problem with the IPython kernel logging. The question is: may there be any relation between running my code and the error? Is it likely the error is caused by my code? I touch IPython API as following: import IPython def beep(): Python.display.display(IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True)) def play_sound(self, etype, value, tb, tb_offset=None): self.showtraceback((etype, value, tb), tb_offset=tb_offset) beep() get_ipython().set_custom_exc((Exception,), play_sound) I use the beep() function in my code. I also work with large data which results in MemoryError exceptions. And more importantly, may the error affect my code behaviour (given I do not try to access the logs)? [EDIT] It seems the issue is different than Spyder's Warning: "Session/line number not unique in database" as I am able to reproduce it with Jupyter Notebook but not with Spyder.
type: Question
has comment: http://stackoverflow.com/comment/87913643
tagged with: python-3.x
has title: Dependency between "Session/line number was not unique in database." error and Python code
has comment: http://stackoverflow.com/comment/87913734
has comment: http://stackoverflow.com/comment/87846438
possible better answer: http://stackoverflow.com/a/64585424
has comment: http://stackoverflow.com/comment/87912572
has comment: http://stackoverflow.com/comment/87846516
tagged with: python

http://stackoverflow.com/comment/87634767
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50307751
has text: @wwii Thanks. I clearly need a little more sleep; didn't spot that.
score: 0

http://stackoverflow.com/comment/87675975
type: Comment
type: QuestionComment
has text: @CristiFati: I made some updates in the question.
score: 0
comment on: http://stackoverflow.com/q/50329878

http://stackoverflow.com/q/50248559
tagged with: python
tagged with: asynchronous
tagged with: tornado
type: AnsweredQuestion
has body: I'm runnning a Bokeh server, using the underlying Tornado framework. I need the server to refresh some data at some point. This is done by fetching rows from an Oracle DB, using Cx_Oracle. Thanks to Tornado's PeriodicCallback, the program checks every 30 seconds if new data should be loaded: server.start() from tornado.ioloop import PeriodicCallback pcallback = PeriodicCallback(db_obj.reload_data_async, 10 * 1e3) pcallback.start() server.io_loop.start() Where db_obj is an instance of a class which takes care of the DB related functions (connect, fetch, ...). Basically, this is how the reload_data_async function looks like: executor = concurrent.futures.ThreadPoolExecutor(4) # methods of the db_obj class ... @gen.coroutine def reload_data_async(self): # ... first, some code to check if the data should be reloaded ... # ... if data_should_be_reloaded: new_data = yield executor.submit(self.fetch_data) def fetch_data(self): """ fetch new data in the DB """ cursor = cx.Cursor(self.db_connection) cursor.execute("some SQL select request that takes time (select * from ...)") rows = cursor.fetchall() # some more processing thereafter # ... Basically, this works. But when I try to read the data while it's being load in fetch_data (by clicking for display in the GUI), the program crashes due to race condition (I guess?): it's accessing the data while it's being fetched at the same time. I just discovered that tornado.concurrent.futures are not thread-safe: tornado.concurrent.Future is similar to concurrent.futures.Future, but not thread-safe (and therefore faster for use with single-threaded event loops). All in all, I think I should create a new thread to take care of the CX_Oracle operations. Can I do that using Tornado and keep using the PerodicCallback function? How can I convert my asynchronous operation to be thread-safe? What's the way to do this? PS: Im using Python 2.7 Thanks
tagged with: cx-oracle
tagged with: multithreading
has answer: http://stackoverflow.com/a/50250379
accepted answer: http://stackoverflow.com/a/50250379
has comment: http://stackoverflow.com/comment/87516270
answer count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87514839
has title: Tornado background task using cx_Oracle

http://stackoverflow.com/comment/87500303
comment on: http://stackoverflow.com/q/50241216
type: QuestionComment
score: 0
has text: @RafaelC No , I am telling there is some mismatch in result form predic_proba() and predict(). max of predict_proba() corresponding to the class should be my prediction but it is showing second highest as my prediction.
type: Comment

http://stackoverflow.com/a/50380338
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87812987
has body: Pandas has spared no expense to make life easier for developers. Compare against to_datetime('today') and filter accordingly: df[pd.to_datetime(df.date, errors='coerce') &gt;= pd.to_datetime('today')] date battle_deaths 1 2018-05-16 18:47:05.119994 25 2 2018-05-16 18:47:05.178768 26 3 2018-05-16 18:47:05.230071 15 4 2018-05-16 18:47:05.230071 15 5 2018-05-16 18:47:05.280592 14 6 2018-05-16 18:47:05.332662 26 7 2018-05-16 18:47:05.385109 25 8 2018-05-16 18:47:05.436523 62 9 2018-05-16 18:47:05.486877 41 This removes the 0th row.
accepted answer of: http://stackoverflow.com/q/50380295
score: 9
has comment: http://stackoverflow.com/comment/87813187
answers question: http://stackoverflow.com/q/50380295
upvote count: 9

http://stackoverflow.com/comment/87727001
comment on: http://stackoverflow.com/q/50354155
score: 0
has text: ...btw, note that `shell=True` *always* uses `/bin/sh`; what your `$SHELL` is is completely irrelevant.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87569977
type: QuestionComment
comment on: http://stackoverflow.com/q/50276363
score: 0
type: Comment
has text: BTW, it's not a good idea to use `map` as a variable name because that "shadows" the built-in `map` function. It won't hurt anything in your current program, but it would result in a mysterious error message if you tried to use the `map` function later in your program.

http://stackoverflow.com/comment/87577559
comment on: http://stackoverflow.com/q/50280247
has text: The interpreter owns memory, not objects. Using ``gc.collect`` will only finalise (destroy) the objects, not necessarily release their memory. See the answer to the linked question for some details on how the CPython gc manages memory arenas.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50361835
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50360977
upvote count: 1
has body: Well it can be done but the urlpatterns need to be changed a bit. url(r'^edit_topic/$', views.edit_topic, name='edit_topic'), When you create your request as &lt;domain_name&gt;/edit_topic?topic_id=&lt;your_id&gt; For example, a request would look like http://127.0.0.1:8000/edit_topic?topic_id=1000 In views.py when a request arrives you can do a GET operation in order to get the value def topic(request): topic = Topic.objects.get(id=request.GET('topic_id'))
answers question: http://stackoverflow.com/q/50360977
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/50303485
type: Answer
has body: You can iterate over your JSON. Ex: for address in data["results"]: for i in address["address_components"]: if i["long_name"] == "11211": print(i) Output: {'long_name': '11211', 'types': ['postal_code'], 'short_name': '11211'}
has comment: http://stackoverflow.com/comment/87632958
score: 2
answers question: http://stackoverflow.com/q/50303439
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/87679781
type: AnswerComment
has text: I am using command prompt and running the above scripts in a file named runner as>> py runner.py
comment on: http://stackoverflow.com/a/50331270
score: 0
type: Comment

python-requests
tags question: http://stackoverflow.com/q/50329050
tags question: http://stackoverflow.com/q/50283632
tags question: http://stackoverflow.com/q/50314709
tags question: http://stackoverflow.com/q/50282981
tags question: http://stackoverflow.com/q/50366668
tags question: http://stackoverflow.com/q/50236505
tags question: http://stackoverflow.com/q/50357490
type: Tag
tags question: http://stackoverflow.com/q/50383210
tags question: http://stackoverflow.com/q/50253483
tags question: http://stackoverflow.com/q/50293845
tags question: http://stackoverflow.com/q/50244034
tags question: http://stackoverflow.com/q/50347722
tags question: http://stackoverflow.com/q/50287283
tags question: http://stackoverflow.com/q/50261869
tags question: http://stackoverflow.com/q/50284830
tags question: http://stackoverflow.com/q/50264078
tags question: http://stackoverflow.com/q/50316885
tags question: http://stackoverflow.com/q/50379308
tags question: http://stackoverflow.com/q/50266855
tags question: http://stackoverflow.com/q/50282684
tags question: http://stackoverflow.com/q/50273021
tags question: http://stackoverflow.com/q/50234569
tags question: http://stackoverflow.com/q/50305821
tags question: http://stackoverflow.com/q/50311516
tag name: python-requests
tags question: http://stackoverflow.com/q/50340047
tags question: http://stackoverflow.com/q/50302097
tags question: http://stackoverflow.com/q/50246304
tags question: http://stackoverflow.com/q/50294533
tags question: http://stackoverflow.com/q/50306251
tags question: http://stackoverflow.com/q/50300407
tags question: http://stackoverflow.com/q/50381369
tags question: http://stackoverflow.com/q/50350624
tags question: http://stackoverflow.com/q/50251870
tags question: http://stackoverflow.com/q/50231746
tags question: http://stackoverflow.com/q/50269036
tags question: http://stackoverflow.com/q/50277180
tags question: http://stackoverflow.com/q/50295729
tags question: http://stackoverflow.com/q/50278020

http://stackoverflow.com/q/50302951
has body: As the title suggests, def multiples_of_3(x, y): y = y + 1 storage_list = [] for i in range(x, y): if i % 3 == 0: storage_list.append(i) print(storage_list) multiples_of_3(3, 9)
downvote count: 1
accepted answer: http://stackoverflow.com/a/50302983
favorite count: 0
has comment: http://stackoverflow.com/comment/87622378
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87622323
has comment: http://stackoverflow.com/comment/87622363
has answer: http://stackoverflow.com/a/50302986
possible better answer: http://stackoverflow.com/a/50302986
tagged with: python
has comment: http://stackoverflow.com/comment/87622366
has title: How do i just print the final list result rather than the previous lists too?
has answer: http://stackoverflow.com/a/50302983
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: printing
has comment: http://stackoverflow.com/comment/87622332
has comment: http://stackoverflow.com/comment/87622395
upvote count: 1

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/50295995
tags question: http://stackoverflow.com/q/50368241

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/50370231

http://stackoverflow.com/comment/87654733
type: Comment
comment on: http://stackoverflow.com/q/50319337
has text: Also, no, I didn't intend to suggest that there is a problem with the way you are getting the token, but rather checking to be sure that you understand that being able to get a token does not prove anything one way or another about your configuration. Any user can get a token, even with invalid or fictitious credentials. It won't work for logging in, but it will still be generated.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87703273
comment on: http://stackoverflow.com/a/50343433
has text: Thank you for your answer, any tips to handle this problem please ?
type: Comment
type: AnswerComment
score: 0

lambda
tags question: http://stackoverflow.com/q/50240317
tags question: http://stackoverflow.com/q/50278213
tags question: http://stackoverflow.com/q/50251073
tags question: http://stackoverflow.com/q/50303244
type: Tag
tags question: http://stackoverflow.com/q/50271762
tags question: http://stackoverflow.com/q/50297639
tags question: http://stackoverflow.com/q/50370917
tags question: http://stackoverflow.com/q/50261638
tags question: http://stackoverflow.com/q/50293176
tags question: http://stackoverflow.com/q/50322431
tags question: http://stackoverflow.com/q/50359697
tags question: http://stackoverflow.com/q/50254248
tag name: lambda
tags question: http://stackoverflow.com/q/50235338
tags question: http://stackoverflow.com/q/50307722
tags question: http://stackoverflow.com/q/50245294
tags question: http://stackoverflow.com/q/50330835

sensors
type: Tag
tags question: http://stackoverflow.com/q/50322925
tag name: sensors

http://stackoverflow.com/comment/87606507
type: QuestionComment
comment on: http://stackoverflow.com/q/50294829
score: 0
has text: @user good question, yes, there can be numbers after names too. Essentially if I can find dates in `.` or `-` format just before the extension, that would be great.
type: Comment

http://stackoverflow.com/comment/87672342
comment on: http://stackoverflow.com/a/50296762
score: 0
type: Comment
has text: Here is a quick sketch of what I'm trying to achieve. The above example is what I have currently, and it is working, it just doesn't scale very well. The example below that is what I'd like to achieve, but I've been unable to find any resources of anything similar. https://i.imgur.com/jlCbApN.png
type: AnswerComment

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/50261000
tags question: http://stackoverflow.com/q/50308352
tags question: http://stackoverflow.com/q/50376081
tags question: http://stackoverflow.com/q/50242364
tags question: http://stackoverflow.com/q/50351530
type: Tag

http://stackoverflow.com/a/50296465
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50296170
has body: Cron is thought to run tasks that happen periodically, as it has easy configuration options for everyday, every hour, each 15 min... Adding cron jobs is not really a good way to configure dynamic tasks to run at a concrete date (or datetime) You could use schedule module as explained in this answer. There is also another library apscheduler, but check if the last version works well with python3 (if you use it ) from datetime import date from apscheduler.scheduler import Scheduler # Start the scheduler sched = Scheduler() sched.start() # Define the function that is to be executed def my_job(text): print text # The job will be executed on November 6th, 2009 exec_date = date(2009, 11, 6) # Store the job in a variable in case we want to cancel it job = sched.add_date_job(my_job, exec_date, ['hello'])
answers question: http://stackoverflow.com/q/50296170
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/54952201
type: Answer
answers question: http://stackoverflow.com/q/50277238
has body: I use sf.bulk.Custom_Object__c.update(data) regularly and have never encountered this issue. I would suggest trying out the following troubleshooting methods: In Salesforce, go to the object in the setup menu and make sure you are using the correct API Name. Sometimes custom objects' labels differ from their API Names (i.e. if the object label was changed after creation) Confirm that your simple-salesforce initialization code (sf = Salesforce(password=userPassword, username=userName, organizationId=orgId)) is bringing you into the correct org (that your orgId is correct) As a last ditch effort, you could try reinstalling simple-salesforce. I suggest this as normally errors I encounter with this type of command results in a SalesforceMalformedRequest error rather than a Attribution error, and it is possible you are using an out-of-date version of Simple-Salesforce
score: 0

http://stackoverflow.com/comment/115329738
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/54065166
has text: Please ignore the second block of code. In my code the line that creates the driver is: `driver = webdriver.Firefox(fp, options=options, executable_path="path-to-geckodriver")`

matrix
tags question: http://stackoverflow.com/q/50313616
tags question: http://stackoverflow.com/q/50356594
tags question: http://stackoverflow.com/q/50256984
tag name: matrix
tags question: http://stackoverflow.com/q/50384045
tags question: http://stackoverflow.com/q/50241698
tags question: http://stackoverflow.com/q/50358784
tags question: http://stackoverflow.com/q/50292546
tags question: http://stackoverflow.com/q/50233916
tags question: http://stackoverflow.com/q/50266736
tags question: http://stackoverflow.com/q/50272134
type: Tag

http://stackoverflow.com/comment/87643814
type: AnswerComment
comment on: http://stackoverflow.com/a/50313812
score: 0
type: Comment
has text: \g<0> is a backreference to the whole match.

http://stackoverflow.com/comment/87871078
type: Comment
has text: Seems to work with simply checking if fill is set to anything: `if fill != '': fill = invert_color(fill)`. I've updated the answer.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50329253

http://stackoverflow.com/a/50337719
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50337632
has body: %timeit x times how long it takes to do nothing with x. It's pretty easy to do nothing. %timeit x[a] times how long it takes to actually do a thing with x, that thing being dynamically work out what the indexing operation means and then copy the 20 specified rows into a new array. Doing things is a lot harder than doing nothing.
type: Answer

http://stackoverflow.com/q/50383331
tagged with: windows
has comment: http://stackoverflow.com/comment/87782222
tagged with: windows-console
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87782612
has comment: http://stackoverflow.com/comment/87782481
has title: Python stops working on Windows and console freezes
upvote count: 2
has comment: http://stackoverflow.com/comment/87782806
type: UnansweredQuestion
has body: Firstly, I'm a pen tester, so I use Python &amp; Perl all the time. I programmed a Python script for mass test exploiting of Wordpress to test all websites on a server. The script works perfectly on Linux (Kali Linux &amp; Ubuntu ), but when I use it on Windows, it works for only 5 or 10 minutes, and then the console stops working completely. I can't exit the script normally. I can only exit Python if I close the console window. I don't think the problem is in the script because other scripts show the same problem. If I change windows, it's still the same problem. Here are some lines of my Python script: #!/usr/bin/python import requests, re, urllib2, os, sys, codecs from multiprocessing.dummy import Pool from time import time as timer import time from random import sample as rand from platform import system from colorama import Fore from colorama import Style from pprint import pprint from colorama import init init(autoreset=True) try: with codecs.open(sys.argv[1], mode='r', encoding='ascii', errors='ignore') as f: ooo = f.read().splitlines() except IOError: pass ooo = list((ooo)) def banners(): if system() == 'Linux': os.system('clear') if system() == 'Windows': os.system('cls') banner = """{}{} \n \n Coded to w \n""".format(fc, sb) print banner Agent = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0'} user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3" baaReflexlibr = requests.get(url) if "/wp-content/" in baaReflexlibr.text: print ''.format(fg, fg, url, fc,fc, sb,fr) wpsbot(url) else: print ''.format(sb, sd, url, fc,fc, sb,fr) except: pass def wpsbot(url): try: some exploits and 0days except: pass banners() def Main(): try: start = timer() ThreadPool = Pool(30) Threads = ThreadPool.map(sitebul, ooo) print('Time: ' + str(timer() - start) + ' seconds') except: pass if __name__ == '__main__': Main()
downvote count: 0
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/comment/87562117
type: AnswerComment
comment on: http://stackoverflow.com/a/50272589
has text: @deceze True, and that makes this answer technically correct. Though I wonder what the question really is. I mean, another answer is that it's the length of the iterable minus 1, or the amount of elements in a list minus 1, but the question is: what is really the question.
type: Comment
score: 2

http://stackoverflow.com/comment/87531909
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50256937
has text: https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe

http://stackoverflow.com/q/50317114
has comment: http://stackoverflow.com/comment/87650050
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: How to match and merge the pandas Dataframe with the list?
has answer: http://stackoverflow.com/a/50317295
score: 0
tagged with: pandas
has body: I have a simple pandas data frame and list which is as fallows import pandas as pd frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']}) mylist =['cat blue', 'sky green', 'dog black'] how to find the match between this dataframe and list. I got the result when the list is like mylist_1 = ['cat','sky','dog'] But when i try to solve with mylist the dataframe is not matching. Here is the piece of code which i used. import pandas as pd frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']}) print(frame) mylist_1 =['cat', 'sky', 'dog'] import nltk frame['Data'] = frame['a'].apply(lambda x : ([i for i in nltk.word_tokenize(x) if i in mylist_1])) print(frame) But how to match with the my_list with the dataframe. Please help me on this issue
answer count: 1
tagged with: sklearn-pandas
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87745957
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50364627
has text: It worked Thanks. will index = false remove the extra column?
type: Comment

http://stackoverflow.com/comment/87478399
comment on: http://stackoverflow.com/a/50230421
score: 0
type: Comment
type: AnswerComment
has text: Hi Sam, Thanks for your reply! Indeed this works for the examples I gave, but unfortunately, in my language, the words "from" and "to" have many synonyms that can occures. I'm not even sure to get the word "go", because sometimes the sentence is 'what's the route from x to y'... But if I can't figure out how to do this with regex I'll take your solution.

http://stackoverflow.com/comment/87742870
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50303717
score: 0
has text: I got this error while persisting custom object to user model Manager isn't available; 'auth.User' has been swapped for 'student.User' , can you help me @neverwalkaloner

http://stackoverflow.com/comment/87646591
type: QuestionComment
has text: If you read everything at both questions carefully and study the code in the linked duplicated, it will answer all your questions.
comment on: http://stackoverflow.com/q/50309792
score: 0
type: Comment

http://stackoverflow.com/comment/87516850
has text: @Alasdair https://www.dropbox.com/s/7hh20d6ua1kyvl2/task.html?dl=0 - it's HTML file and https://www.dropbox.com/s/mp66yv7fjuu8rgd/views.py?dl=0 my views.py
type: QuestionComment
comment on: http://stackoverflow.com/q/50248969
type: Comment
score: 0

http://stackoverflow.com/q/50236055
tagged with: tkinter
has title: How do I use winfo_width() for widgets? What is the difference between width and reqwidth?
has comment: http://stackoverflow.com/comment/87569384
score: 1
has comment: http://stackoverflow.com/comment/87570443
linked to: http://stackoverflow.com/q/4220295
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50270574
linked to: http://stackoverflow.com/q/34373533
upvote count: 1
has body: I want to make a widget appear in the center of the screen without using grid or pack. Here is some example code: import tkinter Win=tkinter.Tk() Welcome=tkinter.Label(Win,text="Welcome.") Welcome.place(x=Win.winfo_width()//2-Welcome.winfo_width()//2,y=16) Win.update() When I ran the code, the widget appeared on the far left of the screen instead of the center. I was told about reqwidth and update_idletasks, which fixed the code, but I was wondering if someone could explain why the code doesn't work without reqwidth and update_idletasks, as I like to fully understand programming concepts.
has answer: http://stackoverflow.com/a/50270574
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87558774
has comment: http://stackoverflow.com/comment/87489987
has comment: http://stackoverflow.com/comment/87501754
tagged with: python
has comment: http://stackoverflow.com/comment/87489615
type: AnsweredQuestion

http://stackoverflow.com/a/64926416
type: Answer
answers question: http://stackoverflow.com/q/50287106
has body: I suppose you use VNC at your server. At least I got the same situation with Ubuntu 18.04, Selenium 3.141.59, ChromeDriver 87.0.4280.20 and TigerVNC 1.3.10. Unfortunately, it's a bug of Chromedriver. https://monorail-prod.appspot.com/p/chromedriver/issues/detail?id=1300 But it was archived without a fix in 2017. I'd recommend do not to use VNC and try Xvfb instead.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87589408
type: QuestionComment
comment on: http://stackoverflow.com/q/50279180
type: Comment
has text: This constructor takes as input a pointer to string because it creates an object that "speak is own language", so it has to recognize the symbols of his language, that might be entire strings like "foo" or whatever else. Unfortunately I don't understand your suggestion. Because I have to bind with that constructor on the first post, but I have to find a way to intercept from python a list<string>. I don't know if my problem is really clear
score: 0

http://stackoverflow.com/a/50298029
has comment: http://stackoverflow.com/comment/87612973
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87613093
has comment: http://stackoverflow.com/comment/87613609
has comment: http://stackoverflow.com/comment/87613356
type: Answer
has comment: http://stackoverflow.com/comment/87612963
accepted answer of: http://stackoverflow.com/q/50297915
score: 0
answers question: http://stackoverflow.com/q/50297915
has body: You can pass the references to other objects like this: class MainApp(QMainWindow, FORM_CLASS): def __init__(self, parent=None): super(MainApp, self).__init__(parent) QMainWindow.__init__(self) self.setupUi(self) self.btnConnect.clicked.connect(self.connect) class MyOtherClass(object): def __init__(self, the_button): self.btn = the_button myApp = MainApp() my_other_class = MyOtherClass(myApp.btnConnect)

http://stackoverflow.com/comment/87493440
type: Comment
type: QuestionComment
score: 0
has text: Oof, I really don't know enough Python implementation details to answer that. Maybe someone else can?
comment on: http://stackoverflow.com/q/50232026

http://stackoverflow.com/q/50375422
type: Question
possible better answer: http://stackoverflow.com/a/50375569
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/50375458
has answer: http://stackoverflow.com/a/68349636
has body: I have a two-level dictionary that looks like this: myDict = {'a':{'2017-01-01':4.1, '2017-01-02':10.8}, 'b':{'2017-01-01':6.2, '2017-01-03':8.5}} I'd want to store this as a dataframe that has the following design: Dates for which data exist in one column and not the other column become np.nan in the dataframe - this is nice because I can then use the backfill functions if needed. The union of all dates becomes the index and the index is of type pd.DatetimeIndex - this is nice so i can do time operations easily on the dataframe Dataframe: mydf = pd.DataFrame({'a':[4,10,np.nan],'b':[6.2,np.nan,8.5]}, index=pd.DatetimeIndex(['2017-01-04','2017-01-02','2017-01-03'])) mydf.index.name = 'Date' I.e., mydf Out[33]: a b Date 2017-01-04 4.0 6.2 2017-01-02 10.0 NaN 2017-01-03 NaN 8.5 The problems I am facing are that of course I don't know in advance which dates comprise the final index (union of all dates), and I also don't know what's the best way to do add data column by column. The pseudocode I have in mind: (1) loop across all dates for all keys in level 1 of the dictionary, then take the union of all dates. This becomes my index. (2) Then create a new dictionary that only has the original keys and the values in the same order as the index in (1), and np.nan where no values can be found (3) Use the dictionary in (2) to create the pandas dataframe However, I see some inefficiencies in this approach in terms of too many loops over the dictionary and copying data more often than potentially required. Any advice is welcome.
tagged with: python
tagged with: dictionary
favorite count: 0
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/50375458
tagged with: dataframe
has title: Convert dict of dictionaries to a pandas DataFrame
has answer: http://stackoverflow.com/a/50375569

http://stackoverflow.com/a/50343852
answers question: http://stackoverflow.com/q/50331025
type: Answer
upvote count: 9
score: 9
has body: Thanks to Silencer, with his help I was able to make it work, so I'll provide the code and hope it helps other people: import cv2 import numpy as np bounding_box_image = cv2.imread('PedestrianRectangles/1/grim.pgm') grayimage = cv2.cvtColor(bounding_box_image, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(grayimage, 254, 255, cv2.THRESH_BINARY) cv2.imshow('mask', mask) cv2.waitKey(0) image, contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: if cv2.contourArea(contour) &lt; 200: continue rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) ext_left = tuple(contour[contour[:, :, 0].argmin()][0]) ext_right = tuple(contour[contour[:, :, 0].argmax()][0]) ext_top = tuple(contour[contour[:, :, 1].argmin()][0]) ext_bot = tuple(contour[contour[:, :, 1].argmax()][0]) roi_corners = np.array([box], dtype=np.int32) cv2.polylines(bounding_box_image, roi_corners, 1, (255, 0, 0), 3) cv2.imshow('image', bounding_box_image) cv2.waitKey(0) cropped_image = grayimage[ext_top[1]:ext_bot[1], ext_left[0]:ext_right[0]] cv2.imwrite('crop.jpg', cropped_image) And the output
downvote count: 0

http://stackoverflow.com/q/50348975
score: 23
has answer: http://stackoverflow.com/a/50349051
upvote count: 23
favorite count: 0
possible better answer: http://stackoverflow.com/a/50349052
type: Question
has answer: http://stackoverflow.com/a/61691955
linked to: http://stackoverflow.com/q/23842713
has body: I have installed Anaconda 2 &amp; 3 in my system. Anaconda 2 contains python 2.7 &amp; Anaconda 3 contains python 3.6. I need to run my python code using command prompt &amp; I need to use python 3.6 While I'm running python --version, I'm getting python 2.7.14. How do I change it to python 3.6?
has comment: http://stackoverflow.com/comment/87713712
has title: How to change python version in command prompt if I have 2 python version installed
tagged with: python
accepted answer: http://stackoverflow.com/a/50349883
has answer: http://stackoverflow.com/a/50349027
has answer: http://stackoverflow.com/a/50349883
has comment: http://stackoverflow.com/comment/87713730
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50349052
has answer: http://stackoverflow.com/a/68482462
has answer: http://stackoverflow.com/a/50349150
has comment: http://stackoverflow.com/comment/87713723
has comment: http://stackoverflow.com/comment/87713648
downvote count: 0
answer count: 7

http://stackoverflow.com/comment/87691950
score: 0
type: Comment
has text: @MattCremeens The problem is with session
type: QuestionComment
comment on: http://stackoverflow.com/q/50336996

http://stackoverflow.com/q/50287179
type: Question
has title: Celery workers work 5 minutes later when receive tasks
type: UnansweredQuestion
answer count: 1
tagged with: flask
tagged with: celery
has body: I have a scheduled task per 5 minutes, but the celery worker completes the work 5 minutes later, rather than completes it once has received it. [2018-05-11 15:05:00,501: INFO/MainProcess] Received task: mimir.core.task.batch_send_share_message.batch_send_member_sent_share_template_message[53e836d3-ac94-42f5-b79e-c525d5e43b15] ETA:[2018-05-11 15:10:00.170054+08:00] [2018-05-11 15:10:00,210: INFO/MainProcess] Task mimir.core.task.batch_send_share_message.batch_send_member_sent_share_template_message[53e836d3-ac94-42f5-b79e-c525d5e43b15] succeeded in 0.0213618567213s: None
score: 0
has comment: http://stackoverflow.com/comment/87591163
has comment: http://stackoverflow.com/comment/87599654
tagged with: python
has answer: http://stackoverflow.com/a/50291844
has comment: http://stackoverflow.com/comment/87592171
has comment: http://stackoverflow.com/comment/87591543

http://stackoverflow.com/comment/87696613
comment on: http://stackoverflow.com/a/50340206
has text: Check the output carefully, this does exactly that.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87584694
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50284167
has text: Unless I'm much mistaken, `input` in python is always read as a string by default... you can try it by giving it an `int` or some other numeric, and then testing `type(my_input_variable)`, it should be `str`. However, you're right in saying that you should explicitely cast it to whatever data type you want if it is anything beside `str` that you are after!

http://stackoverflow.com/comment/113129899
comment on: http://stackoverflow.com/q/50302705
type: QuestionComment
type: Comment
score: 0
has text: Hi I used the function "winsorize_series" posted in my question. Although the results looked slightly different from that of Stata, it did well.

http://stackoverflow.com/q/50265160
has comment: http://stackoverflow.com/comment/87548373
possible better answer: http://stackoverflow.com/a/50266206
has comment: http://stackoverflow.com/comment/87552168
accepted answer: http://stackoverflow.com/a/50363706
tagged with: django-admin
has answer: http://stackoverflow.com/a/50266206
has answer: http://stackoverflow.com/a/50363706
tagged with: django
has comment: http://stackoverflow.com/comment/87551695
has comment: http://stackoverflow.com/comment/87552021
has comment: http://stackoverflow.com/comment/87548337
has answer: http://stackoverflow.com/a/50265416
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: django-email
has title: How to add Banned Users to table,and send details to user's email within Django Admin
has comment: http://stackoverflow.com/comment/87551356
tagged with: django-models
tagged with: python
has body: I have a simple banning function that sets user active to false and a basic emailing function to send emails. The tables I am working with are User,Profile,Report &amp; Banned_User Table. I am looking to: add the user Profile,Reason_reported from Report table and datetime that they were banned into the Banned_User table once banned. send these details to the users email Currently I am recieving a 'Attribute Error at /admin/api/profile/: WSGIRequest' object has no attribute 'report'' and not sure how to go about doing these 2 things. def banning_users(self, request, queryset): for obj in queryset: if hasattr(obj, 'user'): # This object is a Profile, so lookup the user obj = obj.user obj.is_active = False #email function banned_user = Banned_User.objects.create(profile=request.user.profile, report_reasons=request.report.report_reason) banned_user.save() #Sends ban email to user,does not send through the variables yet subject = 'Ban' message = 'You have been banned' email_from = settings.EMAIL_HOST_USER recipient_list = [obj.email] send_mail( subject, message,email_from, recipient_list ) obj.save() self.message_user(request, "User is banned and Email has been sent") Tables are below: Report Table class Report(models.Model): def __str__(self): return str.join(str(self.user_reported), str(self.datetime_sent)) TOXICITY = 'Toxicity' SPORTSMANSHIP = 'Poor sportsmanship' REPORT_REASON_CHOICES = ( (TOXICITY, 'Toxicity'), (SPORTSMANSHIP, 'Unsportsmanlike Behaviour'), ) session = models.ForeignKey( 'Session', on_delete=models.PROTECT, blank=False, null=False, ) user_reported = models.ForeignKey( 'Profile', on_delete=models.PROTECT, blank=False, null=False, related_name='user_reported_report', ) sent_by = models.ForeignKey( 'Profile', on_delete=models.PROTECT, blank=False, null=False, related_name='sent_by_report', ) report_reason = models.CharField( max_length=255, choices=REPORT_REASON_CHOICES, default=TOXICITY, ) datetime_sent = models.DateTimeField(auto_now_add=True,) Banned…
type: Question

http://stackoverflow.com/q/50355919
tagged with: python
accepted answer: http://stackoverflow.com/a/50651904
has answer: http://stackoverflow.com/a/50651904
tagged with: qscintilla
type: AnsweredQuestion
answer count: 3
tagged with: pyqt
possible better answer: http://stackoverflow.com/a/50431088
score: 7
has answer: http://stackoverflow.com/a/50429902
tagged with: pyqt5
has title: How to implement a comment feature that works with multiple selections in QScintilla?
has answer: http://stackoverflow.com/a/50431088
has body: I'm trying to implement a toggle comment feature in QScintilla that works with multiple selection. Unfortunately I don't know very well how to do it, so far I've come up with this code: import sys import re import math from PyQt5.Qt import * # noqa from PyQt5.Qsci import QsciScintilla from PyQt5 import Qsci from PyQt5.Qsci import QsciLexerCPP class Commenter(): def __init__(self, sci, comment_str): self.sci = sci self.comment_str = comment_str def is_commented_line(self, line): return line.strip().startswith(self.comment_str) def toggle_comment_block(self): sci = self.sci line, index = sci.getCursorPosition() if sci.hasSelectedText() and self.is_commented_line(sci.text(sci.getSelection()[0])): self.uncomment_line_or_selection() elif not self.is_commented_line(sci.text(line)): self.comment_line_or_selection() else: start_line = line while start_line &gt; 0 and self.is_commented_line(sci.text(start_line - 1)): start_line -= 1 end_line = line lines = sci.lines() while end_line &lt; lines and self.is_commented_line(sci.text(end_line + 1)): end_line += 1 sci.setSelection(start_line, 0, end_line, sci.lineLength(end_line)) self.uncomment_line_or_selection() sci.setCursorPosition(line, index - len(self.comment_str)) def comment_line_or_selection(self): sci = self.sci if sci.hasSelectedText(): self.comment_selection() else: self.comment_line() def uncomment_line_or_selection(self): sci = self.sci if sci.hasSelectedText(): self.uncomment_selection() else: self.uncomment_line() def comment_line(self): sci = self.sci line, index = sci.getCursorPosition() sci.beginUndoAction() sci.insertAt(self.comment_str, line, sci.indentation(line)) sci.endUndoAction() def uncomment_line(self): sci = self.sci line, index = sci.getCursorPosition() if not self.is_commented_line(sci.text(line)): return sci.beginUndoAction() sci.setSelection( line, sci.indentation(line), line, sci.indentation(line) + len(self.comment_str) ) sci.removeSelectedText() sci.endUndoAction() def comment_selection(self):…
downvote count: 1
favorite count: 0
type: Question
upvote count: 8
tagged with: scintilla

http://stackoverflow.com/a/50384673
score: 0
answers question: http://stackoverflow.com/q/50384598
type: AcceptedAnswer
has body: First thing I would do is isolate the second elements: seconds = [x for (y,x) in my_list ] then I would check if 2 exists in this list with 2 in seconds or in a single step: &gt;&gt;&gt; 2 in [x for (y,x) in my_list ] False &gt;&gt;&gt; 3 in [x for (y,x) in my_list ] True &gt;&gt;&gt; Finally, from @Faibbus comment, in python if you are not interested in a value (you can ignore it) we tend to use _ so the above becomes: 2 in [x for (_,x) in my_list ]
type: Answer
accepted answer of: http://stackoverflow.com/q/50384598

http://stackoverflow.com/a/50304246
type: Answer
has body: This is one approach Demo: res = [] with open(filename, "r") as infile: for i in infile.readlines(): val = i.strip() res.append([val[:5], val[5:10], val[10:15], val[15:]]) with open(filename, "w") as outfile: for i in res: outfile.write(", ".join(i) + "\n")
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50304216

http://stackoverflow.com/q/50367947
answer count: 1
has title: get vscode python error when run pyspark program using vs code
has answer: http://stackoverflow.com/a/50518560
tagged with: pyspark
tagged with: python
type: Question
score: 0
has body: I run my pyspark program in vscode, and get error: PicklingError: Could not serialize object: ImportError: No module named visualstudio_py_debugger . I suppose it has something to do with my vscode setting?
tagged with: visual-studio-code
type: UnansweredQuestion

http://stackoverflow.com/q/50332342
has body: I am attempting to loop over a series of text files I have and I want to do so by checking the value of the next line. The input from the text file looks like: Person1 (COUNT)|key 1|************ Person2 (COUNT)|key // and so on Some people may have a key and others may not. I am trying to write a loop that checks for at least 3 consecutive lines (people with keys) before a space like the Person1 example where each line begins with a character and I want to print only those cases. My current loop looks like this: for line in input: if re.match(r'\S', line): line1 = line print(line1) if re.match(r'\S', input.next()): line2 = line print(line2) if re.match(r'\S', input.next()): line3 = line print(line3) However, I cannot seem to get this loop correct. It seems to be printing the Person three times and only sometimes printing the key. Looking for any guidance here available.
tagged with: python
tagged with: regex
tagged with: python-2.7
tagged with: for-loop
type: UnansweredQuestion
score: 0
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50332501
has title: Checking For Next Line

http://stackoverflow.com/q/50277675
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50277908
score: 1
tagged with: python
has title: Django admin nested models
tagged with: python-3.x
has body: I have model model Word which has foreign key to model Group And I want the structure in django admin panel to be nested, like this: -Group -Word1 (clickable where I can show all the info about this word model) -Word2 (clickable) -Word3 (clickable) I tried to do something like this in admin.py but got an error: no class meta from django.contrib import admin from main_app.models import Profile, Project, User, Word, Phrase, Group def unbound_callable(word): return word.name class WordInline(admin.TabularInline): model = Word fields = ('name', 'model_callable', 'model_admin_callable', unbound_callable) readonly_fields = ('model_callable', 'model_admin_callable', unbound_callable) def model_admin_callable(self, word): return word.name class GroupAdmin(admin.ModelAdmin): model = Group inlines = (Word,) class Meta: model = Group admin.site.register([GroupAdmin, Word, Phrase])
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1

http://stackoverflow.com/comment/87728092
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50355825
has text: How does the column Description look like?

http://stackoverflow.com/comment/87486514
type: QuestionComment
score: 0
has text: Like basically any open source project, pyinstaller support for a particular package is likely going to be added by someone who needs it. If you have time and skills, they take pull requests: https://github.com/pyinstaller/pyinstaller/pulls
type: Comment
comment on: http://stackoverflow.com/q/50234487

http://stackoverflow.com/comment/87622363
type: QuestionComment
has text: Thanks davedwards !
comment on: http://stackoverflow.com/q/50302951
score: 0
type: Comment

http://stackoverflow.com/a/50333693
upvote count: 2
downvote count: 0
score: 2
type: Answer
has body: Consider building separate plots on same figure with y-axes ranges tailored to subsetted data. Below demonstrates with random data seeded for reproducibility (for readers of this post). Data (with U values higher than S values) import pandas as pd import numpy as np import seaborn import matplotlib.pyplot as plt np.random.seed(2018) u_df = pd.DataFrame({'Day': pd.date_range('2016-10-01', periods=10)\ .append(pd.date_range('2016-10-01', periods=10)), 'n_data': np.random.uniform(0,800,20), 'Group': 'U'}) s_df = pd.DataFrame({'Day': pd.date_range('2016-10-01', periods=10)\ .append(pd.date_range('2016-10-01', periods=10)), 'n_data': np.random.uniform(0,200,20), 'Group': 'S'}) df = pd.concat([u_df, s_df], ignore_index=True) df['Day'] = df['Day'].astype('str') Plot fig = plt.figure(figsize=(10,5)) for i,g in enumerate(df.groupby('Group')): plt.title('N_data of {}'.format(g[0])) plt.subplot(2, 1, i+1) seaborn.boxplot(x="Day", y="n_data", data=g[1], palette="PRGn", showfliers=False) plt.tight_layout() plt.show() plt.clf() plt.close('all') To retain original hue and grouping, render all non-group n_data to np.nan: fig = plt.figure(figsize=(10,5)) for i,g in enumerate(df.Group.unique()): plt.subplot(2, 1, i+1) tmp = df.copy() tmp.loc[tmp['Group']!=g, 'n_data'] = np.nan seaborn.boxplot(x="Day", y="n_data", hue="Group", data=tmp, palette="PRGn", showfliers=False) plt.tight_layout() plt.show() plt.clf() plt.close('all')
answers question: http://stackoverflow.com/q/50316180

http://stackoverflow.com/comment/87660941
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50322620
type: QuestionComment
has text: Python doesn't return nothing.. When i try `print(find_triple([6,11,7,2,3]))` i get `None`..

http://stackoverflow.com/q/50242695
has comment: http://stackoverflow.com/comment/87503199
has comment: http://stackoverflow.com/comment/87503374
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/87504227
type: UnansweredQuestion
has body: I am trying to save plots of a pandas' dataframe in a jupyter notebook, but I am getting a blank image of 72 Bytes size. Here is the code I am using: EperDtDF = spark.sql("SELECT timestamp, data.ldr from deviceData where timestamp &gt;= '2018-05-01T00:00:00+02:00' and timestamp &lt; '2018-05-07T23:59:59+02:00'") EperDtDF.cache() EperDtPanda = EperDtDF.toPandas().set_index('timestamp') slice = EperDtPanda[0:4321].plot() # slice of first 6h (double of previous calculation) fig = slice.get_figure() fig.savefig('test2', format='png') The file created is there, with the right name, but having just 72 Bytes, and I cannot open it, as it is a blank image. How to save the plot which is displayed the right way?
tagged with: python
has comment: http://stackoverflow.com/comment/87503259
has title: Save plot from pandas in jupyter notebook
score: 3
tagged with: pandas-groupby
answer count: 0
tagged with: pandas
upvote count: 3
tagged with: matplotlib
downvote count: 0

http://stackoverflow.com/comment/87547223
type: QuestionComment
comment on: http://stackoverflow.com/q/50260339
score: 0
type: Comment
has text: My question is when the cleanup function is executed, does it get executed only during a failure of it gets executed in a normal scenario(when there is no failure) as well?

http://stackoverflow.com/comment/87674775
has text: if its not too much trouble, clear out your python env and install anaconda as your base python distro. from there use venv and you will be a lot better off
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50325466

http://stackoverflow.com/comment/87743029
type: Comment
comment on: http://stackoverflow.com/a/50329465
has text: The input data is provided by some third party source, so it's not possible to escape it while creation and this behavior is very rare, so there should be a way to handle it with some custom code snippet, since I cannot ignore these lines.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50340056
tagged with: python
tagged with: linear-programming
favorite count: 0
has body: I'm trying to minimize a dot product of 2 vectors but it doesn't work and I have no idea why. Can someone please help me? I have a matrix c of this form: c = [[c11, c12, c13, c14, c15], [c21, c22, c23, c24, c25]] I want to get a matrix p of this form: p = [[p11, p12, p13, p14, p15], [p21, p22, p23, p24, p25]] I want to maximize this value : c11*p11 + c12*p12 +c13*p13 + c14*p14 + c15*p15 + c21*p21 + c22*p22 +c23*p23 + c24*p24 + c25*p25 To get that I convert the c and p to 1-D vector and do the dot product so that my function to maximize is: f(p) = c.dot(p) The constraints are: c11 + c12 + c13 + c14 + c15 = 1 c21 + c22 + c23 + c24 + c25 = 1 every element in p must be between 0.01 and 0.99. I have tried scipy.optimize.linprog and it works: from scipy.optimize import linprog c = np.array([0. , 0. , 0. , 0. , 0. , 0. , 20094.21019108, 4624.08079143, 6625.51724138, 3834.81081081]) A_eq = np.array([[1,1,1,1,1,0,0,0,0,0], [0,0,0,0,0,1,1,1,1,1]]) b_eq = np.array([1, 1]) res = linprog(-c, A_eq=A_eq, b_eq=b_eq, bounds=(0.01, 0.99)) res Out[561]: fun: -19441.285871873002 message: 'Optimization terminated successfully.' nit: 13 slack: array([0.03, 0.98, 0.98, 0.98, 0.98, 0.98, 0.03, 0.98, 0.98, 0.98, 0. , 0. , 0.95, 0. , 0. , 0. , 0. , 0. , 0. , 0. ]) status: 0 success: True x: array([0.96, 0.01, 0.01, 0.01, 0.01, 0.01, 0.96, 0.01, 0.01, 0.0 But I'm trying to use scipy.optimize.minimize with SLSQP instead and that's where I get this 'Singular matrix C in LSQ subproblem' . Here is what I've done: from scipy.optimize import minimize def build_objective(ck, sign = -1.00): """ Builds the objective fuction for matrix ck """ # Here I turn my c matrix to a 1-D matrix ck = np.concatenate(ck) def objective(P): return sign*(ck.dot(P)) return objective def build_constraint_rows(ck): """ Builds the constraint functions that specify that the sum of the proportions for each bin equals 1 """ ncol = ck.shape[1] nrow = ck.shape[0] constrain_dict = [] for i in range(nrow): vector = np.zeros((nrow…
has title: scipy.optimize with SLSQP. 'Singular matrix C in LSQ subproblem'
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87696634
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87724184
tagged with: scipy-optimize-minimize
tagged with: scipy
has comment: http://stackoverflow.com/comment/87736270
tagged with: optimization
type: Question
score: 1

http://stackoverflow.com/comment/87575390
has text: I need to ad FIGURES to a subplot. I created two figures, and want to merge them in a single plot. I tried your method, but it does not work. Thanks.
score: 1
comment on: http://stackoverflow.com/q/50279217
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50264829
answers question: http://stackoverflow.com/q/50264691
accepted answer of: http://stackoverflow.com/q/50264691
has body: df.query('column1 &gt; 0 and column2 &gt; 0') \ .eval('(column1 - column2) / totalcolumn').idxmax()
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87660709
type: QuestionComment
score: 2
has text: `self` refers to your Soda instance, so unless you define a method called `split`, it does not have one.
type: Comment
comment on: http://stackoverflow.com/q/50322454

http://stackoverflow.com/comment/87708319
type: QuestionComment
comment on: http://stackoverflow.com/q/50346006
score: 0
has text: This is not a bug. Depending on the implementation, the FFT algorithm performs good for composite lengths (products of powers of small primes). [See here](https://stackoverflow.com/questions/46357589/numpy-fft-is-fast-for-lengths-that-are-products-of-small-primes-but-how-small) for additional information. The prime factors of 1492828 are 2 and **373207**, while for 1492827 they are much smaller (3, 7, 67, 1061), and for 1492826 they are big again...
type: Comment

http://stackoverflow.com/a/50373321
accepted answer of: http://stackoverflow.com/q/50373229
has body: In your TrasactionForm.__init__ method you are referencing self.user before self.user has been even initialized. What you want to do is assign value to self.user in the constructor before using it. Therefore, try changing your constructor to: class TransactionForm(forms.ModelForm): # ... def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') # rest of the constructor...
answers question: http://stackoverflow.com/q/50373229
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/q/50302852
duplicate of: http://stackoverflow.com/q/739654
tagged with: python
duplicate of: http://stackoverflow.com/q/5409450
has body: I have many functions that use the same decorators. Is there a way to put all of them in one, and then just apply one across all the functions?
has comment: http://stackoverflow.com/comment/87628863
has title: How to replace multiple python decorators with one?
score: 2
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/739654
has answer: http://stackoverflow.com/a/50302853
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/5409450

http://stackoverflow.com/q/50310613
score: 3
upvote count: 3
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53844989
has comment: http://stackoverflow.com/comment/87652021
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87637568
linked to: http://stackoverflow.com/q/44140586
tagged with: python
has title: How to Capture Screen using Python with better frame rate
has comment: http://stackoverflow.com/comment/87650241
tagged with: opencv
has comment: http://stackoverflow.com/comment/87637513
has body: So i have this code, which records my screen and saves it as output.avi but it only captures 10-15 frames per second. How do i make it capture around 50-60 frames at least. if i am not wrong cv2 is cpu based or something. how do i use gpu to do this task ? import cv2 from PIL import ImageGrab import numpy as np fourcc = cv2.VideoWriter_fourcc('X','V','I','D') video = cv2.VideoWriter("output.avi",fourcc,8,(1920,1080)) while(True): image = ImageGrab.grab() image = np.array(image) frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) video.write(frame) key = cv2.waitKey(1) cv2.imshow("Hello",frame) if(key==27): break video.release() cv2.destroyAllWindows()

http://stackoverflow.com/comment/87521845
has text: Because we manipulate a big json file and we want that key-value pair remains intact.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50252251
type: Comment

http://stackoverflow.com/comment/87652730
has text: Same problem. My planned solution is to wait for Linux Mint 19 which should be out any day now... It is python 3.6 based so no need for the extra PPA. Its just my home notepad so no big deal.
score: 0
comment on: http://stackoverflow.com/q/50317948
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87479891
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50230908
has text: Thanks, this seems to work nicely. I didn't know about the lambda syntax :)

http://stackoverflow.com/q/50320122
tagged with: pseudocode
type: Question
has answer: http://stackoverflow.com/a/79335288
has title: Algorithm/pseudocode for UK Taxation (capital gains)
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: python
downvote count: 1
favorite count: 0
tagged with: algorithm
score: 1
has body: I've been looking to implement the algorithm (or pseudocode) for the UK CGT taxation (as described on HRMC's website) but I can't get my head around the sort of algorithm I'd need to do this efficiently without looping too many times. I've tried to search as much as possible, and even tried a few of my own implementations but can't seem to get it to work properly. There's a proper example on TimeToTrade's website as well. I've tried explain here to the best of my ability. Assuming I have the following table of buy/sells (date in yyyy-mm-dd): id action amount per share total date 1. buy 2000 £1 £2000 2017-05-05 10:00 2. buy 1000 £1 £1000 2017-05-10 10:00 3. buy 1000 £1.5 £1500 2017-06-01 10:00 4. sell 2000 £2.5 £5000 2017-06-01 10:00 5. sell 1000 £2 £2000 2017-06-01 10:00 6. buy 1500 £0.5 £750 2017-06-20 10:00 According to HRMC the following rules have to be respected: A sale is first matched to a buy (FIFO) on the same day A sale is then matched to a buy (FIFO) within the next 30 days A sale is finally matched with the averaged buys in the past (pooled into a "Section 104 holding") This gives me the following calculation when doing it by hand: 1+2 pooled = Total 3000 shares @ £3000 (£1 per share) 3 has sell transaction(s) on the same day, so this is not pooled for now. 1000 of the 2000 shares are matched with the buy on the same day (first in first out) 1000 shares @ £1.5 = £1500 - a gain of 1000*£2.5-£1500 = £1000 1000 of the remaining 1000 shares from sell 4 are matched with the buy in the next 30 days (6) 1000 shares @ £0.5 = £500 - a gain of 1000*£2.5-£500 = £2000 Sell transaction 4 has a total chargeable gain of £1000+£2000=£3000 5 can no longer match with buy 3 on the same day, as it has been depleted of shares to match 500 of the 1000 shares are matched with the buy 6 as it has 500 shares remaining 500 shares @ 0.5 = £250 - a gain of (500*£2)-£250 = £750 500 of the remaining 500 shares are finally matched with the pooled holdings from (1+2) 500 shares @ 1 = £…

http://stackoverflow.com/comment/87519189
score: 0
has text: Does `merged = df.reset_index().merge( df, left_on=['cluster_name', 'qseqid', 'sseqid', 'qstart', 'qend'], right_on=['cluster_name', 'sseqid', 'qseqid', 'sstar', 'send'] )` blow up your machine? That's a possible way to narrow down your candidate space...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50249340

http://stackoverflow.com/comment/87612309
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50297563
has text: What is a sample of what the log file looks like? Is it a stream of valid JSON values (e.g. `{...}{...}...`), or is it a single, incomplete value (`[{...}, {...},...`)?

http://stackoverflow.com/a/50340361
has comment: http://stackoverflow.com/comment/87697109
answers question: http://stackoverflow.com/q/50340232
has body: In addition to what @jpp said simple datatypes like integers are returned by value not by reference so when you assign it to something and change that something it doesn't get affected a = 10 b = a #b=a=10 b = 11 #b=11, a=10 print a, b --&gt; 10 11 I'd have made this a comment to his but I need reputation to do that :D
score: 0
has comment: http://stackoverflow.com/comment/87696996
has comment: http://stackoverflow.com/comment/87696934
has comment: http://stackoverflow.com/comment/87697041
type: Answer

http://stackoverflow.com/a/50382881
has body: # distance between 2 points eucl.dist &lt;- function(x1, x2) sqrt(sum((x1 - x2) ^ 2)) # area of triangle area &lt;- function(x1,x2,x3) { v1 = x1 - x2 v2 = x1 - x3 0.5* sqrt( (v1[2]*v2[3] - v1[3]*v2[2])**2 + (v1[3]*v2[1] - v1[1]*v2[3])**2 + (v1[1]*v2[2] - v1[2]*v2[1])**2) } # function to calculate curvature (optional for this problem) curvature &lt;- function(x1, x2, x3){ 4 * area(x1, x2, x3) / (eucl.dist(x1,x2)*eucl.dist(x2,x3)*eucl.dist(x3,x1)) } # function to calculate radius radius &lt;- function(x1, x2, x3){ 0.25 * (eucl.dist(x1,x2)*eucl.dist(x2,x3)*eucl.dist(x3,x1)) / area(x1, x2, x3) } # Test on some simple 2D case path2D &lt;- cbind( c(0, 1, 2, 2, 3, 4, 4, 4), c(0, 1, 0,-1,-1, 0, 1, 3), rep(0,8) ) names(path2D) &lt;- x("x","y","z") #plot the path plot( path2D[,1], path2D[,2], type="b", lwd=2, col="slateblue", xlim=c(-1,5), ylim=c(-2,4), xlab="x", ylab="y") # calculate vector with radii rads &lt;- sapply( 1 : (nrow(path2D) - 2), FUN=function(i){ radius(x1 = path2D[i,], x2 = path2D[i+1,], x3 = path2D[i+2,] )} ) # [1] 1.0000000 1.5811388 0.7071068 1.5811388 1.5811388 Inf # Add text to the plot text(path2D[2,1],path2D[2,2], round(rads[1],2), pos=3, cex=.8) text(path2D[3,1],path2D[3,2], round(rads[2],2), pos=4, cex=.8) text(path2D[4,1],path2D[4,2], round(rads[3],2), pos=2, cex=.8) text(path2D[5,1],path2D[5,2], round(rads[4],2), pos=1, cex=.8) text(path2D[6,1],path2D[6,2], round(rads[5],2), pos=4, cex=.8) text(path2D[7,1],path2D[7,2], round(rads[6],2), pos=4, cex=.8)
downvote count: 0
has comment: http://stackoverflow.com/comment/87806506
has comment: http://stackoverflow.com/comment/87805043
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50377031
upvote count: 1

http://stackoverflow.com/q/50324329
has answer: http://stackoverflow.com/a/54196441
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/55963493
has comment: http://stackoverflow.com/comment/87694854
has answer: http://stackoverflow.com/a/54353458
downvote count: 0
possible better answer: http://stackoverflow.com/a/54196441
tagged with: scrapy
has title: running Scrapy but it error: No module named _util
favorite count: 0
score: 9
type: Question
accepted answer: http://stackoverflow.com/a/50353955
has answer: http://stackoverflow.com/a/58809400
has answer: http://stackoverflow.com/a/50353955
upvote count: 9
answer count: 5
tagged with: python
has body: I have installed Scrapy，and import it in python, every things look fine. But it cause error when i try a example in http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tutorial.html. I run scrapy crawl swspider, then i get: &gt; 2018-05-14 14:24:16 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: tutorial) &gt; 2018-05-14 14:24:16 [scrapy.utils.log] INFO: Versions: lxml 3.2.1.0, &gt; libxml2 2.9.1, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted &gt; 18.4.0, Python 2.7.5 (default, Nov 20 2015, 02:00:19) - [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)], pyOpenSSL 0.13.1 (OpenSSL 1.0.1e-fips 11 &gt; Feb 2013), cryptography 0.8.2, Platform &gt; Linux-3.10.0-327.el7.x86_64-x86_64-with-centos-7.2.1511-Core &gt; 2018-05-14 14:24:16 [scrapy.crawler] INFO: Overridden settings: &gt; {'NEWSPIDER_MODULE': 'tutorial.spiders', 'SPIDER_MODULES': &gt; ['tutorial.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'tutorial'} &gt; Traceback (most recent call last): File &gt; "/disk1/wulixin/install/bin/scrapy", line 11, in &lt;module&gt; &gt; sys.exit(execute()) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/cmdline.py", &gt; line 150, in execute &gt; _run_print_help(parser, _run_command, cmd, args, opts) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/cmdline.py", &gt; line 90, in _run_print_help &gt; func(*a, **kw) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/cmdline.py", &gt; line 157, in _run_command &gt; cmd.run(args, opts) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/commands/crawl.py", &gt; line 57, in run &gt; self.crawler_process.crawl(spname, **opts.spargs) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/crawler.py", &gt; line 170, in crawl &gt; crawler = self.create_crawler(crawler_or_spidercls) File "/disk1/wulixin/install/lib/python2.7/site-packages/scrapy/crawler.py", &gt; line 198, in create_crawler &gt; return self._create_crawler(crawler_or_spidercls) File "/disk1/wulixin/install/lib/py…

http://stackoverflow.com/comment/87534063
has text: Rather than checking the truth of the current node, you could check for the existence of the next. So if node.next != None, step to the next node.
comment on: http://stackoverflow.com/q/50257999
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87775480
has text: I suspect you are not reading your CSV properly. Can I see 5-10 rows of your CSV file along with the code that you use to read it? Nipping this problem in the bud is better than solving the XY problem and letting the Y propagate to production code.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50379559
type: Comment

http://stackoverflow.com/comment/120364763
type: Comment
has text: This blog post is really helpful: https://dontrepeatyourself.org/post/django-pagination-with-function-based-view/
type: AnswerComment
comment on: http://stackoverflow.com/a/50269155
score: 0

http://stackoverflow.com/comment/87575789
type: Comment
comment on: http://stackoverflow.com/a/50263301
type: AnswerComment
has text: If you put it into another folder, you have to make it a package in order to import from that folder, i.e. add an `__init__.py` file to the folder.
score: 0

http://stackoverflow.com/a/67372635
score: 1
has body: You can use np.reshape((-1,)) or np.ravel instead of np.flatten to make a 1-dimensional view of your array, without unnecessary copying that flatten does: import numpy as np import multiprocessing as mp unsharedData2 = np.zeros((10, 10)) ravel_copy = np.ravel(unsharedData2) reshape_copy2 = unsharedData2.reshape((-1,)) ravel_copy[11] = 1.0 # -&gt; saves 1.0 in unsharedData2 at [1, 1] reshape_copy2[22] = 2.0 # -&gt; saves 2.0 in unsharedData2 at [2, 2] sharedData2 = mp.Array('d', ravel_copy) sharedData2 = mp.Array('d', reshape_copy2)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50270346
type: Answer

http://stackoverflow.com/comment/87626291
type: QuestionComment
has text: @abarnert Thanks and where are the other files of python 3 located ? and if a program asks for directory of python 3 should I give the directory as "/usr/bin/python3" ?
score: 0
comment on: http://stackoverflow.com/q/50304901
type: Comment

http://stackoverflow.com/comment/87649748
type: AnswerComment
comment on: http://stackoverflow.com/a/50316920
type: Comment
has text: bg_button2_is_equal_to = button2['bg']
score: 0

http://stackoverflow.com/q/50321297
upvote count: 7
tagged with: django-forms
has comment: http://stackoverflow.com/comment/87661755
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/71663314
tagged with: twitter-bootstrap
type: UnansweredQuestion
has body: I'm currently having this error message on django: ["'on' value must be either True or False."] views.py from django.shortcuts import render, redirect from .models import Comment from .forms import sign def index(request): return render(request, 'submits/index.html') def sign_list(request): if request.method == 'POST': form = sign(request.POST) if form.is_valid(): new_contact = Comment(email=request.POST['email'], message=request.POST['message'], checkbox=request.POST['checkbox']) new_contact.save() return redirect('index') else: form = sign() context = {'form' : form} return render(request, 'submits/sign.html', context) forms.py from django import forms from .models import Comment class sign(forms.Form): email = forms.CharField(max_length=500, widget=forms.TextInput(attrs={ 'type' : 'email', 'class' : 'form-control', 'placeholder' : 'Enter your email', 'aria-describedby' : 'emailHelp'})) message = forms.CharField(widget=forms.Textarea(attrs={ 'class' : 'form-control', 'rows' : '3', 'placeholder' : 'Write your proposal'})) checkbox = forms.BooleanField(required=False, initial=True) checkbox_attributes={'class': 'form-check'} models.py from django.db import models # Create your models here. class Comment(models.Model): email = models.CharField(max_length=500) message = models.TextField() checkbox = models.BooleanField() def __str__(self): return 'e-mail: {}, ID: {}'.format(self.email, self.id) Providing the full traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/contact_us/ Django Version: 2.0.3 Python Version: 3.5.2 Installed Applications: ['submits', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contri…
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/58500141
has title: Django error message: ["'on' value must be either True or False."]
answer count: 2
score: 7
tagged with: http://stackoverflow.com/tag/html
downvote count: 0

http://stackoverflow.com/comment/87514309
has text: your solution works but I have the same problem that with the solution I add when I edited my answer a bit before using `readsource = gzip.open(fIn,'rb').__next__` `fInCodec = tokenize.detect_encoding(readsource)[0]` It always return UTF-8 even when their is char that are not UTF-8. But I guess it's another problem.
score: 0
comment on: http://stackoverflow.com/a/50242355
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50304969
type: Answer
has body: Simply test for your break condition before printing: for i in range(0, 1000, 2): mySum += i if mySum &gt;= 500: break print(mySum) So now the loop will end the moment you reach 506, but it won't be printed in the loop. If you wanted mySum to be lower or equal to 500, you also need to alter your test too, so change it to mySum &lt;= 500 instead. You'll end up with mySum set to 462 after the loop, and the last value printed would be 420.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50304874

http://stackoverflow.com/a/59095619
type: Answer
has comment: http://stackoverflow.com/comment/122478513
answers question: http://stackoverflow.com/q/50313441
score: 29
upvote count: 29
downvote count: 0
has body: I think you should use like bellow on tensorflow 2 import tensorflow_datasets mnist = tensorflow_datasets.load('mnist')
has comment: http://stackoverflow.com/comment/116182208

http://stackoverflow.com/a/50334571
has comment: http://stackoverflow.com/comment/87685747
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50334421
has body: One way for that is to use a try-except to handle the exceptions (IndexError) in any way you want. But what you are trying to do is concatenating characters within each sublist that can be done in a more pythonic way like a list comprehension. In [1]: a = [['f', 'e', 'e', 'd'], ['t', 'h', 'e', 'd'], ['o', 'g']] In [2]: [''.join(sub) for sub in a] Out[2]: ['feed', 'thed', 'og'] And for the final result you can use another join method as following: In [3]: " ".join([''.join(sub) for sub in a]) Out[3]: 'feed thed og'

http://stackoverflow.com/comment/87699178
has text: I execute tcpdump where the script was executed and can't catch the packets from the client. @ZdaR
score: 0
comment on: http://stackoverflow.com/q/50341446
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50281167
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50260676
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: One way to do it is to always loop over your whole program, once for each file type. If a single file type is specified, you just loop over that one type, but if all is specified, you loop over all of them. For example, we can create a single-element list of just [sys.argv[1]], except when it's ALL: file_types = [sys.argv[1]] if sys.argv[1] != 'ALL' else ['FOO', 'BAR', 'FOOBAR'] for file_type in file_types: [...] parent_folder = 'C:/path/to/dir/' input_folder = parent_folder + file_type + '_inventory' output_folder = parent_folder + file_type + '_export'
accepted answer of: http://stackoverflow.com/q/50260676

http://stackoverflow.com/comment/87560346
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50271399
has text: @kabanus i'll use it in other function as a paramter

http://stackoverflow.com/comment/87753504
comment on: http://stackoverflow.com/q/50368612
type: QuestionComment
score: 0
has text: Hi AD WAN, its in the same directory. Once I changed its location just to verify then it showed error like " Couldn't find this file". But this error is something different. FYI I am using Python 2.7
type: Comment

http://stackoverflow.com/a/50373711
score: 1
answers question: http://stackoverflow.com/q/50373618
has comment: http://stackoverflow.com/comment/87764704
type: Answer
has body: When you write if nums[i:i+3] == arr1: return True else: return False if the condition is not met, then the function stops executing and returns False. Instead, you want the function to continue executing until it finds a triplet which satisfies that condition.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87652425
type: Comment
has text: Thanks a lot! I was totally lost
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50318320

http://stackoverflow.com/a/50314128
score: 1
answers question: http://stackoverflow.com/q/50314030
downvote count: 0
has body: We can first query the list of Domains for which the project is in [1, 2]: domain_ids = (Domain.objects.filter(project__in=[1, 2]) .values_list('id', flat=True)) now in a second pass, we can filter on both the content_type and object_id: ToolResult.objects.filter(content_type=ContentType.objects.get_for_model(Domain), object_id__in=domain_ids)
type: Answer
upvote count: 1

http://stackoverflow.com/a/50319055
downvote count: 0
has comment: http://stackoverflow.com/comment/87654151
upvote count: 1
has comment: http://stackoverflow.com/comment/87655222
has comment: http://stackoverflow.com/comment/87654871
type: Answer
has comment: http://stackoverflow.com/comment/87654329
has comment: http://stackoverflow.com/comment/87654105
has comment: http://stackoverflow.com/comment/87654178
has comment: http://stackoverflow.com/comment/87654063
answers question: http://stackoverflow.com/q/50318973
score: 1
has body: I assume you're looking to put each of those into individual lists. name_list = [] link_list = [] color_list = [] for article_name in article_name_list_items: names = article_name.find('h1').find('a', class_ = 'name-link').get_text() links = article_name.find('p').find('a', class_ = 'name-link').get('href') colors = article_name.find('p').find('a', class_ = 'name-link').get_text() name_list.append(names) link_list.append(links) color_list.append(colors) Not exactly sure what article_name_list_items looks like but names will get you the text of the &lt;h1&gt; element, links will get you the href of the &lt;p&gt; element, and colors will get you the text of &lt;p&gt; element. You could also opt to include all elements in a list of lists which would be this (initialize new list list_of_all and replace 3 list appends with the single append in the second line): list_of_all = [] list_of_all.append([names, links, colors])

http://stackoverflow.com/comment/87776646
has text: Maybe just print the prompt separately and then use `input()` with no prompt?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50380066
score: 1

http://stackoverflow.com/q/50382027
score: 1
favorite count: 0
type: Question
has body: I have a pandas dataframe like this: Cat | Val A | 10 B | 20 B | 5 A | 8 I want to split columns into [[10, 8],[20,5]] [A,B] I know this is super simple, just cant find the right online resource for it
answer count: 2
has answer: http://stackoverflow.com/a/50382063
has answer: http://stackoverflow.com/a/50382585
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Get a series of data based on dataframe split
tagged with: pandas

http://stackoverflow.com/comment/87763859
score: 2
has text: offtopic: you should try parsing your file line by line or chunk by chunk. Here's the general idea: https://stackoverflow.com/questions/17444679/reading-a-huge-csv-file
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50373842

http://stackoverflow.com/q/50235516
has comment: http://stackoverflow.com/comment/87537797
duplicate of: http://stackoverflow.com/q/49492621
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87565991
tagged with: armv7
answer count: 0
has comment: http://stackoverflow.com/comment/87509635
has comment: http://stackoverflow.com/comment/87499881
type: UnansweredQuestion
has title: paramiko environment variable during tar
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87570876
has body: I'm trying to copy a few tarballs over an ssh session, but during the exec_command of tar xzf ... I see recv_exit_status of 2, even when writing a custom ssh_env file and sourcing it on the machine. I can give the remote machine the absolute path of the tar executable, but the problem persists. How might I fix this, or gather more information to help others help me? Edit: for what it's worth, I believe the problem is related to the fact that tar implicitly invokes gzip Edit re: Martin, the stderr is as follows tar (child): file.tar.gz: cannot open: no such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error exit delayed from previous errors relevant code snippet: client = pmk.SSHClient() client.load_system_host_keys() client.connect(target, port=SSH_PORT, username="root", password="") cur_file = "file.tar.gz" commands = [ "cd tmp", "tar zxf {} -C /app".format(cur_file) ] ] for command in commands: stdin, stdout, stderr = client.exec_command(". /tmp/sshenv ; {}".format(command)) print(stdout.read().decode('utf-8')) if stdout.channel.recv_exit_status() == 0: print("done!") else: print("ERROR: ", stderr.read().decode('utf-8')) print("STDOUT: ", stdout.read().decode('utf-8')) where sshenv is a file as follows, that I have SCP'd over as well: export _=/proc/boot/env export PS1=$(hostname):$PWD # export PATH=/proc/boot:/bin:/usr/bin:/sbin:/usr/sbin:/opt/bin:/flash/bin export SHELL=/bin/sh export USER=root export MAIL=/var/spool/mail/root export LD_LIBRARY_PATH=/proc/boot:/lib:/usr/lib:/lib/dll:/proc/boot:/opt/lib export HOME=/ export TERM=xterm-256color export SSH_TTY=/dev/ttyp0 export LOGNAME=root
tagged with: linux
has comment: http://stackoverflow.com/comment/87499557
has comment: http://stackoverflow.com/comment/87565781
has comment: http://stackoverflow.com/comment/87570984
has comment: http://stackoverflow.com/comment/87532822
score: 1
linked to: http://stackoverflow.com/q/49492621
has comment: http://stackoverflow.com/comment/87499588
tagged with: paramiko

http://stackoverflow.com/a/50324465
downvote count: 0
answers question: http://stackoverflow.com/q/50320424
type: Answer
upvote count: 1
score: 1
has body: Please visit the following link which contains working pip installations for different os: https://github.com/prasad01dalavi/python_packages_installations for python2 in linux sudo apt-get install -y python-dev libmysqlclient-dev &amp;&amp; sudo pip install mysqlclient

http://stackoverflow.com/comment/110494496
comment on: http://stackoverflow.com/a/50313657
type: AnswerComment
has text: Replacing pᵢ, the probability of gray level `i`, by the joint probability of color `(r, g, b)`, pʳᵍᵇ, would do the trick. Yo need to introduce this change into the first formula.
score: 1
type: Comment

http://stackoverflow.com/comment/87740165
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50361307
type: Comment
has text: I've corrected it to be banned_user.profile.user_reported_report.all() which would basically take the profile of the banned user. Grab the user reports and add them as a set to the ban reason.

http://stackoverflow.com/comment/87601775
type: AnswerComment
comment on: http://stackoverflow.com/a/50279298
score: 1
type: Comment
has text: I confirm that the problem began on the 10th of May. It just returns "Okay". Perhaps I need to use the official API - even if you make over 1000 requests, it's very cheap anyway.

http://stackoverflow.com/q/50364860
has comment: http://stackoverflow.com/comment/87746509
has comment: http://stackoverflow.com/comment/87746615
tagged with: flask-restful
tagged with: deployment
has comment: http://stackoverflow.com/comment/87746950
linked to: http://stackoverflow.com/q/16573332
type: Question
tagged with: model
has title: flask + restful web service unable to run text classification model + python
linked to: http://stackoverflow.com/q/36666128
has answer: http://stackoverflow.com/a/50366237
type: UnansweredQuestion
answer count: 1
tagged with: machine-learning
tagged with: python
has body: Code used to create the restful api webservice import numpy as np import pandas as pd #need to "conda install flask" for this to work from flask import Flask, abort, jsonify, request import pickle Text_classification_model = pickle.load(open(r"D:\Sentiment_Analysis_Project\Deb\Sentiment_Analysis\Linear_SVC_TEXT_CLASSI_Final_82per_Model.pkl", "rb")) app = Flask(__name__) #@app.route("/") #def hello(): # return "Hello" @app.route("/") def make_predict(): #all kinds of error checking should go here data = request.get_json(force=True) #convert our json to a numpy array predict_request = data['Clean_Text_Body'] predict_request = np.array[predict_request] #np.array goes in to Linear SVC model, prediction comes out y_hat = Text_classification_model.predict(predict_request) #return our prediction output = [y_hat[0]] return jsonify(results=output) if __name__ == '__main__': app.run() when this is being called as a .py file it is getting executed properly and displaying "http://localhost:5000/" as the url properly. Later when i am trying to post a data in to the model using the following code, import json import requests url = "http://localhost:8082/" data = json.dumps({'Clean_Text_Body':"the product was amazing i just love it"}) headers = {'accept-language': 'en', 'content-type': 'application/json'} r = requests.post(url, data = data, headers=headers) Output = json.loads(r.text)['Output'] ##error section # o/p is string eg: "4" print("results == ", Output) it is giving the following error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python\Anaconda\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Python\Anaconda\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python\Anaconda\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 colu…
score: 0

http://stackoverflow.com/comment/87719073
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50351503
has text: Does the other computer have network connectivity on the relevant port to the target ftp server? Does the target accept connections from the problematic server? This sounds like a network/firewall issue.
score: 1

http://stackoverflow.com/a/50352703
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/87726785
has comment: http://stackoverflow.com/comment/87723328
type: Answer
accepted answer of: http://stackoverflow.com/q/50352569
has body: You can't compare a datetime.time and a str but you certainly can compare a datetime.time and a datetime.time: import datetime df['DAY COURSE INDICATOR'] = df['START_TIME'] &lt; datetime.time(16, 0)
answers question: http://stackoverflow.com/q/50352569
upvote count: 3
has comment: http://stackoverflow.com/comment/87726374
type: AcceptedAnswer

http://stackoverflow.com/q/50337161
has title: python number of button clicks are incrementing on every button press
upvote count: 2
tagged with: tkinter
score: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50337350
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I want to make program that increments the number of clicks by saving on a Text for example if I press a button many times it prints that number of times I pressed correctly but my problem is if I press onother button it starts it's incrementing from the number of clicks of the first one not from zero so please how I can make it start from zero if press other button bttn_clicks=0 button_dict = {} def showqado(): global button,data2 data2 = readqado() for index, dat in enumerate(data2): button = ttk.Button(master, text=dat[0],command=lambda dat=dat: update_count(dat)) button.grid(row=index+1, column=1,pady=0,padx=0) button_dict[dat] = button def update_count(x): global bttn_clicks,my_text,price my_text=StringVar() for name in data2: my_text = button_dict[x].cget('text') bttn_clicks += 1
tagged with: python

http://stackoverflow.com/q/50381634
tagged with: bokeh
has body: I have bokeh plot being generated in the backend, which I want to embed onto an already existing angular 4 webapp. Currently I've use the bokeh.components function which yields the following two html tags. as well as which I can embed onto a small boilerplate: Bokeh Scatter Plots (function() { var fn = function() { Bokeh.safely(function() { (function(root) { function embed_document(root) { var docs_json = <!---docs_json---!> var render_item = <!---items---!> <div class="bk-plotdiv" id=<!--- div_id ---!>> For this I need to parse out the important variables(docs_json,render_id,div_id) from the first two scripts and then have them sent as a json to the Frontend using Flask. much like this google forms question https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/McLDXP414ps Is there a better way to send my bokeh plot to the angular front end, instead of having to go through all of this ?
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: How do I integrate Bokeh with Angular 4?
tagged with: python
score: 3
tagged with: angular
upvote count: 3

http://stackoverflow.com/a/51177481
score: 17
upvote count: 17
answers question: http://stackoverflow.com/q/50259117
type: Answer
has body: What you're looking for is Python's RotatingFileHandler. Use this in your 'handlers' 'file': { 'level': 'WARNING', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'debug.log'), 'backupCount': 10, # keep at most 10 log files 'maxBytes': 5242880, # 5*1024*1024 bytes (5MB) }, When I tried I got PermissionError. This answer explains how to handle it. EDIT: This happens when you use django's development server to run it. Shouldn't be a problem in other cases.
has comment: http://stackoverflow.com/comment/117113075
downvote count: 0

http://stackoverflow.com/comment/87545160
score: 0
comment on: http://stackoverflow.com/q/50263510
type: Comment
type: QuestionComment
has text: It's not clear what you want, but no, this is not possible. `dynamically_defined_method` is just a function local to the body of `method`, not a method of `TestClass`.

http://stackoverflow.com/comment/87522661
comment on: http://stackoverflow.com/q/50252653
type: Comment
type: QuestionComment
score: 0
has text: Try `re.findall(r'qweqrqr([^\u2022]*\u2022.*?)fdsfdas', hello_big_old_world, re.S)`

http://stackoverflow.com/a/50381989
answers question: http://stackoverflow.com/q/50381760
type: Answer
score: 0
has body: Here's a "hacky" solution. Note it does not preserve spaces in "s" as in your output (could possibly be preserved if necessary), but the resulting values are the same: # s = ... # your s string ss = [] split = s.split() for i, n in enumerate(split): try: if split[i+1] == '0': pass elif n != '0': ss.append(n) except IndexError: pass print ' '.join(ss) prints: 8 9243 8607 56 586262 4697424 00000 C S&lt;-&gt;L P A&lt;-&gt;A

http://stackoverflow.com/comment/87551986
type: AnswerComment
comment on: http://stackoverflow.com/a/50252279
score: 1
has text: I tested your solution and it works quite alright :) but is there any possibility to POST a dict, not a list of dicts, in "calculate_vectors" field, because the request should contains info about only one caltulating vector more likely in that way: "calculate_vectors": {'method': 'some_method', 'vector':{'id': 1, 'name': 'some_name'}} ?
type: Comment

http://stackoverflow.com/a/50301573
has body: One way is to use your two lists to resolve the indices and column names required. Then use usecols and names arguments for pd.read_csv to specify column indices and names respectively. idx, cols = list(zip(*((i, x) for i, x in enumerate(columns_name) \ if x not in del_columns_name))) df = pd.read_csv('filename', usecols=idx, names=cols, header=None) As explained in the docs, you should also specify header=None explicitly when no header exists. Explanation Use a generator expression to iterate columns_name and remove items not in del_columns_name. Use enumerate to extract indices. Use zip to create separate tuples for indices and column names.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50301544
has comment: http://stackoverflow.com/comment/87619817
downvote count: 0
has comment: http://stackoverflow.com/comment/87619881
type: Answer

http://stackoverflow.com/comment/87695174
type: QuestionComment
has text: What is eating up the several ms? If you are doing more work than just sending the commands, then you may need to prestage everything then send the commands. `cmd1 = gen_stage1_cmd();cmd2 = gen_stage2_cmd();send_cmds((cmd1, cmd2))`.
comment on: http://stackoverflow.com/q/50339345
score: 0
type: Comment

http://stackoverflow.com/comment/87769736
comment on: http://stackoverflow.com/q/50376214
score: 0
has text: version is Scrapy-1.5.0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87636955
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50310269
has text: I posted an alternative solution to yours in my answer taking into account the first value (just as you did) without using `.apply()`.
score: 1

http://stackoverflow.com/comment/87616957
type: AnswerComment
has text: You have to be a bit more careful with `searchsorted` if you want the nearest element. Particularly, searching for `0` returns `-1`, searching for `10.12` fails to report the index of `10.12`, and searching for a value between two values of the array always picks the index of the left value, even if the right value is closer.
type: Comment
comment on: http://stackoverflow.com/a/50299883
score: 0

http://stackoverflow.com/q/50321207
tagged with: symlink
has comment: http://stackoverflow.com/comment/87660081
has answer: http://stackoverflow.com/a/50322735
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/87661482
has body: I have some python code that opens a file to read it like so... with open("file.txt") as f: print(f.read()) On MacOS, if file.txt is a symlink - Python will follow the symlink and read the target file. However, on Windows it does not do this - how can I achieve this? (Using Python version 3.6.5 and Windows 10) Steps to reproduce. Create FileA.txt in DirectoryA which is above DirectoryB Inside DirectoryB, Run mlink FileA.txt "../FileA.txt" Run a Python script which attempts to read and print from the FileA.txt link in DirectoryB Expected Behaviour: The contents of FileA.txt inside DirectoryA should be printed Actual Behaviour: OSError: [Errno 22] Invalid argument: 'FileA.txt'
type: Question
has comment: http://stackoverflow.com/comment/87660980
answer count: 2
has comment: http://stackoverflow.com/comment/87740056
has comment: http://stackoverflow.com/comment/87740022
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/50321576
has title: Opening a file which is a symlink in Python
has comment: http://stackoverflow.com/comment/87661088
has answer: http://stackoverflow.com/a/50321576
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50322735

http://stackoverflow.com/comment/115680969
type: AnswerComment
comment on: http://stackoverflow.com/a/50377918
has text: and what if a different `ClientError` is thrown? this would make debugging a PITA -- amazon should have created a specific exception for NoTagsExist or provided a function to check if tags exist
type: Comment
score: 1

http://stackoverflow.com/comment/87579403
type: Comment
comment on: http://stackoverflow.com/q/50279713
type: QuestionComment
has text: You're looking for [image stitching](https://docs.opencv.org/3.4/d8/d19/tutorial_stitcher.html).
score: 1

http://stackoverflow.com/q/50367755
possible better answer: http://stackoverflow.com/a/50367908
has body: I am trying to do this code. import urllib import json import requests url = 'http://www.webiron.com/abuse_feed//?format=json' response = urllib.urlopen(url) data_json = json.loads(response.read()) for i in data_json: i['LogEvent'] = 'Trial' i['EvtLen'] = 213 print json.dumps(data_json,indent=6) The Output i am getting is like following: pretty big output (showing part of output) [ { "incidents_reported": 3, "attacker_ip": "178.137.88.8", "event_time": "2018-05-15 19:30:09.832568-07", "event_emails": [ "hostmaster@kyivstar.net", "abuse@kyivstar.net", "noc@kyivstar.net" ], "entry_type": "report", "EvtLen": 213, "emails_deliverable": "Yes", "LogEvent": "Trial", "event_msg": "Fake Referrer Log SPAM Bot", "days_unresolved": "<3" }, { "incidents_reported": 52, "attacker_ip": "221.229.166.171", "event_time": "2018-05-15 19:29:45.039281-07", "event_emails": [ "anti-spam@ns.chinanet.cn.net" ], "entry_type": "report", "EvtLen": 213, "emails_deliverable": "No", "LogEvent": "Trial", "event_msg": "Abusive network connectivity", "days_unresolved": "3" } ] Now check element days_unresolved : "3" or days_unresolved: "<3" is it possible to update or modify such element to simple days_unresolved : 3 with other data?. This is how i want as a required output, is there some method or find such tag and remove it or iterate through entire data set and update it. is there any solution for this?
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50368225
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/50368225
has title: Updating json element
answer count: 4
has comment: http://stackoverflow.com/comment/87752246
has comment: http://stackoverflow.com/comment/87752291
type: Question
has answer: http://stackoverflow.com/a/50367908
has answer: http://stackoverflow.com/a/50368164
has answer: http://stackoverflow.com/a/50368529
tagged with: python

http://stackoverflow.com/q/50265340
has body: I have an application which continues running, the application won't be stopped, it will idle when there are no instructions by a client, and listen to the external event and react if there is any instruction input by the user at anytime There is a configuration file which can be changed while the application is running, and the logging level is one of them. myLoggingLevel is the param below. Is there anyway to change the logging level while the application is running? I am using ConfigParser.RawConfigParser() for the configuration change. import time import logging import datetime def getLogger(loggerName='myLoggerName', logLevel='INFO', log_path='C:/logs/'): class Formatter(logging.Formatter): def formatTime(self, record, datefmt=None): return (datetime.datetime.utcnow()).strftime('%H:%M:%S') logLevel = logLevel.upper() levels = {'DEBUG' : logging.DEBUG, 'INFO' : logging.INFO, 'WARNING' : logging.WARNING, 'ERROR' : logging.ERROR, 'CRITICAL' : logging.CRITICAL} today = datetime.datetime.utcnow().strftime('%Y-%m-%d') full_log_path = log_path + '%s.%s.log' % (loggerName, today) logger = logging.getLogger(loggerName+'.'+today) if not len(logger.handlers): logger.setLevel(levels[logLevel]) fh = logging.FileHandler(full_log_path) formatter = Formatter('%(asctime)s.%(msecs)03d | %(message)s', datefmt='%H:%M:%S') fh.setFormatter(formatter) logger.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.ERROR) ch.setFormatter(formatter) logger.addHandler(ch) logger.propagate = False logger.info('loggerName: %s' % loggerName) return logger def run(myLoggingLevel): while True: log = getLogger(loggerName='testLogLevel', logLevel=myLoggingLevel) log.debug('I am in debug') log.info('I am in info') time.sleep(3) run(myLoggingLevel='debug')
has comment: http://stackoverflow.com/comment/87549626
answer count: 2
has answer: http://stackoverflow.com/a/50363057
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50266599
tagged with: python-2.7
score: 0
has title: Logging level to be changed in the middle of a scripts
tagged with: python
type: Question

http://stackoverflow.com/a/50354884
downvote count: 0
answers question: http://stackoverflow.com/q/50354622
type: Answer
upvote count: 1
has body: You could iterate through your dataframe in a similar way as what you are doing, but since you are using pandas, it might be worth leveraging pandas functions. They are typically much faster than iteration, and the code ends up looking cleaner. term_of_interest = 'HIV' (df.groupby('Researcher') .apply(lambda x: x.Terms.str.contains(term_of_interest) .sum()) .rename('Frequency').to_frame()) Frequency Researcher Dr. Lee 3 Dr. Roberts 0 Dr. Wang 0 Dr.Roberts 1 prof. christopher 1 prof. swaminathan 0
score: 1

http://stackoverflow.com/comment/87721744
type: Comment
type: AnswerComment
has text: I really thought that `pivot_table()` used the sum as default function. Write your comment as an answer so I can accept it :)
score: 0
comment on: http://stackoverflow.com/a/50351608

http://stackoverflow.com/q/50264691
has body: I'm trying to find difference between two columns in a Dataframe but want to apply filter. Below is what I'm trying to do ((df['column1']-df['column2'])/(df['totalcolumn'])).idxmax() above gives me result but I want to consider only rows in which Column1>0 and Column2>0. can anyone help me?
has answer: http://stackoverflow.com/a/50264742
tagged with: python
accepted answer: http://stackoverflow.com/a/50264829
type: Question
has answer: http://stackoverflow.com/a/50264829
answer count: 2
upvote count: 2
tagged with: pandas
score: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87547502
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50264742
has title: python Dataframe difference with filter in one line

http://stackoverflow.com/q/50340064
tagged with: visual-studio-code
has title: Multi-process debugging in VSCode Python
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm running a python program that spawns sub-processes. When a new process launches, I get: pydev debugger: New process is launching (breakpoints won't work in the new process). pydev debugger: To debug that process please enable 'Attach to subprocess automatically while debugging?' option in the debugger settings. How do I enable this option? It looks like it's a pydev option? I'm running python 3.6 with the debugger config type set to pythonExperimental in Visual Studio Code.
type: Question
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/51567938

http://stackoverflow.com/a/50374001
has comment: http://stackoverflow.com/comment/87764297
answers question: http://stackoverflow.com/q/50350067
has body: imaplib does not really parse responses, so you're getting a fairly raw response from the library. The OK is the overall response to the command, which means that the server understood your request. Each line of the response is returned as an item in a list. SEARCH only returns one line, so you have a list of one item. Since imaplib does not do any parsing, you are getting the text of that response in it's original format: a bytes object of space separated numbers, representing Message Sequence Numbers. You should be able to get a list of MSNs with msns = data[0].split(b' '). You can then loop over this list to obtain further information, for example: for msn in msns: resp, data = m.fetch(msn, '(RFC822)')
type: Answer
score: 0

http://stackoverflow.com/q/50311469
type: Question
has comment: http://stackoverflow.com/comment/87639263
has body: I got following Python list: [(1, 2, 'Adam', 'M', '2', '12'), (1, 2, 'Ewa', 'W', '2.0 (E)', '44'), (1, 2, 'Ewa', 'W', '2.0 (E)', '44'), (2, 3, 'Adam', 'M', '2', '12'), (2, 3, 'Ewa', 'W', '2.0 (E)', '44')] I want convert my list with tuples to the following structure: list = [('Adam', '12'), ('Ewa', '44')] I dont have idea how I can make it in the most simplest way. I thought about set(), but 0 and 1 element of tuples are not the same.
score: -2
has answer: http://stackoverflow.com/a/50311523
upvote count: 1
tagged with: python
has title: list with tuples: Getting specific elements without duplicates to new list
possible better answer: http://stackoverflow.com/a/50311495
accepted answer: http://stackoverflow.com/a/50311483
has comment: http://stackoverflow.com/comment/87639325
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50311495
has answer: http://stackoverflow.com/a/50311483
answer count: 3
tagged with: set
downvote count: 3
has comment: http://stackoverflow.com/comment/87639199
has comment: http://stackoverflow.com/comment/87639198
favorite count: 0

http://stackoverflow.com/a/50287683
has comment: http://stackoverflow.com/comment/87593161
answers question: http://stackoverflow.com/q/50287548
type: Answer
accepted answer of: http://stackoverflow.com/q/50287548
has comment: http://stackoverflow.com/comment/87592515
score: 0
has body: You can split the dept_name with .split(" ") and then use only the first letter of each word with [:1]. Example: dept_name = "Counter Avenger Manequin" shop_id = "" for word in dept_name.split(" "): shop_id += word[:1] shop_id += join_date + year[2:] + month + counted print shop_id This will output: CAM71804001 Edit: Same for the year, to get 18 from 2018 use: year = "2018" print year[2:] This will output: 18
type: AcceptedAnswer

http://stackoverflow.com/q/50366029
has comment: http://stackoverflow.com/comment/87748416
has comment: http://stackoverflow.com/comment/87748537
has comment: http://stackoverflow.com/comment/87748255
has body: Description: I have three variable a, x and y. I want to apply the following, if variable a in range(x, y) print the a variable Code: a = "0.50" x = "-14.40" y = "0.50" for a in range(int(x), int(y)): print a Error (of course): ValueError: invalid literal for int() with base 10: '-14.40' Pythonista i need your help here please!!
has comment: http://stackoverflow.com/comment/87748418
downvote count: 6
type: Question
has comment: http://stackoverflow.com/comment/87748719
has answer: http://stackoverflow.com/a/50366345
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50366345
has comment: http://stackoverflow.com/comment/87748586
upvote count: 3
has answer: http://stackoverflow.com/a/55883679
has comment: http://stackoverflow.com/comment/87748540
favorite count: 0
has comment: http://stackoverflow.com/comment/87748341
has comment: http://stackoverflow.com/comment/87748571
linked to: http://stackoverflow.com/q/7267226
type: AnsweredQuestion
has title: How to use float variable with range function in python?
linked to: http://stackoverflow.com/q/477486
answer count: 3
has comment: http://stackoverflow.com/comment/87748329
has comment: http://stackoverflow.com/comment/87748317
has comment: http://stackoverflow.com/comment/87748274
score: -3
has answer: http://stackoverflow.com/a/50366341
has comment: http://stackoverflow.com/comment/87748470
has comment: http://stackoverflow.com/comment/87748332
tagged with: range
accepted answer: http://stackoverflow.com/a/50366341
has comment: http://stackoverflow.com/comment/87748507
tagged with: python

http://stackoverflow.com/comment/87659433
score: 0
comment on: http://stackoverflow.com/a/50321744
type: Comment
type: AnswerComment
has text: @SebastiánRamírez your're welcome. The `HTTPError` means the resource was not found online. Which might means the particular resource wasn't found on the server. See https://en.wikipedia.org/wiki/HTTP_404. Good news, your code works, bad news, the page/resource you're looking for is not available.

http://stackoverflow.com/a/50311646
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/50306024
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/50306024
has body: What you're looking for is the turtle.towards() method, which returns the angle from the turtle's position to a target. It can be used in combination with the turtle.setheading() method: turtle.setheading(turtle.towards(x, y)) The turtle.towards() method is flexible with respect to it arguments. It can take separate x and y values, a combined (x, y) tuple, or another turtle whose position it will target. It's a commonly overlooked method, that folks reimplement, along with turtle.distance().
type: AcceptedAnswer

http://stackoverflow.com/comment/127286801
score: 0
type: Comment
has text: YEEEES THANK YOUUUU this is what I needed
type: AnswerComment
comment on: http://stackoverflow.com/a/71419387

http://stackoverflow.com/a/50278847
has comment: http://stackoverflow.com/comment/87574859
score: 0
answers question: http://stackoverflow.com/q/50278746
type: AcceptedAnswer
has body: If your urls follow the above format, and you want the text between .com and /mlb, you can use the following regular expression: .com([\/\d]+)\/mlb In action: &gt;&gt;&gt; s = 'https://espn.com/1234/44/222/mlb/standings' &gt;&gt;&gt; re.findall(r'.com([\/\d]+)\/mlb', s) ['/1234/44/222'] You could also use join with split: &gt;&gt;&gt; '/'.join(s.split('/')[3:6]) 1234/44/222
has comment: http://stackoverflow.com/comment/87575317
has comment: http://stackoverflow.com/comment/87575507
type: Answer
accepted answer of: http://stackoverflow.com/q/50278746

http://stackoverflow.com/a/50285888
answers question: http://stackoverflow.com/q/50279536
upvote count: 2
has body: Convert main() into async function and execute it by loop.run_until_complete(). When the code has the only one run_until_complete() -- everything becomes much easier. In Python 3.7 you will be able to write just asyncio.run(main())
type: Answer
downvote count: 1
score: 1

http://stackoverflow.com/q/50279896
has comment: http://stackoverflow.com/comment/87576495
tagged with: postgresql
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87577358
tagged with: sql
has comment: http://stackoverflow.com/comment/87576394
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87576633
type: Question
has body: PostgreSQL accessed by Python in AWS Lambda with psycopg2. This function: cur.execute("INSERT INTO table (column1, column2, column3) VALUES ('test1', 'test2', 'test3');") Does not add any row to the database. Psycopg2 does not throw an error. PostgreSQL logs the statement without an error. HOWEVER! There is a fourth column, which is an auto-incremented id. The sequence used to keep track of the id is increased by one, even though the row isn't added. (Weird already) If the same statement is sent in any other way (command line, pgAdmin, Adminer), it works. I have no single idea what is happening. EDIT: full code: def db(): with open('configEC2.json') as json_data_file: POSTGRES = json.load(json_data_file) db = psycopg2.connect( host=POSTGRES["sql"]["host"], user=POSTGRES["sql"]["user"], password=POSTGRES["sql"]["passwd"], dbname=POSTGRES["sql"]["db"] ) return db def dbSetup(): dbR = db() cur = dbR.cursor() return cur cur = dbSetup() cur.execute("INSERT INTO table (column1, column2, column3) VALUES ('test1', 'test2', 'test3');") cur.close()
has comment: http://stackoverflow.com/comment/87577151
accepted answer: http://stackoverflow.com/a/50280452
has comment: http://stackoverflow.com/comment/87576455
answer count: 1
downvote count: 0
has title: PostgreSQL not INSERTing in Python on AWS Lambda with psycopg2
upvote count: 1
tagged with: psycopg2
has answer: http://stackoverflow.com/a/50280452
has comment: http://stackoverflow.com/comment/87576546
tagged with: aws-lambda
favorite count: 0

http://stackoverflow.com/a/50330419
answers question: http://stackoverflow.com/q/50329884
downvote count: 0
has body: Your code doesn't work because int in Python is an immutable type. If I change an int variable, it will not change the value in its address, but it will change whole variable. So any list or object formerly holding it will not be changed. Here are some examples: In [1]: a_list = [1,2,3] In [2]: var = a_list[0] In [3]: var Out[3]: 1 In [4]: id(var) Out[4]: 4465792624 In [5]: var = 30 In [6]: id(var) # A different address Out[6]: 4465793552 In [7]: a_list Out[7]: [1, 2, 3] In [8]: id(a_list[0]) Out[8]: 4465792624 In [9]: a_list[0] = 30 In [10]: a_list Out[10]: [30, 2, 3] That's why if you do this slight change your code will work: for i in somelist: for ind, j in enumerate(i): i[ind] = int(j)
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/87625996
type: Comment
type: QuestionComment
has text: Then you have a much bigger problem, and you need to solve that first. How did you install Python? If you used the installer from Python.org, when it gave you an option to add to your PATH, did you disable that?
score: 1
comment on: http://stackoverflow.com/q/50300785

http://stackoverflow.com/comment/87716374
score: 0
comment on: http://stackoverflow.com/q/50349937
type: QuestionComment
type: Comment
has text: Change `MYdef.file="another text"` to `file="another text"`

http://stackoverflow.com/comment/87737581
type: QuestionComment
has text: Can you do: `which python`, and `python --version`?
comment on: http://stackoverflow.com/q/50360320
score: 1
type: Comment

http://stackoverflow.com/q/50354465
upvote count: 1
possible better answer: http://stackoverflow.com/a/50354827
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50356670
has body: I'm trying to automate the scraping of links from here: https://thegoodpubguide.co.uk/pubs/?paged=1&amp;order_by=category&amp;search=pubs&amp;pub_name=&amp;postal_code=&amp;region=london Once I have the first page, I want to click the right chevron at the bottom, in order to move to the second, the third and so on. Scraping the links in between. Unfortunately nothing I try will allow me to send chrome to the next page. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from datetime import datetime import csv from selenium.webdriver.common.action_chains import ActionChains #User login info pagenum = 1 #Creates link to Chrome Driver and shortens this to 'browser' path_to_chromedriver = '/Users/abc/Downloads/chromedriver 2' # change path as needed driver = webdriver.Chrome(executable_path = path_to_chromedriver) #Navigates Chrome to the specified page url = 'https://thegoodpubguide.co.uk/pubs/?paged=1&amp;order_by=category&amp;search=pubs&amp;pub_name=&amp;postal_code=&amp;region=london' #Clicks Login def findlinks(address): global pagenum list = [] driver.get(address) #wait while pagenum &lt;= 2: for i in range(20): # Scrapes available links xref = '//*[@id="search-results"]/div[1]/div[' + str(i+1) + ']/div/div/div[2]/div[1]/p/a' link = driver.find_element_by_xpath(xref).get_attribute('href') print(link) list.append(link) with open("links.csv", "a") as fp: # Saves list to file wr = csv.writer(fp, dialect='excel') wr.writerow(list) print(pagenum) pagenum = pagenum + 1 element = driver.find_element_by_xpath('//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a') element.click() findlinks(url) Is something blocking the button that i'm not seeing? The error printed in my terminal: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a"}
tagged with: python
has title: Python Selenium unable to click() button
accepted answer: http://stackoverflow.com/a/50356670
has answer: http://stackoverflow.com/a/50354827
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0

http://stackoverflow.com/q/50302994
has comment: http://stackoverflow.com/comment/87622529
favorite count: 0
has comment: http://stackoverflow.com/comment/87622772
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/7585435
has comment: http://stackoverflow.com/comment/87622508
has comment: http://stackoverflow.com/comment/87622559
has comment: http://stackoverflow.com/comment/87622489
answer count: 0
has title: Python3 - reinterpret string as bytes
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87622659
tagged with: python
has comment: http://stackoverflow.com/comment/87622700
has comment: http://stackoverflow.com/comment/87622568
has comment: http://stackoverflow.com/comment/87622515
has comment: http://stackoverflow.com/comment/87622643
has comment: http://stackoverflow.com/comment/87622479
has comment: http://stackoverflow.com/comment/87622436
linked to: http://stackoverflow.com/q/14820429
has comment: http://stackoverflow.com/comment/87622416
has comment: http://stackoverflow.com/comment/87622727
has comment: http://stackoverflow.com/comment/87622844
downvote count: 0
linked to: http://stackoverflow.com/q/1885181
has comment: http://stackoverflow.com/comment/87622464
duplicate of: http://stackoverflow.com/q/63218987
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87622572
has body: I have a string in python with some literal bytes and some literal ascii characters, e.g., print(s) provides: The message - \xe3\x83\xa9\xe3\x82\xa4 ... that was the message Is there an easy way to reinterpret this string as bytes in python, and then decode to utf-16? Or do I have to manually search for and separate out the unicode characters myself? If I could declare the string as a literal, I would be fine, e.g., b"The message - \xe3\x83\xa9\xe3\x82\xa4 ... that was the message".decode('utf-8') but unfortunately I have a string variable.
tagged with: python-unicode
has comment: http://stackoverflow.com/comment/87622798
tagged with: unicode
has comment: http://stackoverflow.com/comment/87622581

http://stackoverflow.com/a/50343850
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87703666
accepted answer of: http://stackoverflow.com/q/50343736
downvote count: 0
has comment: http://stackoverflow.com/comment/87782420
has body: There is no way to get a "country's IP address" since there is no such thing. There are ranges of IP addresses corresponding to different ISP's in different locations. You should pass each request through a proxy that you know is located where you want it to be. For that you will need to create your own proxy list for each country and pass your requests through proxy every time for each country. You should explore some possible free or payed proxies for that. Anyway, once you do, sending a request through a proxy can be done like this: proxyDict = { "http" : "http://1.1.1.1:123", "https" : "https://1.1.1.1:456", "ftp" : "ftp://1.1.1.1:789" } r = requests.get(url, proxies=proxyDict) Of course you should replace the fake addresses above with real proxies that are good for what you want. By the way, i'm sure there are off the shelf solutions for that, so maybe you should seek them out first instead of "reinventing the wheel". For example: https://www.uptrends.com/tools/uptime
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87781183
has comment: http://stackoverflow.com/comment/87754724
has comment: http://stackoverflow.com/comment/87798036
type: Answer
answers question: http://stackoverflow.com/q/50343736
has comment: http://stackoverflow.com/comment/87716408

http://stackoverflow.com/comment/87525956
has text: `list_[a:b]` gets evaluated. So yes, a new copy is made. Perhaps you want `itertools.islice`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50254180
score: 1

http://stackoverflow.com/comment/136153827
comment on: http://stackoverflow.com/a/50232793
type: Comment
score: 0
type: AnswerComment
has text: also use --data with credentials in json format if required by the site's login API call.

http://stackoverflow.com/comment/87739753
has text: I'm pretty sure the OP does mean the [`request`](https://docs.python.org/3/library/urllib.request.html) module in the `urllib` package that comes with the 3.x stdlib, which does have a `urlopen` function.
comment on: http://stackoverflow.com/a/50361645
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/50233902
has answer: http://stackoverflow.com/a/50234207
has body: The R code mentioned below is using a library CALIBERdrugdose and is returning a dataframe by using fuction doseconverter. We need to call this r script or rfunc(x) in python how we can do that? library(CALIBERdrugdose) rfunc &lt;- function(x){ l=doseconvert(c(x)) return(l) } when i tried to run it this way robjects.r(''' # create a function `f` library(CALIBERdrugdose) rfunc &lt;- function(x){ l=doseconvert(c(x)) return(l) } # call the function `f` with argument value 3 rfunc("sadas") ''') it was giving me this error.. RRuntimeError Traceback (most recent call last) &lt;ipython-input-89-5aea02cf4722&gt; in &lt;module&gt;() 10 # call the function `f` with argument value 3 11 rfunc("sadas") ---&gt; 12 ''') D:\workspace\lib\site-packages\rpy2\robjects\__init__.py in __call__(self, string) 350 def __call__(self, string): 351 p = _rparse(text=StrSexpVector((string,))) --&gt; 352 res = self.eval(p) 353 return conversion.ri2py(res) 354 D:\workspace\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs) 176 v = kwargs.pop(k) 177 kwargs[r_k] = v --&gt; 178 return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) 179 180 pattern_link = re.compile(r'\\link\{(.+?)\}') D:\workspace\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs) 104 for k, v in kwargs.items(): 105 new_kwargs[k] = conversion.py2ri(v) --&gt; 106 res = super(Function, self).__call__(*new_args, **new_kwargs) 107 res = conversion.ri2ro(res) 108 return res RRuntimeError: Error in library(CALIBERdrugdose) : there is no package called 'CALIBERdrugdose'
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: rpy2
tagged with: python
tagged with: http://stackoverflow.com/tag/r
score: 0
has title: Calling r script in python?

http://stackoverflow.com/comment/87610975
comment on: http://stackoverflow.com/q/50296531
has text: @kalyan - that's exactly right.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50268454
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87555000
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50268832
has comment: http://stackoverflow.com/comment/87555021
has comment: http://stackoverflow.com/comment/87554842
accepted answer: http://stackoverflow.com/a/50268832
has comment: http://stackoverflow.com/comment/87554723
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87554604
tagged with: python
has body: I'm trying to make a function where I feed it a list of URLs which go through a 301 hop and it flattens it for me. I want to save the resulting list as a CSV so I can hand it to the developers who can implement it and get rid of 301 hops. For example, my crawler will produce this list of 301 hops: URL1 | URL2 | URL3 | URL4 example.com/url1 | example.com/url2 | | example.com/url3 | example.com/url4 | example.com/url5 | example.com/url6 | example.com/url7 | example.com/url8 | example.com/10 example.com/url9 | example.com/url7 | example.com/url8 | example.com/url23 | example.com/url10 | | example.com/url24 | example.com/url45 | example.com/url46 | example.com/url25 | example.com/url45 | example.com/url46 | example.com/url26 | example.com/url45 | example.com/url46 | example.com/url27 | example.com/url45 | example.com/url46 | example.com/url28 | example.com/url45 | example.com/url46 | example.com/url29 | example.com/url45 | example.com/url46 | example.com/url30 | example.com/url45 | example.com/url46 | The output I'm trying to get is URL1 | URL2 example.com/url1 | example.com/url2 example.com/url3 | example.com/url5 example.com/url4 | example.com/url5 example.com/url6 | example.com/10 example.com/url7 | example.com/10 example.com/url8 | example.com/10 example.com/url23 | example.com/url10 ... I've converted the Pandas dataframe to a list of lists using the below code: import pandas as pd import numpy as np csv1 = pd.read_csv('Example_301_sheet.csv', header=None) outlist = [] def link_flat(csv): for row in csv.iterrows(): index, data = row outlist.append(data.tolist()) return outlist This returns each row as a list, and they are all nested together in a list, like below: [['example.com/url1', 'example.com/url2', nan, nan], ['example.com/url3', 'example.com/url4', 'example.com/url5', nan], ['example.com/url6', 'example.com/url7', 'example.com/url8', 'example.com/10'], ['example.com/url9', 'example.com/url7', 'example.com/url8', nan], ['example.com/url23', 'example.com/url1…
tagged with: melt
type: AnsweredQuestion
has title: Pair each item with the last non-null value in a row
tagged with: pandas
score: 1

http://stackoverflow.com/a/50283907
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50283775
downvote count: 0
answers question: http://stackoverflow.com/q/50283775
type: AcceptedAnswer
has body: Most likely describe can df.groupby(["student_name","subject"]).score.describe() Out[15]: count mean std min 25% 50% \ student_name subject joan maths 2.0 85.500000 3.535534 83.0 84.25 85.5 sarah history 2.0 85.000000 2.828427 83.0 84.00 85.0 maths 3.0 77.333333 6.027714 71.0 74.50 78.0 physics 2.0 94.000000 4.242641 91.0 92.50 94.0 75% max student_name subject joan maths 86.75 88.0 sarah history 86.00 87.0 maths 80.50 83.0 physics 95.50 97.0 And with drop_duplicates df.sort_values('score').drop_duplicates(["student_name","subject"],keep='last') Out[22]: student_name subject test_number score 2 sarah maths test3 83 6 sarah history test2 87 8 joan maths test2 88 4 sarah physics test2 97 For mean value with reindex df.groupby(["student_name","subject"], as_index=False).mean().reindex(columns=df.columns) Out[24]: student_name subject test_number score 0 joan maths NaN 85.500000 1 sarah history NaN 85.000000 2 sarah maths NaN 77.333333 3 sarah physics NaN 94.000000
score: 4

http://stackoverflow.com/q/50244270
has answer: http://stackoverflow.com/a/58717917
answer count: 2
tagged with: gradient
downvote count: 0
has comment: http://stackoverflow.com/comment/87506288
possible better answer: http://stackoverflow.com/a/58717917
has title: How can I efficiently compute the Jacobian matrix in TensorFlow?
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/138414265
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87555183
linked to: http://stackoverflow.com/q/61578733
has answer: http://stackoverflow.com/a/53798621
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/138414362
has comment: http://stackoverflow.com/comment/87526562
tagged with: python
has body: I want to calculate the Jacobian matrix by TensorFlow. I have: def compute_grads(fn, vars, data_num): grads = [] for n in range(0, data_num): for v in vars: grads.append(tf.gradients(tf.slice(fn, [n, 0], [1, 1]), v)[0]) return tf.reshape(tf.stack(grads), shape=[data_num, -1]) fn is a loss function, vars are all trainable variables, and data_num is a number of data. But if we increase the number of data, it takes a tremendous time to run the function compute_grads. How can I fix this?
type: Question
accepted answer: http://stackoverflow.com/a/53798621

http://stackoverflow.com/comment/87764181
has text: @Gang It's not, it's valid Python syntax.
score: 1
comment on: http://stackoverflow.com/q/50361617
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50256979
has body: I'm trying to scrape the data from the website "Airdna.co" I'm struggling to get the data. I managed this code as below but I get always a None value: #!/usr/bin/python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup from bs4 import NavigableString import requests import os, os.path, csv url='https://www.airdna.co/market-data/app/fr/new-aquitaine/bordeaux/overview' url = 'https://www.airdna.co/market-data/app/fr/new-aquitaine/bordeaux/overview' response = requests.get(url) encodedText = response.text.encode("latin-1") soup = BeautifulSoup(encodedText, "html.parser") dl_data = soup.find_all("div",class_="overall-box__value ") for data in list(zip(soup.find_all("div",class_="overall-box__value")[0::2],soup.find_all("div",class_="overall-box__value ")[1::2],soup.find_all("div",class_="overall-box__value ")[2::2])): ADRate, ORate, Revenue = data ADRate = ADRate.string.encode('utf-8') ORate= ORate.string.encode('utf-8') Revenue = Revenue.string.encode('utf-8') print ' , '.join([ADRate,ORate,Revenue]) This is the link for the website. After displaying the soup variable, I realized that the body is empty: soup = BeautifulSoup(encodedText,"html.parser") Can anybody show and explain how I would do this?
upvote count: 2
score: 1
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/50260172
downvote count: 1
has title: Parse Airdna.co Using Beautifulsoup
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50308352
has comment: http://stackoverflow.com/comment/87642104
accepted answer: http://stackoverflow.com/a/50308398
score: 2
has answer: http://stackoverflow.com/a/50308398
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/87644131
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87645748
has body: df_tier device_id month_id net_grp watch_hours class 843 201707 TCH 0.250277 Ser 896 201803 NJV 0.820833 Ser 748 201711 SHX 2.461111 Sr 115 201712 SPE 1.478055 Opter 107 201802 US 2.575555 Opter 249 201710 ECC 3.869166 Ser 786 201711 NCK 0.563888 Opter 183 201802 HO 1.690555 Opter 752 201712 LC 0.993611 Opter I am doing a pivot operation on a dataset, the end result will contain around 5 million rows and 600 columns. Above is a sample of the data from which the pivot is created. #Pivot df_tier.pivot_table(index=['device_id'], columns = 'net_grp', values = 'watch_hours', aggfunc = sum,fill_value = 0).reset_index() this operation on a sample of 200000 records takes around 93.7 ms and when I do group by as below: #Grouby df_tier.groupby(['device_id','net_grp']).agg({'tuning_hours':['sum']}).unstack(level='net_grp').fillna(0).reset_index().set_index('device_id') that takes around 15ms. However the output of pivot is more usable as it contains proper column names whereas the one from groupby : The column names in group by are not proper, (watch_hours,sum,TCH),(watch_hours,sum,SPE),(watch_hours,sum,NCK) How do I get only the net_grp say TCH from these as column names? I want to use groupby here because of performance issues when I run on the whole data. Can someone please help me to get the column names properly? Thanks
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87642987
tagged with: pivot-table
tagged with: group-by
has comment: http://stackoverflow.com/comment/87644165
has title: pivot_table vs groupby : column names
tagged with: python
has comment: http://stackoverflow.com/comment/87644217

http://stackoverflow.com/comment/87786068
has text: But I want in postgres not in python
type: Comment
comment on: http://stackoverflow.com/a/50385058
score: 0
type: AnswerComment

http://stackoverflow.com/q/50333012
type: Question
has comment: http://stackoverflow.com/comment/87682181
tagged with: python-3.x
has title: Bypassing Python's private attributes inadvertently
has answer: http://stackoverflow.com/a/50333516
has comment: http://stackoverflow.com/comment/87682310
has comment: http://stackoverflow.com/comment/87685352
tagged with: encapsulation
tagged with: python
has comment: http://stackoverflow.com/comment/87682162
has body: I managed to bypass the setter using the following code : t = TrajetGPS() # will call t.getPoints(), which will return the list by reference # we can then modify it at will, bypassing the setter points = t.points points.append(PointGPS(0, 0, 0)) points.append(PointGPS(1, 1, 1)) print(t) # will show : Points : (0, 0, 0) (1, 1, 1) The TrajetGPS() is defined as a simple class containing a list of PointGPS defined with points = property(getPoints, setPoints) and PointGPS() contains 3 coordinates (latitude, longitude, altitude). But all this doesn't matter here. Is it normal I can bypass the setter without a warning ? Python is designed to be beginner-friendly, but this doesn't seem very friendly as it can be very quick to insert malformed data into the list (without knowing !).
tagged with: class
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50333516
accepted answer: http://stackoverflow.com/a/50333598
answer count: 2
tagged with: oop
score: 1
has answer: http://stackoverflow.com/a/50333598
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/50268765
has body: The problem is you are iterating over a list of dictionary keys, and then you are trying to index that list with elements of the same list. A list indexer must be an integer. In essence, this is what your code is attempting: lst = [10, 20, 30] # this will fail on the first element, lst[10] does not exist for i in [10, 20, 30]: if lst[i]: What you can do instead is iterate over a range defined by the length of the list: line = 'this is a test' num = 0 result = {} for text in line: char = ord(text) num += 1 if char in result: result[char].add(num) else: result[char] = set() result[char].add(num) row = list(result.keys()) print(result) # {32: {5, 8, 10}, # 97: {9}, # 101: {12}, # 104: {2}, # 105: {3, 6}, # 115: {4, 7, 13}, # 116: {1, 11, 14}} for i in range(len(row)): if row[i] &lt; 60: print(row[i], result[row[i]]) # 32 {8, 10, 5} You can implement this logic more efficiently using a dictionary comprehension. There is very rarely a need to make an explicit list out of your dictionary keys. res = {k: v for k, v in result.items() if k &lt; 60}
type: Answer
answers question: http://stackoverflow.com/q/50268093
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50268093

http://stackoverflow.com/q/50369881
has comment: http://stackoverflow.com/comment/87755787
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87755858
has comment: http://stackoverflow.com/comment/87755744
has comment: http://stackoverflow.com/comment/87755673
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50370365
has title: pick three random number from ten and made x**2+x*y-y**2+z smallest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87755828
tagged with: python
has body: Suppose I get L=[1, 1, 1, 3, 1, 1, 1, 1, 1, 1] then func(L) should return -4, because min(x^2+x*y-y^2+z)=-4, for any x, y, z in L. any better way to build func without three for loop?

http://stackoverflow.com/a/50257104
score: 1
has body: Since you are using 3rd party libraries, this is a task well suited for pandas. There is some messy, but not inefficient, work to incorporate index and columns as per your requirement. org = [['A', 'a', 1], ['A', 'b', 2], ['A', 'c', 3], ['B', 'a', 4], ['B', 'b', 5], ['B', 'c', 6], ['C', 'a', 7], ['C', 'b', 8], ['C', 'c', 9]] df = pd.DataFrame(org) pvt = df.pivot_table(index=0, columns=1, values=2) cols = ['\t'] + pvt.columns.tolist() res = pvt.values.T.tolist() res.insert(0, pvt.index.tolist()) res = [[i]+j for i, j in zip(cols, res)] print(res) [['\t', 'A', 'B', 'C'], ['a', 1, 4, 7], ['b', 2, 5, 8], ['c', 3, 6, 9]]
accepted answer of: http://stackoverflow.com/q/50256984
type: Answer
answers question: http://stackoverflow.com/q/50256984
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50293486
has body: Moving the loop outward, will make the code run significantly faster: for c in ['col1', 'col2', 'col3', 'col4', 'col5']: df[c] *= 100. / 3600 This is because the individual loops' calculations will be done in a vectorized way. This also won't modify the index in any way.
type: Answer
answers question: http://stackoverflow.com/q/50293176
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/87706914
has text: excluding or including 999? (same for 99) See answer...
score: 0
comment on: http://stackoverflow.com/q/50345461
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50350554
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/87717817
has comment: http://stackoverflow.com/comment/87717997
answers question: http://stackoverflow.com/q/50350496
has comment: http://stackoverflow.com/comment/87717689
accepted answer of: http://stackoverflow.com/q/50350496
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87717952
has body: You column window is an StructType. Therefore, you cannot write it directly as a CSV. You need to flatten it a little bit. Either cast it to string, or explode its structures, in 2 columns start and end. CSV can only have "simple" types like string, interger or timestamp. try this : df.select( 'window.start', 'window.end', 'count', ).write.csv("good_loc.csv")
downvote count: 0

http://stackoverflow.com/q/50286437
has answer: http://stackoverflow.com/a/50286532
tagged with: django
tagged with: python
answer count: 1
linked to: http://stackoverflow.com/q/10059673
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87588947
has body: This might be frivolous, I don’t know the origin of P in /(?P&lt;topic_id&gt;\d+)$", Google searches aren’t helpful. Python official docs does not elaborate it on 6.2. re [ # page for adding a new new Entry url(r"^new_entry/(?P&lt;topic_id&gt;\d+)$", views.new_entry, name='new_entry'), ] Does the ‘P’ mean ‘pattern’ which seems unnecessary to declare it.
upvote count: 1
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50286532
has title: What does P mean in `/(?P<topic_id>\d+)$`
has comment: http://stackoverflow.com/comment/87588975
downvote count: 0

http://stackoverflow.com/comment/87759383
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50369690
has text: Of course it doesnt work if the third index is not `C3`. As I said it is an answer to his example

http://stackoverflow.com/a/50325085
answers question: http://stackoverflow.com/q/50324604
has comment: http://stackoverflow.com/comment/87666343
has comment: http://stackoverflow.com/comment/87666766
has comment: http://stackoverflow.com/comment/87672063
upvote count: 1
has comment: http://stackoverflow.com/comment/87904159
score: 1
has body: Your code gets it wrong on several counts, tell me if you understand why the following works? def task(num): num = int(num) lst = [2] if num &lt; 3: return lst for i in range(3, num + 1): if i % 2 == 1: for n in range(3, int(i ** 0.5) + 1, 2): if i % n == 0: break else: lst.append(i) return lst (note: the for else clause is quite natural here, for else clauses are used when you search for something in a loop, you break when you find that something, if not break is encountered and the regular stopIteration is used to exit the loop the else part is performed, I say it is natural here since in pseudo code you would say something like "if my number can be divided by another number less than its square it is not prime, otherwise add it to the list of primes" see http://book.pythontips.com/en/latest/for_-_else.html for more detauls) Its by no means a fast way to do it but I tried to stay as close to the spirit of your attempt while improving the aesthetics of the code
has comment: http://stackoverflow.com/comment/87695946
type: Answer
has comment: http://stackoverflow.com/comment/87667015
has comment: http://stackoverflow.com/comment/87694532
downvote count: 0

http://stackoverflow.com/comment/87718191
has text: @zwer - If you are going to go into big O notation then you also have to account the fact of what a list append does to Python. With each append you are walking the list and allocating memory. Allocating memory takes up a lot of time and resources. I've done a lot of speed testing with python for realtime applications. Using a for loop and appending to a list in python is horribly slow.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50350826

scintilla
type: Tag
tags question: http://stackoverflow.com/q/50355919
tag name: scintilla

http://stackoverflow.com/comment/87684734
type: AnswerComment
comment on: http://stackoverflow.com/a/50334156
has text: I get a TypeError unless I use `data.shape[1] // 2` - ??
score: 1
type: Comment

http://stackoverflow.com/a/50352374
answers question: http://stackoverflow.com/q/50352234
type: Answer
score: 4
upvote count: 4
downvote count: 0
has body: By default prophet assumes you have daily data. In your case it is monthly though. If you want to predict monthly data you should write something like this: sub_model = Prophet(weekly_seasonality=False, daily_seasonality=False).fit(df1) future = sub_model.make_future_dataframe(periods=1, freq='M') fcst = sub_model.predict(future) Another important point are the names of the columns you are passing into phrophet. Your date column must be named 'ds' and the variable column which you want to predict must be 'y'
has comment: http://stackoverflow.com/comment/87721161

http://stackoverflow.com/comment/87747526
type: Comment
comment on: http://stackoverflow.com/q/50365621
score: 1
type: QuestionComment
has text: Python 2.6? RLY?

http://stackoverflow.com/comment/87613047
type: AnswerComment
comment on: http://stackoverflow.com/a/50298046
score: 1
type: Comment
has text: @Bprodz tbh, I'm not sure the docs used the best approach to representing this example.

http://stackoverflow.com/q/50333609
has title: urllib2 read response more than once
tagged with: urllib2
has comment: http://stackoverflow.com/comment/87685628
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87684005
has body: I am trying to modify SQLmap connect class (https://github.com/sqlmapproject/sqlmap/blob/master/lib/request/connect.py) to meet my needs. What I want to do is to check if the response contains "CAUGHT BY WAF" and repeat that request until it doesn't contain it. So after line 471 I added: conn = urllib2.urlopen(req) while('CAUGHT BY WAF' in conn.read()): conn = urllib2.urlopen(req) However this doesn't work because after doing conn.read(), SQLmap won't be able to read the response again as you can do it only once. P.S: I tried to use deepcopy: conn = urllib2.urlopen(req) conn2 = copy.deepcopy(conn) while('CAUGHT BY WAF' in conn2.read()): conn = urllib2.urlopen(req) conn2 = conn but still doesn't work (no idea why!!) So my question is: how can I do conn.read() more than once? Thanks!
upvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50333780
has comment: http://stackoverflow.com/comment/87684891
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87492661
score: 0
type: AnswerComment
has text: Sorry for the bad formatting, it's my first post here. There shouldn't be empty lines. My first attempt had everything on two lines.
type: Comment
comment on: http://stackoverflow.com/a/50237611

http://stackoverflow.com/a/50310620
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50308951
downvote count: 0
has comment: http://stackoverflow.com/comment/87639649
upvote count: 1
has comment: http://stackoverflow.com/comment/87638919
type: Answer
has body: I think you might have a minor misunderstanding of how filter works here. This introduction and this answer provide some detailed explanation. I found the Convolution Demo animation in the introduction is extremely helpful in showing how it works. The key point here is how the filter works. Usually, convolutional layer has a set of K filters (64 in your example). For each filter, the actual shape is kernel_size + depth_of_input (5x5x32 in your example). That means one filter will look/apply onto 32 channels/images all at once and gives one conclusion/computed_feature. Therefore, the depth/num_of_features of output is equal to your filters argument rather than input_depth*filters. Please check this code to get an idea about the real and final kernel for computation. Therefore, to answer your last question, the output of either [batch_size, 14, 14, 32] or [batch_size, 14, 14, 48] will always be [batch_size, 14, 14, 64] for your setting.
accepted answer of: http://stackoverflow.com/q/50308951

http://stackoverflow.com/q/50259785
has comment: http://stackoverflow.com/comment/87557900
linked to: http://stackoverflow.com/q/49094112
has body: I'm trying to run an app with PySide2 from Spyder 3.2.8 and Python 3.6.4 in Anaconda in a macOS 10.13.4. attempt N°1 After having seen this stackoveflow page and this github page I changed my graphic backend from Inline to Automatic in Python &gt; Preferences &gt; IPython Console &gt; Graphics and I tried to run the following script (script N°1): script N°1 import sys from PySide2.QtWidgets import * # Create a Qt application app = QApplication.instance() if app is None: print("print something") app = QApplication(sys.argv) # Create a Label and show it label = QLabel("Hello World") label.show() # Enter Qt application main loop app.exec_() but got the following error message after running it: Importing PySide2 disabled by IPython, which has already imported an Incompatible QT Binding: pyqt5 There are similar reported issues here with matplotlib and here with ipython but it didn't help me (or I couldn't implement it properly). Then I tried to implement the content of this page about qtpy by changing the script N°1 in the following way: script N°2 import os os.environ['QT_API'] = 'pyside2' from qtpy.QtWidgets import * import sys # Create a Qt application app = QApplication.instance() if app is None: print("print something") app = QApplication(sys.argv) # Create a Label and show it label = QLabel("Hello World") label.show() # Enter Qt application main loop app.exec_() attempt N°2 With Inline selected in Python &gt; Preferences &gt; IPython Console &gt; Graphics. When I ran the script N°2 , the app launches and I got print something printed in to the console. When closing the app, I got Out[1]: 0 in the console. However when I run the script again, no error message appears in the console but the window of the app doesn't show-up attempt N°3 This time with Automatic selected in Python &gt; Preferences &gt; IPython Console &gt; Graphics. When I ran the script N°2 the first time, the app didn't launch and I got the following error message /anaconda3/lib/python3.6/site-packag…
has comment: http://stackoverflow.com/comment/87569964
upvote count: 3
score: 3
tagged with: pyside2
downvote count: 0
has comment: http://stackoverflow.com/comment/87545072
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50283592
tagged with: python-3.x
type: Question
tagged with: spyder
has title: Unable to see app windows created by PySide2 in Spyder
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50278845
has answer: http://stackoverflow.com/a/50279208
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50278975
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50279021
tagged with: python
score: -1
downvote count: 1
has title: What does arithmetic do inside np.argmax?
tagged with: reinforcement-learning
has comment: http://stackoverflow.com/comment/87574496
answer count: 3
tagged with: artificial-intelligence
has body: I'm researching and trying to implement a Q-Learning example. So far, I've been able to follow the code slowly by breaking it apart and figuring out how it works, however I've stumbled upon a tiny snippet that I can't figure out why it exists... action = np.argmax(q_learning_table[state,:] + np.random.randn(1, 4)) From what I gather, an action is being chosen from the Q-Learning table but only from a specific row in the matrix, whatever value state is. What I don't understand is why the need for the np.random.randn(1, 4). Locally, I've done the following to try and understand it: A = np.matrix([[0, 0, 5, 0], [4, 0, 0, 0], [0, 0, 0, 9]) a = np.argmax(A[2,:] + 100) print(a) My understanding is that I should see the result 103 rather than 3 (location of 9). So, why do I still see 3. What's the purpose of adding 100?
favorite count: 0

http://stackoverflow.com/comment/87492385
score: 1
has text: How was pandas installed? If it was in a virtualenv, for example, you'd have to run it in that env. You could `print(pandas.__file__)` to see where it is on your system. If its not in a system directory, then it is some sort of local install.
comment on: http://stackoverflow.com/q/50237237
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87636503
type: AnswerComment
comment on: http://stackoverflow.com/a/50302342
has text: Nevermind my previous comment, @JohnZwinck, I was forgotting to update the index used in `x` in the following lines. Now that loop runs in about 6 seconds. Thanks!
type: Comment
score: 0

http://stackoverflow.com/comment/87772849
type: Comment
comment on: http://stackoverflow.com/q/50378166
has text: Can you import it in your python shell?
score: 0
type: QuestionComment

http://stackoverflow.com/q/50325385
answer count: 1
has body: I have successfully detected faces, save cropped face in a folder. Then view the total count of detected faces on the video using cv2.puttext. Now I want to show each cropped face on the video just like I am showing the total count. The code is as follows: import numpy as np import cv2 import time from time import strftime num = 0 total = 0 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) previous_millis = 0 while 1: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,'Person Count Algorithm',(10,50), font, 1,(255,0,0),2,cv2.LINE_AA) S1=int(strftime("%S")) #print "timing" #print(S1) millis = int(round(time.time() * 5000)) interval = 2000 #print(millis) if(int(millis-previous_millis) &gt;= interval): previous_millis = millis faces = face_cascade.detectMultiScale(gray, 1.3, 5) #time.sleep(2) 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.putText(img, 'person', (x,y-10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255,0,0), 2) cv2.imwrite('crop_faces/crop'+str(num)+'.jpg',roi_color) num = num + 1 print ("FOUND", len(faces), 'PERSON') total += len(faces) print ('Total Count:', (total)) font = cv2.FONT_HERSHEY_SIMPLEX img = cv2.circle(img, (470, 63), 63, (255,0,0), 3) cv2.putText(img, 'Total Count:', (420,40), font, 0.5,(255,0,0),1,cv2.LINE_AA) cv2.putText(img, str(total), (436,100), font, 2,(255,0,0),2,cv2.LINE_AA) cv2.imshow('image',img) k = cv2.waitKey(1) &amp; 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
has answer: http://stackoverflow.com/a/50325832
type: Question
accepted answer: http://stackoverflow.com/a/50325832
tagged with: python
has title: How to View cropped face on video
tagged with: opencv
type: AnsweredQuestion
score: 0
tagged with: face-detection

http://stackoverflow.com/q/50261869
tagged with: web-scraping
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python-3.x
has body: I've been trying to scrape a website like GitHub that requires login authentication, but unlike Github, it does not have and an API. I've followed these instructions and many others, but nothing seems to work and just returns a 422 error. from lxml import html url = "https://github.com/login" user = "my email" pas = "associated password" sess = requests.Session() r = sess.get(url) rhtml = html.fromstring(r.text) #get all hidden input fields and make a dict of them hidden = rhtml.xpath(r'//form//input[@type="hidden"]') form = {x.attrib["name"]: x.attrib["value"] for x in hidden} #add login creds to the dict form['login'] = user form['password'] = pas #post res = sess.post(url, data=form) print(res) # &lt;Response [422]&gt; I've also tried just sess.post(url, data={'login':user, 'password':pas}) with the same result. geting the cookies first and using them in the post doesn't seem to work either. How can i get my login page, preferably without using Selenium?
score: 3
has title: Python requests 422 error on post
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50263320
has answer: http://stackoverflow.com/a/50263320
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50274456
has comment: http://stackoverflow.com/comment/87566264
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50275728
tagged with: python-3.x
upvote count: 0
has title: Python 3 use a code from a file
type: UnansweredQuestion
tagged with: openpyxl
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87565865
downvote count: 1
has comment: http://stackoverflow.com/comment/87565679
linked to: http://stackoverflow.com/q/2349991
has body: I have two Python files. In my main file I work with a openpyxl module. In my second file I have many string lines with concatenating using Excel file cells, for example: '/ip address=' + sheet['D'+ row].value + '\n' and many others. But there is a problem, if I import that file to a main file using: from file2 import * I get many errors about undefined names like: NameError: name 'sheet' is not defined And it is really defined only in my main file, like: wb = openpyxl.load_workbook(filename='clients.xlsx') sheet = wb.get_sheet_by_name('Page1') How can I import everything from my file2 and get it work?
score: -1

subprocess
tags question: http://stackoverflow.com/q/50326442
tag name: subprocess
type: Tag
tags question: http://stackoverflow.com/q/50259075
tags question: http://stackoverflow.com/q/50248631
tags question: http://stackoverflow.com/q/50242565
tags question: http://stackoverflow.com/q/50353627
tags question: http://stackoverflow.com/q/50344490
tags question: http://stackoverflow.com/q/50364847
tags question: http://stackoverflow.com/q/50315062
tags question: http://stackoverflow.com/q/50354155
tags question: http://stackoverflow.com/q/50329848
tags question: http://stackoverflow.com/q/50341353
tags question: http://stackoverflow.com/q/50295085
tags question: http://stackoverflow.com/q/50308381
tags question: http://stackoverflow.com/q/50364217
tags question: http://stackoverflow.com/q/50284010
tags question: http://stackoverflow.com/q/50283102

http://stackoverflow.com/a/50287016
type: Answer
answers question: http://stackoverflow.com/q/50286883
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50286883
has comment: http://stackoverflow.com/comment/87591791
type: AcceptedAnswer
has body: The regex has to be one valid regex string. You separated three strings by comma, so python interpreted the last two strings as separate arguments (without keyword). the proper 'or' - operator in regex is '|', so your desired filter would look like this: df.filter(regex='AMP|amp|date')

http://stackoverflow.com/comment/87567251
comment on: http://stackoverflow.com/a/50274394
has text: can u help me by using xlrd package.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/87767063
has text: My raspberry pi got hanged while I was installing sudo python setup.py install --compiler-flags "-mfpu=neon" .. i want to install face_recognition for python 2.7.11
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50375225
score: 0

http://stackoverflow.com/comment/87606462
type: Comment
type: QuestionComment
has text: Is opening `http://url:7104` in a browser successful? If not the problem is outside python.
comment on: http://stackoverflow.com/q/50294764
score: 0

http://stackoverflow.com/a/50246783
type: Answer
answers question: http://stackoverflow.com/q/50246236
score: 0
has body: Even I had the Same problem while studying OOPS from Learn Python the Hard Way so I would suggest you to learn OOPS from Interactive Python. http://interactivepython.org/runestone/static/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html Once you are familiar with OOPS concepts, you can continue Learn Python the Hard Way. I hope it helps you. This isn't an answer to your question but I don't have enough rep to comment.

http://stackoverflow.com/q/50296337
tagged with: python
has comment: http://stackoverflow.com/comment/87610266
type: AnsweredQuestion
has body: Not sure if I should be doing this or not... but here goes. I have a url that looks like this: /deals/category/Apparel/ I changed it to category/Apparel to shorten it. but also notice the capitalized Apparel --as it is using the category name. So I added a slug to my Category model and I'm trying to redirect the deals/category/Apparel to category/apparel where the latter represents the slug In my deals app I have this URL: path('category/&lt;str:category&gt;', RedirectView.as_view(pattern_name='category', permanent=True)), and which I'm trying to redirect to (in my core urls file) path('category/&lt;slug:slug&gt;', deals_by_category, name='category') My view for the `deals_by_category' looks like this: def deals_by_category(request,slug): category_deals = Deal.objects.filter(category__slug=slug).order_by('expired','-date_added') category = category_deals[0].category return render(request, 'deals/category.html', {'category_deals': category_deals, 'category':category}) so when I go to deals/category/Apparel it is redirecting to category/Apparel which is not what I want... and I get an error like this: Reverse for 'category' with keyword arguments '{'category': 'Apparel'}' not found. 1 pattern(s) tried: ['category\\/(?P&lt;slug&gt;[-a-zA-Z0-9_]+)$'] I guess I understand that it is looking at the category name and trying to match against a slug, but not exactly sure how to correctly redirect this with the correct format.
score: 0
answer count: 1
has title: Django Redirect - URL with String to URL With Slug
type: Question
accepted answer: http://stackoverflow.com/a/50296721
has answer: http://stackoverflow.com/a/50296721
tagged with: http-redirect
tagged with: django

http://stackoverflow.com/comment/87741350
has text: glad you discovered the issue!
score: 0
comment on: http://stackoverflow.com/a/50331386
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/115425123
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50377764
type: Comment
has text: I could solve my problem which doesn't deserve a question on its own. I used the more specific `nodes.set_facecolor` in my case which solved my problem. My only suggestion of improvement is to explain what `set_array` does and why you use it instead of settings colors directly.

http://stackoverflow.com/q/50366489
has comment: http://stackoverflow.com/comment/87750141
has title: How to get twitter users screen-name or UserId from a specific geolocations?
has comment: http://stackoverflow.com/comment/87750691
has comment: http://stackoverflow.com/comment/87749847
tagged with: python
score: -1
tagged with: twitter
tagged with: tweepy
accepted answer: http://stackoverflow.com/a/50377352
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50377352
has comment: http://stackoverflow.com/comment/87749984
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87749648
favorite count: 0
has body: I want to get tweets from specific geo-location, so i used tweepy (api.search) method. I am successfully getting tweets from the specific geo location. but I am not getting screen name or userid. I am expecting that show_user when True will return me the screen name, who is posting that tweet. but i am not getting any screen name. so please tell me the solution how can i get the screen name who is posting that tweet by given geo location. Using tweepy. public_tweets = tweepy.Cursor(api.search, rpp=100, geocode="44.269493,63.341332,5km",since="2018-05-01",show_user = "True",tweet_mode="extended").items()
type: Question

http://stackoverflow.com/comment/87536431
score: 0
comment on: http://stackoverflow.com/q/50258067
type: Comment
has text: Can adapt something like:`[[el.partition(' ')[2] for el in g] for k, g in itertools.groupby(bodytext.splitlines(), lambda L: L.startswith('=E2=80=A2')) if k]` ? It's a bit hard to be specific as it's not the most readable of an example :)
type: QuestionComment

http://stackoverflow.com/q/50243667
tagged with: version
has comment: http://stackoverflow.com/comment/87546854
favorite count: 0
type: Question
has body: After reset my Mac, I installed Anaconda3 and add Python2 environment to Jupyter Notebook. Then I have this problem when I click the tap. enter image description here Always two same functions appears. Therefore, I guess Jupyter Notebook is working on two Python3s. How can I solve this? Anybody had the same problem? Environment: macOS High Sierra Python3 3.6.4 installed from Anaconda. Python2 2.7.15 already installed from macOS (I guess). Anaconda 4.4.10 Jupyter 5.4.0 Thanks in advance
has comment: http://stackoverflow.com/comment/87513594
has title: How can stop running two Python3 Versions on Jupyter Notebook?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48009983
tagged with: python
tagged with: jupyter
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87505387
score: 1
upvote count: 1

http://stackoverflow.com/q/50270826
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87560435
type: Question
has body: I am using selenium to crawl a javascript website, the issue is that, a Firefox browser opens up, but the call for the URL is not done. however, when I close the browser, it is then that call for URL is done and of course I get the missing driver exception. what do you think the issue comes from. knowing that: all programs are up-to-date my solution works fine, in local, but when I try to deploy it on the server, I start having issues Example: at my local machine, I run this script and everything goes smooth, however when I run it a server (Linux), only the browser opens up and no get URL is called from selenium import webdriver import time geckodriver_path = r'.../geckodriver' driver = webdriver.Firefox(executable_path= geckodriver_path) time.sleep(3) driver.get("http://www.stackoverflow.com")
has comment: http://stackoverflow.com/comment/87559942
has comment: http://stackoverflow.com/comment/87562582
has comment: http://stackoverflow.com/comment/87560407
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/25713824
has title: Selenium Python - Webdriver
score: -1
upvote count: 0
has answer: http://stackoverflow.com/a/50308598
tagged with: selenium

http://stackoverflow.com/q/50308643
has comment: http://stackoverflow.com/comment/88345819
tagged with: python
accepted answer: http://stackoverflow.com/a/50308749
score: -2
has title: in pandas, calculate product of row values in a column (which are grouped by a category) and assign the product value to all rows in each group?
has answer: http://stackoverflow.com/a/50308749
has comment: http://stackoverflow.com/comment/87633361
type: AnsweredQuestion
upvote count: 0
has body: my dataframe df has 3 columns 'part': part number 'test': test name 'test_pass': pass or fail result for each test.1 is pass, 0 is fail. i want to create a fourth column 'part_pass'. For any 'part' if there is at least one 'test_pass' equal to 0, that 'part' is a failing part. For that part i want to get 'part_pass' equal to 0 for all rows for that 'part'. For any 'part' if all the 'test_pass' equal to 1, that 'part' is a passing part. For that part i want to get 'part_pass' equal to 1 for all rows for that 'part'. How do i calculate the product of 'test_pass' grouped by 'part' and assign the resulting value to the rows of 'part_pass' by part group?
downvote count: 2
answer count: 1
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/q/50293081
type: Question
has answer: http://stackoverflow.com/a/50293195
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87602545
has body: I'm trying to get a better understanding of python class system. This question is intended only to satisfy my curiosity. Is it possible to use somehow a class instance as a parent class for another class. So far what I tried to do is class A: pass a = A() class B(a): pass and it gives following error: TypeError: object() takes no parameters class Meta(type): pass class A: pass a = A() class B(a, metaclass=Meta): pass and it gives this error TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I'm wondering, is it possible to somehow proxy all of the class instance methods to metaclass, so my instance would behave as a class
has answer: http://stackoverflow.com/a/50293135
answer count: 4
has answer: http://stackoverflow.com/a/50293489
score: 0
has answer: http://stackoverflow.com/a/50293609
has title: Use class instance as parent class in python

http://stackoverflow.com/comment/87621867
type: Comment
type: QuestionComment
has text: Do you have python 2 or 3? Because `raw_input()` in Python 2.x and `input()` in Python 3.x
score: 0
comment on: http://stackoverflow.com/q/50302730

http://stackoverflow.com/comment/87660840
type: QuestionComment
has text: I found a really good step-by-step tutorial using a DHT22 sensor and storing the data in a database, then recalling the data and finally displaying in a browser and charting the data.
score: 0
comment on: http://stackoverflow.com/q/50303403
type: Comment

http://stackoverflow.com/comment/87606799
type: QuestionComment
comment on: http://stackoverflow.com/q/50295085
score: 2
type: Comment
has text: remove the space before the `-` in `" -regex"`

http://stackoverflow.com/comment/87568198
type: AnswerComment
comment on: http://stackoverflow.com/a/50273675
type: Comment
has text: just need to edit `randint(0, 3)/3` to **`randint(0, fraction)/fraction`** and you can change it to any you want
score: 0

http://stackoverflow.com/a/50280058
answers question: http://stackoverflow.com/q/50271245
type: Answer
score: 0
has body: I fixed this problem by using the Unix epoch time format. Basically I took the current time and minus the time stored in the dict. If the difference is more or equal to 86400 seconds then a day has passed, allowing them to reclaim their bonus

http://stackoverflow.com/comment/87582796
comment on: http://stackoverflow.com/q/50282857
has text: How is `clonedRadarsdetailslist` created? Why is that enclosed in a `""`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50327439
tagged with: flask-restful
has body: I am unable to understand the what purpose does blueprints and namespaces serve in web app. I read the documentation but cannot figure it out exactly. It would be really helpful for me if you give a simple explanation with example for each case. Thanks!
favorite count: 0
accepted answer: http://stackoverflow.com/a/50614959
type: Question
has title: Difference between namespaces and blueprints in flask-restful and flask
answer count: 2
has answer: http://stackoverflow.com/a/50614959
possible better answer: http://stackoverflow.com/a/59147983
downvote count: 0
has answer: http://stackoverflow.com/a/59147983
tagged with: python
tagged with: flask
upvote count: 23
type: AnsweredQuestion
score: 23

http://stackoverflow.com/q/50327935
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50328031
has comment: http://stackoverflow.com/comment/87671785
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50328031
has body: I have df as given below which I am splitting column wise. &gt;&gt;&gt; df ID Started 0 NaN 20.06.2017 13:19:04 1 NaN 10.04.2018 04:48:32 2 WBTS-1509 06.11.2017 10:28:14 3 WBTS-1509 03.03.2018 10:12:29 4 WBTS-1117 07.03.2018 17:04:28 df['Started'].apply(lambda x: x.split(':')[0]) df['ID'].apply(lambda x: x.split('-')[1]) I would like to set 3 list variables col_names = ['ID' , 'Started'] splitby = ['-' , ':'] index_after_split = [1 , 0] do splitting using one line (avoiding loop) using inplace = True. Please help me do same. Thanks
has comment: http://stackoverflow.com/comment/87671724
tagged with: pandas
downvote count: 2
has title: pandas multiple column replace

http://stackoverflow.com/q/50364266
has comment: http://stackoverflow.com/comment/87744845
type: Question
has comment: http://stackoverflow.com/comment/87744876
tagged with: numpy
linked to: http://stackoverflow.com/q/21287624
answer count: 0
type: UnansweredQuestion
has title: `invalid literal for int() with base 10: 'null' ` while converting object to integer
tagged with: python
duplicate of: http://stackoverflow.com/q/38918653
duplicate of: http://stackoverflow.com/q/21287624
tagged with: object
linked to: http://stackoverflow.com/q/38918653
has comment: http://stackoverflow.com/comment/87744745
score: 0
has comment: http://stackoverflow.com/comment/87744838
tagged with: pandas
has body: Here's my dataset id value 1 100 2 50 But the value is object not integer or float In[3]: device_age.dtypes Out[3] device_id object value object dtype: object I want to make it integer int, here's what I try: import numpy as np device_age['value'] = device_age['value'].astype(np.int64) and I also try df['value'] = df['value'].astype(int) The error message is invalid literal for int() with base 10: 'null'
tagged with: dataframe

http://stackoverflow.com/comment/87628340
type: Comment
score: 0
type: QuestionComment
has text: yes that is a text input field.
comment on: http://stackoverflow.com/q/50305964

http://stackoverflow.com/q/50254723
possible better answer: http://stackoverflow.com/a/50254819
has answer: http://stackoverflow.com/a/50254819
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50254827
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50254827
upvote count: 1
tagged with: python
tagged with: git
favorite count: 0
has body: I updated the python version from 3.6.4 to 3.6.5 today. This is because, in the process of distributing to Heroku, it recommends version 3.6.5. Therefore, the following power shell contents were confirmed. Writing objects: 100% (35/35), 11.68 KiB | 0 bytes/s, done. Total 35 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using ÿþpython-3.6.5, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----&gt; Installing ÿþpython-3.6.5 remote: ! Requested runtime (ÿþpython-3.6.5) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: remote: ! Push rejected to XXXXXXXX. remote: To https://git.heroku.com/XXXXXXXX.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/XXXXXXXX.git After changing my runtime.txt file to UTF-8, I now get the following error: Writing objects: 100% (35/35), 11.68 KiB | 0 bytes/s, done. Total 35 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.5, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----&gt; Installing python-3.6.5 remote: ! Requested runtime (python-3.6.5) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push f…
tagged with: heroku
type: AnsweredQuestion
has title: Requested runtime (ÿþpython-3.6.5) is not available for this stack on Heroku
score: 1

http://stackoverflow.com/q/50305764
answer count: 4
tagged with: syntax-error
score: 0
has answer: http://stackoverflow.com/a/50305791
has answer: http://stackoverflow.com/a/50305781
has answer: http://stackoverflow.com/a/50305810
has comment: http://stackoverflow.com/comment/87627792
has body: I want to run the Python Script by using python command from IDLE Python GUI. The location of the file is C:\Users\DELL\Desktop\Hello.py When I run python C:\Users\DELL\Desktop\Hello.py with Windows command promt, it works. However, when I try with IDLE Python GUI and Python (command line), it does not work and gives me a message SyntaxError: invalid syntax Capture
type: Question
has comment: http://stackoverflow.com/comment/87627798
linked to: http://stackoverflow.com/q/7974849
has title: How to execute Python scripts with python command
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50305816
linked to: http://stackoverflow.com/q/17247471
tagged with: python
has comment: http://stackoverflow.com/comment/87627673
linked to: http://stackoverflow.com/q/1186789

http://stackoverflow.com/q/50330119
has answer: http://stackoverflow.com/a/50336691
has title: What's the proper way of moving documents between databases starting from PyMongo 3.6?
type: Question
tagged with: database
tagged with: python
answer count: 1
has body: I used to use pymongo.bulk.BulkOperationBuilder but the docs say that it's deprecated. The official MongoDB has db.cloneCollection() but I can't find anything similar in PyMongo, except copydb but it's not what I need. So I found two ways to bulk insert docs between colls and removing them afterwards. I haven't tested them yet, I wanted to ask you firstly for an advice because there might be a better way. Solution #1. coll_from = mongo['db_1']['coll_name'] coll_to = mongo['db_2']['coll_name'] requests = (InsertOne(doc) for doc in coll_from.find()) result = coll_to.bulk_write(requests, ordered=False) db_from.drop_collection('coll_name') Solution #2. coll_from = mongo['db_1']['coll_name'] coll_to = mongo['db_2']['coll_name'] coll_to.insert_many(coll_from.find()) db_from.drop_collection('coll_name') Is there any better way to bulk-move docs between dbs?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50336691
tagged with: pymongo

http://stackoverflow.com/comment/87592442
has text: @SourajitRoyChowdhury - I think `pivot` cannot working with it, need `f = df.set_index(['ID1','ID2', 'var_name'])['var_value'].unstack(fill_value='')[L].reset_index()`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50285324
type: Comment

http://stackoverflow.com/comment/87526921
has text: why not creating a standard `dict` from the iterators? Like `dict(zip(iter1, iter2))`? Does it get any more standard than that?
score: 1
comment on: http://stackoverflow.com/q/50254721
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87771791
comment on: http://stackoverflow.com/a/50368006
type: AnswerComment
has text: @user3758232 I elaborated a little bit more about what I meant by "refactoring". If you fall back to return the whole data, I would choose `array.array` or numpy-arrays because they store not the Python-objects but raw ints/doubles and so on - less memory needed and faster.
score: 2
type: Comment

http://stackoverflow.com/q/50343468
has answer: http://stackoverflow.com/a/50343971
possible better answer: http://stackoverflow.com/a/50343971
has title: Pandas: Pivoting column headers to row labels
tagged with: python
has answer: http://stackoverflow.com/a/50343988
accepted answer: http://stackoverflow.com/a/50343988
has body: I have extracted data from a website using the following: import pandas as pd import matplotlib.pyplot as plt stat_dict={'Disposals' : 0, 'Kicks' : 1, 'Marks' : 2, 'Handballs' : 3, 'Goals' : 4, 'Behinds' : 5, 'Hitouts' : 6, 'Tackles' : 7, 'Rebounds' : 8, 'Inside50s' : 9, 'Clearances': 9, 'Clangers' : 10, 'FreesFor' : 11, 'FreesAgainst' : 12, 'ContestedPosessions' : 13, 'UncontestedPosesseions' : 14, 'ContestedMarks' : 15, 'MarksInside50' : 16, 'OnePercenters' : 17, 'Bounces' : 18, 'GoalAssists' : 19, 'Timeplayed' : 20} team_lower_case='fremantle' player1="Fyfe, Nat" stat_required='Disposals' rounds=8 tables = pd.read_html("https://afltables.com/afl/stats/teams/" +str(team_lower_case)+"/2018_gbg.html") for df in tables: df.drop(df.columns[rounds+1:], axis=1, inplace=True) # remove unwanted columns df.columns = df.columns.droplevel(0) # remove extra index level stat_table=tables[stat_dict[stat_required]] player_stat=stat_table[stat_table["Player"]==player1] Which produces the following: Player R1 R2 R3 R4 R5 R6 R7 R8 8 Fyfe, Nat 22.0 29.0 38.0 25.0 43.0 27.0 33.0 36.0 How can I set the index to the data in the column 'Player'? How can I pivot the column headers to become row labels and vice-versa? The output I am looking for would be as follows: Round Fyfe, Nat Neale,Lachie R1 22 37 R2 29 28 The end output I would like to get is a scatter plot that plots on the x-axis the column headers e.g. R1, R2 etc... and on the y-axis the row data. I feel like I should be able to plot the data frame directly, but the only way I have had success is by doing the following: for round, disp in player_stat.iterrows(): player1_list=[] player1_list.append(disp) plt.style.use('ggplot') plt.scatter(range(1,rounds+1), player1_list, label=player1) plt.legend(loc="lower right") plt.title("Disposals per round") plt.xlabel("Rounds") plt.ylabel("Disposals") plt.ylim(ymin=0) It seems like I should use .transpose, which is close to what I want and outputs the following: 8 Player Fyfe, Nat R1 22 R…
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
tagged with: pandas
tagged with: matplotlib
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/87724743
type: AnswerComment
score: 0
has text: Please mark this answer as the correct, if it solved your question
type: Comment
comment on: http://stackoverflow.com/a/50353656

http://stackoverflow.com/comment/87655517
type: QuestionComment
has text: *the dotfile is used by flake8 run from the command line* How do you run `flake8`? Do you `cd tests`?
score: 0
comment on: http://stackoverflow.com/q/50301500
type: Comment

http://stackoverflow.com/comment/87669125
type: Comment
has text: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/170987/discussion-on-answer-by-jezrael-pandas-change-column-date-format).
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50286387

http://stackoverflow.com/q/50243859
type: UnansweredQuestion
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/87505481
score: 0
answer count: 1
has title: Splitting a list of lists in half randomly
has comment: http://stackoverflow.com/comment/87505525
type: Question
has body: Trying to make a card game in python, I made a list called a "cardlist", which contains 52 lists as "cards". What I´m trying to do now is to make 2 new lists for the user and computer to use in the game, and they have to contain a random half of the cards. I´m not sure how to do this. import random class Lamb(): def __init__(self, weight, milk, wool, offs, thigh, fert, meat, fat): self.weight = weight self.milk = milk self.wool = wool self.offs = offs self.thigh = thigh self.fert = fert self.meat = meat self.fat = fat def __repr__(self): return f"{self.weight,self.milk,self.wool,self.offs,self.thigh,self.fert,self.meat,self.fat}" def Read(txtfile): datalist=[] f = open(txtfile, "r", encoding="utf-8") for line in f: datalist.append(line.split(',')) f.close() cardlist = [] for i in datalist: cardlist.append(Lamb(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7])) return cardlist
has answer: http://stackoverflow.com/a/50243885

http://stackoverflow.com/comment/87538597
comment on: http://stackoverflow.com/a/50259986
type: AnswerComment
has text: This is also a great answer. The difference is that this one changes the table in place.
score: 0
type: Comment

http://stackoverflow.com/q/50293763
tagged with: python
tagged with: masked-array
has title: Delete masked elements from a list of arrays
has answer: http://stackoverflow.com/a/50469560
tagged with: folium
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/87605608
linked to: http://stackoverflow.com/q/41119334
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/45084306
has comment: http://stackoverflow.com/comment/87605862
score: 0
has body: I'm trying to plot a folium heatmap in Jupyter, but I get the error ValueError: Location values cannot contain NaNs, got: [nan, nan] So I need to delete the masked elements from a list of arrays. My arrays look like this: Xpos Out[68]: masked_array( data=[[--, --, --, ..., --, --, --], [--, --, --, ..., --, --, --], [--, --, --, ..., --, --, --], ..., [-3.6872851848602295, -3.732004165649414, -3.7555367946624756, ..., --, --, --], [-3.819749116897583, -3.824702739715576, -3.804812431335449, ..., --, --, --], [-3.6894078254699707, -3.7181897163391113, -3.7022457122802734, ..., --, --, --]], mask=[[ True, True, True, ..., True, True, True], [ True, True, True, ..., True, True, True], [ True, True, True, ..., True, True, True], ..., [False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True]], fill_value=9.96921e+36, dtype=float32) Each array in the list has a different amount of masked elements, some are only masked at the end, others are completely masked. How do I delete every masked element? So completely removing the completely masked ones and only deleting a few elements in the others. This would result in a list where the arrays have different lengths. My entire code is: #read in data: matplotlib.use('Qt4Agg', warn=False) def ncdump(nc_fid, verb=True): def print_ncattr(key): try: #print("\t\ttype:", repr(nc_fid.variables[key].dtype)) for ncattr in nc_fid.variables[key].ncattrs(): print('\t\t%s:' % ncattr,\ repr(nc_fid.variables[key].getncattr(ncattr))) except KeyError: print("\t\tWARNING: %s does not contain variable attributes" % key) # NetCDF global attributes nc_attrs = nc_fid.ncattrs() if verb: print("NetCDF Global Attributes:") for nc_attr in nc_attrs: print('\t%s:' % nc_attr, repr(nc_fid.getncattr(nc_attr))) nc_dims = [dim for dim in nc_fid.dimensions] # list of nc dimensions # Dimension shape information. if verb: #print("NetCDF dimension information:") for dim in nc_dims: #print…
has comment: http://stackoverflow.com/comment/87605944

http://stackoverflow.com/comment/87538268
type: QuestionComment
type: Comment
has text: Important: how are you inspecting the output shape?
comment on: http://stackoverflow.com/q/50259158
score: 0

http://stackoverflow.com/comment/87547387
comment on: http://stackoverflow.com/a/50263613
type: Comment
type: AnswerComment
has text: Converting to float when you're dealing with integers
score: 0

http://stackoverflow.com/q/50351908
has comment: http://stackoverflow.com/comment/87720578
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has title: Reading multiple csv files into a Pandas Data Frame
upvote count: 5
answer count: 1
tagged with: dataframe
has body: I am attempting to read multiple CSV files into a Pandas data frame. The CSVs aren't comma separated - the fields are delimited by a semicolon ";". I based my code on the answers here. My data is all in a specific subdirectory: /data/luftdaten/5331 This is what I run: import glob import pandas as pd path =r'data/luftdaten/5331' # use your path filenames = glob.glob(path + "/*.csv") count_files = 0 dfs = [] for filename in filenames: if count_files ==0: dfs.append(pd.read_csv(filename, sep=";")) count_files += 1 else: dfs.append(pd.read_csv(filename, sep=";", skiprows=[0])) count_files +=1 big_frame = pd.concat(dfs, ignore_index=True) I use count_files to monitor if it is the first CSV - in which case I import the headers. Otherwise, it skips the headers. The code executes OK. If I run it with a single file in that directory, everything is fine: big_frame.info() Output: RangeIndex: 146 entries, 0 to 145 Data columns (**total 12 column**s): sensor_id 146 non-null int64 sensor_type 146 non-null object etc...... If I run it with 2 or more files in the directory things go wrong from the start. Output with 4 files: RangeIndex: 1893 entries, 0 to 1892 Data columns (total **33 columns**): -2.077 1164 non-null float64 -2.130 145 non-null float64 2.40 145 non-null float64 Running big_frame.head() on the single CSV version gives this, with the correct column names: While running the same with four files imported gives me this: Is there anything obvious that I am doing which is causing not only the number of rows to grow but the columns too? Your guidance would be gratefully appreciated!
favorite count: 0
type: Question
score: 5
has answer: http://stackoverflow.com/a/50352045
accepted answer: http://stackoverflow.com/a/50352045
downvote count: 0
linked to: http://stackoverflow.com/q/20906474
tagged with: python

http://stackoverflow.com/a/50359642
has body: I don't know how to do this with a metaclass, but here's a possible solution using a mixin class. You might be able to use something like this. from inspect import signature from functools import partialmethod, partial class Naked: @staticmethod def echo1(foo): return f"echo1: {foo}" @staticmethod def echo2(bla, bar): return f"echo2: {bar}, {bla}" class PartialMixin: def __init__(self, **kwargs): methods = [m for m in dir(self) if callable(getattr(self, m)) and m not in dir(type)] for method_name in methods: method = getattr(self, method_name) method_kwargs = signature(method).parameters.keys() partial_kwargs = {k:kwargs[k] for k in kwargs if k in method_kwargs} new_method = partial(method, **partial_kwargs) # if the methods are not static, maybe functools.partialmethod should be used. setattr(self, method_name, new_method) class Clothed(PartialMixin, Naked): pass a = Clothed(foo = "Hello", bar = "World") a.echo1() == "echo1: Hello" a.echo2("wsup?") == "echo2: World, wsup?"
has comment: http://stackoverflow.com/comment/88295659
has comment: http://stackoverflow.com/comment/88300143
type: Answer
answers question: http://stackoverflow.com/q/50358462
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/88299541
accepted answer of: http://stackoverflow.com/q/50358462
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50383844
downvote count: 0
has comment: http://stackoverflow.com/comment/87785488
tagged with: keras
has title: Is there a way to put geotif as input data in a tensor flow or keras in python?
tagged with: tensorflow
favorite count: 0
type: Question
has body: I would like to use geotif image as input data in a tensor flow or keras. I know that tensorflow does not support tif. So I tried using gdal to make it into a raster image, but it failed. Please let me know if there is a way to put geotif in tensorflow or keras in python.
has comment: http://stackoverflow.com/comment/87796676
type: UnansweredQuestion
tagged with: geotiff
tagged with: python
has comment: http://stackoverflow.com/comment/87823722
score: 3
has comment: http://stackoverflow.com/comment/87823742
answer count: 0
upvote count: 3

http://stackoverflow.com/a/50297431
type: AcceptedAnswer
has body: you can get the current class like this: class class1: def __init__(self): self.foo = 1 self.bar = 2 def new(self): return self.__class__() Inheritors will return their own classes. You will have to handle the logic for any different __init__ signatures yourself, however. A classmethod would be a better design choice unless you needed information from the current instance to create the new one.
downvote count: 0
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50297337
answers question: http://stackoverflow.com/q/50297337

http://stackoverflow.com/comment/87693200
score: 0
type: Comment
has text: Unfortunately it seems the way Flask runs the code the paths are obscured, but the files are in the correct locations as far as I can tell. I will have to dig into the Apache config some more as this seems to be where the issue lies
type: QuestionComment
comment on: http://stackoverflow.com/q/50336493

http://stackoverflow.com/comment/87773209
type: Comment
type: QuestionComment
has text: Possible duplicate of [Check if string exists in a text file](https://stackoverflow.com/questions/26391805/check-if-string-exists-in-a-text-file)
score: 3
comment on: http://stackoverflow.com/q/50378527

http://stackoverflow.com/comment/87569891
type: Comment
comment on: http://stackoverflow.com/q/50276640
score: 1
has text: It should be the literal `'name'`. No variable called `name` is defined.
type: QuestionComment

http://stackoverflow.com/q/50381369
tagged with: recaptcha
tagged with: invisible-recaptcha
answer count: 0
has comment: http://stackoverflow.com/comment/91798762
upvote count: 3
has comment: http://stackoverflow.com/comment/91775041
has title: python requests form recaptcha
downvote count: 0
has body: i've been trying to do a requests form using python but i'm blocked b the recaptcha. I need the g-recaptcha-response to fill the entire form but i have no idea of how to get it. I've been trying things but I have no clue of what i'm doing. I don't know anything about captcha. here is my code: url = url_add_to_cart c.get(url) c.post(url, data=add_to_cart_FORM, headers={"Refered": link_article}) page = c.get(link_article) if (page.status_code == requests.codes.ok): print ("ok") else: print ("not ok") url1 = "https://www.supremenewyork.com/checkout.json" c.get(url) t = requests.get('http://ip.42.pl/raw') tt = BeautifulSoup(t.text, 'html.parser') ip = tt.text print (ip) page = c.get(link_checkout) soup = BeautifulSoup(page.text, 'html.parser') find_class = soup.find(class_='g-recaptcha') get_captcha_token = find_class.get('data-sitekey') try: content = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data={ 'secret': RECAPTCHA_SECRET, 'response': get_captcha_token, 'remoteip': ip } ).content except: print ("fail") print (get_captcha_token) c.post(url, data=payload_FORM, headers={"Refered": link_checkout}) page = c.get(link_checkout) # page_to_print_for_test = BeautifulSoup(page.text, 'html.parser') # print (page_to_print_for_test.prettify()) if (page.status_code == requests.codes.ok): print ("ok") else: print ("not ok") here is the source code of captcha: image of the HTML code related to the captcha If you need more infos, I will add everything! thank you very much. it is one of the last thing to do to finish my code. (I need to code it properly ^^)
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91798556
favorite count: 0
type: Question
score: 3
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/50271946
has answer: http://stackoverflow.com/a/79426500
tagged with: boto
answer count: 3
has title: get file metadata from S3 using Python boto
upvote count: 14
has answer: http://stackoverflow.com/a/54964979
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have some binary files in AWS S3, i need to get the file metadata like created time, modified time and accessed time using Python Boto API? What we tried was copy the files to EC2 instance, from there we used os module stat method to get the times. I hope when we copy the files to EC2 instance these details are changed. Sample code what i tried: stat = os.stat(inputFile) createdTime = datetime.fromtimestamp(stat[9]).strftime("%A, %B %d, %Y %I:%M:%S") How to directly get these details from S3?
tagged with: python
has answer: http://stackoverflow.com/a/50273181
score: 14

http://stackoverflow.com/a/61744330
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/50299153
upvote count: 1
has body: You can pretty much use Linux commands for moving and copying files in colab as well. Just use a ! before that command and run the cell as you usually do. For example: !mv some_folder another_folder/ should work. Also you need to mount google drive first in your colab notebook.
type: Answer

http://stackoverflow.com/q/50360416
possible better answer: http://stackoverflow.com/a/50360449
tagged with: python
type: Question
answer count: 2
tagged with: django
has answer: http://stackoverflow.com/a/50360449
has body: When I submit a post request from a form, it's processed as not post in the views: Edit The Topic: {% csrf_token %} {{ form.as_p }} Save Changes The views.py, I set test within if request != "POST": def edit_topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if request != "POST": form = TopicForm(instance=topic) # assert request == 'POST' print("\tPOST Method in not post condition.\n", f"\tRequest Method is {request.__dict__['method']}") come by with Quit the server with CONTROL-C. POST Method in not post condition. Request Method is POST [16/May/2018 07:14:31] "POST /edit_topic/5 HTTP/1.1" 200 1770 The post method is treated as not post. What's the problem with my code?
accepted answer: http://stackoverflow.com/a/50360436
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50360436
score: 0
has title: a POST request was judged as NOT POST Method

http://stackoverflow.com/a/50437040
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50292631
has body: You need one more piece of information: your camera's field of view: https://blog.codinghorror.com/content/images/uploads/2007/08/6a0120a85dcdae970b0120a86d9495970b-pi.png I'll refer to horizontal field of view as hFOV and vertical field of view as vFOV. You only need one of these numbers to solve your problem though, as hFOV/vFOV is equal to the aspect ratio (horizontal resolution / vertical resolution). With that information, you can use the camera's position (Pc, a 3D vector), direction (Dc, a 3D vector), resolution (R, a 2D vector) and the point's position in view space (Pp, a 2D vector) to build a 3D vector that the point lies upon in space. If the point lies exactly in the middle of the view (Pp / R = 0.5) then this vector is simply Pc + d * Dc, where d is any positive number, corresponding to the distance from the camera (this will become our variable that we need to solve for. The x coordinate of Pp rotates Dc in x from -hFOV/2 to hFOV/2 about the vector perpendicular to both Dc and the x direction of the screen (you can find this with the cross product). The y coordinate does the same in y. We'll call this rotated vector D'c. Rotating a vector by θ about another vector is solved here: Rotating a Vector in 3D Space So now we have the relationship: Position of marker = Pc + d * D'c Now, d is still an unknown (distance from camera). But if we do this for two cameras, we can solve the system of equations and find the absolute position of the marker. The third camera is useful for verification. Note: This is more or less the same answer as @osama-alkoky, just the manual version. Learning about projection/transformation matrices is a good idea if you're going to be doing a lot of this.
type: Answer

system
tag name: system
tags question: http://stackoverflow.com/q/50319127
type: Tag
tags question: http://stackoverflow.com/q/50358321

http://stackoverflow.com/q/50310454
has answer: http://stackoverflow.com/a/50310482
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe
has body: I have two dfs: df1: no1 no2 other1 1 10 foo 1 50 foo 1 60 cat 1 70 cat 3 12 cat df2: no1 start stop other2 1 2 40 dog 1 100 200 dog 3 5 15 dog I want to merge df1 and df2 on the following conditions: 1) the no1 column matches, if that's true then 2) df1['no2'] is between df2['start'] and df2['stop']: Desired output for the above example would be (don't need the start/stop columns, do need all other columns): df3: no1 no2 other1 other2 1 10 foo dog 3 12 cat dog My tried solution (convoluted, probably not most efficient): I thought np.where might do it for me, using the code below and then dropping all rows where df['merge'] = no. But it's giving me a Can only compare identically-labeled Series objects error that I think has to do with the dfs being of different sizes. Efficiency/speed matters, so I think this isn't the way to go even if I could solve the error. df2['merge'] = np.where((df1['no1'] == df2['no1'] &amp; df2['start'] &lt; df1['no2'] &lt; df2['stop']), yes, no)
type: Question
tagged with: numpy
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Pandas: combine dataframes of different shapes based on comparisons between dataframes
accepted answer: http://stackoverflow.com/a/50310482
favorite count: 0

http://stackoverflow.com/a/50297841
has comment: http://stackoverflow.com/comment/87613052
accepted answer of: http://stackoverflow.com/q/50297777
has body: Let's try using a Counter here: Split sentences into words Compute global word frequency Filter words based on computed frequencies Join and re-assign from collections import Counter from itertools import chain # split words into lists v = df['Col2'].str.split().tolist() # [s.split() for s in df['Col2'].tolist()] # compute global word frequency c = Counter(chain.from_iterable(v)) # filter, join, and re-assign df['Col2'] = [' '.join([j for j in i if c[j] &gt; 1]) for i in v] df Col1 Col2 0 1 how to remove word 1 5 how to remove word
type: Answer
has comment: http://stackoverflow.com/comment/87612540
has comment: http://stackoverflow.com/comment/87613020
has comment: http://stackoverflow.com/comment/87613405
has comment: http://stackoverflow.com/comment/87613084
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50297777
has comment: http://stackoverflow.com/comment/87612518
score: 9
upvote count: 9

http://stackoverflow.com/q/50344236
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87708214
has body: I've got a Dataset in tensorflow which returns tuples because it is designed to be used to create features and labels. How can I iterate over it in python and extract these tuples? import tensorflow as tf import numpy as np sess = tf.Session() def generator(): index = 0 while True: feature = np.ones([1,4]) * index label = feature[0:1,0:2] print('yielding:', feature, label) yield feature, label index +=1 dataset = tf.data.Dataset.from_generator( generator=generator, output_types=(tf.float64, tf.float64), output_shapes=(tf.TensorShape([1,4]),tf.TensorShape([1,2])), ) iterator = dataset.make_one_shot_iterator() data = iterator.get_next() print(data[0].eval(session=sess)) print(data[1].eval(session=sess)) print(data[0].eval(session=sess)) print(data[1].eval(session=sess)) output: yielding: [[0. 0. 0. 0.]] [[0. 0.]] [[0. 0. 0. 0.]] yielding: [[1. 1. 1. 1.]] [[1. 1.]] [[1. 1.]] yielding: [[2. 2. 2. 2.]] [[2. 2.]] [[2. 2. 2. 2.]] yielding: [[3. 3. 3. 3.]] [[3. 3.]] [[3. 3.]] The problem is, that the iterator steps each time I evaluate one of the data elements. But I'm unable to get the values for data[0] and data[1] that correspond to the same step. I'm looking for something like eval_tuple(data) which would return ([[2. 2. 2. 2.]] [[2. 2.]]). Note: I'm not fixated on evaluating the data tuple I've created in the code above. The goal is to extract matching feature-label pairs from the dataset object.
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/87738370
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: get both values from a tensorflow dataset
answer count: 0

http://stackoverflow.com/comment/103426184
type: Comment
has text: Those libraries are changing the attribute names like method and all in new versions and no proper instructions about that. You can verify that attribute in the sample code in their document. I've gone through similar issue. Salesforce-bulk library changed thier attribute post_bulk_batch in 1.1.0 to post_batch in 2.1.0 version
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50277238

http://stackoverflow.com/comment/87486898
type: QuestionComment
comment on: http://stackoverflow.com/q/50234165
has text: So what would you do with 20 events, each separated 5 seconds from the previous one?
score: 0
type: Comment

http://stackoverflow.com/q/50273680
has answer: http://stackoverflow.com/a/50275068
answer count: 1
tagged with: twitter
type: Question
has body: Ive got a python script intending to scrape tweets from twitter and append them to a csv file. Im using the tweepy module however it is only returning 1 tweet. Is this a problem with my for loop, or with the call to the twitter API? for status in tweepy.Cursor(twitterapi.search,q="labour party",since="2018-05-01", until="2018-05-10").items(200): if 'RT' not in status.text: with open('C:/Users/User/Desktop/twittersentiment.csv', 'wb') as f: w = csv.writer(f) favourites = status.user.favourites_count location = status.user.location.encode('utf8') tweet_text = ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",status.text.encode('utf8')).split()) date = status.created_at.strftime('%m/%d/%Y') a = [location] b=[favourites] c=[tweet_text] d=[date] zip(a,b,c,d) w.writerow(zip(a,b,c,d))
tagged with: python
tagged with: tweepy
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50275068
has title: Tweepy only returning 1 tweet

http://stackoverflow.com/q/50246699
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50382529
has answer: http://stackoverflow.com/a/50855855
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/69539286
downvote count: 0
tagged with: python
upvote count: 7
has comment: http://stackoverflow.com/comment/88088562
tagged with: pyopenssl
linked to: http://stackoverflow.com/q/5937337
has title: ./python: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory
tagged with: openssl
answer count: 3
linked to: http://stackoverflow.com/q/49320993
has comment: http://stackoverflow.com/comment/88088566
score: 7
has body: I need to try python 3.7 with openssl-1.1.1 in Ubuntu 16.04. Both python and openssl versions are pre-release. Following instructions on how to statistically link openssl to python in a previous post, I downloaded the source for opnssl-1.1.1. Then navigate to the source code for openssl and execute: ./config sudo make sudo make install Then, edit Modules/Setup.dist to uncomment the following lines: SSL=/usr/local/ssl _ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto Then download python 3.7 source code. Then, navigate inside the source code and execute: ./configure make make install After I execute make install I got this error at the end of the terminal output: ./python: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory generate-posix-vars failed Makefile:596: recipe for target 'pybuilddir.txt' failed make: *** [pybuilddir.txt] Error 1 I could not figure out what is the problem and what I need to do.
tagged with: ssl
has comment: http://stackoverflow.com/comment/87517156
has answer: http://stackoverflow.com/a/50528187

http://stackoverflow.com/comment/87812697
type: QuestionComment
has text: @anishtain4, that's the reason why I posted this question. My whole intent for posting this question is to save runtime. I have already mentioned that in question itself.
comment on: http://stackoverflow.com/q/50358598
score: 2
type: Comment

http://stackoverflow.com/comment/87559556
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50265888
has text: BTW, it looks like you're using both Python 2 and Python 3. That can be confusing when you're trying to debug things. I suggest you stick with Python 3, unless you need to use some ancient library that hasn't been ported to Python 3 yet.

http://stackoverflow.com/comment/108441485
has text: Unfortunately it didn't work for me in admin , and in view I had to save both instances, any suggestions please?
type: AnswerComment
comment on: http://stackoverflow.com/a/50468648
score: 0
type: Comment

http://stackoverflow.com/a/53350392
type: Answer
score: 1
upvote count: 3
answers question: http://stackoverflow.com/q/50355598
has body: To get the shape we can try this way: dask_dataframe.describe().compute() "count" column of the index will give the number of rows len(dask_dataframe.columns) this will give the number of columns in the dataframe
downvote count: 2

http://stackoverflow.com/comment/87786304
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50384929
has text: It should have double quotes instead of single quotes I guess!
score: 0

http://stackoverflow.com/comment/87818884
type: Comment
has text: @DavisHerring I am sorry that I didn't state the idea properly. Your comment is not literally wrong. It is right actually, but OP should be using `__init__.py` in their packages, unless he is trying on purpose to achieve what PEP420 allows (from abstract: Namespace packages are a mechanism for splitting a single Python package across multiple directories on disk.) . In the general case you want (regular) packages to be self-contained. `__init__.py` allows for initialization code and for name management (management of the exported names) if you need. But removing `__init__.py` brings ambiguity.
comment on: http://stackoverflow.com/a/50371471
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87498541
type: Comment
comment on: http://stackoverflow.com/a/50240557
type: AnswerComment
has text: hi, I used this line, is it fine ? return render_to_response('app/index.html', context_instance=RequestContext(request))
score: 0

http://stackoverflow.com/a/50307039
answers question: http://stackoverflow.com/q/50306051
downvote count: 0
has body: Yes, the syntax is different for Python2 - regarding the encoding argument. Python2 open description: open(name[, mode[, buffering]]) Python3 open description: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) As you can see, in Python 2.7 open doesn't accept the encoding argument, hence the Type Error. However you can use the built-in io module to open your files. This would allow you to specify the encoding, and also provide compatibility with Python3. For example, import io filepath = r'G:\Kodi EPG\ChannelGuide.xml' with io.open(filepath, "w", encoding = 'UTF-8') as xml_file: xml_file.write(file_blanker) Note that you don't have to explicitly close your files when using the the with statement.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104376836
upvote count: 5
score: 5
accepted answer of: http://stackoverflow.com/q/50306051
type: Answer

http://stackoverflow.com/q/50270182
score: 1
has answer: http://stackoverflow.com/a/50270304
answer count: 1
downvote count: 0
upvote count: 1
has body: I would like to setup an equation using sympy. But the use of exponents seems to be throwing an error: import sympy from sympy import init_printing init_printing(use_unicode=True) E0, V0, B0, dB0, V = sympy.symbols('E0 V0 B0 dB0 V') E0 + 9*V0*B0/16 * ( [(V0/V)^2/3 - 1 ]^3 * dB0 + \ [(V0/V)^2/3 - 1 ]^2 * [6-4*(V0/V)^(2/3)] \ ) Returns the error: TypeError: unsupported operand type(s) for ^: 'Mul' and 'int'
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50270304
has title: Issue using exponents in sympy
has comment: http://stackoverflow.com/comment/87557776
tagged with: python
type: AnsweredQuestion
tagged with: sympy

http://stackoverflow.com/comment/87686493
has text: Thanks for the answer, but I get `TypeError: Required argument 'vars_list' (pos 2) not found` even if the first argument is "'%s,%s,%s,%s'" and the second is a list [1, 1526081542, 1526309772, 1526151777, 1526254283]. Any idea why?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50335056
type: Comment

http://stackoverflow.com/a/73180753
score: 1
upvote count: 1
has body: the true way is using annotate as Andrey said, anyway when using complex properties than can not be calculated in annotate, you can use django-queryable-properties
type: Answer
answers question: http://stackoverflow.com/q/50341867
has comment: http://stackoverflow.com/comment/129353271
downvote count: 0

http://stackoverflow.com/comment/87765474
comment on: http://stackoverflow.com/q/50374409
type: QuestionComment
has text: I will try to save chunks but this is the ground truth data to my deep neural network so I will eventually need to stack all the data together for training (as I have 5 of these lists of 42000 numpy arrays) and I think I will probably run into another MemoryError. Is there a way to keep appending my data to an excel file or something like hdf5?
score: 0
type: Comment

http://stackoverflow.com/a/50289963
has body: use a try / except and break while os.path.isfile(filename): try: # try to do this # &lt;your code&gt; except FileNotFoundError: # if this error occurs break # exit the loop The reason your code doesn't currently work is you're checking the previous file exists in your while loop. Not the next one. Hence you could also do while True: strjpgs = "Extracted Layers: \n \n" filename = "source" + str(n) + ".html" if not os.path.isfile(filename): break # &lt;rest of your code&gt;
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50289925
score: 2
type: Answer

http://stackoverflow.com/a/50895406
downvote count: 0
answers question: http://stackoverflow.com/q/50289628
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50289628
type: Answer
score: 4
upvote count: 4
has body: The good news is that tensorflow sessions are thread-safe: Is it thread-safe when using tf.Session in inference service? To use a keras model in multiple processes, you have to do the following: set up the model call _make_predict_function() set up a session and use it to get the tensorflow graph finalize this graph everytime you predict something, supply this graph as_default_graph() Here is some sample code: # the usual imports import numpy as np import tensorflow as tf from keras.models import * from keras.layers import * # set up the model i = Input(shape=(10,)) b = Dense(1)(i) model = Model(inputs=i, outputs=b) # now to use it in multiprocessing, the following is necessary model._make_predict_function() sess = tf.Session() sess.run(tf.global_variables_initializer()) default_graph = tf.get_default_graph() default_graph.finalize() # now you share the model and graph between processes # in each process you can call this: with default_graph.as_default(): return model.predict(something)
has comment: http://stackoverflow.com/comment/89419659

http://stackoverflow.com/a/50269024
score: 1
downvote count: 1
has body: Declare global efgh and then use it Ex: global efgh efgh = 'test2' def fun_a(abcd): print '%s - %s'%(abcd, efgh) fun_a('test1')
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50268960

http://stackoverflow.com/a/50316847
type: Answer
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50316580
has comment: http://stackoverflow.com/comment/87680614
score: 2
answers question: http://stackoverflow.com/q/50316580
has body: It should work with command_str = "'print(\"test\")'" or equivalently command_str = '\'print("test")\'' Explanation The outermost quotes and the escaping are for the local Python. So in either case, the local Python string will be 'print("test")'. There is no quoting or escaping required for the local shell, as subcommand.run(...) won't invoke it unless shell=True is passed. Thus the single quotes within the python string are for the remote shell (presumably bash or other sh-compatible shell). The argument passed to the remote Python is thus print("test"). (And the double quotes in there are to signify the string literal to print to the remote python.) Can we do without escaping (without \)? As there are three levels involved (local Python, remote shell, remote Python), I don't think so. Can we do with a single type of quotes? Yes, with a bit more escaping. Let's build this from behind (or inside-out). We want to print test This needs to be escaped for the remote Python (to form a string literal instead of an identifier): "test" Call this with the print() function: print("test") Quite familiar so far. Now we want to pass this as an argument to python -c on a sh-like shell. To protect the ( and ) to be interpreted by that, we quote the whole thing. For the already present " not to terminate the quotation, we escape them: "print(\"test\")" You can try this in a terminal: $&gt; echo "print(\"test\")" print("test") Perfect! Now we have to represent the whole thing in (the local) Python. We wrap another layer of quotes around it, have to escape the four(!) existing quotation marks as well as the two backslashes: "\"print(\\\"test\\\")\"" (Done. This can also be used as command_str.) Can we do with only single quotes (') and escaping? I don't know, but at least not as easily. Why? Because, other than to Python, double and single quotes aren't interchangeable to sh and bash: Within single quotes, these shells assume a raw string without escaping until the closing ' occurs.…

http://stackoverflow.com/q/50356360
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/50356433
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61069669
has title: Selenium - use session from current Chrome instance
tagged with: python
has comment: http://stackoverflow.com/comment/87731753
score: 0
answer count: 2
has body: I'm trying to automate some form filling for a web app. Users have to login to the application and then start filling up pages of forms. I have the following Python script using Selenium that can open a window to my application: from selenium import webdriver driver = webdriver.Ie("C:\\Python\\Selenium\\Chrome\\chromedriver.exe") driver.add_cookie() driver.set_page_load_timeout(30) driver.get("myurl/formpages") driver.maximize_window() driver.quit() However, when Selenium starts the Chrome window, the user is not logged in. I want to bypass the need to log in every time. On another Chrome window, I am already logged in as my test user. So whenever I go to the url on my Chrome window, I am already logged in and don't have to log in again. Is there any way to pass this data into my Selenium script so that it uses the session currently on my existing Chrome instance, therefore not having to log in via the script?
has comment: http://stackoverflow.com/comment/87730164

http://stackoverflow.com/a/50423050
accepted answer of: http://stackoverflow.com/q/50368286
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87861057
answers question: http://stackoverflow.com/q/50368286
has comment: http://stackoverflow.com/comment/87872841
type: Answer
has body: If I understand the first part of your question, you want to know how to pass more than one thing in the context part of your return render(request, "carts/home.html",{"cart":cart_obj}). One way to do this is to store all the template variables you want in a dict and then pass the dict as the context, like so: template_vars = { 'cart': cart_obj, 'entry': entry_obj, 'some_var': some_value, } return render(request, "carts/home.html", template_vars) Or you could do it the way you've got it right now, just adding stuff in: return render(request, "carts/home.html", { 'cart': cart_obj, 'entry': entry_obj, 'some_var': some_value, }) Let me know if that helps at all.
score: 2

http://stackoverflow.com/q/50238979
type: UnansweredQuestion
answer count: 1
tagged with: neural-network
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50241487
has comment: http://stackoverflow.com/comment/87510016
has body: I have a large dataset with first and last names as well as an identifier string that I do not want to include in the actual training of a classifier. I do however want to associate these names with their respective data entries. Each row is defined in a csv file as follows: firstname(string),lastname(string),identifier(string),(int),(int),(int),...(int) I have the dataInput with multiple rows of the data above, and a targetList with 1's and 0's pertaining to my result. data = genfromtxt(dataInput, delimiter=',') answers = genfromtxt(targetList, delimiter = ',') from sklearn.neural_network import MLPClassifier clf = MLPClassifier(solver='lbfgs', alpha=1e-5) # generate random indices to test test_idx = random.sample(range(1,8000), 100) train_target = np.delete(answers, test_idx) train_data = np.delete(data, test_idx) test_target = answers[test_idx] test_data = data[test_idx] #Code errors out here clf.fit(train_data, train_target) clf.predict(test_data) The result is that the dataset becomes a 1D array and does not process the result. Without the strings, this code works. However, I've been requested to include these names and identifiers in my result. How can I format the csv data and tell the classifier to associate the identifying strings and fit the data without fitting the strings?
has title: Scikit-learn including strings in Supervised Learning results
downvote count: 1
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/q/50282280
has answer: http://stackoverflow.com/a/50284954
has body: Once you are satisfied with the results of your classification model what alternative can you recommend to mapping your prediction values back to their text form? Classification model was created using scikit. What I have been doing is just inverting the dictionary and then remapping, see below. d={'Reported Harms':['Fell','Constipation','Surgical Delay'],'Complaint Description':['Patient Fell on face','Could not use bathroom','Medical rep was late']} df=pd.DataFrame(data=d) harms=df["Reported Harms"].unique() harms_dict={value:index for index, value in enumerate(harms)} results=df["Reported Harms"].map(harms_dict) df['prediction']=[0,1,2] inv_map={v:k for k, v in harms_dict.items()} df["prediction"]=df["prediction"].map(inv_map) Thank you As some requested to see the model, import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB import seaborn as sns from sklearn.feature_extraction.text import CountVectorizer vect=CountVectorizer(min_df=1) df=pd.read_excel('Test_data.xlsx',sheet_name='Test') dff=pd.read_excel('Data_input.xlsx',sheet_name='Complaints') corpus=df["Complaint Description"] vectorizer=CountVectorizer(min_df=1) X=vectorizer.fit_transform(corpus).toarray() print(X.shape) harms=df["Reported Harms"].unique() harms_dict={value:index for index, value in enumerate(harms)} results=df["Reported Harms"].map(harms_dict) x_train,x_test,y_train,y_test=train_test_split(X,results,test_size=1,random_state=1,) clf=MultinomialNB() clf.fit(x_train,y_train) clf.score(x_test,y_test) vec_text=vectorizer.transform(dff["Complaint Description"]).toarray() ids=dff["Complaint Description"] dff['prediction']=clf.predict(vec_text) inv_map={v:k for k, v in harms_dict.items()} dff["prediction"]=dff["prediction"].map(inv_map) s=dff['prediction'].value_counts() sns.barplot(x=s.index,y=s.values) writer = pd.ExcelWriter('Legacy_list.xlsx') dff.to_excel(writer, 'Complaints edit',index=False) wri…
has comment: http://stackoverflow.com/comment/87583424
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87583976
has answer: http://stackoverflow.com/a/50282362
tagged with: python
has answer: http://stackoverflow.com/a/50282321
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
score: 1
upvote count: 1
has title: Alternative way to repopulate dataframe with Classification model predictions once you are done testing?
accepted answer: http://stackoverflow.com/a/50282362
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/50282321

http://stackoverflow.com/comment/87744697
comment on: http://stackoverflow.com/a/50336242
type: AnswerComment
has text: You can place the fixture in conftest file or in the test file, it will work either way.
score: 0
type: Comment

http://stackoverflow.com/q/50382471
has answer: http://stackoverflow.com/a/50382516
has body: I am learning python and would like verification on a hunch I have about CL args and Python's clipboard. When passing CL args to a script does that arg automatically get added to the clipboard. The code that makes me ask this question is pasted below: import shelve, pyperclip, sys #mcb.py - saves and loasd pieces of text to the clipboard #usage: py.exe mcb.py save &lt;keyword&gt; - saves clipboard to keyword # py.exe mcb.py list - loads all keywords to clipboard # py.exe mcb.py &lt;keyword&gt; -loads keyword to clipboard mcbShelf = shelve.open('mcb') if len(sys.argv)==3 and sys.argv[1].lower()=='save': mcbShelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 2: if sys.argv[1].lower =='list': pyperclip.copy(str(list(mcbShelf.keys()))) elif sys.argv[1] in mcbShelf: pyperclip.copy(mcbShelf[sys.argv[1]]) mcbShelf.close()
type: UnansweredQuestion
answer count: 1
has title: command line argument to clipboard
type: Question
score: 0
tagged with: python

http://stackoverflow.com/q/50250478
score: 1
has title: Efficient way to scrape images from website in Django/Python
answer count: 1
tagged with: selenium
upvote count: 1
linked to: http://stackoverflow.com/q/18408307
favorite count: 0
type: Question
downvote count: 0
tagged with: django
tagged with: python
has body: First I guess I should say I am still a bit of a Django/Python noob. I am in the midst of a project that allows users to enter a URL, the site scrapes the content from that page and returns images over a certain size and the page title tag so the user can then pick which image they want to use on their profile. A pretty standard scenario I assume. I have this working by using Selenium (headless Chrome browser) to grab the destination page content, some python to determine the file size and then my Django view spits it all out into a template. I then have it coded in such a way that the image the user selects will be downloaded and stored locally. However I seriously doubt the scalability of this, its currently just running locally and I am very concerned about how this would cope if there were lots of users all running at the same time. I am firing up that headless chrome browser every time a request is made which doesn't sound efficient, I am having to download the image to determine it's size so I can decide whether it's large enough. One example took 12 seconds to get from me submitting the URL to displaying the results to the user, whereas the same destination URL put through www.kit.com (they have very similar web scraping functionality) took 3 seconds. I have not provided any code as the code I have does what it should, I think the approach however is incorrect. To summarise what I want is: To allow a user to enter a URL and for it to return all images (or just the URLs to those images) from that page over a certain size (width/height), and the page title. For this to be the most efficient solution, taking into account it would be run concurrently between many users at once. For it to work in a Django (2.0) / Python (3+) environment. I am not completely against using the API from a 3rd party service if one exists, but it would be my least preferred option. Any help/pointers would be much appreciated.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50250829
accepted answer: http://stackoverflow.com/a/50250829

http://stackoverflow.com/comment/87597088
score: 0
has text: Try and step back for a bit. Do something else entirely. Then retry, but with the most simple example you can think of first, and proceed from there. The linked posts should provide you with all you need, but perhaps you've just been at it for so long now that everything just seems like a mess. Btw I forgot that MySQL does not use `||` for string concatenation, but `CONCAT()`, so it's `CONCAT(%(Location1)s, '%%')` instead.
comment on: http://stackoverflow.com/q/50289226
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87736054
has text: So I took at the code of the html file and it's really weirdly spaced with spaces between each character, but when the file is launched, the webpage looks totally normal. Not sure why the weird spacing is happening in html file when opened up in an editor.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50359367

php
tags question: http://stackoverflow.com/q/50358412
tags question: http://stackoverflow.com/q/50302391
tags question: http://stackoverflow.com/q/50265145
tags question: http://stackoverflow.com/q/50271956
tags question: http://stackoverflow.com/q/50295136
tags question: http://stackoverflow.com/q/50316993
tags question: http://stackoverflow.com/q/50358321
tags question: http://stackoverflow.com/q/50366257
tags question: http://stackoverflow.com/q/50289882
tags question: http://stackoverflow.com/q/50296733
tags question: http://stackoverflow.com/q/50262095
tags question: http://stackoverflow.com/q/50316345
tags question: http://stackoverflow.com/q/50264265
tags question: http://stackoverflow.com/q/50342869
tag name: php
tags question: http://stackoverflow.com/q/50309729
tags question: http://stackoverflow.com/q/50236505
tags question: http://stackoverflow.com/q/50234444
tags question: http://stackoverflow.com/q/50283520
tags question: http://stackoverflow.com/q/50260825
tags question: http://stackoverflow.com/q/50306948
type: Tag

http://stackoverflow.com/comment/87774767
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50378970
has text: Also see https://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-both-file-and-console-with-scripting
type: Comment

http://stackoverflow.com/q/50310687
tagged with: pycurl
favorite count: 0
type: Question
has title: Unparsable argument: 5PL getting this error while trying to post the file through pycurl in python
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/50310733
tagged with: post
has answer: http://stackoverflow.com/a/50310733
tagged with: opencpu
type: AnsweredQuestion
downvote count: 0
upvote count: 1
has body: I am trying to post a file and a couple of arguments to a function at the given URL. But I am getting an error (Unparsable argument: 5PL). Can anyone help to fix this error? import pycurl c = pycurl.Curl() values = [ ("infile", (pycurl.FORM_FILE, "5pl.csv")), ("model","5PL"), ("log", "F") ] c.setopt(c.URL, "http://granitepoint.ocpu.io/dose-response-R/R/readData") c.setopt(c.HTTPPOST, values) c.perform() c.close()
answer count: 1

http://stackoverflow.com/comment/87671102
has text: Could you share a [MCVE](https://stackoverflow.com/help/mcve) so we can see what's going on? What does `df.dtypes` show for 'movieId'?
type: QuestionComment
comment on: http://stackoverflow.com/q/50327507
type: Comment
score: 0

http://stackoverflow.com/a/50377231
has body: import csv list_noun = ['tomorrow', 'space', 'Film'] with open('noun.csv', 'w') as f: [csv.writer(f).writerow([word]) for word in list_noun]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50377044

http://stackoverflow.com/q/50346326
has title: ProgrammingError: relation "django_session" does not exist
has answer: http://stackoverflow.com/a/50346820
has answer: http://stackoverflow.com/a/75620290
has comment: http://stackoverflow.com/comment/87709247
score: 24
has comment: http://stackoverflow.com/comment/129597290
possible better answer: http://stackoverflow.com/a/61223672
has comment: http://stackoverflow.com/comment/87709073
has comment: http://stackoverflow.com/comment/87708983
has comment: http://stackoverflow.com/comment/87708881
answer count: 4
has answer: http://stackoverflow.com/a/61223672
accepted answer: http://stackoverflow.com/a/50346820
type: Question
has comment: http://stackoverflow.com/comment/87708570
has comment: http://stackoverflow.com/comment/87708600
has comment: http://stackoverflow.com/comment/87708915
has body: Got this error after changing my database from sqlite to postgresql. I've made all my settings changes: Here's my settings: DATABASES = { 'default': { 'ENGINE': "django.db.backends.postgresql_psycopg2", 'NAME': "postr1", 'USER': "zorgan", 'PASSWORD': config('DB_PASSWORD'), 'HOST': "localhost", 'PORT': '', } } as well as performing makemigrations and migrations which were all successful. So I'm able to succesfully start my local server: System check identified no issues (0 silenced). May 15, 2018 - 08:59:39 Django version 1.11.8, using settings 'draft1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. however when I go to the site it returns this error: ProgrammingError at /news/ relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... Any idea what the problem is?
downvote count: 0
tagged with: python
upvote count: 24
favorite count: 0
has comment: http://stackoverflow.com/comment/87709099
has answer: http://stackoverflow.com/a/77767627
has comment: http://stackoverflow.com/comment/87708721
tagged with: django
tagged with: postgresql
type: AnsweredQuestion

http://stackoverflow.com/comment/87670136
has text: You need to install the chromedriver which is detailed in the source link above that I sent you. There is even a link to the instructions for solving this inside the error message.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50315971

boost
tags question: http://stackoverflow.com/q/50384689
tag name: boost
tags question: http://stackoverflow.com/q/50281820
type: Tag
tags question: http://stackoverflow.com/q/50334718
tags question: http://stackoverflow.com/q/50372568

http://stackoverflow.com/comment/87711097
type: Comment
has text: Check my edit, is that what you are looking for? Ask questions if you do not understand my code. @FlyingThunder
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50346682

http://stackoverflow.com/comment/87749875
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50366700
has text: This works fine, I actually tried on list_B that's why it didn't work... sorry about that
score: 0

http://stackoverflow.com/comment/87588054
comment on: http://stackoverflow.com/a/50285324
has text: Sorry, give me a sec.
score: 0
type: Comment
type: AnswerComment

color-detection
tags question: http://stackoverflow.com/q/50362934
type: Tag
tag name: color-detection

http://stackoverflow.com/comment/87690329
comment on: http://stackoverflow.com/q/50336996
has text: Then please give us the full error message.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50249156
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50249654
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50249654
score: 1
has title: tensorflow sess does not close automatically
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 1
has body: I have a code as follows: import tensorflow as tf a = tf.constant([1,2,3]) with tf.Session() as sess: print('12') print(sess.run(a)) However, I get results 12 [1 2 3] when I run the code. It seems the sess does not close automatically. Can someone explain how it happens? Thanks.

http://stackoverflow.com/comment/87620074
comment on: http://stackoverflow.com/a/50301616
has text: As-is, this will just set `some_module.DO_IMPORT` to True forever, but you could set it back after the tests are done (probably in a tearDown method or something, I haven't used unittest for a while).
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50298317
has body: Use below code import os root_src = 'D:\Downloads' files = os.listdir(root_src) file = random.choice(files) new_root = os.path.join(root_src, 'new') copyfile(os.path.join(root_src, file), new_path)
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50298255
downvote count: 1
answers question: http://stackoverflow.com/q/50298255
type: Answer
upvote count: 2

http://stackoverflow.com/a/50244911
answers question: http://stackoverflow.com/q/50243645
has comment: http://stackoverflow.com/comment/87527763
type: Answer
has comment: http://stackoverflow.com/comment/87507761
has comment: http://stackoverflow.com/comment/87508229
score: 0
has comment: http://stackoverflow.com/comment/87507421
has body: Follow Step 3 in the link (pyaudio could not import _portaudio): Open Terminal in the directory. Run the following command line one by one. ./configure make make install # you may need to be root link Then, portaudio will be installed. After this, please follow next steps in the link: Get the dependencies for pyaudio. Uninstall pyaudio and reinstall pyaudio.
has comment: http://stackoverflow.com/comment/87507357
has comment: http://stackoverflow.com/comment/87507543

http://stackoverflow.com/comment/87655123
comment on: http://stackoverflow.com/q/50319628
score: 0
type: Comment
type: QuestionComment
has text: That did the trick. Add as answer

http://stackoverflow.com/comment/87762604
comment on: http://stackoverflow.com/a/50373107
score: 0
type: Comment
type: AnswerComment
has text: The problem is that the shapefile is not a polygon (I think). When using `PLT.intersection(poly)`, it yields the following error: `AttributeError: 'GeoAxesSubplot' object has no attribute 'intersection'`

http://stackoverflow.com/comment/87852490
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50368728
has text: redis-cli -a arista --latency -h host -p port min: 0, max: 1, avg: 0.02 (3601 samples) # redis-cli --intrinsic-latency 100 Max latency so far: 1 microseconds. Max latency so far: 6 microseconds. Max latency so far: 7 microseconds. Max latency so far: 73 microseconds. Max latency so far: 109 microseconds. Max latency so far: 274 microseconds. Max latency so far: 480 microseconds. Max latency so far: 1280 microseconds. Max latency so far: 2715 microseconds. ^C 489827298 total runs (avg latency: 0.2042 microseconds / 204.15 nanoseconds per run). This is running on a VM

http://stackoverflow.com/comment/87662486
comment on: http://stackoverflow.com/q/50323333
type: Comment
score: 1
has text: What does `repr(sum)` show for each session?
type: QuestionComment

http://stackoverflow.com/comment/87721429
has text: google mask r-cnn satellite. there is a paper about house segmentation training but probably works for farm crop segmentation too
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50351457

http://stackoverflow.com/comment/87913366
type: Comment
type: AnswerComment
has text: thats because you are appending to list_3 which is a dict, you want to append to list_3['f']...
comment on: http://stackoverflow.com/a/50306595
score: 0

http://stackoverflow.com/q/50273979
type: Question
tagged with: permission-denied
answer count: 0
tagged with: django
tagged with: python
type: UnansweredQuestion
has body: Error: I tried to put my oTree experiment game in the devserver and this error occours. I do not now, what it means, as it has nothing to do with my code I guess? Request Method: GET Request URL: http://localhost:8000/p/wypb8dnj/Intro/Understanding1/3/ Django Version: 1.11.2 Python Version: 3.6.3 Installed Applications: ['otree', 'django.contrib.auth', 'django.forms', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'huey.contrib.djhuey', 'idmap', 'raven.contrib.django.raven_compat', 'radiogrid', 'Intro'] Installed Middleware: ['otree.middleware.CheckDBMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Template error: In template c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\otree\templates\otree\Base.html, error at line 0 13 1 : {% load staticfiles %} 2 : {% load i18n %} 3 : {% load otree %} 4 : 5 : 6 : 7 : 8 : {% block head_title %}{% block title %} 9 : {% endblock %}{% endblock %} 10 : Traceback: File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\otree\views\abstract.py" in dispatch 236. response.render() File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "c:\users\welschre\appdata\local\programs\python\python36\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "c:\users\welschre\appdata\local\programs\python\py…
has comment: http://stackoverflow.com/comment/87592706
has comment: http://stackoverflow.com/comment/87564716
has comment: http://stackoverflow.com/comment/87592716
score: 0
tagged with: otree
has comment: http://stackoverflow.com/comment/87666874
has title: What does this permission-denied error mean?
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87565339
has comment: http://stackoverflow.com/comment/87575778

http://stackoverflow.com/a/50263766
accepted answer of: http://stackoverflow.com/q/50263686
has body: The issue here is that the i in the done() function refers to a variable i that is being declared locally in the function by deafult, not the global variable i declared at the beginning of your program. To fix this issue, add global i in your done() function prior to i being referenced there: def done(): global i quitvalue=str(input("Play Again?(y/n):")) if quitvalue=='n' and i==0: SystemExit elif quitvalue=="y": i=1
answers question: http://stackoverflow.com/q/50263686
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87738905
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171120/discussion-between-ajax1234-and-cs).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50360670
type: AnswerComment

http://stackoverflow.com/comment/87748255
has text: What is wrong with `<` and `>` ?
score: 10
type: QuestionComment
comment on: http://stackoverflow.com/q/50366029
type: Comment

http://stackoverflow.com/comment/87776269
type: AnswerComment
comment on: http://stackoverflow.com/a/50379990
score: 0
has text: Amazing. +1. Is it possible without using chain?
type: Comment

http://stackoverflow.com/comment/87780119
comment on: http://stackoverflow.com/q/50382020
type: Comment
score: 0
type: QuestionComment
has text: @Austin I get the exact same error

http://stackoverflow.com/q/50241418
type: Question
score: 0
type: UnansweredQuestion
has title: Compare a list and a file for match in python
has body: I want to loop over each element in a List and check if that element matches any of the products in the text file. I have done this: print("Opening a file") pro_file = open("inventory.txt", "r") #open text file for reading #print(pro_file.read()) #read text file line by line productList = ['chips', 'biscuits', 'pasta', 'cheese', 'bread', 'rice', 'honey', 'butter', 'cake', 'salt']; for key in productList: for line in pro_file.readlines(): if key in line: print("found" + key) The nested for loops are only giving the match of first item in the productList. I have stated learning python few days back, so any help would be appreciated.
has comment: http://stackoverflow.com/comment/87500494
has answer: http://stackoverflow.com/a/50241705
tagged with: python
has answer: http://stackoverflow.com/a/50241473
answer count: 2

postgresql
tags question: http://stackoverflow.com/q/50255222
tags question: http://stackoverflow.com/q/50258986
tags question: http://stackoverflow.com/q/50293947
tags question: http://stackoverflow.com/q/50262542
tags question: http://stackoverflow.com/q/50384184
type: Tag
tags question: http://stackoverflow.com/q/50322966
tags question: http://stackoverflow.com/q/50325649
tags question: http://stackoverflow.com/q/50296981
tags question: http://stackoverflow.com/q/50382554
tags question: http://stackoverflow.com/q/50272309
tags question: http://stackoverflow.com/q/50377100
tags question: http://stackoverflow.com/q/50316869
tags question: http://stackoverflow.com/q/50274199
tags question: http://stackoverflow.com/q/50343523
tags question: http://stackoverflow.com/q/50315481
tags question: http://stackoverflow.com/q/50280620
tags question: http://stackoverflow.com/q/50276248
tags question: http://stackoverflow.com/q/50379274
tags question: http://stackoverflow.com/q/50240289
tags question: http://stackoverflow.com/q/50338615
tags question: http://stackoverflow.com/q/50253723
tags question: http://stackoverflow.com/q/50279896
tags question: http://stackoverflow.com/q/50258168
tag name: postgresql
tags question: http://stackoverflow.com/q/50330935
tags question: http://stackoverflow.com/q/50334946
tags question: http://stackoverflow.com/q/50327518
tags question: http://stackoverflow.com/q/50346326

http://stackoverflow.com/a/50237678
answers question: http://stackoverflow.com/q/50237335
has comment: http://stackoverflow.com/comment/87493107
type: Answer
has body: i've tried what Alex suggested... so I changed part of the code: vpool = concurrent.futures.ThreadPoolExecutor(max_workers=8) print(vpool.map(fdownload, vfilelist0)) vpool.shutdown() ...but got the following results: 2018-05-08 12:44:25.115066 Loading variables... 2018-05-08 12:44:25.115066 Starting to process 10.11.12.13... 2018-05-08 12:44:25.115066 Disabling known hosts... 2018-05-08 12:44:25.115066 Opening FTP connection... 2018-05-08 12:44:26.567149 Reading objects list... 2018-05-08 12:45:30.580015 Separating files from folders... 2018-05-08 12:45:30.584015 Closing FTP connection... 2018-05-08 12:45:30.585015 Vectorizing download file list... 2018-05-08 12:45:30.596016 Filtering latest file for each object... 2018-05-08 12:45:30.648019 Vectorizing only latest files... 2018-05-08 12:45:30.652019 Starting simultaneous downloads... &lt;generator object Executor.map.&lt;locals&gt;.result_iterator at 0x04332D20&gt;
score: 0

http://stackoverflow.com/a/51567255
has body: You can use keras.layers.GlobalAveragePooling1D in order to average the time series. If the input shape is (batch_size, steps, features), the output shape is (batch_size, features). Weather or not you are using a Sequential model doesn't matter in this case. This layer works juts like any other layer in Keras. More information here: https://keras.io/layers/pooling/#globalaveragepooling1d
type: Answer
answers question: http://stackoverflow.com/q/50309488
score: 0

http://stackoverflow.com/q/50335402
accepted answer: http://stackoverflow.com/a/50335430
has answer: http://stackoverflow.com/a/50335435
has comment: http://stackoverflow.com/comment/87687458
score: -2
has comment: http://stackoverflow.com/comment/87687613
tagged with: python
has answer: http://stackoverflow.com/a/50335458
has comment: http://stackoverflow.com/comment/87687015
answer count: 4
has comment: http://stackoverflow.com/comment/87687506
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50335430
upvote count: 0
has title: Column name in pandas dataframe resulting from groupby
downvote count: 2
possible better answer: http://stackoverflow.com/a/50335435
has answer: http://stackoverflow.com/a/50335476
favorite count: 0
type: Question
has body: I have the following code: import pandas as pd import numpy as np df = pd.DataFrame({'clif_cod' : [1,2,3,3,4,4,4], 'peds_val_fat' : [10.2, 15.2, 30.9, 14.8, 10.99, 39.9, 54.9], 'mes' : [1,2,4,5,5,6,12], 'ano' : [2016, 2016, 2016, 2016, 2016, 2016, 2016]}) vetor_valores = df.groupby(['mes','clif_cod']).sum() which yields me this output: ano peds_val_fat mes clif_cod 1 1 2016 10.20 2 2 2016 15.20 4 3 2016 30.90 5 3 2016 14.80 4 2016 10.99 6 4 2016 39.90 12 4 2016 54.90 How do I select rows based on mes and clif_cod? When I do list(df) I only get ano and peds_val_fat.

http://stackoverflow.com/comment/87645748
has text: Unfortunately never working with multiprocessing, so no suggestion, sorry :(
type: QuestionComment
comment on: http://stackoverflow.com/q/50308352
type: Comment
score: 0

http://stackoverflow.com/comment/87485892
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50231064
has text: I have a huge csv file, I'd like to avoid doing per-newline split. Regex solution is also much shorter :)

http://stackoverflow.com/q/50359442
tagged with: series
accepted answer: http://stackoverflow.com/a/50360118
score: 4
type: AnsweredQuestion
answer count: 2
tagged with: functional-programming
tagged with: pandas
has body: this is my first question here so please be patient with me. My problem is as follows: Assume we have a pandas Dataframe and we want to apply dynamically some pd.Series methods to a set of columns of this Dataframe. Why the following example doesn't work? testframe=pd.DataFrame.from_dict({'col1': [1,2] ,'col2': [3,4] }) funcdict={'col1':[pd.Series.astype,str.replace],'col2':[pd.Series.astype,str.replace]} argdict= {'col1':[['str'],['1','A']],'col2':[['str'],['3','B']]} for col in testframe.columns: for func in funcdict[col]: idx=funcdict[col].index(func) testframe[col]=testframe[col].func(*argdict[col][idx]) Expected outcome would be col1 col2 0 'A' 'B' 1 '1' '4' But instead i get AttributeError: 'Series' object has no attribute 'func' Remarkably testframe['col1']=testframe['col1'].astype(*argdict['col1'][0]) works as expected, so somehow python seems to have a problem with the '.func' syntax despite the fact that print(func) yields the desired output: 'function NDFrame.astype at 0x00000186954EB840' etc.
downvote count: 0
linked to: http://stackoverflow.com/q/31174295
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50360118
possible better answer: http://stackoverflow.com/a/50360280
tagged with: python
has answer: http://stackoverflow.com/a/50360280
has title: Apply a method from a list of methods to pandas dataframe

http://stackoverflow.com/q/50380203
has title: How to convert date columns from object type to date type in Python
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50380333
accepted answer: http://stackoverflow.com/a/50380333
linked to: http://stackoverflow.com/q/311627
favorite count: 0
type: Question
has body: I have this data frame where the date columns are 'datetime' type datetime64[ns] 2014-04-30T00:00:00 000000000 Now I want the date in this format - 2014-04-30 . So I used below code df['StartingDate2'] = XY['StartingDate'].dt.strftime('%m/%d/%Y') Now, this works accurately, but converts my date to object type. I read here that In Python, dates are objects. But I want to write my final data frame as a table in redshift and so I need my date columns defined as date for my python data frame. Any suggestion about how to do that , will be greatly appreciated. Update: sample dataframe p1 = {'name': ['johnny', 'tommy', 'bobby', 'rocky', 'jimmy'], 'StartingDate': ['2015-07-14T00:00:00.000000000', '2013-10-30T00:00:00.000000000', '2014-04-30T00:00:00.000000000', '2014-01-27T00:00:00.000000000', '2016-01-15T00:00:00.000000000'], 'Address': ['NY', 'NJ', 'PA', 'NY', 'CA'], 'comment1': ['Very good performance', 'N/A', 'Need to work hard', 'No Comment', 'Not satisfactory'], 'comment2': ['good', 'Meets Expectation', 'N', 'N/A', 'Incompetence']} XY = pd.DataFrame(data = p1) XY['today'] = datetime.datetime.now() When I am using to_datetime() solution - it doesn't work XY['today2'] = pd.to_datetime(XY['today'], format = '%m/%d/%Y') XY['StartingDate2'] = pd.to_datetime(XY['today'], format = '%m/%d/%Y') Alternatively - this works, when strftime() and to_datetime() are used in combination. XY['StartingDate2'] = XY['StartingDate2'].dt.strftime('%m/%d/%Y') XY['StartingDate2'] = pd.to_datetime(XY['StartingDate2']) But although this solution works for the sample data, is not working for me. The data I have looks like this - array(['2015-09-29T14:34:39.000000000', '2015-10-07T14:13:03.000000000', '2015-10-07T19:17:50.000000000', ..., '2017-12-05T14:06:42.000000000', '2017-12-06T16:36:44.000000000', '2017-12-06T18:26:49.000000000'], dtype='datetime64[ns]'
has answer: http://stackoverflow.com/a/50380354
possible better answer: http://stackoverflow.com/a/50380354
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/87807778

http://stackoverflow.com/comment/87746744
comment on: http://stackoverflow.com/a/50364252
type: Comment
score: 0
type: AnswerComment
has text: i will edit my question and add the updated function

http://stackoverflow.com/a/50294642
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50294023
has body: A possible approach is to use advanced numpy indexing which is maybe faster (values must be ordered so wont work on python 3.0 - 3.5) indices = np.fromiter(values.values(), dtype=int, count=len(values)) keys = np.array([get_vector(v) for v in values.keys()]) matr[indices] = keys

http://stackoverflow.com/comment/87587590
has text: I mean what happen `from channels.generic.websocket import AsyncWebsocketConsumer` in shell? You can call `AsyncWebsocketConsume` in shell but can't only in consumers.py?
type: QuestionComment
comment on: http://stackoverflow.com/q/50285479
score: 0
type: Comment

http://stackoverflow.com/q/50335857
tagged with: pandas
upvote count: 2
score: 0
has answer: http://stackoverflow.com/a/50335919
downvote count: 2
has body: After using my script my algorithms return the exptected outcome in a list of lists like this: pred=[[b,c,d],[b,a,u],...[b,i,o]] I already have a dataframe that needs those values added in a new matching column. The list is exactly x long like the other columns in the frame and I just need to create a new column with all the values of the lists. However when I try to put the list into the column I get the error: ValueError: Length of values does not match length of index Looking at the data, it puts the entire list into one row instead of each entry in a new row. EDIT: All values in the list should be put in the column namend pred sent token pred 0 a b 0 b c 0 b d 1 a b 1 b a 1 c u Solution: x = [] for _ in pred: if _ is not None: x += _ df_new = pd.DataFrame(df) df_new["pred"] = list(itertools.chain.from_iterable(x))
favorite count: 0
has title: List of lists to rows in a pandas dataframe
type: Question
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50336865
has answer: http://stackoverflow.com/a/50336865
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/50335919
answer count: 2
has comment: http://stackoverflow.com/comment/87687871

http://stackoverflow.com/comment/87501362
has text: I updated the question, to show the error i'm getting, and also the line that contains the error
comment on: http://stackoverflow.com/q/50241441
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50371972
has body: I'm having trouble publishing messages using kombu 4.1. My use case is that I have a server that collects messages from a rabbitmq queue (queue 1), performs some processing task and then republishes them to a different queue, (queue 2). I have no problem consuming from queue 1 but when I try to publish to queue 2 there is an intermittent fault that causes me to disconnect from rabbitmq. I've activated both retries and the combined ConsumerProducerMixin but the problem remains. I have also published this issue on the kombu github page to no avail:- https://github.com/celery/kombu/issues/857 Does anyone have any insight into this issue, will it be fixed in kombu 4.2, is there any work around that doesn't involve switching to another library? Thank You
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: kombu
favorite count: 0
type: Question
has title: Kombu disconnects on publish
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87948725
tagged with: rabbitmq
has answer: http://stackoverflow.com/a/51263347

http://stackoverflow.com/q/50270511
has title: Fastening the data extraction
has comment: http://stackoverflow.com/comment/87558441
type: Question
accepted answer: http://stackoverflow.com/a/50270952
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87558440
has answer: http://stackoverflow.com/a/50270952
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/87558922
favorite count: 0
has comment: http://stackoverflow.com/comment/87558983
tagged with: sql
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87558653
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87559104
has comment: http://stackoverflow.com/comment/87558540
has comment: http://stackoverflow.com/comment/87558741
has body: I am having more than 1 million rows of data in SQL database. I want to write that whole data to TSV file. I am using the below code to fetch top 100000 rows. It takes nearly 20 minutes to fetch and write it to TSV file. Any other method to fasten this process? cursor.execute("select top(100000) from dbo.StoreLocations_Repo_V10") store_details = cursor.fetchall() store_details_list = [list(elem) for elem in store_details] df = pd.DataFrame(store_details_list) with open('result.tsv', 'w', encoding='UTF-8') as f: df.to_csv(f, header=False, sep='\t')

http://stackoverflow.com/q/50336458
has answer: http://stackoverflow.com/a/66921126
has comment: http://stackoverflow.com/comment/87692827
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/87706483
has comment: http://stackoverflow.com/comment/87693082
accepted answer: http://stackoverflow.com/a/50351832
has comment: http://stackoverflow.com/comment/87711587
downvote count: 0
tagged with: mysql
has answer: http://stackoverflow.com/a/50351832
has answer: http://stackoverflow.com/a/50338505
favorite count: 0
has body: Headscratcher here for me. I am attempting to connect to a database on my local MySQL 8.0.11.0 install from Python. Here's the code I'm using : conn = pymysql.connect(host='localhost', port=3306, user='root', password='placeholder', db='CustomerInfo') Python is returning the following : Traceback (most recent call last): File "D:\Python\FileCheck.py", line 38, in &lt;module&gt; conn = pymysql.connect(host='localhost', port=3306, user='root', password='placeholder', db='CustomerInfo') File "C:\Program Files\Python36\lib\site-packages\pymysql\__init__.py", line 90, in Connect return Connection(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\pymysql\connections.py", line 704, in __init__ self.connect() File "C:\Program Files\Python36\lib\site-packages\pymysql\connections.py", line 974, in connect self._request_authentication() File "C:\Program Files\Python36\lib\site-packages\pymysql\connections.py", line 1203, in _request_authentication auth_packet = self._read_packet() File "C:\Program Files\Python36\lib\site-packages\pymysql\connections.py", line 1059, in _read_packet packet.check_error() File "C:\Program Files\Python36\lib\site-packages\pymysql\connections.py", line 384, in check_error err.raise_mysql_exception(self._data) File "C:\Program Files\Python36\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)") I have confirmed that I have access to the database when logging in through MySQL Workbench. The weird thing is that Python is telling me "using password: NO" even though I'm sending a password. I've tried changing passwd to "password" in the script and creating a new user with the appropriate privileges. Neither has worked. Not sure what to check next. EDIT: Here are grants for root: GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, S…
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87692619
has title: PyMySQL Access Denied "using password (no") but using password
score: 6
tagged with: pymysql
tagged with: python
possible better answer: http://stackoverflow.com/a/66921126
upvote count: 6
has comment: http://stackoverflow.com/comment/87689111
tagged with: mysql-8.0

http://stackoverflow.com/a/50337657
has body: You may use a negative lookahead to make sure those substrings do not occur right after [[: (\[\[)(?!Special:MyLanguage/|File:|Image:|Category:)(.*?]]) and replace with \1Special:MyLanguage/\2. See the regex demo. Details (\[\[) - Group 1: File:|Image:|Category:) - the can't be followed with any of the substrings listed in the alternation group (.*?) - Group 2: any 0+ chars other than line break chars, as few as possible, followed with . Python demo: import re rx = r"(\[\[)(?!Special:MyLanguage/|File:|Image:|Category:)(.*?]])" s = "Special:MyLanguage/text\n\n\n\nText and " res = re.sub(rx, r"\1Special:MyLanguage/\2", s) print(res) Output: Special:MyLanguage/text Special:MyLanguage/Text and
has comment: http://stackoverflow.com/comment/87691984
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50337594
has comment: http://stackoverflow.com/comment/87691921
answers question: http://stackoverflow.com/q/50337594
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/87600696
type: AnswerComment
has text: Have you tried passing pd.concat([AllFields, reading_book1], axis=1), so that you merge two dafarames instead of a list ?
score: 0
comment on: http://stackoverflow.com/a/50258085
type: Comment

http://stackoverflow.com/comment/87555715
has text: I wish to include it, because in my in question it doesn't appear, it ends as it reaches the `strong`.
type: AnswerComment
comment on: http://stackoverflow.com/a/50268923
type: Comment
score: 0

http://stackoverflow.com/comment/87663124
comment on: http://stackoverflow.com/a/50319770
type: Comment
has text: still I am getting no module named pandas. It should not occur now. Cannot understand.
score: 0
type: AnswerComment

http://stackoverflow.com/q/50289998
has answer: http://stackoverflow.com/a/50290257
possible better answer: http://stackoverflow.com/a/50290257
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50290060
has answer: http://stackoverflow.com/a/50290314
has body: I have data in the below format : pastLocation | currentLocation delhi | bangalore delhi | london,pune,delhi mumbai | mumbai pune | pune, noida I have to create a new column named as changeInLocation where if pastLocation is present in currentLocation then value of new column would be 0 else 1. For example, in second row, pastLocation i.e. Delhi is present in corresponding currentLocation so value of changeInLocation should be 0 Output should be in following format: pastLocation | currentLocation | changeInLocation delhi | bangalore | 1 delhi | london,pune,delhi | 0 mumbai | mumbai | 0 pune | pune, noida | 0
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/50290060
tagged with: pandas
has title: Create a new column based on condition applied from two other string columns in python
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/87491151
has text: Sure I'll post the output.....I'm not sure how to phrase the recursive function..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50236792

http://stackoverflow.com/comment/87607597
type: QuestionComment
has text: In *nmap* output: "*5060/ __udp__ open*". You might want to use `socket.SOCK_DGRAM`.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50294596

http://stackoverflow.com/q/50329789
has body: I am rather new to Python and I think I'm trying to attempt something quite complicated? I have repeatedly tried to search for this and think I'm missing some base knowledge as I truly don't understand what I've read. Effectively I have 3 arrays, which contain x points, y points, and z points. They create an approximately hemispherical shape. I have these points from taking a contour of a 2D axisymmetrical semicircular shape, extracting the x points and y points from it into separate arrays, and creating a "z points" array of zeros of the same length as the previous two arrays. From this, I then rotate the y points into the z-domain using angles to create a 3D approximation of the 2D contour. This 3D shape is completely bounded (in that it creates both the bottom and the top), as linked below: 3d Approximation I've butchered the following code from my much longer program, it's the only part that is pertinent to my question however: c, contours, _ = cv2.findContours(WB, mode = cv2.RETR_EXTERNAL, method = cv2.CHAIN_APPROX_NONE) # Find new contours in recently bisected mask contours = sorted (contours, key = cv2.contourArea, reverse = True) # # Sort contours (there is only 2 contours left, plinth/background, and droplet) contour = contours[1] # Second longest contour is the desired contour xpointsList = [xpoints[0][0] for xpoints in contour] # Create new array of all x co-ordinates ypointsList = [ypoints[0][1] for ypoints in contour] # Create new array of all y co-ordinates zpointsList = np.zeros(len(xpointsList)) # # Create an array of 0 values to represent the z domain. True contour sits at 0 on all points in the z-domain angles = np.arange(0,180,5, dtype = int) # # Creating an array of angles between to form a full drop in degrees of 5 i = 0 b = 0 d = 0 qx = np.zeros(len(xpointsList)*len(angles)) # Setting variable to equal the length of x points times the length of iterative angle calculations qy = np.zeros(len(ypointsList)*len(angles)) # Setting variable to equal …
tagged with: arrays
answer count: 1
has answer: http://stackoverflow.com/a/50349872
tagged with: python
score: 0
tagged with: volume
tagged with: convex-hull
has title: Volume of 3-Space Object using 3-Space co-ordinates
type: Question
linked to: http://stackoverflow.com/q/48112329
tagged with: 3d
type: UnansweredQuestion

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/50289370
tag name: kivy-language
tags question: http://stackoverflow.com/q/50269698
tags question: http://stackoverflow.com/q/50317173
tags question: http://stackoverflow.com/q/50314617

http://stackoverflow.com/q/50237918
tagged with: python
has title: truncate all rows from a pandas dataframe
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50237945
has comment: http://stackoverflow.com/comment/87493188
answer count: 3
tagged with: pandas
score: 7
downvote count: 0
upvote count: 7
accepted answer: http://stackoverflow.com/a/50237995
has answer: http://stackoverflow.com/a/50237974
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50237995
has comment: http://stackoverflow.com/comment/87493133
has body: I need to test that some code works if a dataframe has no rows in it. In SQL you can clean all the rows out of a table with the truncate command. I found the Pandas truncate command, but can't get rid of the very last row. I did this: df.truncate(after=0, before=0) ..but it left the 0th row. Any ideas?
possible better answer: http://stackoverflow.com/a/50237974

http://stackoverflow.com/q/50256573
tagged with: python
tagged with: rdd
tagged with: fpgrowth
linked to: http://stackoverflow.com/q/49623801
has comment: http://stackoverflow.com/comment/87580711
score: 0
answer count: 0
tagged with: apache-spark
duplicate of: http://stackoverflow.com/q/49623801
has comment: http://stackoverflow.com/comment/87536381
has comment: http://stackoverflow.com/comment/87536068
has comment: http://stackoverflow.com/comment/87536346
type: Question
has title: FP Growth (Frequent Pattern Mining) Giving Error with Pyspark
has body: I have been trying to use the Frequent Pattern Mining Algorithm as in the example with PySpark. The code used to work. from pyspark.ml.fpm import FPGrowth df = spark.createDataFrame([(0, [1, 2, 5]),(1, [1, 2, 3, 5]),(2, [1, 2])], ["id", "items"]) fpGrowth = FPGrowth(itemsCol="items", minSupport=0.5, minConfidence=0.6) model = fpGrowth.fit(df) model.freqItemsets.show() Source: https://spark.apache.org/docs/2.2.0/ml-frequent-pattern-mining.html I am getting the error with .fit: An error occurred while calling o448.fit.: java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.xbean.asm5.ClassReader.&lt;init&gt;(Unknown Source) at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432) at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40) at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103) at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732) at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432) at org.apache.xbean.asm5.ClassReader.a(Unknown Source) at org.apache.xbean.asm5.ClassReader.b(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.spark.util.ClosureCleaner$$anonf…
type: UnansweredQuestion
tagged with: pyspark

http://stackoverflow.com/a/50381714
accepted answer of: http://stackoverflow.com/q/50381491
answers question: http://stackoverflow.com/q/50381491
type: Answer
has body: Foreign key relations allow multiple instances of this model to be associated with a single instance of the other model, i.e. class Profile(models.Model): ... courses = models.ForeignKey(Course) only allows one Course to be associated with a given Profile (but multiple Profiles can be associated with a single Course). You may think of it like a parent > child relation where Course is a parent and Profiles are children. If you need to associate multiple Courses to be associated with a Profile (and still be able to have multiple Profiles associated with a Course), you should use a ManyToMany relation, such as: class Profile(models.Model): ... courses = models.ManyToMany(Course) This effectively creates a third, hidden table (called a through table) which links both sides: This is an example of how that through table looks like. Note that you don't have to create this manually as normally there is no model (it is implicit) and the database table is automatically generated by Django: class ProfileCourse(models.Model): profile = models.ForeignKey(Profile) course = models.ForeignKey(Profile)
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87498907
type: AnswerComment
has text: this is exactly what i was looking for! simple and works well!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50240291

http://stackoverflow.com/comment/87746633
has text: @BcK that's what I've been trying to do but I can't figure it out which is why I'm asking for help here. I have very limited access to a macbook and so I'm trying to learn all this on a PC, which is why I'm finding these seemingly not-"excusable" tasks difficult.
comment on: http://stackoverflow.com/q/50364847
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87610327
type: Comment
has text: Actually, I should have been more explicit: the `if '_underscript'` block *replaces* the need for your call to `subprocess.call(['script'])`. Are you running `script` twice?
type: AnswerComment
comment on: http://stackoverflow.com/a/50293308
score: 0

http://stackoverflow.com/a/50280158
downvote count: 0
has body: I haven't looked at a bunch to know if the same pattern applies, but if they always follow text that says "TRIAL REGISTRATION NUMBER:" inside html &lt;h4&gt; tags, you could parse the actual html document for &lt;h4&gt; tags containing this term, then take the text from the following paragraph in &lt;p&gt; tags. BeautifulSoup makes this relatively straightforward. But again, you've only shown one example. I don't know if it always follows this pattern or not. From there they appear to be semicolon-delimited, which is simple to split on.
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50279933
score: 2
answers question: http://stackoverflow.com/q/50279933

http://stackoverflow.com/comment/87699134
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50341471
score: 0
has text: Your desired results is not a matrix.

http://stackoverflow.com/q/50283552
has comment: http://stackoverflow.com/comment/87584852
has title: Creating a circle in pygame with points on circumference
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87590322
has comment: http://stackoverflow.com/comment/87617840
has comment: http://stackoverflow.com/comment/87592057
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/87586609
tagged with: collision-detection
accepted answer: http://stackoverflow.com/a/50288011
has comment: http://stackoverflow.com/comment/87585567
has answer: http://stackoverflow.com/a/50288011
type: Question
tagged with: geometry
tagged with: python-2.7
score: 2
upvote count: 2
has body: I'm looking to create a circle in pygame that I can move around a space with "sensors" on the edges. I want there to be a "front", "left" and "right" sensor on the circumference, that I can use to manipulate the circle's movements. Basically, these points are to help detect surrounding obstacles, and allow the circle to be rotated as it moves (to help control movement). In the image below you can see the idea, the circle starts at a location, has the pointers, and moves around the space and avoids the square obstacle, and I'm able to turn it at various angles without losing sense of what the "front" and "back" of it is. I don't care if the dots on the circle's edges to identify the "sensors" are seen or not in the overall graphic, just drew and labelled them to illustrate the idea. Side note: I realize looking at the image that the R and L labels are backwards given the orientation of the circle itself, but still the same idea.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87586836

http://stackoverflow.com/q/50369637
score: 3
tagged with: python-2.7
downvote count: 0
has answer: http://stackoverflow.com/a/50369961
has title: How to base64 encode an image using python
has body: I have a stream of data that comes from a device and I need to convert it into a jpeg and then base64 encode it to transfer it over the network. My Python 2.7 code so far looks like this: from PIL import Image import io image = Image.open(io.BytesIO(self.imagebuffer)) # Image buffer contains the image data from the device. image.save("test.jpg") # Writes the image to the disk in jpeg format image.show() # Opens the image using the OS image view I can see I have the image I want and can save it to the disk in jpeg format. What I don't understand is if I can base64 encode the image from the image object or if I need to write it to the disk first. I would like to avoid writing it if possible. The 2nd question I have is what is PIL doing in this process? Is it taking the data and putting the required special codes into the file to make it a jpeg file? I think the answer tot his is yes as I can change the file extension to .bmp and the correct file is written on the disk. So in summary, is it possible to get a base64 encoded version of my jpeg file from the image object without writing it to disk first?
favorite count: 0
has answer: http://stackoverflow.com/a/50371374
type: Question
has answer: http://stackoverflow.com/a/50371663
has answer: http://stackoverflow.com/a/70017474
tagged with: encoding
tagged with: python-imaging-library
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87758504
tagged with: base64
tagged with: python
has answer: http://stackoverflow.com/a/71038016
has comment: http://stackoverflow.com/comment/87755248
upvote count: 3

opencv
tags question: http://stackoverflow.com/q/50262079
type: Tag
tags question: http://stackoverflow.com/q/50331025
tags question: http://stackoverflow.com/q/50343108
tags question: http://stackoverflow.com/q/50292671
tags question: http://stackoverflow.com/q/50351457
tags question: http://stackoverflow.com/q/50271548
tags question: http://stackoverflow.com/q/50295870
tags question: http://stackoverflow.com/q/50272801
tags question: http://stackoverflow.com/q/50330601
tags question: http://stackoverflow.com/q/50319617
tags question: http://stackoverflow.com/q/50309181
tags question: http://stackoverflow.com/q/50345331
tags question: http://stackoverflow.com/q/50354682
tags question: http://stackoverflow.com/q/50325385
tags question: http://stackoverflow.com/q/50260321
tags question: http://stackoverflow.com/q/50331792
tags question: http://stackoverflow.com/q/50320887
tags question: http://stackoverflow.com/q/50242939
tags question: http://stackoverflow.com/q/50373507
tags question: http://stackoverflow.com/q/50358964
tags question: http://stackoverflow.com/q/50341162
tags question: http://stackoverflow.com/q/50364235
tags question: http://stackoverflow.com/q/50273023
tags question: http://stackoverflow.com/q/50290875
tags question: http://stackoverflow.com/q/50318247
tags question: http://stackoverflow.com/q/50314242
tags question: http://stackoverflow.com/q/50337074
tags question: http://stackoverflow.com/q/50367191
tags question: http://stackoverflow.com/q/50337569
tags question: http://stackoverflow.com/q/50290414
tags question: http://stackoverflow.com/q/50253535
tags question: http://stackoverflow.com/q/50244451
tags question: http://stackoverflow.com/q/50314634
tags question: http://stackoverflow.com/q/50246672
tags question: http://stackoverflow.com/q/50271308
tags question: http://stackoverflow.com/q/50368191
tags question: http://stackoverflow.com/q/50364352
tags question: http://stackoverflow.com/q/50276424
tags question: http://stackoverflow.com/q/50346028
tags question: http://stackoverflow.com/q/50232140
tags question: http://stackoverflow.com/q/50375489
tags question: http://stackoverflow.com/q/50306303
tags question: http://stackoverflow.com/q/50231968
tags question: http://stackoverflow.com/q/50257152
tags question: http://stackoverflow.com/q/50279713
tags question: http://stackoverflow.com/q/50241077
tags question: http://stackoverflow.com/q/50305634
tags question: http://stackoverflow.com/q/50292631
tags question: http://stackoverflow.com/q/50274063
tags question: http://stackoverflow.com/q/50353508
tags question: http://stackoverflow.com/q/50362934
tags question: http://stackoverflow.com/q/50348064
tags question: http://stackoverflow.com/q/50277215
tags question: http://stackoverflow.com/q/50232744
tags question: http://stackoverflow.com/q/50273650
tags question: http://stackoverflow.com/q/50363071
tags question: http://stackoverflow.com/q/50296181
tags question: http://stackoverflow.com/q/50310713
tags question: http://stackoverflow.com/q/50310613
tags question: http://stackoverflow.com/q/50368683
tags question: http://stackoverflow.com/q/50269401
tags question: http://stackoverflow.com/q/50266553
tag name: opencv
tags question: http://stackoverflow.com/q/50284122
tags question: http://stackoverflow.com/q/50238800
tags question: http://stackoverflow.com/q/50247500
tags question: http://stackoverflow.com/q/50252558
tags question: http://stackoverflow.com/q/50348640
tags question: http://stackoverflow.com/q/50338907
tags question: http://stackoverflow.com/q/50252468
tags question: http://stackoverflow.com/q/50375225
tags question: http://stackoverflow.com/q/50243536
tags question: http://stackoverflow.com/q/50317467

http://stackoverflow.com/q/50337112
tagged with: case-statement
has body: I have to test many cases, but this solution is not very elegant: if '22' in name: x = 'this' elif '35' in name: x = 'that' elif '2' in name: # this case should be tested *after* the first one x = 'another' elif '5' in name: x = 'one' # and many other cases Is there a way to do this sequence of cases with a list? L = [['22', 'this'], ['35', 'that'], ['2', 'another'], ['5', 'one']]
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50337149
tagged with: list
score: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/50337130
has title: A simpler list of cases
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50337149
answer count: 2
tagged with: if-statement
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50337130

http://stackoverflow.com/q/50239023
has comment: http://stackoverflow.com/comment/87495402
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87495676
has answer: http://stackoverflow.com/a/50239842
has comment: http://stackoverflow.com/comment/87496669
has comment: http://stackoverflow.com/comment/87496021
has comment: http://stackoverflow.com/comment/87503889
has comment: http://stackoverflow.com/comment/87495744
tagged with: python
linked to: http://stackoverflow.com/q/20638006
accepted answer: http://stackoverflow.com/a/50239842
has comment: http://stackoverflow.com/comment/87496457
has comment: http://stackoverflow.com/comment/87496170
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87495510
has title: I am trying to web scrape a website and when I am trying to turn this into a csv file, data isn't going to the correct column
has body: I am new to web scraping and for practice I am trying to web scrape a website and turn the results into a csv file. When I come to the part to turn the results into a csv file, it doesn't put the address in the address column. I want the data to go into the address column. The code is as follows. from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.allagents.co.uk/find-agent/london/' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') containers = page_soup.findAll('div', {'class':'itemlabel3'}) filename = "webscrape.csv" f = open(filename, "w") headers = "Company Name, Address, Telephone Number\n" f.write(headers) for container in containers: comp_name = container.find('div', {'class':'labelleft2 col-md- 10'}).div.h4.a.text address = container.find('div', {'class':'labelleft2 col-md- 10'}).div.p.text tel = container.find('div', {'class':'labelleft2 col-md- 10'}).div.find('p', {'style':'clear: both; margin-bottom: 15px;'}).strong.text print("Company Name:", comp_name) print("Address:", address) print("Telephone", tel) f.write(comp_name.replace(",", ("|")) + "," + address.replace(",", ("|")) + "," + tel + "\n") f.close() Any help is appreciated. Thanks you in advance.
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/87495780
favorite count: 0

http://stackoverflow.com/q/50384883
upvote count: 11
type: AnsweredQuestion
answer count: 2
has title: Python - How To Convert Pandas Dataframe To JSON Object?
possible better answer: http://stackoverflow.com/a/59951868
downvote count: 0
score: 11
linked to: http://stackoverflow.com/q/50859373
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50384929
has comment: http://stackoverflow.com/comment/87785498
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has body: I'm using df.to_json() to convert dataframe to json. But it gives me a json string and not an object. How can I get JSON object? Also, when I'm appending this data to an array, it adds single quote before and after the json and it ruins the json structure. How can I export to json object and append properly? Code Used: a=[] array.append(df1.to_json(orient='records', lines=True)) array.append(df2.to_json(orient='records', lines=True)) Result: ['{"test:"w","param":1}','{"test:"w2","param":2}]'] Required Result: [{"test":"w","param":1},{"test":"w2","param":2}] Thank you!
tagged with: python
accepted answer: http://stackoverflow.com/a/50384929
has answer: http://stackoverflow.com/a/59951868
has comment: http://stackoverflow.com/comment/87785461

http://stackoverflow.com/q/50304718
has comment: http://stackoverflow.com/comment/87626020
has answer: http://stackoverflow.com/a/50309396
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50305134
answer count: 2
tagged with: turtle-graphics
has answer: http://stackoverflow.com/a/50305134
downvote count: 0
has comment: http://stackoverflow.com/comment/87626198
upvote count: 1
tagged with: python
tagged with: fractals
has body: I have a recursive function drawing a fractal, using the python turtle module: def fract(t, order, size): if order == 0: t.forward(size) else: for angle in (60, -120, 60, 0): fract(t, order - 1, size / 3) t.left(angle) I have another function calling the first function and modifying the last angle, so that the fractals build a circle def circle(t, order, size): for i in range(order): fract(t, 2, size) t.right(360 / order) circle(t, 4, 300) While this works as intended, the real goal is to get the same result in a single recursive function. Obviously this is not a real programming case, but a task from a python beginner's book, which I'm totally stuck with. I suppose the awkward title of the question reflects my lack of understanding the problem.
tagged with: recursion
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87626443
has title: Varying recursive function at given depth
accepted answer: http://stackoverflow.com/a/50309396
score: 1
has comment: http://stackoverflow.com/comment/87626324

http://stackoverflow.com/q/50342113
has comment: http://stackoverflow.com/comment/87700177
tagged with: algorithm
tagged with: python
has comment: http://stackoverflow.com/comment/87700223
has title: Building chains from nested list
has body: I have a nested list: [['мама', 'мыть', '10', 'рама'], ['мыть', 'рама', '5', 'долго'], ['мама', 'мыть', '10', 'рама'], ['мыть', 'рама', '3', 'вчера'], ['мыть', 'рама', '10', 'вчера'], ['рама', 'вчера', '1', 'поздно']] What I need is to build chains where last two non-digital string elements of one list are equal to first two non-digital string elements of another list, for example in: ['Мама', 'мыть', '10', 'рама'] and ['мыть', 'рама', '5', 'долго'] 'мыть', 'рама' are a match, so the final output should be: [['мама', 'мыть', '10', 'рама', '5', 'долго'], ['мама', 'мыть', '10', 'рама', '3', 'вчера'], ['мама', 'мыть' '10', 'рама', '3', 'вчера', '1', 'поздно']] Digits are kind of probability and should be left as is. I think there should be some kind of iterative search, but I am not sure. Any help would be appreciated.
score: 2
has comment: http://stackoverflow.com/comment/87700250
tagged with: python-3.x
tagged with: list
has comment: http://stackoverflow.com/comment/87700267
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87700168
has comment: http://stackoverflow.com/comment/87700226
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50342443
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87700927

http://stackoverflow.com/comment/87603542
has text: Good solution :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50293599
score: 0

http://stackoverflow.com/comment/87738595
has text: Dont use `dir` use `vars` and forgo the `prop` helper function.
type: AnswerComment
comment on: http://stackoverflow.com/a/50360595
type: Comment
score: 1

http://stackoverflow.com/q/50384894
score: 1
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87795693
upvote count: 1
has answer: http://stackoverflow.com/a/50402682
linked to: http://stackoverflow.com/q/50391080
has body: tl;dr what is the most efficient way to dynamically choose some entries of a tensor. I am trying to implement syntactic GCN in Tensorflow. Basically, I need to have a different weight matrix for every label (lets ignore biases for this question) and choose at each run the relevant entries to use, those would be chosen by a sparse matrix (for each entry there is at most one label in one direction and mostly no edge so not even that). More concretely, when I have a sparse matrix of labeled edges (zero-one), is it better to use it in a mask, a sparse-dense tensor multiplication or maybe just use normal multiplication (I guess not the latter, but for simplicty use it in the example) example: units = 6 # output size x = ops.convert_to_tensor(inputs[0], dtype=self.dtype) labeled_edges = ops.convert_to_tensor(inputs[1], dtype=self.dtype) edges_shape = labeled_edges.get_shape().as_list() labeled_edges = expand_dims(labeled_edges, -2) labeled_edges = tile( labeled_edges, [1] * (len(edges_shape) - 1) + [units, 1]) graph_kernel = math_ops.multiply(self.kernel, labeled_edges) # here is the question basically outputs = standard_ops.tensordot(x, graph_kernel, [[1], [0]]) outputs = math_ops.reduce_sum(outputs, [-1])
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87797598
has title: boolean_mask or sparse dot product in tensorflow
tagged with: neural-network
tagged with: python
tagged with: nlp
tagged with: performance
has comment: http://stackoverflow.com/comment/87795326

http://stackoverflow.com/comment/87669481
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50326886
has text: @mika72 f contains a str object `print(type(f))` outputs `<class 'str'>`

http://stackoverflow.com/comment/87535632
comment on: http://stackoverflow.com/q/50258511
score: 0
has text: @Andomar With the combination of both questions you get the logic of finding the key, if you think it is not duplicated I invite you to reopen it, the community will decide. :D
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50264150
has answer: http://stackoverflow.com/a/50264303
type: Question
accepted answer: http://stackoverflow.com/a/50264174
has answer: http://stackoverflow.com/a/50264164
tagged with: python
has answer: http://stackoverflow.com/a/50264174
favorite count: 0
tagged with: replace
answer count: 4
has answer: http://stackoverflow.com/a/50264226
has title: Removing vowels from a string
score: 2
possible better answer: http://stackoverflow.com/a/50264164
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9060653
has comment: http://stackoverflow.com/comment/87548602
downvote count: 0
tagged with: string
has body: I'm suppose remove all the vowels from the any string that would be entered. I'm trying to make the code as simple as possible. Thank you for the help. def anti_vowel(text): for i in text: i.strip(['i','o','a','u','e']) return i

http://stackoverflow.com/q/50256836
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
has title: PYTHON: Changing Column names
answer count: 1
has body: I am reading a excel sheet by using pandas as - pd.read_excel() and then putting it in a list and appending it to the final Data-frame. The sheet which i am reading have a column name Sales and in the final data-frame i have column with name Item. AllFields is the Data-frame with all the list of columns. So my question is while appending the list to the final data-frame the records of the Sales Columns comes under the column name Item. Example of data which i am reading from sheet Sales 2013 2014 2015 2016 2017 2018 2019 Units Sold 0 0 0 0 0 0 0 Unit Sale Price $900 $900 $900 $900 $900 $900 $900 Unit Profit $500 $500 $500 $500 $500 $500 $500 and then appending to the data-frame which have columns Full Project Item Market Project Project Step Round Sponsor Subproduct 2013 2014 2015 2016 2017 2018 2019 reading_book1 = pd.read_excel(file, sheet_name="1-Rollout", skiprows=restvalue).iloc[:10] EmptyList1 = [reading_book1] RestDataframe = RestDataframe.append(AllFields).append(EmptyList1) RestDataframe['Project'] = read_ProjectNumber RestDataframe['Full Project'] = read_fullProject RestDataframe['Sponsor'] = read_Sponsor RestDataframe['Round'] = read_round RestDataframe['Project Step'] = read_projectstep RestDataframe['Market'] = "Rest of the World Market" FinalDataframe = FinalDataframe.append(CADataframe).append(RestDataframe)
has answer: http://stackoverflow.com/a/50258085
has comment: http://stackoverflow.com/comment/87531697
type: Question
has comment: http://stackoverflow.com/comment/87532852

http://stackoverflow.com/comment/87646331
type: Comment
has text: I'm using it along with requests to check available urls
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50315197

http://stackoverflow.com/q/50333418
has answer: http://stackoverflow.com/a/50334595
has answer: http://stackoverflow.com/a/50334406
linked to: http://stackoverflow.com/q/6657820
has body: I'm in need of some knowledge on how to fix an error I have made while collecting data. The collected data has the following structure: ["Author", "Message"] ["littleblackcat", " There's a lot of redditors here that live in the area maybe/hopefully someone saw something. "] ["Kruse", "In other words, it's basically creating a mini tornado."] I normally wouldn't have added "[" or "]" to .txt file when writing the data to it, line per line. However, the mistake was made and thus when loading the file it will separate it the following way: Is there a way to load the data properly to pandas?
tagged with: pandas
answer count: 5
has answer: http://stackoverflow.com/a/50334552
has title: How to load a dataframe from a file containing unwanted characters?
linked to: http://stackoverflow.com/q/46310030
tagged with: dataframe
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/50334283
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50334183
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87683928
downvote count: 0
has comment: http://stackoverflow.com/comment/87683110
favorite count: 0
type: Question

http://stackoverflow.com/comment/87703897
has text: @ Ami , yes, Testing it now. This was a sample data i posted, i actually have around 1000 vertex :p
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50343824

http://stackoverflow.com/q/50360539
has answer: http://stackoverflow.com/a/50360601
tagged with: oop
type: UnansweredQuestion
has title: Reducing syntactic cruft when a method accesses instance variables?
tagged with: python
has answer: http://stackoverflow.com/a/50360595
score: 2
has comment: http://stackoverflow.com/comment/87737717
answer count: 3
has body: The following code is a simplified example of a task I'm working on, using Python, that seems to be a natural fit for an OOP style: class Foo: def __init__(self): self.x = 1 self.y = 1 self.z = 1 def method(self): return bar(self.x,self.y,self.z) def bar(x,y,z): return x+y+z f = Foo() print(f.method()) In the example code above, I have three instance variables in my object, but in my actual application it would be more like 10 or 15 variables, and if I implement what I have in mind in this style, then I'm going to end up with a lot of code that looks like this: return bar(self.a.self.b,self.c,self.d,self.e,self.f,self.g,self.h,self.i) Wow, it sure would be nice to be able to write this in a style more like this: return bar(a,b,c,d,e,f,g,h,i) That would be a lot more concise and readable. One way to do this might be to rewrite bar so that it takes a Foo object as an input rather than a bunch of scalar variables, but I would prefer not to do that. Actually, that would just push the syntactic cruft down into the bar function, where I guess I would have code that looked like this: def bar(f): return f.a+f.b+f.c Is there a nicer way to handle this? My understanding is that without the "self.", I would be referencing class variables rather than instance variables. I thought about using a dictionary, but that seems even cruftier, with all the ["a"] stuff. Might there be some automated way to take a dictionary with keys like "a","b","c",... and kind of unload the values into local variables named a, b, c, and so on?
upvote count: 2
has answer: http://stackoverflow.com/a/50360656
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/50324561
has comment: http://stackoverflow.com/comment/87665281
type: Question
linked to: http://stackoverflow.com/q/47059198
answer count: 9
has answer: http://stackoverflow.com/a/50325006
type: UnansweredQuestion
score: 26
has answer: http://stackoverflow.com/a/60060092
has title: ValueError: The field admin.LogEntry.user was declared with a lazy reference
has answer: http://stackoverflow.com/a/67781274
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/65112242
has body: I'm developing a new django project and stuck with migration. I would like to make a UserModel, and in order to do that, I did two things so far. 1. I made AuthUser model and set a Meta class in the class below. In models.py class AuthUser(AbstractUser): user_type_id = models.PositiveIntegerField(choices=UserTypes.choices()) user_id = models.PositiveIntegerField() class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' @property def user_type(self): return UserTypes(self.user_type_id) def original_orm(self): if self.user_type.value == UserTypes.raijosha.value: return RaijoshaUsers.objects.filter(id=self.user_id).first() elif self.user_type.value == UserTypes.shuttennsha.value: return Users.objects.filter(id=self.user_id).first() In settings.py, I set AUTH_USER_MODEL. AUTH_USER_MODEL = 'recommend.AuthUser' Here's the error codes. Operations to perform: Apply all migrations: admin, auth, contenttypes, recommend, recommend_raijousha, sessions Traceback (most recent call last): File "manage.py", line 25, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 164, in handle pre_migrate_apps = pre_migrate_state.apps File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/d…
has comment: http://stackoverflow.com/comment/87665104
has comment: http://stackoverflow.com/comment/87664860
has answer: http://stackoverflow.com/a/78448614
has answer: http://stackoverflow.com/a/65556167
tagged with: migration
has answer: http://stackoverflow.com/a/66983574
has answer: http://stackoverflow.com/a/74921066
downvote count: 0
upvote count: 26
has comment: http://stackoverflow.com/comment/87664829
has answer: http://stackoverflow.com/a/51240725
favorite count: 0

http://stackoverflow.com/q/50343100
tagged with: dataframe
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/92447923
tagged with: pandas
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has title: String or Unicode type required for dfgui running wx with kivy python
linked to: http://stackoverflow.com/q/28935315
has body: I intended to write a code which helps me display Table / Dataframe on GUI (Kivy). To which I found the solution here. Apparently it uses a non-official package from a github repo which is dfgui. The Problem occurred to me when I executed as told on StackOverflow link. However returned Error that wx._core.PyAssertionError: C++ assertion "!items.IsEmpty()" failed at /usr/include/wx-3.0/wx/ctrlsub.h(154) in InsertItems(): need something to insert I Brokedown the problem by selective execution in foll. way import dfgui import pandas as pd xls = pd.read_excel('Res.xls') df = pd.DataFrame(xls) dfgui.show(df) #dfgui.show(xls) Apparently the same as df which then returned TypeError: String or Unicode type required and led me to this link, which I couldn't understand much. Point me in North, or perhaps a different solution could be great too.
has comment: http://stackoverflow.com/comment/92441832
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5125377

http://stackoverflow.com/q/50266369
tagged with: django-models
tagged with: python
has title: Picture not showing up on django
has comment: http://stackoverflow.com/comment/87550892
has comment: http://stackoverflow.com/comment/87587911
type: AnsweredQuestion
tagged with: django-templates
tagged with: django-views
downvote count: 0
has comment: http://stackoverflow.com/comment/87568514
has comment: http://stackoverflow.com/comment/87551237
score: 1
upvote count: 1
has body: I am trying to make clone of www.producthunt.com and while I was working on it I made model by which people can upload the picture of the product and title, body, etc. While I made the models.py, views.py, and the detail.html[Page where the user gets redirected to his own post after posting] I found that the picture wasn't able to showup it had an image symbol and that's it! So, my views.py looks like: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): products = Product.objects return render(request, 'products/home.html',{'products':products}) @login_required(login_url="/accounts/signup") def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): product.url = request.POST['url'] else: product.url = 'http://' + request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('/products/' + str(product.id)) else: return render(request, 'products/create.html',{'error':'All fields are required.'}) else: return render(request, 'products/create.html') def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'products/detail.html',{'product':product}) And the detail.html looks like: {% extends 'base.html' %} {% block content %} {{ product.title }} {% endblock %} The product's model looks like: from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=200) url =…
answer count: 1
has comment: http://stackoverflow.com/comment/87551152
has comment: http://stackoverflow.com/comment/87551132
favorite count: 0
has answer: http://stackoverflow.com/a/50267104
type: Question
accepted answer: http://stackoverflow.com/a/50267104
tagged with: django

http://stackoverflow.com/q/50277510
has title: Extracting arg values from string formatted by inspect.formatargvalues
linked to: http://stackoverflow.com/q/1419046
tagged with: python
accepted answer: http://stackoverflow.com/a/50278270
has answer: http://stackoverflow.com/a/50278270
tagged with: parsing
type: AnsweredQuestion
score: 0
answer count: 1
has body: I'm trying to parse a string that has been formatted using inspect.formatargvalues and I want to be able to extract the argument values and save them in a dictionary. Here are some examples of the text: CALL function.a(timeout_secs=10) CALL function.b(x=something good (happy days, ABC 123), y_z=None, check_this=True, check_this_2=None, extra_info=None, press=False, timeout_secs=30) CALL function.c(key='A_B') CALL function.d(target=&lt;Tab.Chrome: 'tab-chrome'&gt;) CALL function.e(music_type=&lt;MusicType.ALBUM: 1&gt;, term=None, genre=None, results=True) CALL function.f(button='END', delay=None) At the moment I'm extracting the parameters using regex to get: timeout_secs=10 x=something good (happy days, ABC 123), y_z=None, check_this=True, check_this_2=None, extra_info=None, press=False, timeout_secs=30 key='A_B' target=&lt;Tab.Chrome: 'tab-chrome'&gt; music_type=&lt;MusicType.ALBUM: 1&gt;, term=None, genre=None, results=True button='END', delay=None Then I'm splitting on ',' and then converting the array into a dictionary. dict(parameter.split("=") for parameter in array_of_parameters) This works for the most part but obviously breaks when parsing: x=something good (happy days, ABC 123), y_z=None, check_this=True, check_this_2=None, extra_info=None, press=False, timeout_secs=30 Is there a way to convert the arguments to a dictionary where it covers all these scenarios?
tagged with: string
has comment: http://stackoverflow.com/comment/87572679
type: Question

http://stackoverflow.com/a/50302601
score: 1
type: Answer
downvote count: 0
has body: Finding and removing a random element in a collection is generally O(k) when using pop, however, you can modify the action so that the list is shuffled when checking for length, that way, both the add and pop operations remain O(1): import random class RandomStack: def __init__(self, _d = None): self.stack = _d if _d else [] def __len__(self): random.shuffle(self.stack) return len(self.stack) def add(self, _val): self.stack.append(_val) def poprandom(self): return self.stack.pop() a = RandomStack() for i in range(16): a.add(i) if len(a) &gt; 10: val = a.poprandom() print(val) Output: 2 4 9 0 6 12
upvote count: 1
answers question: http://stackoverflow.com/q/50302553

http://stackoverflow.com/q/50328748
downvote count: 0
upvote count: 1
has title: Split list into sublists based on string split
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50329240
has comment: http://stackoverflow.com/comment/87673586
has comment: http://stackoverflow.com/comment/87674967
has comment: http://stackoverflow.com/comment/87673529
has answer: http://stackoverflow.com/a/50329240
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/50329144
type: AnsweredQuestion
has body: I have a list like this: a = [['cat1.subcat1.item1', 0], ['cat1.subcat1.item2', 'hello], [cat1.subcat2.item1, 1337], [cat2.item1, 'test']] So there may be several subcategories with items, split by a dot. But the number of categoryies and the level of depth isn't fixed and not equal among the categories. I want the list to look like this: a = [['cat1', [ ['subcat1', [ ['item1', 0], ['item2', 'hello'] ]], ['subcat2', [ ['item1', 1337] ]], ]], ['cat2', [ ['item1', 'test'] ]] ] I hope this makes sense. In the end I need a json string out of this. If it is somehow easier it could also directly be converted to the json string. Any idea how to achieve this? Thanks!
linked to: http://stackoverflow.com/q/7204805
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/50329144
score: 1
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/50274927
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am a complete Python beginner (CS student who only knows Java at this point) and I'm currently using PyCharm to try to learn. However, I've been encountering this problem which I don't even know how to search for because I don't understand what's happening. When I try to run: print('test') in the PyCharm console, I get this output: The print statement happens before the imports and seemingly before Python even initializes. I've been encountering some strange interactions as a result of this. For example, if I change the print to an input(), the program will take input but the string in the argument of the input function will not be printed. Can anyone explain what's going on here? Should I be running my programs differently? There is my run configuration:
accepted answer: http://stackoverflow.com/a/50275505
has answer: http://stackoverflow.com/a/50275505
tagged with: python
has comment: http://stackoverflow.com/comment/87567035
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87566536
tagged with: pycharm
has comment: http://stackoverflow.com/comment/87566768
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87567205
answer count: 1
downvote count: 0
has title: PyCharm printing before imports?

http://stackoverflow.com/comment/87530679
comment on: http://stackoverflow.com/q/50244767
score: 0
has text: Btw: the fact that "汉字" is displayed as "µ▒ëσ¡ù" means that your terminal isn't configured to use UTF-8. This is outside Python's control, you need to configure the command-line program or use a better one.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87549622
type: AnswerComment
comment on: http://stackoverflow.com/a/50246378
type: Comment
has text: @PhaniKumarYadavilli ,trying to save a incoming .gz file on the go for which we are getting error related to the header. I have tried decompressing incoming data in chunks but no luck. Reference Based Messaging is good but I can not use in my case.
score: 0

http://stackoverflow.com/a/50271516
type: Answer
has comment: http://stackoverflow.com/comment/87560462
has comment: http://stackoverflow.com/comment/87560818
has comment: http://stackoverflow.com/comment/87561010
has comment: http://stackoverflow.com/comment/87560283
downvote count: 0
has body: Why don't you just use the dateparser package? Parsing dates from natural language is pretty complex with lots of edge cases. If you are just curious what they are doing, the best way to find out is to look at the source code. dateparser: date translation: en.json dataparser: numeral translation: data en.json Edit: You can convert a list of strings into regexes: import re regexes = list(map(lambda x: re.compile(x), items))
upvote count: 1
answers question: http://stackoverflow.com/q/50271452
has comment: http://stackoverflow.com/comment/87560797
score: 1

http://stackoverflow.com/comment/87595208
has text: BUT, why do you need `itertools` ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50289564
score: 0

http://stackoverflow.com/comment/87654949
comment on: http://stackoverflow.com/a/50319600
has text: Can I see the url? You can only use one of the available classes like `available-columns` or `trans-fade-in` whatever meets your needs
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/122874758
type: AnswerComment
has text: definitely the cleanest answer!
comment on: http://stackoverflow.com/a/60540583
score: 1
type: Comment

http://stackoverflow.com/comment/87621579
type: Comment
score: 0
type: AnswerComment
has text: Just to tell you what happens. It opens up firefox on a blank page and then like 20 seconds later prints the error and keeps firefox open
comment on: http://stackoverflow.com/a/50301964

http://stackoverflow.com/a/50335531
has comment: http://stackoverflow.com/comment/87689979
type: Answer
has comment: http://stackoverflow.com/comment/87689947
has comment: http://stackoverflow.com/comment/87688747
accepted answer of: http://stackoverflow.com/q/50335429
score: 0
type: AcceptedAnswer
has body: Use merge on columns X and Y, with parameter `right_index' set to True: df.merge(df2, on=['X', 'Y'], right_index=True) Output: X Y ID 1 2 23 2 30 2 2 2 5 3 4 90
answers question: http://stackoverflow.com/q/50335429
has comment: http://stackoverflow.com/comment/87688842

http://stackoverflow.com/q/50328096
tagged with: python
tagged with: text-processing
downvote count: 1
has body: I have a database full of strings such as: as.web.product.viewed(AT)2018-01-28T19:00:52.032Z(THEN)as.web.product.viewed(AT)2018-01-28T19:02:20.132Z (another possible delimiter is "(WITH)" and action is as.web.product.purchased so ideally I'd need a solution that is as generic as possible) There can be any number of actions in a sequence, and in more or less any order. I need to be able to isolate the action name (such as as.web.product.viewed) and the time at which it happened, as well as maintain the order of the actions. What would be the most Python-esque way of doing this? EDIT: desired output (for the example above) - 2 lists such as: ['as.web.product.viewed','as.web.product.viewed'] ['2018-01-28T19:00:52.032Z','2018-01-28T19:02:20.132Z']
type: AnsweredQuestion
answer count: 1
tagged with: string-parsing
score: -1
tagged with: parsing
favorite count: 0
accepted answer: http://stackoverflow.com/a/50328413
type: Question
tagged with: text-parsing
has comment: http://stackoverflow.com/comment/87672424
has answer: http://stackoverflow.com/a/50328413
has title: Python: parsing text of unknown length
upvote count: 0
has comment: http://stackoverflow.com/comment/87672481

http://stackoverflow.com/comment/87716842
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50350456
has text: And will the other elements of `l2` always begin with the one in `l1` (so `a` in `a1`.)
score: 3

http://stackoverflow.com/comment/87627066
comment on: http://stackoverflow.com/a/50303726
score: 1
type: Comment
has text: Pasting into a shell works fine for me, and I see no reason why it would not. Any serious Python shell (certainly cpython 2 and 3) configures `__name__` to be `'__main__'`.
type: AnswerComment

http://stackoverflow.com/q/50237248
tagged with: outer-join
tagged with: pandas
has body: I want to combine two dataframe's data. Dataframe is string df1=pd.read_csv('test1.csv',encoding='utf8',index_col=['id_df1'],header=0) df2=pd.read_csv('test2.csv',encoding='utf8',index_col=['id_df2'],header=0) print(df1) print(df2) out: id_df1 student contact_person 1 john Amy 2 jeff Cindy 3 steven Bob 4 tina Amy id_df2 student parents_list 1 tina (Amy) (Bob) 2 steven (Eric) (Bob) 3 john (Amy) 4 jeff (Frank) (Harry) print(type(df1['contact_person'][0])) print(type(df2['parents_list'][0])) out: &lt;class 'str'&gt; &lt;class 'str'&gt; if df1['student']==df2['student'] &amp; df1['contact_person'] match df2['parents_list'] I want to use "outer" method like this: output id_df1 id_df2 student contact_person parents 0 1 3 john Amy (Amy) 1 3 2 steven Bob (Eric) (Bob) 2 4 1 tina Amy (Amy) (Bob) 3 2 null jeff Cindy null 4 null 4 jeff null (Frank) (Harry)
score: 1
has title: How to use Python merge or join two pandas dataframe with string
has comment: http://stackoverflow.com/comment/87494658
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/50239379
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87494430
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50239379
has comment: http://stackoverflow.com/comment/87492273

http://stackoverflow.com/q/50349301
has comment: http://stackoverflow.com/comment/87720959
answer count: 0
downvote count: 0
tagged with: music21
type: UnansweredQuestion
has title: Run music21 on full processor power
tagged with: dataset
tagged with: python
tagged with: multicore
has body: I am trying to create dataset by extracting only specific songs from larger dataset . By specific I mean songs only with two instruments where one is from keyboard family and another is from string family. Simplified code looks like this: for midi_file_path in Path(dir_path).glob('**/*.mid'): try: song = converter.parse(midi_file_path) parts = instrument.partitionByInstrument(song) if parts: if len(parts) == 2: if (parts.parts[0].id in keyboard_instruments and parts.parts[1].id in string_instruments) or \ (parts.parts[1].id in keyboard_instruments and parts.parts[0].id in string_instruments): print(midi_file_path) except Exception as e: print("Exception ", midi_file_path, e) pass This process takes a lot of time, and I would like to optimise it. The main question is why processor does not run on full power, but only around 17%. The last version of music21 says - "Feature Extraction runs multicore by default" .
upvote count: 1
score: 1
tagged with: cpu-cores
favorite count: 0
type: Question

http://stackoverflow.com/comment/87771994
has text: This works perfectly, thanks. Is there a reason that this adds all the links compared to my code which only added one link?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50377708

http://stackoverflow.com/comment/87631672
has text: Do you happen to be on OS X? Check out [this GitHub thread](https://github.com/Homebrew/legacy-homebrew/issues/41253#issuecomment-117830571) where someone had a similar problem and resolved it. Scroll down to where people are saying it worked for them and see if that resolves your issue.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50302222

http://stackoverflow.com/comment/87539277
type: QuestionComment
has text: Please add error message + traceback
score: 0
comment on: http://stackoverflow.com/q/50260582
type: Comment

http://stackoverflow.com/a/50290394
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87631029
upvote count: 1
answers question: http://stackoverflow.com/q/50287133
type: Answer
has body: You might find the following approach a bit easier: import pandas as pd tables = pd.read_html("https://afltables.com/afl/stats/teams/adelaide/2018_gbg.html") for df in tables: df.drop(df.columns[9:], axis=1, inplace=True) # remove unwanted columns df.columns = df.columns.droplevel(0) # remove extra index level for table in tables: print(table[:3:], '\n') # show first 3 rows This will give you a list of pandas dataframes. Each one contains all the information for each table. So for example, the first one contains Disposals: Player R1 R2 R3 R4 R5 R6 R7 Tot 0 Atkins, Rory 14.0 17.0 22.0 28.0 24.0 28.0 16.0 149 1 Betts, Eddie 14.0 20.0 16.0 6.0 NaN NaN 10.0 66 2 Brown, Luke 15.0 23.0 23.0 16.0 16.0 24.0 11.0 128 Player R1 R2 R3 R4 R5 R6 R7 Tot 0 Atkins, Rory 8.0 13.0 12.0 16.0 17.0 18.0 10.0 94 1 Betts, Eddie 7.0 6.0 10.0 2.0 NaN NaN 7.0 32 2 Brown, Luke 10.0 17.0 17.0 10.0 11.0 16.0 9.0 90 You could then use pandas to work with the data.
accepted answer of: http://stackoverflow.com/q/50287133
has comment: http://stackoverflow.com/comment/87624289
score: 1

http://stackoverflow.com/comment/87688402
has text: Thanks you for your help :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50335638
score: 0

http://stackoverflow.com/q/50339000
answer count: 0
has comment: http://stackoverflow.com/comment/87694709
linked to: http://stackoverflow.com/q/9256687
has title: defaultdict not synchronized in python3's multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87694440
tagged with: python
type: UnansweredQuestion
has body: I'm having this problem for a little while and haven't figured it out yet, i.e., how to synchronize a dictionary across children processes. This is typically useful when trying to process a bunch of files independently while keep track of some stats regarding the files/datasets. With useful tips from: Using defaultdict with multiprocessing?, i came up with something similar to this: class MyManager(BaseManager): pass MyManager.register('defaultdict', defaultdict, DictProxy) def partial_test(string, multi_dict, idx): k = string[idx] multi_dict[k].append(idx) // record indices, failed! // multi_dict[k] += 1 // this works as expected! def job(): mgr = MyManager() mgr.start() multi_d = mgr.defaultdict(list) pool = multiprocessing.Pool(processes=4) partial_job = partial(partial_test, 'mississippi', multi_d) N = len('mississippi') pool.map(partial_job, range(N)) pool.close() pool.join() print(multi_d.items()) The output is: [('m', []), ('i', []), ('s', []), ('p', [])] For my application, I had to use partial() with pool.map(), but then the dictionary didn't get updated properly. Also, as i mentioned above, if multi_dict was used as a counter as in the link's example, everything worked as expected (definition changed to defaultdict(int) of course). Anybody knows why?
score: 0

http://stackoverflow.com/comment/87718029
comment on: http://stackoverflow.com/q/50350996
type: QuestionComment
score: 0
has text: You need to set a seed when you use random functions, so that your output will be "random", but with consistent results. See [`np.random.seed()`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.seed.html)
type: Comment

http://stackoverflow.com/q/50303020
has answer: http://stackoverflow.com/a/50303214
has title: How to search for a string like \x60\xe2\x4b(indicating a emoticon) using regular expression in python
has answer: http://stackoverflow.com/a/50303060
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/50303207
tagged with: regex
has comment: http://stackoverflow.com/comment/87622542
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50303164
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87622803
downvote count: 2
tagged with: emoticons
has body: import re string="b'@DerkGently @seanferg85 @Umbertobaggio @EL4JC and he already had Popular support.. most people know this already. A\xe2\x80\xa6 '" print(re.findall(r"\x[0-9a-z]{2}",string)) The the list returned by the findall() function is empty :(
type: Question

http://stackoverflow.com/comment/87759617
has text: Does that touch the disk, before bs64?
type: Comment
comment on: http://stackoverflow.com/a/50371663
score: 0
type: AnswerComment

http://stackoverflow.com/a/50256563
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87531746
answers question: http://stackoverflow.com/q/50256456
has body: According to the docs, password is not a keyword argument like you entered, instead it's passwd as you can see --> here
type: Answer
upvote count: 2

http://stackoverflow.com/q/50327858
has answer: http://stackoverflow.com/a/75176149
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has title: How to change size of CharField
favorite count: 0
tagged with: textinput
type: Question
tagged with: django-admin
accepted answer: http://stackoverflow.com/a/50328053
answer count: 2
tagged with: django
has answer: http://stackoverflow.com/a/50328053
tagged with: python
tagged with: django-widget
has body: This code is changing sizes of all CharFields in class. How I can change size of one CharField? formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '20'})}, }
possible better answer: http://stackoverflow.com/a/75176149
has comment: http://stackoverflow.com/comment/87671560

http://stackoverflow.com/comment/87574185
score: 0
comment on: http://stackoverflow.com/q/50272484
type: Comment
type: QuestionComment
has text: Konstantin below gave the answer that I was looking for. I did not understand that len(A) - 1 is assigned to next_odd. These syntax shortcuts are normally not thaught in the textbooks.

http://stackoverflow.com/comment/87604033
comment on: http://stackoverflow.com/a/50284954
has text: Kumar, "# You can directly do this (or continue with train_test_split as you originally had) clf.fit(X, results)" for this portion why would you do this as opposed to the test split? I'm trying to wrap my head around it.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50319476
downvote count: 0
has body: Assuming I have a class that implements the Sequence interface, i.e. has __len__ and __getitem__ methods, what is the recommended way to document this? Is an informal description in the classes docstring enough, should I subclass collections.abc.Sequence or do something else entirely?
has comment: http://stackoverflow.com/comment/87655769
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python-collections
tagged with: python
has title: Proper way to document that a class implements a collections interface?
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87655052

http://stackoverflow.com/comment/87638853
has text: Thank you for this very informative answer. Can you please elaborate on why it's bad to overwrite original tensor references? Rather than having a never-ending supply of references (something I don't want to do) as I continually update a value downstream, how can I update a variable otherwise?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50311127

http://stackoverflow.com/q/50363046
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has title: How to include boolean conditions to python's list comprehension?
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/50363116
possible better answer: http://stackoverflow.com/a/50363116
has comment: http://stackoverflow.com/comment/87742393
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87742518
answer count: 2
has comment: http://stackoverflow.com/comment/87784373
tagged with: python
has answer: http://stackoverflow.com/a/50363072
tagged with: string
accepted answer: http://stackoverflow.com/a/50363072
has comment: http://stackoverflow.com/comment/87742455
tagged with: boolean-logic
has body: INPUT: I have a list of strings with places I can work: ALL_CHANCES = ['I can work in China', 'I can work in Germany', 'I can work in Singapore', 'I can work in Norway'] I have another list of strings with places better not to work at: HIGH_TAX = ['Germany', 'Norway'] OUTPUT: I am looking for a simple list comprehension one-liner to filter list 1 for items that have substrings occurring in list 2: GOOD_CHANCES = ['I can work in China', 'I can work in Singapore'] CHALLENGE: However, when I do GOOD_CHANCES = [item for item in ALL_CHANCES if (not any(word for word in HIGH_TAX) in item)] I yield the following error: '&lt;string&gt;' requires string as left operand, not bool How to include boolean conditions to python's list comprehension?

http://stackoverflow.com/q/50352627
type: AnsweredQuestion
tagged with: odoo-11
upvote count: 0
has title: Error Element '<xpath expr="//form/footer/button[@name='create_payment']" name="">' cannot be located in parent view
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/50365430
has answer: http://stackoverflow.com/a/50365430
favorite count: 0
has body: Why I am getting this error: Element ' ' cannot be located in parent view Error context: View `account.register.payments.wizard.from.invoices.inherited` [view_id: 660, xml_id: account_bankgiro_payment_file.view_account_payment_from_invoices_inherit_account_bankgiro, model: account.register.payments, parent_id: 384] None" while parsing /home/prachh/odoo-new/11/apps/account_bankgiro_payment_file/views/inherited_account_register_payments.xml:11, near while everything seems correct? Here is my code: account.payment.bankgiro.download account.payment.bankgiro Click on the file to save it somewhere on your computer. Then upload that file on your bank's homebanking website. account.bankgiro.pay.tree account.payment.bankgiro account.invoice.pay.tree account.invoice account.payment.bankgiro.tree account.payment.bankgiro account.payment.bankgiro.form account.payment.bankgiro BankGiro Transfer bankgiro_tr outbound account.register.payments.wizard.from.invoices.inherited account.register.payments {'invisible':[('payment_method_code','=','bankgiro_tr')]} {'invisible':[('payment_method_code','=','bankgiro_tr')]} {'invisible':[('payment_method_code','=','bankgiro_tr')]} {'invisible':[('payment_method_code','=','bankgiro_tr')]}
type: Question
score: -2
tagged with: python
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/a/50282531
has comment: http://stackoverflow.com/comment/87620618
has comment: http://stackoverflow.com/comment/87585635
has body: I'd recommend using regex lookarounds: &gt;&gt;&gt; re.split('(?&lt;!,),(?=\s)', text) ['abc,, def', ' ghi'] Details (?&lt;! # negative lookbehind , # comma ) , (?= # positive lookahead \s # whitespace ) Semantically, this means "split on a single comma only (comma that is not preceded or succeeded by any commas)."
has comment: http://stackoverflow.com/comment/87586141
has comment: http://stackoverflow.com/comment/87581672
accepted answer of: http://stackoverflow.com/q/50282499
type: Answer
answers question: http://stackoverflow.com/q/50282499
has comment: http://stackoverflow.com/comment/87581748
has comment: http://stackoverflow.com/comment/87581704
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87506360
has text: did you try `position:fixed`
type: Comment
comment on: http://stackoverflow.com/q/50244024
type: QuestionComment
score: 0

http://stackoverflow.com/q/50246084
downvote count: 0
upvote count: 1
tagged with: django
tagged with: paypal-rest-sdk
score: 1
linked to: http://stackoverflow.com/q/15185661
answer count: 1
has body: I am programming on Django and using paypalrestsdk https://github.com/paypal/PayPal-Python-SDK I am getting this error: OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] Basically I have created BillingPlan(code snippet https://gist.github.com/axilaris/2f9cf8f5c27a8a2095c5c9abf0dc4121), and this appears: Payment created successfully 2018-05-08 22:44:45,358 INFO Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token 2018-05-08 22:44:45,358 DEBUG Level: sandbox 2018-05-08 22:44:45,358 DEBUG Request: Headers: {'Authorization': 'Basic [binary]', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'User-Agent': 'PayPalSDK/PayPal-Python-SDK 1.13.1 (requests 2.12.1; python 3.6.3; OpenSSL 1.0.2k 26 Jan 2017)', 'PayPal-Request-Id': 'b337cb66-b036-4a0a-9f70-aaa7011e73bb'} Body: grant_type=client_credentials 2018-05-08 22:44:45,362 DEBUG Starting new HTTPS connection (1): api.sandbox.paypal.com From cffi callback &lt;function _verify_callback at 0x12972a268&gt;: Traceback (most recent call last): File "/Users/some/Documents/project/somedotcom/somedotcomenv/lib/python3.6/site-packages/OpenSSL/SSL.py", line 313, in wrapper _lib.X509_up_ref(x509) ... File "/Users/some/Documents/project/somedotcom/somedotcomenv/lib/python3.6/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] more complete detail of the traces can be found here: https://gist.github.com/axilaris/c181aaaa8261add4240fb2d042bd1ffc How do I resolve this error ? Thanks. my environment: pyOpenSSL==17.5.0 paypalrestsdk==1.13.1 Django==1.11.7 cryptography==2.1.3
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50247493
tagged with: python
has answer: http://stackoverflow.com/a/50247493
favorite count: 0
tagged with: openssl
has title: Django paypalrestsdk error - OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

http://stackoverflow.com/q/50311201
favorite count: 0
type: Question
has title: Creating interaction sessions based on timestamps in pandas
tagged with: time-series
accepted answer: http://stackoverflow.com/a/50311285
has answer: http://stackoverflow.com/a/50311285
score: 5
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87638878
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87638652
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50311383
downvote count: 0
has answer: http://stackoverflow.com/a/50311383
has body: I am trying to define which apps were used in different mobile usage sessions. Basically, a session is a series of actions by a single user made within a small range of time (aka. session delta). In other words, if no interaction happens within 5 minutes of the previous interaction, a user’s session is deemed closed. The next interaction is considered a separate session. I would like to know how many mobile sessions are there in the dataset. Also, I would like to know which apps were launched in each session. All the rows in my data frame are time stamped. Here is an example from the dataset: timestamp App 6784 2018-04-08 14:31:29.209 Google 6785 2018-04-08 14:58:42.875 Google 6786 2018-04-08 18:18:04.757 Chrome 6787 2018-04-08 21:08:41.368 Google 6788 2018-04-11 10:53:10.744 Google 6789 2018-04-14 19:54:37.441 Google 6790 2018-04-14 19:54:59.833 Google 6791 2018-04-14 19:55:10.844 YouTube 6792 2018-04-14 19:55:34.486 Google 6793 2018-04-14 20:23:00.315 Google 6794 2018-04-15 08:23:44.873 Google 6795 2018-04-15 08:24:07.257 Google 6796 2018-04-16 16:42:35.538 Google 6797 2018-04-16 16:42:48.351 Google 6798 2018-04-17 08:10:54.734 Google 6799 2018-04-17 08:13:28.855 Google 6800 2018-04-17 08:16:49.408 Google 6801 2018-04-17 08:18:55.049 Google 6802 2018-04-17 08:21:04.201 Google 6803 2018-04-17 08:26:14.254 Google And this is the desired output: timestamp App SessionID 6784 2018-04-08 14:31:29.209 Google 1 6785 2018-04-08 14:58:42.875 Google 2 6786 2018-04-08 18:18:04.757 Chrome 3 6787 2018-04-08 21:08:41.368 Google 4 6788 2018-04-11 10:53:10.744 Google 5 6789 2018-04-14 19:54:37.441 Google 6 6790 2018-04-14 19:54:59.833 Google 6 6791 2018-04-14 19:55:10.844 YouTube 6 6792 2018-04-14 19:55:34.486 Google 6 6793 2018-04-14 20:23:00.315 Google 7 6794 2018-04-15 08:23:44.873 Google 8 6795 2018-04-15 08:24:07.257 Google 8 6796 2018-04-16 16:42:35.538 Google 9 6797 2018-04-16 16:42:48.351 Google 9 6798 2018-04-17 08:10:54.734 Google 10 6799 2018-04-17 08:13:28.855 Google 1…

http://stackoverflow.com/comment/87818534
type: AnswerComment
comment on: http://stackoverflow.com/a/50399219
type: Comment
has text: Excellent answer and supplementary timings, thanks. One question, do you have a reference for `when materializing the zip you're creating tuples of Python objects`? I thought that tuple objects are only produced when you call `list`, `next`, etc. But I wasn't aware that `tuples` are created internally before being consumed by `Counter`.
score: 0

http://stackoverflow.com/a/50354824
score: 1
has comment: http://stackoverflow.com/comment/87726303
type: Answer
has comment: http://stackoverflow.com/comment/87726150
accepted answer of: http://stackoverflow.com/q/50352542
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Feeding the entire input even with the zero vectors gives the fastest processing time. But like you have said, because of bias in the network, this will return a non-zero output. Since you want the outputs to be zero when the input vector need to be zero, a simple trick would be to apply a mask that will make the predictions zero if the input vectors are zero. The mask which returns 1 when the input vectors are non-zero but 0 otherwise, can be obtained by a simple logic: a_sum = tf.reduce_sum(all_outputs, 2) mask = tf.cast(tf.greater(a_sum, tf.zeros_like(a_sum)), tf.float32) You then multiply the predictions with the mask.
answers question: http://stackoverflow.com/q/50352542

http://stackoverflow.com/comment/87931999
comment on: http://stackoverflow.com/a/50301497
type: Comment
score: 0
type: AnswerComment
has text: Thank you for your help, i used this to take a better idea, but i had to write a custom tag filter, so instead of that i converted the dict into a list of list ordered by the values entry, and that solves my problem. Thank you for the answer. !!

http://stackoverflow.com/q/50282890
score: 1
has answer: http://stackoverflow.com/a/69403854
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89593704
has answer: http://stackoverflow.com/a/51416473
has answer: http://stackoverflow.com/a/53107197
type: Question
upvote count: 2
tagged with: pyinstaller
has title: Got errors, while running exe file built with pyinstaller and Google Cloud API integration in python
tagged with: python
type: UnansweredQuestion
has body: I am working one file python project. I integrated google-cloud-API for realtime speech streaming and recognition. It works with python aaa.py command well. Now I need windows build file(.exe), so I used pyinstaller program and I got aaa.exe file successfully. But I got this error while running speech streaming by using Google cloud API. [Errno 2] No such file or directory: 'D:\AI\ai\dist\AAA\google\cloud\gapic\speech\v1\speech_client_config.json' So I copied this speech_client_config.json file in needed path, after that I got below error again. Exception in 'grpc._cython.cygrpc.ssl_roots_override_callback' ignored E0511 01:13:14.320000000 3108 src/core/lib/security/security_connector/security _connector.cc:1170] assertion failed: pem_root_certs != nullptr Then, I can not find solution to get working version with google-cloud API. I am using python version 2.7.14 I need your friendly help. Thanks.
tagged with: python-2.7
tagged with: google-cloud-platform
answer count: 3

http://stackoverflow.com/comment/87690120
comment on: http://stackoverflow.com/q/50335758
type: Comment
score: 0
type: QuestionComment
has text: Hey! Thanks for the responses people. Patrick, Ian thank you. I'm new to stack overflow and coding so pardon my question structure.

http://stackoverflow.com/q/50321160
type: Question
has answer: http://stackoverflow.com/a/50321230
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50321255
tagged with: split
tagged with: python
has comment: http://stackoverflow.com/comment/87673719
has title: in python3, how to split lists of list at a specific position?
type: AnsweredQuestion
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/50321255
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/50321230
downvote count: 1
has answer: http://stackoverflow.com/a/50321284
has body: ['2006/10/18 21:15:51 4.823 -82.592 37.3 SOUTH OF PANAMA'] ['2006/10/18 10:08:45 32.165 -115.891 7.3 BAJA CALIFORNIA, MEXICO'] There are two lists from the same original list: a = [['2006/10/18 21:15:51 4.823 -82.592 37.3 SOUTH OF PANAMA'], ['2006/10/18 10:08:45 32.165 -115.891 7.3 BAJA CALIFORNIA, MEXICO'] ] Here I want to split each of them before the country names, like: ['2006/10/18 21:15:51 4.823 -82.592 37.3]' '[SOUTH OF PANAMA'] ['2006/10/18 10:08:45 32.165 -115.891 7.3]' '[BAJA CALIFORNIA, MEXICO'] my problem is how to use split() (or maybe some other ways) to let python understand I want to separate these lists at this specific position?
favorite count: 0

http://stackoverflow.com/comment/87584268
has text: @Parseltongue Yes, if you want a DataFrame for each pair-wise combination you will probably need a loop to generate all of them. In that case, it might just be better to change how `correl` is created to make the separate `df`s in that part. Personally, I think having the large `overlap_df` is useful since it contains all the information in one place, but perhaps it's too big and not really what you want in the end.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50281242

tensorflow2.0
tags question: http://stackoverflow.com/q/50285097
tag name: tensorflow2.0
type: Tag

scons
tag name: scons
tags question: http://stackoverflow.com/q/50298132
tags question: http://stackoverflow.com/q/50306006
type: Tag

http://stackoverflow.com/q/50310730
answer count: 3
tagged with: algorithm
has answer: http://stackoverflow.com/a/50310839
upvote count: 3
has comment: http://stackoverflow.com/comment/87637481
has comment: http://stackoverflow.com/comment/87637815
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50310839
has comment: http://stackoverflow.com/comment/87637659
has answer: http://stackoverflow.com/a/50310871
downvote count: 0
accepted answer: http://stackoverflow.com/a/50310873
tagged with: python
has comment: http://stackoverflow.com/comment/87637499
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87637624
has answer: http://stackoverflow.com/a/50310873
has title: Can I keep new words in dictionary by matching key as prefix
has comment: http://stackoverflow.com/comment/87637679
has comment: http://stackoverflow.com/comment/87637588
tagged with: optimization
type: AnsweredQuestion
score: 3
has body: I have a dictionary say, stringToListDict = {'foo' : [], 'bar' : []} Now lets say we do +foofoo stringToListDict = {'foo' : ['foofoo'], 'bar' : []} +barbar stringToListDict = {'foo' : ['foofoo'], 'bar' : ['barbar']} +foobarbar stringToListDict = {'foo' : ['foofoo', 'foobarbar'], 'bar' : ['barbar']} +notMatchingAnyKey Simply discard this new string. As you can see the added string goes by matching keys as prefix. I can do this by traversing through each key one by one of the dictionary till I get a matching prefix. But is there any other elegant or efficient approach? You don't have to worry of edge scenarios like what would happen if : stringToListDict = {'foo' : ['foofoo'], 'foobar' : [], 'bar' : ['barbar']} then +foobarbar FYI, this is not an assignment.
has comment: http://stackoverflow.com/comment/87637635

http://stackoverflow.com/a/50371440
upvote count: 11
has body: Looking at the code and documentation you cannot do this 'out of the box'. But I do see the possibility described to make your own custom throttle based on one of the existing one's: from rest_framework.throttling import AnonRateThrottle class AnonTenPerTenMinutesThrottle(AnonRateThrottle): def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: &lt;allowed number of requests&gt;, &lt;period of time in seconds&gt; So we always return a rate for 10 request per 10 minutes. Args: string: rate to be parsed, which we ignore. Returns: tuple: &lt;allowed number of requests&gt;, &lt;period of time in seconds&gt; """ return (10, 600)
downvote count: 0
score: 11
type: Answer
answers question: http://stackoverflow.com/q/50370544

music21
type: Tag
tag name: music21
tags question: http://stackoverflow.com/q/50349301

http://stackoverflow.com/q/50354041
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87724455
type: UnansweredQuestion
has body: I am trying to write a dictionary to a csv file in python. I've tried nearly every tutorial that I could find but did not get a good result yet. I want to later edit that file in excel but it looks like this right now: My python code: s = file_name dict = App.get_running_app().get_widget_contents() with open(s, 'w') as f: writer = csv.writer(f) for row in dict.items(): writer.writerow(row) What I need is that the key is in column A, and the values are in column B. Furthermore each row should be used instead of every second row. It would be nice to remove the "," between the key and the value. I am very happy if someone could help me with this. Greetings, Finn
tagged with: python
has title: python: dictionary to .csv-file
has answer: http://stackoverflow.com/a/50354212
has answer: http://stackoverflow.com/a/50354083
score: 0
has comment: http://stackoverflow.com/comment/87724407

http://stackoverflow.com/comment/87620831
comment on: http://stackoverflow.com/q/50302102
score: 0
type: QuestionComment
has text: not all possible int values can be converted back to an character, what would you like to happen in this case? That character cannot be printed. You can ignore it if you want to.
type: Comment

http://stackoverflow.com/comment/87478610
comment on: http://stackoverflow.com/a/50230421
has text: Maybe you will have to go through the data and maintain a list or dictionary for those words then. Because regex also follows a pattern and can not work just on a random pattern.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87695980
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50326442
type: QuestionComment
has text: Usually the shell API just calls base `CreateProcess` for this, but how to pass a monitor handle in [`STARTUPINFO`](https://msdn.microsoft.com/en-us/library/ms686331) is only partly documented. It gets passed in `hStdOutput`, and `dwFlags` should contain the undocumented flag value `STARTF_HASSHELLDATA` (0x00000400). If this can work at all with the program (unlikely as that is), then in Python you can use `si = subprocess.STARTUPINFO()`; set `si.dwFlags = 0x400` and set `si.hStdOutput` to the monitor handle. Then pass this to `subprocess.Popen` as `startupinfo=si`.

http://stackoverflow.com/q/50268137
has answer: http://stackoverflow.com/a/50268782
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50268525
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-import
has title: Do I have to reload a module in python to capture changes?
tagged with: python
possible better answer: http://stackoverflow.com/a/50268782
tagged with: module
has answer: http://stackoverflow.com/a/50268525
has body: I am running python 3.6.4 (anaconda, spyder). Do I need to reload a user-defined module in order to capture the changes? For example, suppose I wrote the simple function and save it in test.py file: def plus5(x): return x + 5 Then in the IPython console I type import test as t and then I change the user-defined function to: def plus5(x): return x + 500 Then when I type in IPython console t.plus5(0) it returns 500 without re-importing or reloading the module first. If I change the function name from plus5 to something else then I have to re-import the module to see the change. But when I change the function statements then it automatically captures the changes without re-importing the module From the Python documentation: Note: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload() e.g. import importlib; importlib.reload(modulename).

http://stackoverflow.com/q/50347080
tagged with: django
has comment: http://stackoverflow.com/comment/87710519
tagged with: python
has comment: http://stackoverflow.com/comment/87710314
has comment: http://stackoverflow.com/comment/87716301
has body: I have a ChoiceField in a form and want to save its value in a model. The problem is that the form is never valid if the field is required. When I set required to False, the form is valid but does not contain any data - it's just blank. models.py: class CVSS(models.Model): av = models.CharField( max_length=10, null=True, ) forms.py: class CVSSForm(forms.ModelForm): AV = [ (u'N', u'Network'), (u'A', u'Adjacent'), (u'L', u'Local'), (u'P', u'Physical'), ] av = forms.ChoiceField( # required=False, widget=forms.RadioSelect(), choices=AV, ) class Meta: model = CVSS fields = ['av',] views.py: def edit(request, fid): cvss = get_object_or_404(CVSS, finding_id=fid) cvss_form = CVSSForm(instance=cvss) if request.method == 'POST': cvss_form = CVSSForm(request.POST, instance=cvss) if cvss_form.is_valid(): cvss_form.save() edit.html: {% include "dojo/form_fields.html" with form=cvss_form %} The form is rendered from form_fields.html: {% elif field|is_radio %} {% if field.auto_id %} {{ field.label }}{% if field.field.required%}*{% endif %} {% endif %} {% for choice in field %} {{ choice.tag }} {{ choice.choice_label }} {% endfor %} {% for error in field.errors %} {{ error }} {% endfor %} {% if field.help_text %} {% endif %} {% else %}
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50347459
has title: Django ChoiceField always invalid or empty
type: Question
has answer: http://stackoverflow.com/a/50347366
has comment: http://stackoverflow.com/comment/87715370
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87710726
tagged with: choicefield
has answer: http://stackoverflow.com/a/72548046

http://stackoverflow.com/comment/87746650
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50364314
type: Comment
has text: Is there an error line number?

http://stackoverflow.com/comment/87859696
has text: Hi Samu, thank you for you suggestion. I added a url for if it was just `account/$` but sadly this does not seem to fix the problem. This is as the slug is in the url, but it seems my view does not pick it up. Although if I remove the `slug` argument in my view I do get an error saying: `home() got an unexpected keyword argument 'slug'`, so I think something is going through.
type: Comment
comment on: http://stackoverflow.com/a/50368330
score: 0
type: AnswerComment

http://stackoverflow.com/a/50360363
type: AcceptedAnswer
has body: I meanwhile found my mistake: I had not yet specified the return statement of the method I used to generate the classinstance object, i. e. my code was def GetInstance(property): newclassinstance = myclass(property) classinstance = GetInstance("SomeProperty") Which when typing classinstance. will not suggest anything as PTVS can't know that classinstance is of type myclass until I add return newclassinstance to the GetInstance method.
answers question: http://stackoverflow.com/q/50339517
accepted answer of: http://stackoverflow.com/q/50339517
type: Answer
score: 0

http://stackoverflow.com/q/50283382
linked to: http://stackoverflow.com/q/47988796
type: Question
has comment: http://stackoverflow.com/comment/87583324
has comment: http://stackoverflow.com/comment/87618232
has answer: http://stackoverflow.com/a/65487452
answer count: 2
has comment: http://stackoverflow.com/comment/87583280
downvote count: 0
type: UnansweredQuestion
tagged with: visual-studio
has answer: http://stackoverflow.com/a/62992502
has body: I have a very simple program written but when I click start on the Visual Studio debugger nothing happens! Sorry total noob here. Working with python 3.6.5 32 bit for Windows. The program runs from the terminal just fine. def main(): print ("hello world!") if __name__ == "__main__": main()
tagged with: python
has comment: http://stackoverflow.com/comment/87618439
has comment: http://stackoverflow.com/comment/87593332
linked to: http://stackoverflow.com/q/47273900
favorite count: 0
has comment: http://stackoverflow.com/comment/87584286
has comment: http://stackoverflow.com/comment/87583273
score: 4
upvote count: 4
has title: Visual Studio code Debugger won’t start on my Python
tagged with: debugging
has comment: http://stackoverflow.com/comment/87618391

http://stackoverflow.com/comment/87674207
type: Comment
has text: But that's a hardware limitation, not a software limitation. It's the same way we describe python 3 ints (python 2 longs) as having infinite size. This is very common in computer science.
type: AnswerComment
comment on: http://stackoverflow.com/a/50328646
score: 0

http://stackoverflow.com/comment/87555207
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50260803
has text: Is this a publicly available web app? If so you can open up the devtools in your web browser and view the network traffic. You can inspect the actual urls that the app is getting its data from. If you are lucky this is an api that provides some way to fetch the data you want.
score: 0

http://stackoverflow.com/comment/87733853
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50358317
type: Comment
has text: Don't use exec here, better to use something like a dictionary.

http://stackoverflow.com/comment/87502686
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50242528
has text: You probably want `zip()`
score: 4

http://stackoverflow.com/a/50264792
has body: Use sys.stdin.read to control how many characters you're reading at a time: import sys a = sys.stdin.read(32) assert len(a) &lt;= 32 The assertion will never fire. Note: Be aware you may be cutting some integers off when specifying a size. For example if you do read(4) on input 12 3456 you may get 3 as the second number when it's actually 3456. Also pay attention to performance issues.
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/50264768
has comment: http://stackoverflow.com/comment/87584044
downvote count: 0
has comment: http://stackoverflow.com/comment/87583442

facebook-chatbot
tags question: http://stackoverflow.com/q/50270479
type: Tag
tag name: facebook-chatbot

http://stackoverflow.com/comment/87909308
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50447709
has text: You've beaten me by 20 minutes!! Updated the package and works as expected. Thank you

http://stackoverflow.com/a/50375828
type: Answer
answers question: http://stackoverflow.com/q/50374265
score: 0
has body: Correct answer from @jasonharper! For posterity, here's a deeper look of what's going on. The above disassembly shows the results of eval mode: &gt;&gt;&gt; list(compile('x + 2', '&lt;stdin&gt;', 'eval').co_code) [101, 0, 0, 100, 0, 0, 23, 83] The opcodes can be viewed with: &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.opname[101] 'LOAD_NAME' &gt;&gt;&gt; dis.opname[100] 'LOAD_CONST' &gt;&gt;&gt; dis.opname[23] 'BINARY_ADD' &gt;&gt;&gt; dis.opname[83] 'RETURN_VALUE' The two numbers following the opcode represent a 16-bit operand, though only the first byte is what we need here. So this corresponds to: LOAD_NAME 0 LOAD_CONST 0 BINARY_ADD RETURN_VALUE Those operands are indices to the compiled code object's variable names and constant pool, respectively. &gt;&gt;&gt; c = compile('x + 2', '&lt;stdin&gt;', 'eval') &gt;&gt;&gt; c.co_names ('x',) &gt;&gt;&gt; c.co_consts (2,) So far, this is what we have in the question. But in reality, executing Python code results in: &gt;&gt;&gt; list(compile('x + 2', '&lt;stdin&gt;', 'exec').co_code) [101, 0, 0, 100, 0, 0, 23, 1, 100, 1, 0, 83] &gt;&gt;&gt; dis.opname[1] 'POP_TOP' I.e., the result is discarded and a None is introduced as the return value. In interactive mode, we have: &gt;&gt;&gt; list(compile('x + 2', '&lt;stdin&gt;', 'single').co_code) [101, 0, 0, 100, 0, 0, 23, 70, 100, 1, 0, 83] &gt;&gt;&gt; dis.opname[70] 'PRINT_EXPR' The result is printed (via sys.displayhook) and a None becomes the actual return value. So the printing is introduced by the code generation phase, not by the VM.

http://stackoverflow.com/q/50378092
tagged with: jupyter-lab
upvote count: 8
answer count: 3
tagged with: odoo
has comment: http://stackoverflow.com/comment/101072770
tagged with: python
has title: How to load the Odoo Environment into a Jupyter Notebook?
tagged with: jupyter
has answer: http://stackoverflow.com/a/65369145
tagged with: jupyter-notebook
score: 8
type: Question
has answer: http://stackoverflow.com/a/78704282
has comment: http://stackoverflow.com/comment/101065896
type: UnansweredQuestion
has body: Odoo (ERP) Odoo is an all-in-one management software that offers a range of business applications that form a complete suite of enterprise management applications targeting companies of all sizes. Odoo is an all-in-one business software including CRM, website/e-commerce, billing, accounting, manufacturing, warehouse - and project management, and inventory. The Community version is the open source version while the Enterprise version supplements the Community edition with commercial features and services. Terminal Usually I launch a Python Terminal with the Odoo environment loaded like this: /odoo_path/odoo-bin --addons-path=/addons_path shell --config=/config_path/.odoo.conf -d database_name Inside the console I can call to self, and the environment variable is available (self.env). And I can run some commands over the connected database. If I want to do some fast tests this is very useful. But it is kind of inconvinient if I want to run some small scripts or test some code snippets. Jupyter Notebooks and Jupyter Lab are very good tools for that. Jupyter Jupyter is a project which produces browser-based interactive environments for programming, mathematics, and data science. It supports a number of languages via plugins ("kernels"), such as Python, Ruby, Haskell, R, Scala and Julia. Jupyter Notebook is the traditional and most stable application. JupyterLab has a new interface and is more suitable for working with larger projects consisting of multiple files. JupyterLab is in beta as of February 2018. (source: windows.net) Requests What I want to achieve is load the Odoo environment into a Jupyter Notebook and work with these code snippets instead of the simple Python Terminal. So I am wondering if anyone knows if this is doable or which would be a good place to start. Is there a better alternative? Is this a silly idea?
has answer: http://stackoverflow.com/a/65250562
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/50300737
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/50297255
has body: Yes; a small error in the loop for drawing the lines: #loops through in intervals of 0.1 for t in range(0, 11, 1): t = i/10 You have assigned t as the loop variable when it should be i. for t in range(0, 11, 1): ^ This shoud be i
upvote count: 3

http://stackoverflow.com/q/50315989
has title: How to extract rar files inside google colab
answer count: 7
has answer: http://stackoverflow.com/a/59505356
has answer: http://stackoverflow.com/a/61330686
favorite count: 0
has body: I have a dataset in google drive which I want to use in google colab.But I can't unrar the rar files by any means.So far I have tried installing python libraries and also ubuntu packages like "unrar ,rar ,unrar-free ,unar ,unp" and I just can't open the damn file.Here are the results of each command: !rar x data.rar RAR 5.40 Copyright (c) 1993-2016 Alexander Roshal 15 Aug 2016 Trial version Type RAR -? for help Extracting from meta-data.rar Cannot create meta-data/sample_submission.csv No such file or directory Cannot create meta-data/test.csv No such file or directory Cannot create meta-data/train.csv No such file or directory Cannot create directory meta-data Input/output error Total errors: 4 !unrar data.rar UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal Extracting from meta-data.rar Cannot create meta-data/sample_submission.csv No such file or directory Cannot create meta-data/test.csv No such file or directory Cannot create meta-data/train.csv No such file or directory Cannot create directory meta-data Input/output error Total errors: 4 !unp meta-data.rar RAR 5.40 Copyright (c) 1993-2016 Alexander Roshal 15 Aug 2016 Trial version Type RAR -? for help Extracting from meta-data.rar Cannot create meta-data/sample_submission.csv No such file or directory Cannot create meta-data/test.csv No such file or directory Cannot create meta-data/train.csv No such file or directory Cannot create directory meta-data Input/output error Total errors: 4 UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal Extracting from meta-data.rar Cannot create meta-data/sample_submission.csv No such file or directory Cannot create meta-data/test.csv No such file or directory Cannot create meta-data/train.csv No such file or directory Cannot create directory meta-data Input/output error Total errors: 4 Can't exec "file": No such file or directory at /usr/bin/unp line 419. Failed to detect file type of meta-data.rar. WARNING: There were errors while processing files! None…
has answer: http://stackoverflow.com/a/58589245
type: Question
score: 14
accepted answer: http://stackoverflow.com/a/58589245
tagged with: rar
tagged with: python
tagged with: google-colaboratory
has answer: http://stackoverflow.com/a/52800540
has answer: http://stackoverflow.com/a/65972091
has answer: http://stackoverflow.com/a/63555740
possible better answer: http://stackoverflow.com/a/63555740
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58570865
upvote count: 14
downvote count: 0

http://stackoverflow.com/comment/87581404
type: Comment
has text: I also have some problem reading in the text files. Should it rather be something like: f2 = open("File2.txt", 'r') d2 = {} for line in f2: fields = [s.rstrip() for s in line.strip().split("\t")]
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50281673

http://stackoverflow.com/q/50294025
upvote count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50294587
tagged with: visual-studio-code
type: UnansweredQuestion
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Debugging not working in Visual Studio Code with Python
tagged with: python
score: 4
has body: I'm fairly new to python and to date I've been using Komodo as my interpreter. I decided to try something more robust, so I installed Visual Studio Code version 1.23.1 and I'm running Python 3.6.4. When I run a basic script it runs properly, but I noticed in the debugger window none of the variables appear, in fact nothing appears. Not sure what I've done wrong. The debug is set to DEBUE Python: Current File.

http://stackoverflow.com/comment/87652780
comment on: http://stackoverflow.com/q/50318322
has text: Yes, but I doubt this will be more performant, I suspect it will be less performant
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50308649
has body: You are probably lacking an import statement, but nevertheless, referencing to User directly is typically not a good idea, since later, you might change the model you use for users. Like the documentation says, you should use the AUTH_USER_MODEL settings: from django.conf import settings from django.db import models class SomeModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL)
accepted answer of: http://stackoverflow.com/q/50308614
has comment: http://stackoverflow.com/comment/87633530
has comment: http://stackoverflow.com/comment/87634135
has comment: http://stackoverflow.com/comment/87634223
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50308614
has comment: http://stackoverflow.com/comment/87633437
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87636646
has text: Nicely noted. Question is if that is a mistake or intentional. My guess it is an error.
comment on: http://stackoverflow.com/a/50310269
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87768944
score: 0
has text: if you remove sorted from the printAll for, you get a different error :
comment on: http://stackoverflow.com/q/50376287
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87557442
type: Comment
comment on: http://stackoverflow.com/q/50269901
type: QuestionComment
score: 2
has text: Keras manages its own internal session and graph (you can get them from the [backend](https://keras.io/backend/) with `get_session()` and `get_session().graph`). In theory it should be possible to run a Keras model in another session for the same graph (e.g. `with tf.Session(graph=K.get_session().graph) as sess`, but you'd need to move over the variable values from one session to another and pick the placeholders and output nodes to call `sess.run` yourself... Is there any reason you not to use Keras internal session?

http://stackoverflow.com/q/50297291
tagged with: data-analysis
has answer: http://stackoverflow.com/a/50298065
type: Question
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50297694
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50297703
has title: Subtracting values across grouped data frames in Pandas
has answer: http://stackoverflow.com/a/50297694
has body: I have a set of IDs and Timestamps, and want to calculate the "total time elapsed per ID" by getting the difference of the oldest / earliest timestamps, grouped by ID. Data id timestamp 1 2018-02-01 03:00:00 1 2018-02-01 03:01:00 2 2018-02-02 10:03:00 2 2018-02-02 10:04:00 2 2018-02-02 11:05:00 Expected Result (I want the delta converted to minutes) id delta 1 1 2 62 I have a for loop, but it's very slow (10+ min for 1M+ rows). I was wondering if this was achievable via pandas functions? # gb returns a DataFrameGroupedBy object, grouped by ID gb = df.groupby(['id']) # Create the resulting df cycletime = pd.DataFrame(columns=['id','timeDeltaMin']) def calculate_delta(): for id, groupdf in gb: time = groupdf.timestamp # returns timestamp rows for the current id time_delta = time.max() - time.min() # convert Timedelta object to minutes time_delta = time_delta / pd.Timedelta(minutes=1) # insert result to cycletime df cycletime.loc[-1] = [id,time_delta] cycletime.index += 1 Thinking of trying next: - Multiprocessing
type: AnsweredQuestion
answer count: 3
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/50297703
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/88188358
type: Comment
has text: There, fixed the problem in my example. Enjoy!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50341645

http://stackoverflow.com/q/50380769
type: Question
has answer: http://stackoverflow.com/a/71283414
has body: I am pretty new to django and its ways. I am trying to create an autocomplete field for a form. My code is as below forms.py from django import forms class LeaveForm(forms.Form): leave_list = ( ('Casual Leave', 'Casual Leave'), ('Sick Leave', 'Sick Leave') ) from_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'style': 'width: 400px'})) start_date = end_date = forms.CharField(widget=forms.TextInput(attrs={'type': 'date', 'style': 'width: 175px'})) leave_type = forms.ChoiceField(choices=leave_list, widget=forms.Select(attrs={'style': 'width: 400px'})) comments = forms.CharField(required=True, widget=forms.Textarea(attrs={'style': 'width: 400px; height: 247px'})) def clean_from_email(self): data = self.cleaned_data['from_email'] if "@testdomain.com" not in data: raise forms.ValidationError("Must be @testdomain.com") return data What I want to achieve is that when an user types words into the "From Email" field the list of emails I have stored in an external DB should appear in the autocomplete list option. models.py from django.db import models class ListOfUsers(models.Model): emp_number = models.CharField(db_column='Emp_Number', primary_key=True, max_length=50, unique=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=40) # Field name made lowercase. supervisor = models.CharField(db_column='Supervisor', max_length=40) # Field name made lowercase. email = models.CharField(db_column='Email', max_length=50, blank=False, null=False, unique=True) # Field name made lowercase. class Meta: managed = False db_table = 'List of users' Any idea how this can be done ? Update : I started messing around with django-autocomplete-light and now able to get a reply from the autocomplete url. It looks like this {"results": [{"id": "user1@mydomain.com", "text": "user1@mydomain.com"}, {"id": "user2@mydomain.com", "text": "user2@mydomain.com"}, {"id": "user3@mydomain.com", "text": "user3@mydomain.com"}]} views.py class EmailAutocom…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/58851827
answer count: 3
accepted answer: http://stackoverflow.com/a/50613330
tagged with: autocomplete
has comment: http://stackoverflow.com/comment/87778916
has answer: http://stackoverflow.com/a/50613330
tagged with: python
tagged with: django-autocomplete-light
possible better answer: http://stackoverflow.com/a/71283414
favorite count: 0
upvote count: 14
has answer: http://stackoverflow.com/a/68679775
has comment: http://stackoverflow.com/comment/87797397
tagged with: django
score: 13
downvote count: 1
has title: how to create a autocomplete input field in a form using Django

http://stackoverflow.com/q/50234569
tagged with: python-requests
upvote count: 6
has comment: http://stackoverflow.com/comment/87487050
type: AnsweredQuestion
tagged with: python
favorite count: 0
type: Question
has title: What is the difference between requests, requests2, and requests3?
has answer: http://stackoverflow.com/a/50234791
accepted answer: http://stackoverflow.com/a/50234791
answer count: 1
downvote count: 0
has body: I use requests quite regularly. Recently I discovered there is also a requests2 and an upcoming requests3 While there's a page which briefly mentions what's coming in requests3, I've been unable to determine what requests2 is and why I'd use that over requests. I'm assuming the 2 means its a newer better version, maybe? Requests2 Has a better looking pypi.org page Looks like it has the same but older changes from requests Otherwise I could find no other information. Could someone explain the differences between requests and requests2 and for the sake of completeness requests3?
score: 6

http://stackoverflow.com/comment/87703620
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50342517
score: 2
has text: Tre setting an encoding Ex: `encoding='latin1'` or `encoding='iso-8859-1' `

http://stackoverflow.com/comment/87743300
has text: Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
comment on: http://stackoverflow.com/q/50363545
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50238512
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50238752
tagged with: virtualenv
tagged with: ubuntu
tagged with: tensorflow
favorite count: 0
has title: installing and configuring virtualenv on ubuntu
answer count: 3
tagged with: azure
has comment: http://stackoverflow.com/comment/87494602
score: 1
has comment: http://stackoverflow.com/comment/87494472
tagged with: python
has answer: http://stackoverflow.com/a/71109487
has comment: http://stackoverflow.com/comment/87494571
has answer: http://stackoverflow.com/a/50238767
linked to: http://stackoverflow.com/q/34694701
has body: I have installed virtualenv on my system using http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv according to these guidelines, the initial step is: $ sudo apt-get install python-pip python-dev python-virtualenv However, I do not want to touch my parent environment. The only reason I believe virtualenv might be of some help for my case is because I have some weird errors that point to python version inconsistencies. So my requirements are: virtualenv with e.g. python 3.5 tensorflow no influence on my parent environment ability to disable virtualenv with no side effects Is it doable how?
type: Question
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/118347661
type: Comment
score: 0
type: AnswerComment
has text: How would you correct that logits error that causes the model not to learn? Just to remove them?
comment on: http://stackoverflow.com/a/50320630

http://stackoverflow.com/comment/87607648
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50291471
has text: Hello, I tried your solution and I'm getting an error: "The model Character is abstract, so it cannot be registered with admin."

http://stackoverflow.com/q/50332764
linked to: http://stackoverflow.com/q/5189699
answer count: 3
has comment: http://stackoverflow.com/comment/87681761
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87681872
has comment: http://stackoverflow.com/comment/87681624
favorite count: 0
has comment: http://stackoverflow.com/comment/87684302
type: Question
has comment: http://stackoverflow.com/comment/87682061
has comment: http://stackoverflow.com/comment/87681595
has comment: http://stackoverflow.com/comment/87682579
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50336316
has comment: http://stackoverflow.com/comment/87681892
has body: How can you create a class attribute that will always contain the same list? It should always reference the same list although the contents of the list can be changed. The obvious solution is to use property. class Table(list): def filter(kwargs): """Filter code goes here.""" class db: _table = Table([1, 2]) table = property(lambda self: self._table) db.table.append(3) I would have assumed that db.table should return a list and that you should be able to append to this list. But no, this code throws an exception: AttributeError: 'property' object has no attribute 'append' How do you create a attribute that always refers to the same list? ILLUSTRATION: db.table = [x for x in db.table if x &gt; 2] db.filter(3) # This filter method got lost when reassigning the table in the previous line.
linked to: http://stackoverflow.com/q/1358711
has comment: http://stackoverflow.com/comment/87681673
has comment: http://stackoverflow.com/comment/87681804
tagged with: python
has comment: http://stackoverflow.com/comment/87682011
has answer: http://stackoverflow.com/a/50333153
has answer: http://stackoverflow.com/a/50333383
has title: Non-mutable list attribute
score: 3
has comment: http://stackoverflow.com/comment/87681728
has comment: http://stackoverflow.com/comment/87681578

http://stackoverflow.com/comment/131735907
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53310545
has text: Still working as of Python 3.11

http://stackoverflow.com/comment/87714508
type: AnswerComment
comment on: http://stackoverflow.com/a/50344381
has text: To add to this: If they *actually* ran `spacy.en.download` instead of `spacy download en` (and it's not a typo), this would indicate that they're using spaCy v1.6 or lower, before the models as Python packages were introduced. In this case, the model would have been installed in the `spacy/data` directory, also in the site packages. An easy way to find that location is to run `python -c "import spacy; print(spacy.__file__)"`.
type: Comment
score: 3

http://stackoverflow.com/comment/133728284
has text: `"console": "none"` is no longer an accepted input these days but you can output it to the terminal by setting it to `"console": "integratedTerminal"` instead.
comment on: http://stackoverflow.com/a/50382353
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87637073
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50310493
has text: That depends on the target language. If your target language is Japanese, then no British UTF-16 is probably not suitable. You have to choose the encoding based on the target language.

http://stackoverflow.com/comment/87602487
has text: I like it! Nice answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/50293008
score: 1
type: Comment

http://stackoverflow.com/comment/87675763
type: Comment
type: QuestionComment
has text: Ummmh... I'm sorry, but I don't quite understand what you mean. I'm weak in Python. Is there an example code?
score: 0
comment on: http://stackoverflow.com/q/50323693

http://stackoverflow.com/a/50274460
answers question: http://stackoverflow.com/q/50274372
type: Answer
upvote count: 1
downvote count: 0
has body: This is one approach. Using a simple iteration and enumerate Demo: mylist = [2,3,4,1,9,4] res = [] for i, v in enumerate(mylist): try: if mylist[i+1] &gt; v: res.append(mylist[i+1]) except IndexError: pass print(res) Output: [3, 4, 9]
score: 1

http://stackoverflow.com/q/50232369
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50232648
has comment: http://stackoverflow.com/comment/87482026
has comment: http://stackoverflow.com/comment/87482045
has comment: http://stackoverflow.com/comment/87482516
has comment: http://stackoverflow.com/comment/87482242
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87482352
score: 1
has comment: http://stackoverflow.com/comment/87482281
favorite count: 0
has body: when i try to create a post, it will show me this error Exception Type: AttributeError at /home/ Exception Value: 'HomeView' object has no attribute 'user' and my view.py is class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) @login_required def post(self, request): if request.method == 'POST': form = HomeForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('home:home') else: return redirect(reverse('home:home')) else: form = HomeForm() args = {'form': form} return render(request, self.template_name, args) Traceback: File "/home/zola/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/zola/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/zola/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/zola/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/zola/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/zola/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 22. if test_func(request.user): please help I've been missing for a long time. using this language. then help me with this error
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/87482320
tagged with: django
has title: class has no attributed user
tagged with: python
accepted answer: http://stackoverflow.com/a/50232648

http://stackoverflow.com/comment/105502590
has text: This answer copies code from another answer but is presented as if you wrote it. You should link to the original answer.
comment on: http://stackoverflow.com/a/50314256
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50230440
has comment: http://stackoverflow.com/comment/87479282
has comment: http://stackoverflow.com/comment/87478763
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50230847
has comment: http://stackoverflow.com/comment/87479027
tagged with: python
has body: import random random.sample(range(1, 100), 10) df = pd.DataFrame({"A": random.sample(range(1, 100), 10), "B":random.sample(range(1, 100), 10), "C":random.sample(range(1, 100), 10)}) df["D"]="need_to_calc" df I need the value of Column D, Row 9 to equal the average of the block of cells from rows 6 through 8 across columns A through C. I want to do this for all rows. I am not sure how to do this in a single pythonic action. Instead I have hacky temporary columns and ugly nonsense. Is there a cleaner way to define this column without temporary tables?
has answer: http://stackoverflow.com/a/50231121
score: 2
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 1
favorite count: 0
type: Question
has title: Rolling average across several columns and rows

http://stackoverflow.com/comment/130532269
type: AnswerComment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: Comment
comment on: http://stackoverflow.com/a/73885800
score: 0

http://stackoverflow.com/comment/87575317
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50278847
has text: @skimchi1993 see my update. It grabs regions of the url based on of indices, and maintains `/`
type: Comment

http://stackoverflow.com/comment/87490880
type: QuestionComment
has text: Added responses to your questions Federico in my initial post
comment on: http://stackoverflow.com/q/50236505
type: Comment
score: 0

http://stackoverflow.com/a/50299165
has body: import concurrent.futures as futures Allows you to reference the module under the futures namespace in your code (as opposed to concurrent.futures without the as syntax). However, the typing is mostly redundant--you're importing something and declaring its name to be the exact same thing. The standard syntax for this type of import is the from &lt;package&gt; import &lt;module&gt;. The salient point about your question is that the as syntax is mainly to support multiple imports of the same name without clobbering each other. For example. from concurrent import futures from other.module import futures as my_futures Anything else and you are abusing the as syntax and to me would be considered anti-pattern, because the language provided you a correct way to do what you wanted.
upvote count: 1
answers question: http://stackoverflow.com/q/50299143
has comment: http://stackoverflow.com/comment/87615139
has comment: http://stackoverflow.com/comment/87615130
type: Answer
score: -1
downvote count: 2

http://stackoverflow.com/comment/87657145
has text: When I plot each histogram, add up all the frequencies and divide by 4, I don't get the average frequency I should see on the averaged histogram for each bin.
score: 0
comment on: http://stackoverflow.com/a/50320378
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87725705
type: QuestionComment
comment on: http://stackoverflow.com/q/50354482
score: 1
has text: Meanwhile, if you want something cleverer than “brute force” always searching every string: if you can isolate the rule used in your source text (like italics with two or more capitals in one sentence), you can use that. If, say, it has an acceptable number of false negatives but too many false positives, you can do a hybrid that applies the rule, then filters the positives by searching the source. Or maybe a fuzzy rule that quantifies how likely it is to be a book title based on format, then filter the borderline ones. And so on.
type: Comment

http://stackoverflow.com/q/50278029
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/60208567
has answer: http://stackoverflow.com/a/77584070
has comment: http://stackoverflow.com/comment/87591416
tagged with: pycharm
tagged with: pyd
has comment: http://stackoverflow.com/comment/87573086
downvote count: 0
possible better answer: http://stackoverflow.com/a/55019719
score: 19
has comment: http://stackoverflow.com/comment/87579384
has answer: http://stackoverflow.com/a/55019719
favorite count: 0
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/68709215
has comment: http://stackoverflow.com/comment/87573379
has title: How to import a .pyd file as a python module?
has body: I am using PyCharm. I have a python script in the following location: C:\Users\XYZ\PycharmProjects\Project1\playground.py playground.py only has a line of code as shown below: import PyTbl In the Project1 folder there's another file: C:\Users\XYZ\PycharmProjects\Project1\PyTbl.pyd When I run the Python script playground.py I get the following error: ImportError: numpy.core.multiarray failed to import Traceback (most recent call last): File "C:/Users/XYZ/PycharmProjects/Project1/playground.py", line 1, in &lt;module&gt; import PyTbl SystemError: initialization of PyTbl raised unreported exception If I hover my mouse over the line of Python code in playground.py in the PyCharm editor I get the following error message: "No module named PyTbl" Any idea how should I import a .pyd file into a Python script?
tagged with: windows
tagged with: python
accepted answer: http://stackoverflow.com/a/60208567

http://stackoverflow.com/comment/87484967
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50233670
has text: Assume... But I see this Error... "ValueError: cannot reindex from a duplicate axis".. Don't add to df.. Can you help me again? Thans jezrael.

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/50368883
tag name: google-oauth
tags question: http://stackoverflow.com/q/50280198
tags question: http://stackoverflow.com/q/50239268
tags question: http://stackoverflow.com/q/50261442

http://stackoverflow.com/comment/87570777
comment on: http://stackoverflow.com/q/50273261
type: Comment
type: QuestionComment
score: 0
has text: What are `X` and `Y`? What does the resulting `csv` file look like? The `csv` format is just numbers (or strings) separated by delimiters. The are `numpy` functions for writing and reading `csv` - `np.savetxt` and `np.loadtxt`. But they work best with simple 2d numeric arrays. There also binary save methods like `np.save` and `np.load`.

http://stackoverflow.com/q/50334091
has body: I have a numpy array of shape, say, (1000, 80) and I want to convert it to (100, 40, 2). You can think of it as having 1000 observations where the first 40 columns refer to a specific feature across 40 days and the next 40 columns to a 2nd feature across the same 40 days. So, I want to the 2nd dimension to be the 40 days while the 3rd should be the values of these two features for each day. Here's a simple example with what I tried: import numpy as np data = [[11, 22, 33, 44], [55, 66, 77 ,88], [99, 100, 101, 102]] data = np.array(data) # This works but I have to manually do it for every day np.c_[data[:, ::2], data[:, 1::2]].reshape((3, 2, 2)) # This does not work np.c_[data[:, i::2] for i in range(2)].reshape((3, 2, 2)) Desired output: array([[[ 11, 33], [ 22, 44]], [[ 55, 77], [ 66, 88]], [[ 99, 101], [100, 102]]])
favorite count: 0
type: Question
tagged with: numpy
has title: How to reshape numpy array keeping each nth element
tagged with: python
has answer: http://stackoverflow.com/a/50334156
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50334156

http://stackoverflow.com/q/50344429
type: UnansweredQuestion
type: Question
has body: I'm trying to write an information in csv file and get it (in order to check if it was written correctly) after pressing a button, however, I get instead information from PutOnShelfScreen1 class (True or False depending on the location of widget). I am kind of stuck in my attempts to fugure out where I am wrong. Here is my code. from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty import csv Builder.load_string(''' &lt;Sample@Image&gt;: size: self.size allow_stretch: False keep_ratio: False do_rotation: False &lt;PutOnShelfScreen1&gt;: canvas: Rectangle: source: 'BackForGame113.png' size: self.size pos: self.pos BoxLayout: orientation: 'horizontal' spacing: 30 padding: [10, 150, 10, 10] Button: id: Tools background_color: [63, 191, 63, 0.3] text: '' Button: id: Transportation background_color: [63, 191, 63, 0.3] text: '' Button: id: Furniture background_color: [63, 191, 63, 0.3] text: '' FloatLayout: Button: id: Next pos_hint: {'x': 0.8, 'y': 0.9} size_hint: .2, .1 background_color: [63, 191, 63, 0.3] text: '&gt;' on_press: root.DataBase(database) StencilView: id: armchair ScatterPlane: pos: 500, 500 size: my_image2.size Image: id: my_image2 source: 'path\\image.png' on_touch_up: root.Count(Furniture, Tools, Transportation, armchair) ''') data = ['Bla', '6'] class PutOnShelfScreen1(Screen): def Count(self, Transportation, Furniture, Tools, armchair): Transportation = self.ids.Transportation Furniture = self.ids.Furniture Tools = self.ids.Tools armchair = self.ids.my_image2.parent i = 0 if (armchair.collide_widget(Furniture)) is True: i += 1 print(armchair.collide_widget(Furniture)) class DataBase(): database = ObjectProperty def __init__(self, i, **kwargs): super().__init__(**kwargs) self.data = data.append(i) self.database = 'results.csv' def Table(self): with open('результаты.csv', 'w') as database: wr = csv.writer(database, delimiter=' ', quoting=csv.QUOTE_MINIMA…
has title: Referencing csv file in kv
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/87710663
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/87728621
score: 0
answer count: 0

http://stackoverflow.com/comment/87785252
comment on: http://stackoverflow.com/q/50384348
has text: My next step would be to `print sys.path` in the three cases to see the differences.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50364799
downvote count: 0
has comment: http://stackoverflow.com/comment/88171864
score: 3
has body: You can use boto3 for accessing any services of Amazon.
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/50364766
has comment: http://stackoverflow.com/comment/87747068

http://stackoverflow.com/a/50333170
has comment: http://stackoverflow.com/comment/87689910
has comment: http://stackoverflow.com/comment/87688334
has comment: http://stackoverflow.com/comment/87689891
has comment: http://stackoverflow.com/comment/87688266
answers question: http://stackoverflow.com/q/50321799
type: Answer
upvote count: 1
has body: In below line you should set your own project project_id = 'bigquery-public-data' so it will be as project_id = 'your_project' And in query itself you shoud add project as below query_job = client.query(""" SELECT * FROM `bigquery-public-data.new_york.tlc_yellow_trips_2016` LIMIT 1000""")
has comment: http://stackoverflow.com/comment/87691962
has comment: http://stackoverflow.com/comment/87692031
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87691944

http://stackoverflow.com/comment/87726481
has text: @MatthiasFripp Just to confirm from the output of your modified code the file location for 'nails' and 'pins' would be different right and not same(/tmp/data.txt)? Again to clarify the file location should be picked for those files which has CommonChar lines in them with unique second argument (pins or nails or xyz)....
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50259904
type: Comment

http://stackoverflow.com/comment/87487319
comment on: http://stackoverflow.com/q/50234922
type: QuestionComment
has text: why does 11 correspond to first (1), second (2) and forth (8)? Because 1+2+8 = 11?
type: Comment
score: 0

http://stackoverflow.com/a/50262471
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87617641
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87608113
has body: You forgot to return the wrapper from the decorator. It should be: class Metaclass(type): def __new__(self, name, bases, attrs): for k, v in attrs.iteritems(): if isinstance(v, types.FunctionType): attrs[k] = self.decorator(v) return super(Metaclass, self).__new__(self, name, bases, attrs) @classmethod def decorator(cls, func): def wrapper(*args, **kwargs): print(func.__name__) return wrapper You can now use the metaclass: &gt;&gt;&gt; class TestClass(object): __metaclass__ = Metaclass def foo(self): return "bar" &gt;&gt;&gt; t = TestClass() &gt;&gt;&gt; x = t.foo() foo &gt;&gt;&gt; print x None The method has been correctly be replaced by the wrapper. In you previous (now deleted) question you asked for print "this method is from Testclass". You can simply pass the class name to the decorator: class Metaclass(type): def __new__(self, name, bases, attrs): for k, v in attrs.iteritems(): if isinstance(v, types.FunctionType): attrs[k] = self.decorator(v, name) return super(Metaclass, self).__new__(self, name, bases, attrs) @classmethod def decorator(cls, func, name): def wrapper(self, *args, **kwargs): print "%s defined in %s called from %s instance" % (func.__name__, name, self.__class__.__name__) return func(self, *args, **kwargs) return wrapper You obtain now: &gt;&gt;&gt; class TestClass(object): __metaclass__ = Metaclass def foo(self): return "bar" &gt;&gt;&gt; t = TestClass() &gt;&gt;&gt; x = t.foo() foo defined in TestClass called from TestClass instance &gt;&gt;&gt; print x bar
answers question: http://stackoverflow.com/q/50262312
type: Answer
accepted answer of: http://stackoverflow.com/q/50262312

http://stackoverflow.com/q/50276304
type: UnansweredQuestion
tagged with: flask
has comment: http://stackoverflow.com/comment/87569303
linked to: http://stackoverflow.com/q/10805535
tagged with: http://stackoverflow.com/tag/html
has title: Flask select form not sending full option value in request
has comment: http://stackoverflow.com/comment/87570244
has comment: http://stackoverflow.com/comment/87569772
tagged with: python
duplicate of: http://stackoverflow.com/q/10805535
has body: I have a select field in a form that is populated with values based on column names in an external table. &lt;select name="joincolumn1" form ="form1" required&gt; {% for option in options['tempTable'] %} &lt;option value = {{option}}&gt;{{option}}&lt;/option&gt; {% endfor%} &lt;/select&gt; The issue is: whenever there is a option that has more than one word The request won't send the full value. If the selected value is "hostname" it works just fine. If it is "host name" the value comes back as "host" print(request.args['joincolumn1']) not the full name of the selected value.
type: Question
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87571666

http://stackoverflow.com/a/50646225
answers question: http://stackoverflow.com/q/50307820
has body: import tkinter from tkinter import filedialog from tkinter import * from tkinter import messagebox from tkinter.filedialog import askdirectory import os import matplotlib.pyplot as plt import skimage.external.tifffile as tiff import pandas as pd from pandas import DataFrame import numpy as np def load_images_from_folder(folder): images=[] for filename in os.listdir(folder): if any([filename.endswith(x) for x in ['.tif']]): img=tiff.imread(os.path.join(folder, filename)) if img is not None: images.append(img) return images tkinter.Tk().withdraw() dirname = askdirectory(initialdir="/", title='Please select a directory') os.chdir(dirname) data = pd.DataFrame([]) ratiodata = [] foldernames = [] for folder in os.listdir(dirname): if not folder.endswith('.xlsx'): images=load_images_from_folder(folder) green=[image[..., 1].mean() for image in images] red=[image[..., 0].mean() for image in images] ratios= [img[..., 1].mean() / img[..., 0].mean() for img in images] #PLOTS temp = pd.DataFrame({folder + " ratios" : ratios}) data = pd.concat([data,temp],axis=1) data.to_excel('test.xlsx', sheet_name='sheet1')
score: 0
type: Answer

http://stackoverflow.com/comment/87649734
has text: Have you tried anything yet? You should look into `Threading` and `multiprocessing` modules
score: 0
comment on: http://stackoverflow.com/q/50316978
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50296384
has body: I downloaded and installed TensorFlow 1.8.0 and TensorFlow-gpu 1.8.0 from the PyCharm package manager after installing CUDA 9.0 and cuDNN 7.0 as was instructed on the TF and NVIDIA websites so that I could use my laptop's GPU. However, whenever I try to import TensorFlow from PyCharm, it throws the following error: ImportError: Could not find 'cudnn64_7.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and this DLL is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 7 from this URL: https://developer.nvidia.com/cudnn The directory containing cudnn64_7.dll is indeed in the PATH environment variable. I am new to PyCharm, but I read on another post that adding the path to PyCharm's environment variable could be the problem, so I tried that: But this did not work either. I know all of the libraries and dependencies are working because I can import TensorFlow just fine from the command prompt. In fact, within my computer, I made a different user account and used PyCharm there to import TensorFlow and once again it worked fine. I suspect it has something to do with the interpreter that my PyCharm is using, because that is the only difference between the two user accounts. On the user account that works I had not previously installed Anaconda3, whereas on the user account that does not work I had, and its respective PyCharm is using the interpreter located in an Anaconda3 file. How can I fix this?
tagged with: python
has answer: http://stackoverflow.com/a/57223041
tagged with: pycharm
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87616607
has title: Cannot import TensorFlow from PyCharm
has comment: http://stackoverflow.com/comment/87619294
tagged with: tensorflow
type: Question
score: 0

http://stackoverflow.com/comment/87638033
type: QuestionComment
comment on: http://stackoverflow.com/q/50310920
has text: Please give us text in text, not in screenshots and photos.
score: 1
type: Comment

http://stackoverflow.com/a/50319866
has comment: http://stackoverflow.com/comment/87656013
score: 3
has comment: http://stackoverflow.com/comment/87655518
accepted answer of: http://stackoverflow.com/q/50319824
has comment: http://stackoverflow.com/comment/87655920
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87655636
has comment: http://stackoverflow.com/comment/87655865
answers question: http://stackoverflow.com/q/50319824
has comment: http://stackoverflow.com/comment/87656653
has comment: http://stackoverflow.com/comment/87655451
has comment: http://stackoverflow.com/comment/87656163
has body: Try using the regular expression like this: df.Description = df.Description.str.replace(r'[\d#\-\*]', '') This gives 0 A&amp;W MONTREAL QC 1 ahi DOLLARAMA MONTREAL QC 2 PC PAYMENT FROM Name: foo, dtype: object
downvote count: 0
type: Answer

http://stackoverflow.com/a/50278904
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/87575101
has comment: http://stackoverflow.com/comment/87574560
type: Answer
has body: You can achieve this with annotations. This allows you to write any text you want on the chart and reference it to your data. You can also control where the text appears using position anchors or by applying an additional calculation on top of the x and y data. For example: x_data = [1, 2, 3, 4] y_data = [10, 11, 12, 13] z_data = [40, 60, 80, 100] annotations = [ dict( x=x, y=y, text='' if 4 &gt; x &gt; 1 else z, # Some conditional to define outliers showarrow=False, xanchor='center', # Position of text relative to x axis (left/right/center) yanchor='middle', # Position of text relative to y axis (top/bottom/middle) ) for x, y, z in zip(x_data, y_data, z_data) ] trace0 = go.Scatter( x=x_data, y=y_data, mode='markers', marker=dict( size=z_data, ) ) data = [trace0] layout = go.Layout(annotations=annotations) py.iplot(go.Figure(data=data, layout=layout), filename='bubblechart-size') Edit If using cufflinks, then the above can be adapted slightly to: bubbles_to_annotate = df[(df['avg_pos'] &lt; 2) | (df['avg_pos'] &gt; 3)] # Some conditional to define outliers annotations = [ dict( x=row['avg_pos'], y=row['avg_neg'], text=row['subreddit'], showarrow=False, xanchor='center', # Position of text relative to x axis (left/right/center) yanchor='middle', # Position of text relative to y axis (top/bottom/middle) ) for _, row in bubbles_to_annotate.iterrows() ] df.iplot(kind='bubble', x='avg_pos', y='avg_neg', size='counts', text='subreddit', xTitle='Average Negative Sentiment', yTitle='Average Positive Sentiment', annotations=annotations, filename='simple-bubble-chart') You will still need to define the annotations since you need a conditional argument. Then pass this directly to cufflinks via annotations.
accepted answer of: http://stackoverflow.com/q/50277856
upvote count: 4
answers question: http://stackoverflow.com/q/50277856

multiclass-classification
tags question: http://stackoverflow.com/q/50282420
tag name: multiclass-classification
type: Tag

http://stackoverflow.com/comment/87662474
type: QuestionComment
has text: @user202729 At the risk of going down a rabbit hole... filter out all string literals too. :P Hopefully the code OP is trying to parse isn't any more convoluted than that.
score: 0
comment on: http://stackoverflow.com/q/50323357
type: Comment

http://stackoverflow.com/comment/87741131
type: Comment
has text: tensorflow has tf.gather_nd. Is there not an analog to numpy?
type: AnswerComment
comment on: http://stackoverflow.com/a/50362288
score: 1

http://stackoverflow.com/comment/87760857
comment on: http://stackoverflow.com/q/50372272
type: QuestionComment
has text: `df['b'] = None` ?
score: 1
type: Comment

http://stackoverflow.com/a/50286683
has body: Pipeline is used to chain sequential data transformation models followed last by the classifier / regressor. Something like first converting the text to numbers using TfidfVectorizer and then training the classifier. pipe = Pipeline([('vectorizer',TfidfVectorizer()), ('classifier', RandomForestClassifier())]) For only a single class, no need of Pipeline. Here in your code, its used as a placeholder, so that the parameters can be used by using the 'classifier' prefix. And the classifier itself can be substituted from the params.
answers question: http://stackoverflow.com/q/50272416
type: Answer
has comment: http://stackoverflow.com/comment/92765936
score: 0
has comment: http://stackoverflow.com/comment/92677465

http://stackoverflow.com/comment/87723191
comment on: http://stackoverflow.com/a/50352719
type: Comment
type: AnswerComment
has text: Actually, I forgot. You don't need the `dropna=False` if you use `fill_value=0`. `df.unstack(fill_value=0).stack()`
score: 1

http://stackoverflow.com/a/50326081
score: 0
has body: Here is a skeleton for your app. library(shiny) ui &lt;- basicPage( textInput("description", label = "Enter the Description:"), textInput("region", label = "Enter the Region:"), verbatimTextOutput("txtoutput") ) server &lt;- function(input, output) { output$txtoutput &lt;- renderPrint({ print(paste("description: ", input$description, "and region: ", input$region)) }) } shinyApp(ui, server) I dont know exactly how you want to combine R/shiny with python and where/how the input from "description" and "region" are used in the python code. Anyway, you might want to look at this package - rPython. Or you further explain, what exactly you are trying to achieve.
answers question: http://stackoverflow.com/q/50266675
type: Answer

http://stackoverflow.com/comment/87640463
comment on: http://stackoverflow.com/a/50304743
type: Comment
has text: Then call map compose with a lambda func. See my edit.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/110250769
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50286093
has text: @Jivan and also this: https://stackoverflow.com/questions/18310668/is-freeing-handled-differently-for-small-large-numpy-arrays

http://stackoverflow.com/q/50304415
score: 2
type: AnsweredQuestion
upvote count: 2
downvote count: 0
has body: I am running a python script on OSX to upload video file (single_file) to YouTube: # define recording date as date of file modification # https://developers.google.com/youtube/v3/docs/videos#resource recordingDate = datetime.fromtimestamp(os.path.getctime(single_file)).isoformat("T")+"Z" # define video title as file name filename, file_extension = os.path.splitext(os.path.basename(single_file)) try: initialize_upload(youtube, args, single_file, title, recordingDate) except HttpError, e: print " An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) in some cases it works well, but in others Google returns the following error - Invalid value for: Invalid format: \"2017-09-22T22:50:55Z\" is malformed at \"Z\" How should I fix it to get correct date from the file? YouTube expects the value in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
answer count: 1
accepted answer: http://stackoverflow.com/a/50431773
tagged with: youtube-api
has answer: http://stackoverflow.com/a/50431773
favorite count: 0
type: Question
has title: How to get date in correct format for YouTube upload?
has comment: http://stackoverflow.com/comment/87869775
tagged with: datetime
tagged with: python
tagged with: datetime-format
has comment: http://stackoverflow.com/comment/87870572

http://stackoverflow.com/q/50282200
type: Question
has body: I have a case where I'd like to automatically run a common function, check_upgrade(), for most of my click commands and sub-commands, but there are a few cases where I don't want to run it. I was thinking I could have a decorator that one can add (e.g. @bypass_upgrade_check) for commands where check_upgrade() should not run. I was hoping for something like (thanks Stephen Rauch for the initial idea): def do_upgrade(): print "Performing upgrade" def bypass_upgrade_check(func): setattr(func, "do_upgrade_check", False) return func @click.group() @click.pass_context def common(ctx): sub_cmd = ctx.command.commands[ctx.invoked_subcommand] if getattr(sub_cmd, "do_upgrade_check", True): do_upgrade() @bypass_upgrade_check @common.command() def top_cmd1(): # don't run do_upgrade() on top level command pass @common.command() def top_cmd2(): # DO run do_upgrade() on top level command pass @common.group() def sub_cmd_group(): pass @bypass_upgrade_check @sub_cmd.command() def sub_cmd1(): # don't run do_upgrade() on second-level command pass @sub.command() def sub_cmd2(): # DO run do_upgrade() on second-level command pass Unfortunately, this only works for the top-level commands, since ctx.invoked_subcommand refers to sub_cmd_group and not sub_cmd1 or sub_cmd2. Is there a way to recursively search through sub-commands, or perhaps using a custom Group to be able to achieve this functionality with both top-level commands as well as subcommands?
has title: Click: how do I apply an action to all commands and subcommands but allow a command to opt-out?
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50284146
accepted answer: http://stackoverflow.com/a/50284146
tagged with: python-click
linked to: http://stackoverflow.com/q/50263363
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/50309299
has comment: http://stackoverflow.com/comment/87634733
answer count: 1
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/50309471
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50309471
has body: I am trying to find the strings that matches all patterns. Code: import re mail_li = ['lokesh.g@uni-passau.de', 'lokesh dot gat uni-passau dot de', 'lokesg.g(at)uni-passau.de', 'lokesh.g(at) uni-passau.de', 'onefullword@gw.uni-passau.de', 'lokesh(dot) g(at) uni-passau (dot) de', '@laskdjak'] regex = r"(de$)(@)" for i in mail_li: if(re.findall(regex,i)): print(i) I want to check all the conditions like: @ symbol or at or (at) dot or .de de at end I tried to write regex but its not working properly. Can someone help?
has comment: http://stackoverflow.com/comment/87634533
tagged with: python
tagged with: regex
has title: matching many patterns in single strings
has comment: http://stackoverflow.com/comment/87634849
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50335389
tagged with: python
has title: Count number of sequence (not duplicated)
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50335563
accepted answer: http://stackoverflow.com/a/50335638
has answer: http://stackoverflow.com/a/50335638
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50335563
has body: I actually have a multifasta file such this: &gt;seqA_0042_0035 AGGACCATGA &gt;seqB_0035_0042 ATGGATGGAGGAGATG &gt;seqC_0042_0035 AGGATGGAGGATAG &gt;seqA_0042_0035 ATGGAGAGAG &gt;seqD_0042_0035 ATTGGGAA &gt;seqC_0035_0042 ATGGGAGAGAAGA &gt;seqA_0042_0035 And I simply would like to count how many sequences (with ID name) I have BUT only count once if I have a seqA for exemple, even if it appears twice, I want to keep juste once. The _number_number does not matter, they change all the time. For this exemple I would have as output: number of sequence: 4 Thank you :)

http://stackoverflow.com/q/50343561
has comment: http://stackoverflow.com/comment/87753165
type: UnansweredQuestion
tagged with: digit
has comment: http://stackoverflow.com/comment/87703020
tagged with: python
linked to: http://stackoverflow.com/q/5676646
score: 0
tagged with: numbers
answer count: 0
duplicate of: http://stackoverflow.com/q/5909873
has body: I have this Partition 0 | 0 | 0 | 4 Partition 1 | 4 | 4 | 4 Partition 2 | 8 | 8 | 8 Partition 3 | 16 | 16 | 16 Partition 4 | 32 | 32 | 32 I want to do this Partition 0 | 0 | 0 | 4 Partition 1 | 4 | 4 | 4 Partition 2 | 8 | 8 | 8 Partition 3 | 16 | 16 | 16 Partition 4 | 32 | 32 | 32 Below is my Python 3 code, summarized. Where a,b,c,d are appropriate ints. for i in range(5) print(("Partition %d | %d | %d | %d") % (a, b, c, d)) Basically, I want that space in between | | to be always the same, no matter the digit. Is there any way to achieve this simply using formatting perhaps? I can think of achieving this using string formatting and adding/subtracting spaces depending on the number of digits but that sounds way too complicated. I tried searching, but I'm stil learning so I don't know what terms I need to use to describe my problem. If you could refer to me to a relevant link to read that will be great as well.
tagged with: string
linked to: http://stackoverflow.com/q/5909873
type: Question
has title: How to print a number so it takes up exactly same space regardless of its number of digits?
tagged with: format
has comment: http://stackoverflow.com/comment/87702987

http://stackoverflow.com/q/50366333
tagged with: mysql
tagged with: jupyter-notebook
type: Question
has title: I cannot print correctly character from MySQL with pyodbc
has comment: http://stackoverflow.com/comment/87784929
has body: I use pyodbc to connect MySQL, and successful put some chinese data to MySQL but I can't print it out for correct character In[1]: import pyodbc cn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 ANSI Driver}; SERVER=localhost; PORT=3306;DATABASE=db; UID=root; PASSWORD=******;OPTION=3;CHARSET=UTF8;") cn.setencoding(encoding='utf-8') cursor = cn.cursor() In[2]: cursor.execute("insert into tc_lite values(2018, 05 ,06 ,0 ,0 ,'中文','測試',127, 110)") cursor.execute("select * from tc_lite;") cursor.fetchall() out[2]: [(2018, 5, 6, 0, 0, '銝剜?', '皜祈岫', 127.0, 110.0)] but when I use pymysql to connect, it can show the correct character In[3]: conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='******',db="trydb", charset='utf8') cursor = conn.cursor() In[4]: cursor.execute("select * from tc_lite;") cursor.fetchall() out[4]: ((2018, 5, 6, 0, 0, '中文', '測試', 127.0, 110.0),) If I want to use pyodbc, how can I fix it to show like pymysql's output I work on win7, python 3.6.1, pyodbc 4.0.16, Jupyter Notebook 5.5.0
has comment: http://stackoverflow.com/comment/87758150
has answer: http://stackoverflow.com/a/50388062
tagged with: python
tagged with: pyodbc
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50388062
score: 0
answer count: 1

http://stackoverflow.com/a/53077941
score: 0
has body: i had same problem when using LSTMBlockFusedCell(). the solution is in https://github.com/tensorflow/tensorflow/issues/23369 # for LSTMBlockFusedCell(), https://github.com/tensorflow/tensorflow/issues/23369 tf.contrib.rnn # restore meta graph meta_file = args.restore + '.meta' loader = tf.train.import_meta_graph(meta_file, clear_devices=True) ...
answers question: http://stackoverflow.com/q/50298058
type: Answer

http://stackoverflow.com/q/50318132
tagged with: pygame
has comment: http://stackoverflow.com/comment/87652802
type: Question
score: 0
has body: After a long time trying to install pygame for 2.7 it finally installs and I now have it downloaded, but there is now the problem that it keeps not responding after a couple seconds of being open. Any answer will be appreciated, the code that I have so far is just. import pygame pygame.init() pygame.display.set_mode((640,480)) so I need some help please.
answer count: 1
has title: pygame window keeps not responding
tagged with: python
accepted answer: http://stackoverflow.com/a/50318697
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50318697

http://stackoverflow.com/comment/87768757
comment on: http://stackoverflow.com/a/50374273
has text: here are steps @FlameDra -- 1 )Hover the cursor over the element and right click mouse. 2) Select ‘Inspect Element’. 3) See the highlighted element code. 4) Right click on the highlighted code. 5) Select ‘Copy CSS Path’
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87543835
score: 0
comment on: http://stackoverflow.com/q/50262856
type: Comment
type: QuestionComment
has text: I'm assuming your actual lines of code are more complicated than just printing different things?

http://stackoverflow.com/q/50315792
has comment: http://stackoverflow.com/comment/87647582
tagged with: python
tagged with: plot
score: 0
tagged with: differential-equations
tagged with: matplotlib
answer count: 1
has body: I want to plot the solution of my differential equation but I got this: 'ValueError: x and y must have same first dimension, but have shapes (360,) and (1,)' When I write _plt.plot(t,final[:1])_ I got 'Equality object is not subscriptable' statement. Here is my code: import numpy as np import matplotlib.pyplot as plt from sympy.abc import * import sympy as sy L= float(input('L:')) R= float(input('R:')) v=220*sy.sqrt(2) i=sy.Function('i') q=sy.dsolve(sy.Eq(sy.Derivative(i(t)*L,t)+i(t)*R,v*sy.sin(t)),i(t)).evalf() constant=sy.solve(q.subs(i(t),0),dict=True) t=np.linspace(0,360,360) final=q.subs(constant[0]).evalf() plt.plot(t,final) plt.show() What should I do?
has comment: http://stackoverflow.com/comment/87656287
upvote count: 1
downvote count: 1
has title: How can I plot a differential equation in python?
favorite count: 0
has answer: http://stackoverflow.com/a/50318262
type: Question
tagged with: sympy
type: UnansweredQuestion

http://stackoverflow.com/comment/87585754
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50273699
has text: Fix it! Thank for your help Like this way, encoded_image = base64.b64encode(image_np) payload = { 'from': 'rasp', 'image': encoded_image.decode('utf-8'), 'shape': IMAGE_SHAPE, }
score: 0

http://stackoverflow.com/comment/87650354
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50316049
has text: When you say that your data is less than 260, only 140, what do you mean? Is it intentionally 140 or when you train is it only finding 140 then stopping? Posting your training code (or some minimal amount of code to reproduce the issue) would help. Only having what works doesn't let us identify where there may be a difference between your working example and the "similar training code" that does not work.

http://stackoverflow.com/q/50240030
accepted answer: http://stackoverflow.com/a/60022080
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/60022080
tagged with: format
possible better answer: http://stackoverflow.com/a/50240139
tagged with: python
type: AnsweredQuestion
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/50240139
upvote count: 2
has body: I try to create a simple function, that returns a right aligned number with a preceding dollar sign. Expected output: $1000 $10 $100 My current code is: def aligned_num(num): print('${0:4}'.format(num)) But this gives: $1000 $ 10 $ 100 Can someone help me? Thanks.
has title: Format right aligned number with a preceding dollar sign
downvote count: 0
tagged with: formatting

http://stackoverflow.com/a/50351496
answers question: http://stackoverflow.com/q/50347675
has body: SOLVED by re-installing gsl library using conda: conda install gsl
type: Answer
score: 0

http://stackoverflow.com/q/50383706
has comment: http://stackoverflow.com/comment/87801946
has body: Is there a way to align python basemaps like this figure below? Here's some sample basemap code to produce a map: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 4.5)) plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.00) m = Basemap(projection='robin',lon_0=0,resolution='c') m.fillcontinents(color='gray',lake_color='white') m.drawcoastlines() plt.savefig('world.png',dpi=75)
upvote count: 6
tagged with: matplotlib-basemap
type: Question
downvote count: 0
answer count: 1
score: 6
has title: Aligning maps made using basemap
accepted answer: http://stackoverflow.com/a/50493150
tagged with: python
has answer: http://stackoverflow.com/a/50493150
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87784606

http://stackoverflow.com/a/50274902
has body: You can use itertools.groupby: import itertools tin = [('a1', 'meow'), ('b1', 'woof'), ('c1', 'mooo'), ('d1', 'oink')] rop = [('b1', 'forest'), ('a1', 'home'), ('d1', 'shed')] sounds = ['woof', 'mooo', 'oink'] places = ['forest', 'home', 'shed'] new_s = {a:[i for _, i in b] for a, b in itertools.groupby(sorted(tin+rop, key=lambda x:x[0]), key=lambda x:x[0])} final_s = {a:dict(zip(['sound', 'place'], b if len(b) == 2 else [None]+b if b[0] in places else b+[None])) for a, b in new_s.items()} Output: {'a1': {'sound': 'meow', 'place': 'home'}, 'b1': {'sound': 'woof', 'place': 'forest'}, 'c1': {'sound': 'mooo', 'place': None}, 'd1': {'sound': 'oink', 'place': 'shed'}}
type: Answer
answers question: http://stackoverflow.com/q/50274807
score: 0

http://stackoverflow.com/comment/89317089
has text: Hard to say without your configuration. You could ask a new question. Does OSX use LD_LIBRARY_PATH or LD_PRELOAD or similar? Where are the GCC versions installed? Which exact errors you got now? We can't solve that here.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50432058

http://stackoverflow.com/comment/87642964
type: Comment
comment on: http://stackoverflow.com/q/50299592
type: QuestionComment
score: 1
has text: Show us the real code so we can see where it gets stringified? As a workaround you can call `ast.literal_eval` on the string but ideally you want to stop it being stringified in the first place, or at least understand why your code is doing it.

http://stackoverflow.com/q/50235950
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87499477
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/87489656
type: Question
has title: Displaying file content in html page produces empty field
has body: I am building a web application which will search for my .feature files (which are regular text files) and display their path along with the content. I am using Python and Flask. I searched the web for ways to display the file content and as you can see from the source I found 5 ways to do it. But the end html page renders the file content as an empty box. I know the files path is correct because when I enter a gibberish path, I receive "Not found" for this element. I suspect it's a security problem. Source code of the template: Available scenarios Available scenarios: {% for scenario in scenarios %} {{ scenario }} {% endfor %} Is there a way to make work or I need to do everythin in the back end and send text to the template? The behavior is consistent over every browser and there are no errors in the console.
answer count: 0
tagged with: frontend
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87499053
tagged with: javascript

http://stackoverflow.com/comment/87628626
comment on: http://stackoverflow.com/q/50306006
type: Comment
has text: You should probably run it from Visual Studio Tools command prompt.
type: QuestionComment
score: 0

http://stackoverflow.com/a/50254533
has body: transform df.Value.bfill().div( df.groupby(df.Value.notna()[::-1].cumsum()).Value.transform('size') ) 0 10.0 1 3.0 2 3.0 3 3.0 4 4.0 5 4.0 6 4.0 7 4.0 8 NaN 9 NaN Name: Value, dtype: float64 np.bincount and pd.factorize a = df.Value.notna().values f, u = pd.factorize(a[::-1].cumsum()[::-1]) df.Value.bfill().div(np.bincount(f)[f]) 0 10.0 1 3.0 2 3.0 3 3.0 4 4.0 5 4.0 6 4.0 7 4.0 8 NaN 9 NaN Name: Value, dtype: float64 Alternative shorter version. This works because cumsum naturally gives me what factorize does. a = df.Value.notna().values[::-1].cumsum()[::-1] df.Value.bfill().div(np.bincount(a)[a]) Details In both options above, we need to identify where the null values are and use cumsum on the reversed series to define groups. In the transform option, I use groupby and size to count the size of those groups. The second option uses bin counting and slicing to get at the same series. Thank you @ScottBoston for reminding me to mention the reversed element [::-1]
answers question: http://stackoverflow.com/q/50254331
downvote count: 0
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87526684
accepted answer of: http://stackoverflow.com/q/50254331
score: 7
type: Answer

api-doc
tag name: api-doc
type: Tag
tags question: http://stackoverflow.com/q/50367739

http://stackoverflow.com/comment/87660915
has text: As written, this function doesn't take 3 arguments, it takes one argument that's a list of 3 elements. If you want to do that, you don't need splat at all—just `def f(lst): return list(map(lambda x: x+1, lst))`.
comment on: http://stackoverflow.com/a/50322606
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/87577368
type: QuestionComment
comment on: http://stackoverflow.com/q/50278105
has text: how much memory do you have? I think this grid should result in ~1 GB of memory.
score: 0
type: Comment

http://stackoverflow.com/comment/87483522
score: 0
type: Comment
has text: That is what I have done exactly there . Please have look into my descriprion
type: AnswerComment
comment on: http://stackoverflow.com/a/50233034

http://stackoverflow.com/comment/87564196
type: QuestionComment
score: 0
has text: Rolled back edit as it inadvertently fixed the issue. Please be careful of changing indentation in other people's Python questions.
type: Comment
comment on: http://stackoverflow.com/q/50271719

http://stackoverflow.com/comment/87493113
type: QuestionComment
has text: You could compare `sys.executable` and the `__file__` path to one of the modules that does import on both sides to see if the paths are different.
score: 0
comment on: http://stackoverflow.com/q/50237237
type: Comment

http://stackoverflow.com/q/50244662
type: Question
has comment: http://stackoverflow.com/comment/87517248
answer count: 0
has body: I'm new to Python and I'm working on something that I believe is quite simple. I'm just trying to do some grid search regarding the regularization parameter of a LASSO model using Python's Skicit Learn. Say I have the following ddataframe (showing only a couple lines and a few columns): notnull_df = AsianPerCap FemalePctDiv HispPerCap HousVacant LandArea \ 0 0.27 0.75 0.41 0.21 0.12 1 0.30 0.91 0.35 0.02 0.02 2 0.29 0.71 0.39 0.01 0.01 3 0.25 0.49 0.44 0.01 0.02 4 0.74 0.20 0.48 0.01 0.04 LemasPctOfficDrugUn 0 0.32 1 0.00 2 0.00 3 0.00 4 0.00 Learning_Y = 0 0.20 1 0.67 2 0.43 3 0.12 4 0.03 I have the following: # Defining a way to evaluate models from sklearn.metrics import r2_score, mean_squared_error def evaluate(y_true, y_pred, verbose = False): R2 = r2_score(y_true, y_pred) MSE = mean_squared_error(y_true, y_pred) if verbose == True: print('R2: {}'.format(r2_score(y_true, y_pred))) print('MSE: {}'.format(mean_squared_error(y_true, y_pred))) print('---') return R2, MSE # Defining a Kfold cross-validation scheme n_splits = 10 kf = KFold(n_splits, shuffle = True) # We will fool around with Lasso first splits = kf.split(notnull_df) clf = Lasso(alpha = 0.0001, random_state = 0) R2_Lasso = np.zeros((n_splits, 1)) MSE_Lasso = np.zeros((n_splits, 1)) idx = 0 for train_idx, cv_idx in splits: X_train = notnull_df.iloc[train_idx] X_cv = notnull_df.iloc[cv_idx] Y_train = Learning_Y.iloc[train_idx] Y_cv = Learning_Y.iloc[cv_idx] clf.fit(X_train, Y_train) Y_pred = clf.predict(X_cv) R2, MSE = evaluate(Y_cv, Y_pred, verbose = True) R2_Lasso[idx] = R2; MSE_Lasso[idx] = MSE; idx = idx + 1 This works fine, even the verbose part. It will generate the R2_Lasso and MSE_Lasso arrays as I need. Now comes the trouble. Consider the following implementation of a grid search for the regularization parameter: l1_alpha = [0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.3, 1, 3, 10] avg_R2 = np.zeros((len(l1_alpha), 1)) avg_MSE = np.zeros((len(l1_alpha), 1)) R2_Lasso = np.zeros((n_spl…
type: UnansweredQuestion
tagged with: function
downvote count: 0
has title: Why is ```print``` not working inside for loop and variables are not changing in Python?
upvote count: 1
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/87517117
tagged with: user-defined-functions
score: 1
has comment: http://stackoverflow.com/comment/87507217
favorite count: 0
tagged with: jupyter-notebook

http://stackoverflow.com/q/50262171
downvote count: 0
tagged with: python
has title: Joining two dataframes by summing values between two dates, sumif equivalent
tagged with: merge
score: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/87543135
tagged with: date
has comment: http://stackoverflow.com/comment/87543109
favorite count: 0
type: Question
has body: I have two dataframes, df1 and df2: import pandas as pd import datetime import numpy as np df1 = pd.DataFrame() df1["StartDate"] = pd.date_range(start=('2016/01/01'), end = ('2017/12/31'), freq="6D") df1["EndDate"] = df1["StartDate"] + datetime.timedelta(5) df1["Value_three"] = pd.Series(np.random.randn(len(df.Date))+2) df1 has a start date, end date and value (named value_three). df2 has a date, value_one and value two. df2 = pd.DataFrame() df2["Date"] = pd.date_range(start=('2016/01/01'), end=('2017/12/31'), freq="D") df2["Value_one"] = pd.Series(np.random.randn(len(df.Date))) df2["Value_two"] = pd.Series(np.random.randn(len(df.Date))+1) What am I looking to achieve is something similar to the SUMIFS function in Excel: SUMIFS In this case, I'd like add two columns to df1 that are values_1 and value_2 summed respectively where the "Date" column is df2 is between df1.StartDate and df1.EndDate. Let's assume it is not possible to pre-aggregate this in Vertica/MSSQL/etc. We also cannot use resample as the start date and end date can be irregular (in this case, separated by 11 days, but the gap can be ever changing). I've tried join, merge, melt, concat, and I am proving a failure! Hopefully someone can kindly assist.
has comment: http://stackoverflow.com/comment/87542513
has answer: http://stackoverflow.com/a/50263923
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87638140
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50306513
has text: awesome! this works like a charm and I will surely use it for the future for more complex stuff

http://stackoverflow.com/comment/87719406
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50351357
has text: Thanks, but, looks like this approach moves the grid. Is there a way to move **labels** not the grid?
type: AnswerComment

http://stackoverflow.com/a/50325898
has body: It appears your data has 13 different classes, which is why your confusion matrix has 13 rows and columns. Furthermore, your classes aren't labeled in any way, just integers from what I can see. If this isn't the case, and your training data has actual labels, you can pass a list of unique labels to confusion_matrix conf_mat = confusion_matrix(class_label, class_label_predicted, df['task'].unique())
has comment: http://stackoverflow.com/comment/87667526
has comment: http://stackoverflow.com/comment/87667808
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50325786

http://stackoverflow.com/q/50356183
accepted answer: http://stackoverflow.com/a/50356210
has title: categorize numerical series with python
favorite count: 0
type: Question
tagged with: enumerate
has answer: http://stackoverflow.com/a/50356210
linked to: http://stackoverflow.com/q/50341199
tagged with: python
has body: I'm figuring out how to assign a categorization from an increasing enumeration column. Here an example of my dataframe: df = pd.DataFrame({'A':[1,1,1,1,1,1,2,2,3,3,3,3,3],'B':[1,2,3,12,13,14,1,2,5,6,7,8,50]}) This produce: df Out[9]: A B 0 1 1 1 1 2 2 1 3 3 1 12 4 1 13 5 1 14 6 2 1 7 2 2 8 3 5 9 3 6 10 3 7 11 3 8 12 3 50 The column B has an increasing numerical serie, but sometimes the series is interrupted and keeps going with other numbers or start again. My desired output is: Out[11]: A B C 0 1 1 1 1 1 2 1 2 1 3 1 3 1 12 2 4 1 13 2 5 1 14 2 6 2 1 3 7 2 2 3 8 3 5 3 9 3 6 4 10 3 7 4 11 3 8 4 12 3 50 5 I appreciate your suggestions, because I can not find an ingenious way to do it. Thanks
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50238919
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50234165
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50234165
has body: Suppose you build a graph with the indices as nodes import networkx as nx import itertools G = nx.Graph() G.add_nodes_from(df.index) Add ass edges all row-pairs with distance less than 20: G.add_edges_from( [(r1[0], r2[0]) for (r1, r2) in itertools.product(df.iterrows(), df.iterrows()) if r1[0] &lt; r2[0] and r1[1]['time_end'] + 20 &gt; r2[1]['time_start']] ) Now find all the connected-components: groups = dict(itertools.chain.from_iterable([[(ee, i) for ee in e] for (i, e) in enumerate(nx.connected_components(G))])) &gt;&gt;&gt; df.index.map(lambda j: groups[j]) Int64Index([0, 1, 2, 3, 4, 4], dtype='int64') Note that 4 and 5 have been identified correctly as belonging to the same group. At this point, you just need to group by groups in the usual way. For example, for the start time: &gt;&gt;&gt; df.time_start.groupby(df.index.map(lambda j: groups[j])).min() 0 1532 1 1627 2 1755 3 2649 4 3028 Name: time_start, dtype: int64
type: Answer

http://stackoverflow.com/comment/87743339
type: QuestionComment
has text: how working `datevar['2000-01-01']` ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50363545

http://stackoverflow.com/comment/87756129
type: Comment
score: 0
type: AnswerComment
has text: @MaxU I agree, but imagine that it isnt alphabetically ordered, your solution is not valid anymore too. He gave an example and I gave a possible solution. btw maybe someone else will find the answer useful
comment on: http://stackoverflow.com/a/50369690

http://stackoverflow.com/a/50315699
has body: You could use enumerate(): new_list = [f(val+index) for (index, val) in enumerate(my_list)]
upvote count: 8
answers question: http://stackoverflow.com/q/50315675
type: Answer
score: 8
downvote count: 0

http://stackoverflow.com/a/50278928
score: 0
has comment: http://stackoverflow.com/comment/87575377
type: Answer
answers question: http://stackoverflow.com/q/50278120
has comment: http://stackoverflow.com/comment/87580465
has body: This answer might help you: How to send JSON as part of multipart POST-request In your case it would be files = { 'Path': ( 'C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', open('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', 'rb'), 'application/octet-stream' ) 'data': (None, '{"key": "Path"}', 'application/json'), } response = requests.post( 'http://127.0.0.1:8881/models/faewrfaw/v1/predict', files=files )

http://stackoverflow.com/q/50329878
has answer: http://stackoverflow.com/a/53052394
has body: I have the following piece of PySpark code that has always worked fine, except today: row_stats = dataframe .withColumn("exploded" , explode(col("products"))) .withColumn("score", col("exploded").getItem(target_field)) .where(col("score").isNotNull()) .select(mean_(col("score")).alias("mean"),stddev_(col("score")).alias("stddev")).first() mean = 0 std = 0 if row_stats is not None: print "row_stats.mean" print row_stats.mean mean = Decimal(float(row_stats.mean)) std = Decimal(float(row_stats.stddev)) I got the error at the line mean = Decimal(float(row_stats.mean)): TypeError: float() argument must be a string or a number Theprint outputs: &lt;type 'NoneType'&gt; None How to properly handle this error in order to get mean and std equal to 0?
has comment: http://stackoverflow.com/comment/87675739
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/50330458
score: 0
answer count: 2
has title: PySpark code raises: TypeError: float() argument must be a string or a number
has comment: http://stackoverflow.com/comment/87675778
has comment: http://stackoverflow.com/comment/87684628
has comment: http://stackoverflow.com/comment/87675975
has comment: http://stackoverflow.com/comment/87676361
type: Question

http://stackoverflow.com/comment/87680284
comment on: http://stackoverflow.com/q/50331895
has text: yes, with there score also any suggestions @aran-fey
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/50242948
tagged with: decode
has comment: http://stackoverflow.com/comment/87513632
score: 0
has comment: http://stackoverflow.com/comment/87504558
has comment: http://stackoverflow.com/comment/87505556
answer count: 1
accepted answer: http://stackoverflow.com/a/50261461
tagged with: unicode
type: Question
has title: UnicodeDecodeError adding model in Django
has body: When trying to add a model containing unicode in Django 1.9, I get the following error: UnicodeDecodeError at /cleaner/clean/add/ 'utf-8' codec can't decode byte 0x96 in position 209: invalid start byte This occurs in the model class. class Clean(models.Model): name = models.CharField(max_length=100) cv = models.TextField(max_length=10000, blank = True, null = True) cvfile = models.FileField(validators=[validate_file_extension]) #override save method def save(self, *args, **kwargs): get_text = self.cvfile.read() self.cv = get_text self.cv=self.cv.decode("utf-8") super(Clean, self).save(*args, **kwargs) I thought self.cv.decode("utf-8") would solve this as I'm using python 3.6.4, but it does not. Is there a way to solve this?
has answer: http://stackoverflow.com/a/50261461
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87504495
type: AnsweredQuestion

http://stackoverflow.com/a/51074222
score: 0
has body: Try it https://github.com/Skorpyon/aiorestframework Create some middleware for authentication: import re from xml.etree import ElementTree as etree from json.decoder import JSONDecodeError from multidict import MultiDict, MultiDictProxy from aiohttp import web from aiohttp.hdrs import ( METH_POST, METH_PUT, METH_PATCH, METH_DELETE ) from aiorestframework import exceptions from aiorestframework omport serializers from aiorestframework import Response from aiorestframework.views import BaseViewSet from aiorestframework.permissions import set_permissions, AllowAny from aiorestframework.app import APIApplication from my_project.settings import Settings # Generated by aiohttp-devtools TOKEN_RE = re.compile(r'^\s*BEARER\s{,3}(\S{64})\s*$') async def token_authentication(app, handler): """ Authorization middleware Catching Authorization: BEARER &lt;token&gt; from request headers Found user in Tarantool by token and bind User or AnonymousUser to request """ async def middleware_handler(request): # Check that `Authorization` header exists if 'authorization' in request.headers: authorization = request.headers['authorization'] # Check matches in header value match = TOKEN_RE.match(authorization) if not match: setattr(request, 'user', AnonymousUser()) return await handler(request) else: token = match[1] elif 'authorization_token' in request.query: token = request.query['authorization_token'] else: setattr(request, 'user', AnonymousUser()) return await handler(request) # Try select user auth record from Tarantool by token index res = await app['tnt'].select('auth', [token, ]) cached = res.body if not cached: raise exceptions.AuthenticationFailed() # Build basic user data and bind it to User instance record = cached[0] user = User() user.bind_cached_tarantool(record) # Add User to request setattr(request, 'user', user) return await handler(request) return middleware_handler And for data extraction from request: DATA_METHODS = [METH_POST, METH_PUT, METH_PATCH, METH_DELETE] JSON_CO…
type: Answer
answers question: http://stackoverflow.com/q/50373051

http://stackoverflow.com/comment/87479947
has text: Becasue `-1 != '-1'`
type: Comment
score: 1
comment on: http://stackoverflow.com/q/50231330
type: QuestionComment

http://stackoverflow.com/comment/87577737
has text: Thanks for the advice. I have gotten this far but don't understand the syntax error I'm getting. https://api.stripe.com import stripe stripe.api_key = "sk_test_kLyQtpKGLBRmorVmYCToOdai" stripe.InvoiceItem.create{ customer=input['custid'], amount=input['opponboarding'], currency="usd", description="Onboarding Fee" } subscription=stripe.Subscription.create{ customer=input['custid'], items=[{'plan':input['oppplan']}], } Error: Traceback (most recent call last): SyntaxError: invalid syntax (usercode.py, line 8)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50277068
type: Comment

http://stackoverflow.com/q/50361308
has comment: http://stackoverflow.com/comment/87759838
answer count: 1
downvote count: 0
upvote count: 1
has body: I am making a small game for my AP Econ class and have been following a tutorial to create a tile map and am having difficulty with collisions. I have searched through the questions on this site as well as anywhere else that I could find programming related questions (Primarily here) but have not been able to find any that are don't have a map built by hand (Building a map by hand in a text document or directly in the python file with a list). I am new at python so the answer might be fairly straight forward XD. Main Program: https://pastebin.com/VbGVzJab Textures: https://pastebin.com/iTBpiub3 Colors: https://pastebin.com/ywMKv6Z1 Globals: https://pastebin.com/E40a7Kss Map_Engine: https://pastebin.com/PJgnSFJP Map_Editor: https://pastebin.com/mvgaYBDF Tutorial I have been following: https://www.youtube.com/watch?v=sxk4Oi9QOrM&amp;t=997s This is how my folders are set up: My issue is that I my character (player) continues to walk instead of stopping at the water (Or whichever tile type is designated (In my case it is currently water). Thank you all in advance!!
favorite count: 0
linked to: http://stackoverflow.com/q/48069508
has comment: http://stackoverflow.com/comment/87779290
score: 1
tagged with: python
tagged with: pygame
tagged with: collision-detection
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50374013
has title: Collisions w/ Tiles on Tile Map Python 3.6
type: UnansweredQuestion

http://stackoverflow.com/comment/87676817
comment on: http://stackoverflow.com/a/50328487
has text: Ok. Yeah got that. BUt If i need to define the schema then how will I map nested columns in RDD and define nested columns schema?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87490937
has text: @TokeFaurby You use `%S` for the integer part of the seconds and `%f` for the fractional part of the seconds. There is no format specifier for "seconds with fractions" or "seconds as floats".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50236669
score: 0

http://stackoverflow.com/comment/114514087
has text: thanku for detailed response, very helpful indeed. I converted each sequence to sliding window of size 10(now each sequence spans multiple sequences 10+, depending on the size of the original seq).it it necessary that one orignial sequence that spans for example 10 sequence should be in same batch and order(no shuffle etc) to be able to learn? Also, I am seing overfitting on a very simple network as well. If i break sequences longer than 60 into separate 60 length sequences instead of sliding, will it have same effect or it will only learn to predict 60th element?
type: Comment
comment on: http://stackoverflow.com/a/50330740
score: 0
type: AnswerComment

http://stackoverflow.com/q/50234733
has comment: http://stackoverflow.com/comment/87505668
has comment: http://stackoverflow.com/comment/87491049
has comment: http://stackoverflow.com/comment/87488163
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87505629
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87487906
has body: I have a matrix and a vector of the centroids of each row in the matrix. I would like to compare every element in the matrix to every element in the vector and find which element in the vector of centroids is closest to the data point in the matrix. Is there a way to do this without using a loop? I will use a large amount of a data and want it to be as fast as possible Here is a very simple example in python of the way in which I am doing it right now: import scipy as sp test_array = sp.array([(1,1,1),(3,4,5),(6,12,18)]) sumx = test_array.sum(axis=1) centroid_vector = sumx / len(test[0]) for i in centroid_vector: x = abs(test_array - i) minimum = sp.argmin(x) The desired result is a matrix with the minimum distance, original value (from test_array) and the index of the element in the centroid vector to which the distance is the smallest. In this case, it would look something like this: [(0, 1, 1), (0, 1, 1), (0, 1, 1), (1, 3, 2), (0, 4, 2), ... (6, 18, 3)]
score: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/50254982
has title: Compare all elements in two numpy arrays without using a loop
upvote count: 2
has comment: http://stackoverflow.com/comment/87487848
downvote count: 0
answer count: 1
tagged with: scipy

http://stackoverflow.com/comment/87693542
comment on: http://stackoverflow.com/a/50338578
type: Comment
has text: Median would be taking the array of values, giving them all appropriate array numbers, and finding center values. Example: Array[0] being the smallest value, Array[4] being the largest, would leave Array[2] as the median.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50348060
answers question: http://stackoverflow.com/q/50347910
score: -1
upvote count: 0
has body: You can use curl and grep. You still have to download the entire file, unless the ebi.ac.uk server api provides server side filtering. curl 'https://www.ebi.ac.uk/ena/data/view/FO203355&amp;display=text' | grep '^FT' &gt; lines.txt
downvote count: 1
type: Answer

http://stackoverflow.com/q/50260946
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50260993
possible better answer: http://stackoverflow.com/a/50260993
type: Question
has title: python import statements with two pythons installed
has comment: http://stackoverflow.com/comment/87539990
has body: On my Windows 7 laptop I have both Python 2 and Python 3 installed, and I've been switching back and forth between them like py -2 myscript.py etc. I explicitly installed a package called pdfminer by using pip2 and I've verified that it's on my disk at C:\Python27\Lib\site-packages\pdfminer However, when I try to run a script I get an error: &gt; py -2 pdfminer.py Traceback (most recent call last): File "pdfminer.py", line 4, in &lt;module&gt; from pdfminer.pdfparser import PDFParser File "C:\Users\me\Documents\myprog\pdfminer.py", line 4, in &lt;module&gt; from pdfminer.pdfparser import PDFParser ImportError: No module named pdfparser The import statement is exactly as given in the PDFMiner documentation, and I even added the Python 2 scripts directory explicitly to the PATH just in case that would help, but it didn't (I actually think that's redundant because from printing out sys.path it seems it was already there): import sys sys.path.append("C:\Python27\Lib\site-packages\\") from pdfminer.pdfparser import PDFParser Within site-packages\pdfminer there is a file pdfparser.py and within it class PDFParser(PSStackParser). The case doesn't match the import statement, but actually making the import statement lowercase to match the file also doesn't help. I don't really see anything wrong here. Is there anything else I could try?
linked to: http://stackoverflow.com/q/36250353
has comment: http://stackoverflow.com/comment/87540058
tagged with: python
has answer: http://stackoverflow.com/a/50261082
accepted answer: http://stackoverflow.com/a/50261082
duplicate of: http://stackoverflow.com/q/36250353
has comment: http://stackoverflow.com/comment/87540214

http://stackoverflow.com/a/50321351
type: Answer
accepted answer of: http://stackoverflow.com/q/50321335
has comment: http://stackoverflow.com/comment/87658680
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87658700
downvote count: 0
has body: When you do searchString in value you're only checking the keys of that value dictionary. You would need a second loop to check against the values of the nested dictionary for key, value in addressBook.items(): inside = False for v in value.values(): if searchString in v: inside = True break if searchString in key or inside: Unrelated note: searchString in key is checking substrings, not an exact match
answers question: http://stackoverflow.com/q/50321335
upvote count: 2

http://stackoverflow.com/q/50247596
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/87512923
type: UnansweredQuestion
has body: I am trying to perform a principal component analysis and plot the scree plot using matplotlib function bar(). I observe this error while running the following code. import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn import preprocessing import matplotlib.pyplot as plt scaled_data = preprocessing.scale(data.T) pca=PCA() pca.fit(scaled_data) pca_data = pca.transform(scaled_data) per_var = np.round(pca.explained_variance_ratio_*100, decimals=1) labels = ['PC'+str(i) for i in range(1,len(per_var)+1)] plt.bar(x=range(1,len(per_var)+1), height=per_var, tick_label=labels) plt.xlabel('Principal Component') plt.ylabel('Percentage of Variance Explained') plt.title('Scree Plot') plt.show() Error: TypeError: bar() missing 1 required positional argument: 'left'
has title: bar() missing 1 required positional argument: 'left'
upvote count: 5
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/87514429
has answer: http://stackoverflow.com/a/51418775
score: 4
tagged with: pca
has answer: http://stackoverflow.com/a/50247726
tagged with: matplotlib
downvote count: 1

http://stackoverflow.com/comment/122766082
has text: As a workaround for this specific issue, you could save each of your 50 sheets into a list of 50 mini dataframes, then write your summary to excel, and then write each of the 50 mini dataframes to its own sheet after.
comment on: http://stackoverflow.com/q/50296531
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50319337
answer count: 2
has comment: http://stackoverflow.com/comment/87654641
has answer: http://stackoverflow.com/a/50320053
tagged with: amazon-rds
has comment: http://stackoverflow.com/comment/87654882
downvote count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/87655117
favorite count: 0
linked to: http://stackoverflow.com/q/50383753
tagged with: aws-lambda
type: Question
has comment: http://stackoverflow.com/comment/87654617
score: 5
linked to: http://stackoverflow.com/q/45189345
has answer: http://stackoverflow.com/a/78976417
possible better answer: http://stackoverflow.com/a/78976417
has title: How to authenticate in MySQL RDS using IAM DB Authentication and Python
has body: I have an AWS RDS DB running MySQL 5.6.39, with IAM DB Authentication Enabled. First of all, I completed with success the Tutorial: Configuring a Lambda Function to Access Amazon RDS in an Amazon VPC and this was my starting point for the next steps. I want to log in with IAM credentials and so, following this and this tutorials, I did: When I created the RDS MySQL instance, I selected Enabling IAM database authentication. Created a user named lambda: CREATE USER 'lambda' IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS'; GRANT ALL PRIVILEGES ON test_db.* TO 'lambda'@'%'; FLUSH PRIVILEGES; Created an IAM policy, and attached it to the role I was using as an Execution role for my lambda function: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "rds-db:connect" ], "Resource": [ "&lt;DB-ARN&gt;/lambda" ] } ] } Created a lambda function: import sys import boto3 import logging import pymysql #rds settings rds_host = "&lt;RDS-ENDPOINT&gt;" username = "lambda" db_name = "test_db" logger = logging.getLogger() logger.setLevel(logging.INFO) client = boto3.client('rds',region_name='eu-west-2') token = client.generate_db_auth_token(rds_host,3306, name) ssl = {'ca': 'rds-combined-ca-bundle.pem'} logger.info("token: "+ token) conn = pymysql.connect(rds_host, user=username, passwd=token, db=db_name, connect_timeout=5, ssl=ssl) logger.info("SUCCESS: Connection to RDS mysql instance succeeded") def handler(event, context): ... I got the following error: error: (1045, "Access denied for user 'lambda'@'&lt;LAMBDA_IP&gt;' (using password: YES)") In an attempt to find If it was a python error I used AWS CLI, from an EC2 instance with the policy attached. Get the token: aws rds generate-db-auth-token --hostname &lt;RDS-ENDPOINT&gt; --port 3306 --username lambda Connect to the DB, using the token I got in the last step: mysql -h &lt;RDS-ENDPOINT&gt; -u lambda --enable-cleartext-plugin --password='&lt;TOKEN&gt;' I got the same error: mysql: [Warning] Using a passw…
accepted answer: http://stackoverflow.com/a/50320053
upvote count: 5
has comment: http://stackoverflow.com/comment/87654551
tagged with: python
tagged with: amazon-web-services
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87655056
has comment: http://stackoverflow.com/comment/87654733

http://stackoverflow.com/comment/87585607
comment on: http://stackoverflow.com/a/50283621
score: 0
has text: What happens with `list(fn(d, ''))`, `''` is the root of the tree, both `'A'` and `'F'` have `''` in the original `quote` variable. What version of python are you using?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87624289
score: 0
type: AnswerComment
type: Comment
has text: Great - that works a treat. I've been trying to remove the column headers 'Unnamed: 1_level_0' etc... as well as resetting the index to the 'Disposals' column but can't figure out how to do that? I've been able to adjust the headings by: tables = pd.read_html("https://afltables.com/afl/stats/teams/" +str(team_lower_case)+"/2018_gbg.html",header=1) Which sets the headers to Player, R1, R2 etc... but not sure about the index?
comment on: http://stackoverflow.com/a/50290394

http://stackoverflow.com/comment/87482242
has text: `post.user=request.user`
type: QuestionComment
comment on: http://stackoverflow.com/q/50232369
type: Comment
score: 0

http://stackoverflow.com/q/50372601
accepted answer: http://stackoverflow.com/a/50373050
has body: I would like to read just one part (not chunks) from a txt-file (10GB) with lines and write them into another file. The size of the part should be exactly 25MB. I have tried with linecache.getlines, but it was not very exactly. Thanks.
has title: Python: how to get part of file by size
has comment: http://stackoverflow.com/comment/87761152
has comment: http://stackoverflow.com/comment/87761569
linked to: http://stackoverflow.com/q/50062474
type: Question
tagged with: python-3.x
tagged with: split
has answer: http://stackoverflow.com/a/50373050
has comment: http://stackoverflow.com/comment/87762254
tagged with: size
tagged with: python
has comment: http://stackoverflow.com/comment/87761719
has answer: http://stackoverflow.com/a/50373220
linked to: http://stackoverflow.com/q/519633
possible better answer: http://stackoverflow.com/a/50373220
has comment: http://stackoverflow.com/comment/87761308
type: AnsweredQuestion
score: 0
tagged with: large-files
answer count: 2

http://stackoverflow.com/comment/88245221
type: AnswerComment
has text: I think shape (11) refers to the shape of my actual df1 dataframe (it contains 11 columns). but I am not sure where the "shape (3)" is coming from?
score: 0
comment on: http://stackoverflow.com/a/50251874
type: Comment

http://stackoverflow.com/q/50279057
has title: Alexa site rank API
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87682722
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/50279298
score: 2
has comment: http://stackoverflow.com/comment/87681576
upvote count: 2
has body: Today I was working on Alexa API to get sites popularity rank using this code: import urllib.request, sys, re site = 'https://stackoverflow.com/questions/' xml = urllib.request.urlopen('http://data.alexa.com/data?cli=10&amp;dat=s&amp;url=%s'%site).read() try: rank = int(re.search(r'&lt;POPULARITY[^&gt;]*TEXT="(\d+)"', xml).groups()[0]) except: rank = -1 print('Your rank for %s is %d!\n' % (site, rank)) It was working perfectly, but suddenly it stopped!, I checked the API link manually: http://data.alexa.com/data?cli=10&amp;dat=s&amp;url=https://stackoverflow.com/questions/ and it just returns a word "Okay" rather than a XML string .. What is the problem ?!
downvote count: 0
has answer: http://stackoverflow.com/a/62873765
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51537499
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60357856
tagged with: alexa-skills-kit

http://stackoverflow.com/q/50361970
favorite count: 0
type: AnsweredQuestion
tagged with: python
has body: In Maya there is a ls command which lists all objects in a scene (or DAG). pm.ls() Here is reference to ls command. We can list specific type of element by passing type parameter. pm.ls(type="joint") Some possible types are, camera, mesh, joint etc. My question is what are all types available to ls() command? Documentation doesn't help much. Where do I find it?
has title: How do I get list of all types in Maya's ls command?
tagged with: mel
tagged with: pymel
type: Question
score: 1
answer count: 1
downvote count: 0
tagged with: maya
upvote count: 1
has answer: http://stackoverflow.com/a/50367307
accepted answer: http://stackoverflow.com/a/50367307

http://stackoverflow.com/q/50382104
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/50386728
tagged with: dataframe
tagged with: concatenation
tagged with: function
answer count: 3
has answer: http://stackoverflow.com/a/50382302
tagged with: python
type: UnansweredQuestion
has title: Concatenating DataFrames through function calls
has answer: http://stackoverflow.com/a/50382254
has body: I am trying to concatenate a single row dataframe (df) and add it to the end of another dataframe (df_all) using the following code: import pandas as pd import numpy as np from IPython.display import display, HTML global df_all df_all = pd.DataFrame() def save_data(df): df_all = pd.concat([df, df_all], axis=0) display(df_all) return df_all def opt(): df = pd.DataFrame(np.random.randn(1, 4), columns=list('ABCD')) # one row data display(df) save_data(df) Using this loop I suppose to get 3 rows are saved to df_all. But I am getting an error message (local variable 'df_all' referenced before assignment) for i in range (3): opt() display(df_all)
type: Question

http://stackoverflow.com/comment/87652672
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50318304
has text: As you suggests, will it be a better practice to add two lines `self.weight=None self.ratio=None` before `self.weight_kg()`?

http://stackoverflow.com/q/50383910
tagged with: pandas
has comment: http://stackoverflow.com/comment/87784202
linked to: http://stackoverflow.com/q/33642951
answer count: 1
downvote count: 0
has title: pandas read_json for multi line jsons returns a JSONReader and not a dataframe
has comment: http://stackoverflow.com/comment/87783564
favorite count: 0
type: Question
has body: I have a file file1.json whose contents are like this (each dict in a separate line): {"a":1,"b":2} {"c":3,"d":4} {"e":9,"f":6} . . . {"u":31,"v":23} {"w":87,"x":46} {"y":98,"z":68} I want to load this file into a pandas dataframe, so this is what i did: df = pd.read_json('../Dataset/file1.json', orient='columns', lines=True, chunksize=10) But this instead of returning a dataframe returns a JSONReader. [IN]: df [OUT]: &lt;pandas.io.json.json.JsonReader at 0x7f873465bd30&gt; Is it normal, or am i doing something wrong? And if this is how read_json() is supposed to behave when there're multiple dictionaries in a single json file (without being any comma separated) and with each dict in a separate line, then how can i best fit them into a dataframe? EDIT: if i remove the chunksize paramter from the read_json() this is what i get: [IN]: df = pd.read_json('../Dataset/file1.json', orient='columns', lines=True) [OUT]: ValueError: Expected object or value
has comment: http://stackoverflow.com/comment/87783467
has comment: http://stackoverflow.com/comment/87784742
has answer: http://stackoverflow.com/a/50383952
upvote count: 5
has comment: http://stackoverflow.com/comment/87784002
score: 5
has comment: http://stackoverflow.com/comment/87787263
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87783840
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50383952

http://stackoverflow.com/q/50233238
accepted answer: http://stackoverflow.com/a/50233425
favorite count: 0
has answer: http://stackoverflow.com/a/50233425
type: Question
has title: (Django) Running asynchronous server task continously in the background
score: 1
tagged with: channel
tagged with: webserver
tagged with: python
tagged with: asynchronous
type: AnsweredQuestion
has body: I want to let a class run on my server, which contains a connected bluetooth socket and continously checks for incoming data, which can then by interpreted. In principle the class structure would look like this: Interpreter: -> connect (initializes the class and starts the loop) -> loop (runs continously in the background) -> disconnect (stops the loop) This class should be initiated at some point and then run continously in the background, from time to time a http request would perhaps need data from the attributes of the class, but it should run on its own. I don't know how to accomplish this and don't want to get a description on how to do it, but would like to know where I should start, like how this kind of process is called.
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1

http://stackoverflow.com/a/50269074
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87555885
answers question: http://stackoverflow.com/q/50268691
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50268691
score: 5
has body: A Pipeline object from scikit-learn does not have the partial_fit, as seen in the docs. The reason for this is that you can add any estimator you want to that Pipeline object, and not all of them implement the partial_fit. Here is a list of the supported estimators. As you see, using SGDClassifier (without Pipeline), you don't get this "no attribute" error, because this specific estimator is supported. The error message you get for this one is probably due to text data. You can use the LabelEncoder to process the non-numeric columns.
has comment: http://stackoverflow.com/comment/87555847
has comment: http://stackoverflow.com/comment/87555988
type: Answer
has comment: http://stackoverflow.com/comment/87556172
upvote count: 6

http://stackoverflow.com/q/50301594
linked to: http://stackoverflow.com/q/5082452
has answer: http://stackoverflow.com/a/56250854
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50301728
has answer: http://stackoverflow.com/a/50301906
has answer: http://stackoverflow.com/a/50301665
has answer: http://stackoverflow.com/a/50301715
accepted answer: http://stackoverflow.com/a/50301724
tagged with: input
has title: User inputs and sorted lists in Python 3
tagged with: python
has body: I need help producing an output like this: 1. Enter a member: samantha Names: ['Samantha'] 2. Enter a member: susan Names: ['Samantha', 'Susan'] 3. Enter a member: billy Names: ['Billy', 'Samantha', 'Susan'] 4. Enter a member: billy 4. Enter a member: samantha 4. Enter a member: Jason Names: ['Billy', 'Jason', 'Samantha', 'Susan'] 5. Enter a member: Members: 1. Billy 2. Jason 3. Samantha 4. Susan I've made an effort to create a program which does this, but to no avail. I will be commenting in my questions in the code itself. Thanks in advance for the help. def function(): x = [] #a = "1." # I tried to number the questions by adding these but it doesnt work while True: #a += 1 name = input("Enter name: ").title() x.append(name) print("Names:", x) #if name == name: # this condition is made so that an input that is typed in again doesn't get included in the list #name = input("Enter name: ").title() # where should I add an insert() here to have the list alphabetically ordered? if not name: # pressing enter prints out the second half of the output, listing the members #print("\nMembers:", x).sort() break function()
tagged with: sorting
has answer: http://stackoverflow.com/a/50301724
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/50301665
score: 1
downvote count: 0
answer count: 7
upvote count: 1
has answer: http://stackoverflow.com/a/50301897
favorite count: 0
type: Question

http://stackoverflow.com/a/50271858
has body: The problem is that when you write python (alone), the command line calls python shell and the following commands are run inside the python shell and not in the command line anymore. Calling a script from the shell has a different format (look it up). You can enter exit() to exit the shell back to command line again
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50271715

http://stackoverflow.com/comment/87673802
score: 1
has text: Possible duplicate of [Pyspark: Replacing value in a column by searching a dictionary](https://stackoverflow.com/questions/43976237/pyspark-replacing-value-in-a-column-by-searching-a-dictionary)
comment on: http://stackoverflow.com/q/50321549
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87721801
type: Comment
type: QuestionComment
has text: @Wen I mean have index "order_id" in df to be seen as an index in dataframe after groupby
comment on: http://stackoverflow.com/q/50352702
score: 0

http://stackoverflow.com/comment/87608817
has text: It's not similar with that answer because for me I need to keep also new rows coming from dataframe B.
comment on: http://stackoverflow.com/q/50295783
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50301696
score: 0
tagged with: selenium
tagged with: cgi
has comment: http://stackoverflow.com/comment/87624439
linked to: http://stackoverflow.com/q/45590237
type: Question
has body: I am using python 2.7 I am trying to run a python script from webpage using CGI that executes selenium webdriver for some automation processes. For now I am trying to setup CGI by running a simple hello world script. #!/usr/local/bin/Python27/python import cgi import cgitb cgitb.enable() print 'Content-Type: text/html' print() print("hello world") I have done configuration in httpd.conf "added ".py" in addhandler" My cgi script is in the CGI bin, path is: "C:\xampp\cgi-bin\myscript.py" In the web browser I am trying to run it by this url: "http://localhost:31337/cgi-bin/myscript.py" Can someone please look and tell if I am doing something wrong? I really have to get this done soon but stuck here from long time. Basically I just need to execute a python script by click of a button on web page. Using CGI is one of the options. If there is any other and better way that you can suggest, I can try that as well. I am completely new to programming and have little experience. I also found a similar question but I am stuck at the initial part of setup. link to question: Running Selenium webdriver from a Python CGI script? Thank you in advance.
answer count: 0
type: UnansweredQuestion
has title: Setting up XAMPP to run cgi scripts from web page windows
tagged with: python
has comment: http://stackoverflow.com/comment/87673145

http://stackoverflow.com/a/50289111
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: If I got it right - you need to get all onclick attributes of &lt;area&gt; tags on a page. Try something like this: import requests from bs4 import BeautifulSoup TAG_NAME = 'area' ATTR_NAME = 'onclick' url = 'http://epaper.bhaskar.com/indore/129/10052018/mpcg/1/' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.text, 'html.parser') # there are 3 &lt;area&gt; tags on page; putting them into a list area_onclick_attrs = [x[ATTR_NAME] for x in soup.findAll(TAG_NAME)] print(area_onclick_attrs) Output: [ "return show_pophead('78545','51022929357','1')", "return show_pop('78545','51022928950','4')", "return show_pop('78545','51022929357','1')", ]
accepted answer of: http://stackoverflow.com/q/50287283
type: Answer
answers question: http://stackoverflow.com/q/50287283

http://stackoverflow.com/comment/88081424
type: Comment
score: 0
has text: As a developer this question can be read. Not sure why it was closed but it came up as a "test" for me to review and according to the system the question cannot be understood, lol. I voted leave it open and got "stop and listen".
comment on: http://stackoverflow.com/q/50317635
type: QuestionComment

http://stackoverflow.com/a/50356830
score: 3
answers question: http://stackoverflow.com/q/50355150
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87811086
downvote count: 0
has comment: http://stackoverflow.com/comment/87816204
has comment: http://stackoverflow.com/comment/87812633
type: Answer
has body: The code is theoretically fine. What you underestimate is the complexity of the computation. Formula M(n)=n-F(M(n-1)) actually means tmp = M(n-1) M(n) = n - F(tmp) So if you represent this calculation as a tree of necessary calls, you might see that its a binary tree and you should go through all its nodes to calculate the results. Given that M(n) and F(n) are about n/2 I'd estimate the total number of the nodes to be of order 2^(n/2) which becomes a huge number once you put n = 300 there. So the code works but it just will take a very very long time to finish. The one way to work this around is to employ caching in a form of memoization. A code like this: femCache = dict() def female(num): #print("female " + str(num)) global femCache if num in femCache: return femCache[num]; else: res = 1 # value for num = 0 if num &gt; 0: res = num - male(female(num-1)) femCache[num] = res return res maleCache = dict() def male(num): #print("male " + str(num)) global maleCache if num in maleCache: return maleCache[num]; else: res = 0 # value for num = 0 if num &gt; 0: res = num - female(male(num-1)) maleCache[num] = res return res print(male(300)) should be able to compute male(300) in no time.
accepted answer of: http://stackoverflow.com/q/50355150
has comment: http://stackoverflow.com/comment/87811546

http://stackoverflow.com/a/50366567
has comment: http://stackoverflow.com/comment/87749879
has comment: http://stackoverflow.com/comment/87750925
has comment: http://stackoverflow.com/comment/87749932
downvote count: 0
answers question: http://stackoverflow.com/q/50366484
has body: You're almost there in your example, just needs a little tweaking s = 'azcbobobegghakl' longest = [s[0],] # make them lists so we can manipulate them (unlike strings) current = [s[0],] for letter in range(0, len(s) -1): if s[letter + 1] &gt;= s[letter]: current.append(s[letter + 1]) if len(current) &gt; len(longest): longest = current else: current = [s[letter+1],] # reset current if we break an alphabetical chain longest_string = ''.join(longest) # turn out list back into a string output of longest_string: 'beegh'
has comment: http://stackoverflow.com/comment/87750640
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/50280144
has comment: http://stackoverflow.com/comment/87576904
upvote count: 1
has comment: http://stackoverflow.com/comment/87577743
favorite count: 0
has comment: http://stackoverflow.com/comment/87577515
has comment: http://stackoverflow.com/comment/87577290
tagged with: anaconda
has title: Problems running pygame script
score: 1
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/87577371
tagged with: pygame
tagged with: directory
type: Question
has answer: http://stackoverflow.com/a/50281023
has body: Currently trying to run a pygame script. The Script itself is fine however I think the installation is causing me some problems. I am using a mac and my script is located on my desktop. If I would like to load images on to the script I must place this in '/users/himansu' In addition I am using spyder (anaconda) when running this. I have tried terminal which keeps bringing up the error: AttributeError: module 'pygame' has no attribute 'init' When I hit run in spyder it loads the pygame script however my keys are not moving the object on screen rather the cursor remains inside the spyder application.. This I know hasn't got anything to do with the code which is posted below: import pygame import os pygame.init() display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('A bit Racey') clock = pygame.time.Clock() carImg = pygame.image.load('racecar.png') def car(x,y): gameDisplay.blit(carImg,(x,y)) def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 print(x_change) gameExit = False while not gameExit: #event handling loop for event in pygame.event.get(): if event.type == pygame.QUIT: #one way to exit the loop gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change gameDisplay.fill(white) car(x,y) pygame.display.update() clock.tick(60) game_loop() pygame.quit() quit() The code worked (the keys moved the object) when I was moving some files around however it is now back to normal. My working directory inside spyder is '/users/himansu'. I feel like if I can get this script running in terminal it may function. Thank you.
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50255903
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/87532310
tagged with: for-loop
has comment: http://stackoverflow.com/comment/87530079
possible better answer: http://stackoverflow.com/a/50255973
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87602416
has comment: http://stackoverflow.com/comment/87530632
has comment: http://stackoverflow.com/comment/87530680
favorite count: 0
type: Question
tagged with: tuples
has answer: http://stackoverflow.com/a/50256565
has title: Find overlapping elements in a list of tuples?
tagged with: intersection
has answer: http://stackoverflow.com/a/50255973
has body: From my understanding of the intersection function, it finds complete overlap between elements in a list. For example: tup_1 = [(1,2,3),(4,5,6)] tup_2 = [(4,5,6)] ol_tup = set(tup_1).intersection(tup_2) print ol_tup would yield: set([(4, 5, 6)]) However, suppose my list of tuples are set up as this: tup_1 = [(1,2,3),(4,5,5)] tup_2 = [(4,5,6)] Where there's an overlap in 2 elements of the 2nd tuple in tup_1 and 1st tuple in tup_2. If I want to python to return these 2 tuples: (4,5,5) and (4,5,6), is there an easier way than this nested for loop (below)? for single_tuple_1 in tup_1: for single_tuple_2 in tup_2: if single_tuple_1[0] == single_tuple_2[0] and single_tuple_1[1] == single_tuple_2[1]: print single_tuple_1,single_tuple_2 EDIT: For this case, suppose order matters and suppose the tuples contain 5 elements: tup_1 = [(1,2,3,4,5),(4,5,6,7,8),(11,12,13,14,15)] tup_2 = [(1,2,3,4,8),(4,5,1,7,8),(11,12,13,14,-5)] And I would like to find the tuples that intersect with each other in their respective first 4 elements. So the result should be: [(1,2,3,4,5),(1,2,3,4,8),(11,12,13,14,15),(11,12,13,14,-5)] How would the code change to accommodate this?
tagged with: python
accepted answer: http://stackoverflow.com/a/50256565
score: 2

http://stackoverflow.com/a/50310636
type: Answer
score: 0
has body: Your code does the same than: items = [item['pk'] for item in json.loads(json_result)] This is called a list comprehension.
upvote count: 2
downvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50310616
accepted answer of: http://stackoverflow.com/q/50310616

http://stackoverflow.com/comment/87551716
has text: The issue is that when I run the script, I eventually get a timeout. Othertimes the address variable embeddded into data_request isn't recognized.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50266855

udp
tags question: http://stackoverflow.com/q/50294596
tag name: udp
type: Tag
tags question: http://stackoverflow.com/q/50354009
tags question: http://stackoverflow.com/q/50319570

http://stackoverflow.com/comment/87714894
comment on: http://stackoverflow.com/q/50346850
type: Comment
score: 0
type: QuestionComment
has text: I had not thought of that! That sounds like a perfect solution to my problem.

http://stackoverflow.com/q/50246105
has comment: http://stackoverflow.com/comment/87510311
accepted answer: http://stackoverflow.com/a/50246196
tagged with: time-series
has comment: http://stackoverflow.com/comment/87509945
upvote count: 2
has answer: http://stackoverflow.com/a/50246196
downvote count: 0
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87510128
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: datetime
answer count: 1
has title: Pandas - Resample/GroupBy DateTime Index and perform calculations
has body: I will try my best to explain what I need help with. I have the following df (thousands if not millions of rows) with a datetime index like the sample below: INDEX COL A COL B 2018-05-07 21:53:13.731 0.365127 9391.800000 2018-05-07 21:53:16.201 0.666127 9391.800000 2018-05-07 21:53:18.038 0.143104 9391.800000 2018-05-07 21:53:18.243 0.025643 9391.800000 2018-05-07 21:53:18.265 0.640484 9391.800000 2018-05-07 21:53:18.906 -0.100000 9391.793421 2018-05-07 21:53:19.829 0.559516 9391.800000 2018-05-07 21:53:19.846 0.100000 9391.800000 2018-05-07 21:53:19.870 0.006560 9391.800000 2018-05-07 21:53:20.734 0.666076 9391.800000 2018-05-07 21:53:20.775 0.666076 9391.800000 2018-05-07 21:53:28.607 0.100000 9391.800000 2018-05-07 21:53:28.610 0.041991 9391.800000 2018-05-07 21:53:29.283 -0.053518 9391.793421 2018-05-07 21:53:47.322 -0.046302 9391.793421 2018-05-07 21:53:49.182 0.100000 9391.800000 What I would like to do is group the rows in 5 second intervals and perform (sometimes complex) calculations on each 5 second interval/subset. Let's say for example I want to calculate the percentage of positive vs negative values in column A within each 5 second block. 2018-05-07 21:53:10 to 2018-05-07 21:53:15 only contains one row and column A is a positive so I would create a new column C with 100%. Similarly 2018-05-07 21:53:15 to 2018-05-07 21:53:20 has 8 rows in column A, 7 which are positive and 1 of which is negative. So column C would be 87.5%. I would post sample code but I'm really unsure the best way to do this. A sample output (new df) may be something like the below with COL D being simply the minimum number in COL B for that 5 second grouping: INDEX COL C COL D (MIN) 2018-05-07 21:53:10 100% 9391.800000 2018-05-07 21:53:15 12.5% 9391.793421 2018-05-07 21:53:20 100% 9391.800000 2018-05-07 21:53:25 66.7% 9391.793421 2018-05-07 21:53:30 nan nan 2018-05-07 21:53:35 nan nan 2018-05-07 21:53:40 nan nan 2018-05-07 21:53:45 100% 9391.793421 Please keep in mind I want to do man…
type: Question

http://stackoverflow.com/comment/87659414
comment on: http://stackoverflow.com/a/50321806
score: 0
type: Comment
has text: You don't have to instantiate a class to use a static method (which is what this user is looking for), in fact, in python, that is frowned upon.
type: AnswerComment

http://stackoverflow.com/comment/87757934
type: QuestionComment
comment on: http://stackoverflow.com/q/50352842
score: 0
has text: I want to attach a certain policy to all buckets though. Just in case, some privilege escalation occurred etc.
type: Comment

http://stackoverflow.com/comment/87770569
type: AnswerComment
type: Comment
has text: I realize that, and if you’re using this App Engine for data science, package support is something to keep in mind when selecting your language version. Another thing to keep in mind is that GCP is constantly evolving and growing - they are way better than they were a year ago - and it is reasonable to expect that at some point, Python 3 will be their standard moving forward.
comment on: http://stackoverflow.com/a/50376996
score: 0

http://stackoverflow.com/a/50292679
accepted answer of: http://stackoverflow.com/q/50292618
has body: The unittest docs explain this: By default main calls sys.exit() with an exit code indicating success or failure of the tests run. sys.exit() exits the script immediately, so your final line is never called. You can avoid this behaviour by passing exit=False: unittest.main(exit=False)
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87601556
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50292618
has comment: http://stackoverflow.com/comment/125836747

http://stackoverflow.com/comment/87626035
type: QuestionComment
score: 0
has text: @openmark no effect :/
comment on: http://stackoverflow.com/q/50303670
type: Comment

http://stackoverflow.com/comment/87724201
comment on: http://stackoverflow.com/a/50337326
score: 0
has text: Re' garbage collector: you didn't answer the question: what I'm asking is literally "if I have more incref than decref, will the GC be able to detect that the object isn't referenced from any code that's actually alive and delete it or not?" Or you need to explain what you mean by "leaked reference".
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50324940
accepted answer: http://stackoverflow.com/a/50325736
has comment: http://stackoverflow.com/comment/87666884
tagged with: nested-lists
has title: How to create all possible groupings of elements as list of lists in Python
upvote count: 3
has body: Suppose I have the following list: data= ['a','b','c','d','e','f','g','h','i'] How can I create all possible groups of 3 lists without repeats in each group? Example output will be: [[['a','b','c'],['d','e','f'],['g','h','i']],[['a','b','e'],['c','d','g'],['f','h','i']]...] etc EDIT: There should be no repeats in the code. For example, if the code outputs [['a','b','c'],['d','e','f'],['g','h','i']] then it shouldnt output variants like [['a','b','c'],['g','h','i'],['d','e','f']] or [['c','b','a'],['d','e','f'],['g','h','i']]
downvote count: 0
tagged with: combinations
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/50326072
has comment: http://stackoverflow.com/comment/87666748
has answer: http://stackoverflow.com/a/50325438
tagged with: python
has comment: http://stackoverflow.com/comment/87666674
has answer: http://stackoverflow.com/a/50325339
answer count: 4
possible better answer: http://stackoverflow.com/a/50325339
has comment: http://stackoverflow.com/comment/87666946
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50325736

http://stackoverflow.com/q/50384613
has answer: http://stackoverflow.com/a/75957063
has answer: http://stackoverflow.com/a/50385023
tagged with: python
has comment: http://stackoverflow.com/comment/87785027
has title: Pdf in django-rest-framework
type: AnsweredQuestion
answer count: 2
upvote count: 3
score: 3
has body: I am trying to make pdf in Django from xhtml2pdf import pisa from django.http import HttpResponse from django.template.loader import get_template from django.template import Context from rest_framework.views import APIView from .models import Brand class ABCView(APIView): def post(self, request,format=None): report = Brand.objects.all() template_path = 'profile_brand_report.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' context = {'report': report} template = get_template(template_path) html = template.render(Context(context)) print (html) pisaStatus = pisa.CreatePDF(html, dest=response) return response but I am getting an unexpected error I don't know what I am doing wrong, I am getting this error argument of type 'Context' is not iterable or is there any other way to do it .thanks for help in advance
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/75957063
accepted answer: http://stackoverflow.com/a/50385023

http://stackoverflow.com/q/50358785
tagged with: string
type: Question
tagged with: encoding
tagged with: byte
tagged with: python
score: 0
has body: I want to write a string to a file using Python. I know how to do that, so that's not a problem. I also wish to encode that string once it has been written. The encoding doesn't really matter, so I'll stick to let's say UTF-32. What I do for that is after I wrote the string, I read from the file again, encode the string into bytes and then re-write to the same file. I can do the encoding part, but my problem arises with the decoding. I want to read it as bytes so that I can convert it back to a str. What I do for this is the same principle: Read from file, decode and write to the same file. What I get from reading the encoded string looks like b'\xff\xfe\x00\x001\x00\x00\x004\x00\x00\x002\x00\x00\x00' When I read this as bytes, it doubles the b and the backslashes. If I read it like this, as a string, and then try to decode, it keeps saying 'str' object does not have attribute decode or something. I know that I can't decode the string, but if I try with bytes it seems to be "doubling" the bytes. Here is my code: def readfile(filename): f = open(filename, 'r') s = f.read() f.close() return s def readfile_b(filename): f = open(filename, 'rb') s = f.read() f.close() return s def writefile(filename, writeobject): f = open(filename, 'w') f.write(writeobject) f.close() def encode(filename): s = readfile(filename) s_enc = bytes(s, 'utf-32') writefile(filename, str(s_enc)) def decode(filename): s_enc = readfile_b(filename) print(s_enc) s = str(s_enc, 'utf-32') writefile(filename, s) encode("Example.txt") decode("Example.txt") Output (for decode(), encode() didn't have any errors): b"b'\\xff\\xfe\\x00\\x00H\\x00\\x00\\x00e\\x00\\x00\\x00l\\x00\\x00\\x00l\\x00\\x00\\x00o\\x00\\x00\\x00'" Traceback (most recent call last): File "C:/bla/bla/bla/bla/Example.py", line 29, in &lt;module&gt; decode("MamaAccount.txt") File "C:/bla/bla/bla/bla/Example.py", line 26, in decode s = str(s_enc, 'utf-32') UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-3: code point …
type: UnansweredQuestion
has title: Encoding and decoding string in Python
answer count: 1
has answer: http://stackoverflow.com/a/50358900

http://stackoverflow.com/comment/87552428
comment on: http://stackoverflow.com/q/50266996
type: Comment
type: QuestionComment
score: 1
has text: From the code he doesn't seem to be reshaping anything though. @Juanvulcano, just random guessing, could it be that the images don't all have the same shape so you're building a list of arrays instead of a tensor?

http://stackoverflow.com/a/50244063
answers question: http://stackoverflow.com/q/50243709
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/50243709
score: 7
has body: Here's one way without looking too hard at the docs.. fake image: im = Image.new('P', (16,4), 127) Get the (pixel) size of the single band image; create a new 3-band image of the same size; use zip to create pixel tuples from the original; put that into the new image.. w, h = im.size ima = Image.new('RGB', (w,h)) data = zip(im.getdata(), im.getdata(), im.getdata()) ima.putdata(list(data)) Or even possibly new = im.convert(mode='RGB')
type: Answer

http://stackoverflow.com/comment/87559456
has text: Stack Overflow is not a code writing service. Please show your code. Since Stack Overflow hides the Close reason from you: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/).*
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50270685

http://stackoverflow.com/comment/87619231
has text: Thank you so much!. Now that you mention it, I just noticed that i have never used return, I'm going to start reading even more about it in order to improve myself. Thanks again!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50301247
type: AnswerComment

http://stackoverflow.com/a/50260714
has comment: http://stackoverflow.com/comment/87543696
has body: The call to b.shorten(storeURL) will return a dict with key/value pairs, including the url. Python will throw that error when you concatenate a string and dict like you're doing in print(). I'd suggest something like: response = b.shorten(storeURL) shortURL = response['url']
score: 1
has comment: http://stackoverflow.com/comment/87550026
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50260409
has comment: http://stackoverflow.com/comment/87541031
has comment: http://stackoverflow.com/comment/87540085
accepted answer of: http://stackoverflow.com/q/50260409
has comment: http://stackoverflow.com/comment/87541225
type: Answer
has comment: http://stackoverflow.com/comment/87561690

http://stackoverflow.com/a/50307936
has comment: http://stackoverflow.com/comment/87633675
type: Answer
has comment: http://stackoverflow.com/comment/88799991
has body: When you execute code in Sublime there is no way to capture input. More technically, the console is connected to stderr and stdout but not stdin. So it's not possible to run an interactive program from within Sublime directly. However after seeing your code, a question arises - why don't you cast your price variable at the first time with user input method, so that you won't need multiple time to cast it from str to int and vice versa. To make you clear of this, see the following code , it's exactly the same but more smart approach i think. def calculateit(): price = int(input("please enter your price: ")) tip = price * 0.25 final = tip + price print (f"since the price of your meal is {price} your tip is {tip}" ) print (f"the total cost of your meal is {final}" ) calculateit()
score: 0
answers question: http://stackoverflow.com/q/50307589

http://stackoverflow.com/q/50254813
has title: Plot points on basemap with different markers depending on conditions in pandas data frame
has answer: http://stackoverflow.com/a/50263275
accepted answer: http://stackoverflow.com/a/50263275
linked to: http://stackoverflow.com/q/43018428
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: pandas
tagged with: matplotlib
answer count: 1
tagged with: python
has body: I am using matplotlib basemap to plot a trajectory from data in a pandas dataframe. Simply plotting lat, lon data as below works fine: map = Basemap(projection='stere',lon_0=lon,lat_0=lat, llcrnrlon=-65, llcrnrlat=55, urcrnrlon=50 , urcrnrlat=75) map.drawcountries() map.bluemarble() #Place marker at Kangerlussuaq x,y = map(lon, lat) map.plot(x, y, 'bo', markersize=10) plt.text(x, y, ' Kangerlussuaq', fontsize=12) #Plot trajectory map.plot(datacopy.long.tolist(), datacopy.lat.tolist(), 'r-', latlon=True) However, I want parts of the trajectory to be plotted with a different marker depending on the ambient temperature measured at each lat/lon but the following code gives me the error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). if datacopy['Ambient temp']&lt;280: map.plot(datacopy.long.tolist(), datacopy.lat.tolist(), 'r-', latlon=True) else: map.plot(datacopy.long.tolist(), datacopy.lat.tolist(), 'b-', latlon=True) Is this error due to the data being in a pandas dataframe and is there a way around it? Thanks
tagged with: matplotlib-basemap
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/113593673
has text: Hi. Have you figured out a way to do this? Currently trying to do same thing :)
type: Comment
comment on: http://stackoverflow.com/q/50366293
type: QuestionComment
score: 1

http://stackoverflow.com/comment/87633328
score: 0
type: AnswerComment
has text: Yes, but then I will get [None,None,None,None] shape if I print the shape of decon, Thank you so much for Your ans,
type: Comment
comment on: http://stackoverflow.com/a/50307810

http://stackoverflow.com/a/50315031
accepted answer of: http://stackoverflow.com/q/50315010
has comment: http://stackoverflow.com/comment/135235699
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50315010
score: 10
upvote count: 10
has body: You need to call writer.save() or writer.close() in later API after the for construct. Once this method is called, the writer object is effectively closed and you will not be able to use it to write more data. writer = ExcelWriter('test_output.xlsx') for n, df in enumerate(df_list): df.to_excel(writer, 'sheet%s' % str(n + 1)) writer.close()
type: Answer
has comment: http://stackoverflow.com/comment/87645939
has comment: http://stackoverflow.com/comment/95308502

http://stackoverflow.com/a/50322554
has body: The statement if (bolivia == "La Paz" or "Sucre"): Has the following two statements: 1) bolivia == "La Paz" 2) "Sucre" The latter statement "Sucre" is a string which is a Truthy value, thus the if statement as a whole will pass as they are joined together with the or keyword. What you likely want to evaluate is if bolivia == "La Paz" or bolivia == "Sucre": Or consider the in keyword: if bolivia in ("La Paz", "Sucre"):
answers question: http://stackoverflow.com/q/50322529
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50322529
type: Answer

http://stackoverflow.com/comment/87617625
comment on: http://stackoverflow.com/q/50300170
score: 0
type: QuestionComment
has text: @Håken Lid thanks for your reply. It is not possible that the aisles or slots are fractions. They indeed should be integers. However, xlwings imports them als floats. It is not a major problem but i still have to figure out how to import them as integers to make everything look nicer.
type: Comment

http://stackoverflow.com/a/50336510
score: 1
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50335782
has body: Using the same logic create Series, then we using intersection for list s=pd.Series(customer_emails) pd.DataFrame(np.reshape([len(set(x).intersection(set(y)))for x in s for y in s ],(3,3)),index=s.index,columns=s.index) Out[299]: Backpack Baseball Bat Gloves Backpack 4 2 3 Baseball Bat 2 3 1 Gloves 3 1 3

http://stackoverflow.com/comment/87779265
has text: I am good now, thanks for the help everyone.
type: QuestionComment
comment on: http://stackoverflow.com/q/50381448
score: 0
type: Comment

http://stackoverflow.com/q/50367191
upvote count: 0
linked to: http://stackoverflow.com/q/38109270
tagged with: jupyter
has comment: http://stackoverflow.com/comment/87750973
has title: Python jupyter library import error
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: opencv
has body: I have installed Anaconda to use jupyter notebook. After a while I installed cv2 library using cmd. It installed perfectly and works in normal cmd python window. But when I'm trying to load cv2 library into my jupyter notebook, I'm getting an error; ModuleNotFoundError: No module named 'cv2'
type: Question
duplicate of: http://stackoverflow.com/q/38109270
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50367497
tagged with: jupyter-notebook
score: -1

http://stackoverflow.com/comment/87635736
type: Comment
type: AnswerComment
has text: @juanpa.arrivillaga I understand from your answer that data is stored directly as binary instead of text (csv) which would store each of these 25 characters in separate char memory. I thought some compression was involved, i guess not, its just storage. 1. Wish to correct my understanding. 2. What if the data was only text? I guess the difference wont be huge.
comment on: http://stackoverflow.com/a/50309835
score: 0

http://stackoverflow.com/q/50381324
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I'm new in python programming and i have a question about reading from csv file. What am I trying to do is to split in 2 my csv file and save in two list. So form my next csv file: 5.1,3.5,1.5,0.2,setosa 4.9,3.0,1.4,0.2,setosa 4.6,3.1,1.5,0.2,setosa I need my lists to look like: firstList = [ [5.1, 3.5, 1.5, 0.2], [4.9, 3.0, 1.4, 0.2], [4.6, 3.1, 1.5, 0.2] ] secondList = ['setosa', 'setosa', 'setosa'] I tried different time, but my closest result is the next one: firstList = [] secondList = [] with open('file.csv') as file: fileReader = csv.reader(file, delimiter=',') for row in fileReader: firstList.append(row) secondList.append(row[4]) And the output for this one is: firstList = [ ['5.1', '3.5', '1.5', '0.2', 'setosa'], ['4.9', '3.0', '1.4', '0.2', 'setosa'], ['4.6', '3.1', '1.5', '0.2', 'setosa'] ] secondList = ['setosa', 'setosa', 'setosa'] I just want to get rid of string 'setosa' from my firstList and also convert everything else into int Any help would be grateful. Thank you!
has title: Get specific column from csv file in python
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50381498
has answer: http://stackoverflow.com/a/50381498

http://stackoverflow.com/a/50304237
has body: You have to use f.write(b) to save b in your file
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50304216

http://stackoverflow.com/comment/87774856
type: Comment
type: QuestionComment
has text: I wrote my code in my first commande. I do not get what I expect, is there an issue?
score: 0
comment on: http://stackoverflow.com/q/50379171

http://stackoverflow.com/a/50306146
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50304607
has body: If you represent your sequence of None checks using lambdas, like so: check_1 = lambda r: r.books_count check_2 = lambda r: r.string check_3 = lambda r: int(r) Then we can generalize a solution for any number of those checks. This function is similar (in a way) to how functools.reduce works: def my_reduce(fs, arg, stop_value=None): res = arg for f in fs: res = f(res) if res == stop_value: return stop_value return res Then use it like this: my_reduce([check_1, check_2, check_3], good_value) Out[1]: 42 my_reduce([check_1, check_2, check_3], bad_value) is None Out[2]: True

http://stackoverflow.com/comment/87496947
score: 2
type: AnswerComment
type: Comment
has text: @Nils_Denter do not import it. It is [a builtin](https://docs.python.org/3/library/functions.html) - it is always available (unless overwritten by an assignment).
comment on: http://stackoverflow.com/a/50239725

http://stackoverflow.com/comment/87792418
has text: it is not advisable to use `type()` for this. Python has `isinstance()` function for this very purpose. Read this for more info https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50367023
score: 0

http://stackoverflow.com/a/51407248
has body: The difference is that if you're reusing variables every iteration starts with a broadcast of the variables from their original location all GPUs, while if you're copying variables this broadcast is unnecessary, so not sharing should be faster. The one downside of not sharing is that it's easier for a bug or numerical instability somewhere to lead to different GPUs ending up with different values for each variable.
answers question: http://stackoverflow.com/q/50277910
has comment: http://stackoverflow.com/comment/89785756
has comment: http://stackoverflow.com/comment/89787867
type: Answer
score: 0

http://stackoverflow.com/q/50333757
has answer: http://stackoverflow.com/a/50333814
tagged with: text
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50333814
type: Question
has body: I'm trying to clean some NexisLexis news data using Neal Caren's Python script. However, when I do try to run it, this specific line gives me a ZeroDivisionError: meta_list=[m for m in meta_list if float(lnraw.count(m))/(len(workfile)&gt;.20)] With the workfile being: workfile=re.sub(' Copyright .*?\\r\\n','ENDOFILE',lnraw) workfile=workfile.replace('\xef\xbb\xbf\r\n','') workfile=workfile.split('ENDOFILE') workfile=[f for f in workfile if len(f.split('\r\n\r\n'))&gt;2] I cannot seem to fix it, the non-zero condition does seem to be met with the >.20?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Cleaning LexisNexis txt file, ZeroDivisionError
tagged with: jupyter

http://stackoverflow.com/comment/87745109
has text: Well I tried it and it seems to meet my expectations so far. Just did not hear about it yet (and when I search for "dijkstra in python" I did not get it on DDG or Google). Regarding the metric property, I am not sure to understand what you mean by setting weight attribute. By "metric graph", I mean that my weights satisfy the triangle inequality. My intuition leads me to think this could help to optimize dijkstra, but I may be wrong.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50356800

http://stackoverflow.com/q/50327559
possible better answer: http://stackoverflow.com/a/50328125
has title: How to insert a range of numbers into sqlite3
downvote count: 0
has answer: http://stackoverflow.com/a/50327760
accepted answer: http://stackoverflow.com/a/50327760
upvote count: 1
score: 1
tagged with: sqlite
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87671506
has comment: http://stackoverflow.com/comment/87671459
type: Question
tagged with: python-3.x
answer count: 2
has body: This is my code: import sqlite3 connector = sqlite3.connect("Database_1.db") cursor = connector.cursor() def Table_making(): cursor.execute("CREATE TABLE IF NOT EXISTS Tester(Tester_1 INT)") def data_entry(): for x in range(1,10): cursor.executemany("INSERT INTO Tester(Tester_1) VALUES(?)", x) connector.commit() cursor.close() connector.close() Table_making() data_entry() As you can see I am trying to insert a range of numbers from (0,10) to Table_1, but I continuously run into this error: TypeError: 'int' object is not iterable How can i get around this error and insert the range of numbers?
has answer: http://stackoverflow.com/a/50328125
type: AnsweredQuestion

join
type: Tag
tags question: http://stackoverflow.com/q/50366424
tags question: http://stackoverflow.com/q/50368792
tag name: join
tags question: http://stackoverflow.com/q/50276334
tags question: http://stackoverflow.com/q/50257586
tags question: http://stackoverflow.com/q/50306145
tags question: http://stackoverflow.com/q/50314757
tags question: http://stackoverflow.com/q/50347679
tags question: http://stackoverflow.com/q/50258168
tags question: http://stackoverflow.com/q/50337660
tags question: http://stackoverflow.com/q/50358812

http://stackoverflow.com/q/50317601
has comment: http://stackoverflow.com/comment/87662916
tagged with: spark-structured-streaming
tagged with: python
has comment: http://stackoverflow.com/comment/87651434
has title: Structured Streaming - Running different function by key for message in the same batch
score: 0
has comment: http://stackoverflow.com/comment/87651369
tagged with: apache-spark
answer count: 0
has comment: http://stackoverflow.com/comment/87662861
has comment: http://stackoverflow.com/comment/87651430
type: Question
tagged with: apache-kafka
has body: I have implemented a Kafka consumer in PySpark (Spark 2.2.1) I'm using the structured-streaming technology. Each receiving batch contains messages where the value column is from different types (distinguish by the key), and its schema is different. Now, I want to run different logic on the value column according to the message column key. How can I group (by key) the received messages, and run specific logic for each group in PySpark? Here is a snippet from my code, which works when all messages are of the same type: lines = spark.readStream.format("kafka")... schema_struct = get_schema_struct(...) udf_identical_func = udf( lambda k,msg: do_something_identical_to_all_types(k,msg)), schema_struct ) res = lines.select(udf_identical_func("key","value")) udf_specific_toEach_type_func = udf( lambda k,msg: do_something_specific_to_each_type(k,msg)), schema_struct ) res= res.select(udf_specific_toEach_type_func) q = res.writeStream.... q.awaitTermination() Thanks for any help
has comment: http://stackoverflow.com/comment/87662931
type: UnansweredQuestion
tagged with: pyspark

http://stackoverflow.com/comment/87618691
type: Comment
score: 0
type: AnswerComment
has text: Updated to handle 1.
comment on: http://stackoverflow.com/a/50300922

http://stackoverflow.com/comment/87766754
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50375093
has text: This might help: https://stackoverflow.com/questions/29188656/print-month-using-the-month-and-day

http://stackoverflow.com/comment/87527528
score: 0
type: AnswerComment
has text: Thanks for the concise answer!
comment on: http://stackoverflow.com/a/50254907
type: Comment

http://stackoverflow.com/q/50272484
downvote count: 4
accepted answer: http://stackoverflow.com/a/50272690
has body: From "Elements of Programming Interviews in Phyton", page 37, this little program reorders an array of integers so that the even numbers appear first. def even_odd(A): next_even, next_odd = 0, len(A) - 1 while next_even &lt; next_odd: if A[next_even] % 2 == 0: next_even += 1 else: A[next_even], A[next_odd] = A[next_odd], A[next_even] next_odd -= 1 My question: what does the "-1" in "len(A) - 1" do/mean?
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: syntax
has comment: http://stackoverflow.com/comment/87561839
possible better answer: http://stackoverflow.com/a/50272589
has comment: http://stackoverflow.com/comment/87561960
favorite count: 0
has answer: http://stackoverflow.com/a/50272690
has comment: http://stackoverflow.com/comment/87561835
type: Question
score: -2
has title: What does "len(A) - 1" mean?
has comment: http://stackoverflow.com/comment/87574185
has comment: http://stackoverflow.com/comment/87561832
tagged with: python
has answer: http://stackoverflow.com/a/50272589

http://stackoverflow.com/comment/92140541
has text: (This post does not seem to provide a [quality answer](https://stackoverflow.com/help/how-to-answer) to the question. Please either edit your answer and improve it, or just post it as a comment to the question.)
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52602974

http://stackoverflow.com/comment/87604210
type: QuestionComment
has text: pstatix, exactly. It wants the exact value as <K,V> where K = string and V = <k, v>
type: Comment
comment on: http://stackoverflow.com/q/50293845
score: 0

http://stackoverflow.com/comment/87487341
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50233656
has text: @Balaji It's hard to understand in comments. Please add this part in your question above.
type: AnswerComment

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/50337632
tags question: http://stackoverflow.com/q/50267783
type: Tag

http://stackoverflow.com/q/50257235
type: Question
has answer: http://stackoverflow.com/a/50323225
upvote count: 0
score: -2
tagged with: python
has title: Importing module in other package causes error
has comment: http://stackoverflow.com/comment/87549412
type: AnsweredQuestion
has body: I have the following project structure: project/ app1/ __init__.py views.py helper.py app2/ __init.py file2.py app1/__init__.py: from flask import Flask app = Flask(__name__) from app1 import views In app1.helper, I can do from app1 import app and it works. If I try to do the same import in app2.file2, I get ImportError: No module named flask_app. I tried sys.path.append/insert but it didn't work.
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/50323225
has comment: http://stackoverflow.com/comment/87535880
favorite count: 0

http://stackoverflow.com/a/50254907
answers question: http://stackoverflow.com/q/50254244
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/50254244
has comment: http://stackoverflow.com/comment/87527528
downvote count: 0
score: 1
upvote count: 1
has body: You usually determine the encoding based on the HTTP headers returned by the server. Instead of determining that yourself, use the requests module which performs all that for you, so getting the content is as simple as: import requests req = requests.get("your_url") if req.status_code == 200: print(req.text) # print out the decoded content or do whatever you want with it If the encoding is not present in the header itself then it gets a bit more complicated - you'll have to treat the response as ascii encoded HTML, try to find a &lt;meta http-equiv="Content-Type" ... /&gt; tag and extract from its content the encoding. Once you have it, you'll have to decode the content again with the encoding in question. In the requests response, the non-decoded content is available in req.content so to get ascii encoded HTML use req.content.decode("ascii") then parse its HTML and seek for the codec (search SO on how to parse HTML in Python), and, finally, when you have the codec just re-decode the content with that codec: req.content.decode(your_discovered_codec) to get to the properly decoded content.

http://stackoverflow.com/q/50254340
tagged with: python-imaging-library
has title: NumPy 2D array iteration speed
tagged with: python
has comment: http://stackoverflow.com/comment/87672874
has comment: http://stackoverflow.com/comment/87527832
has body: I have a loop which fills up a 2-D NumPy array with pixel information for PIL, this array is called 'Shadows'. The colours are either white or blue. I want to build up a final image from these where the white is dominant. i.e. if one image in the loop has a blue pixel on co-ordinate x,y and another image in the loop has a white pixel on the same co-ordinate then the final pixel will be white. This is currently done by: import math, random, copy import numpy as np from PIL import Image, ImageDraw colours = {0: (255,255,255), 1: (0,0,255)} #width and height of area of interest w = 100 #100 meter h = 200 #200 meter NumberOfDots = 10 DotRadius = 20 NumberOfRuns = 3 Final = np.array([[colours[0] for x in range(w)] for y in range(h)]) Shadows = np.array([[colours[0] for x in range(w)] for y in range(h)]) for SensorNum in range(NumberOfRuns): Shadows = np.array([[colours[0] for x in range(w)] for y in range(h)]) for dot in range(NumberOfDots): ypos = random.randint(DotRadius, h-DotRadius) xpos = random.randint(DotRadius, w-DotRadius) for i in range(xpos - DotRadius, xpos + DotRadius): for j in range(ypos - DotRadius, ypos + DotRadius): if math.sqrt((xpos - i)**2 + (ypos - j)**2) &lt; DotRadius: Shadows[j][i] = colours[1] im = Image.fromarray(Shadows.astype('uint8')).convert('RGBA') im.save('result_test_image'+str(SensorNum)+'.png') #This for loop below is the bottle-neck. Can its speed be improved? if SensorNum &gt; 0: for i in range(w): for j in range(h): #White space dominates. #(pixel by pixel) If the current images pixel is white and the unfinshed Final #images pixel is blue then set the final pixel to white. if np.all(Shadows[j][i]==colours[0]) and np.all(Final[j][i]==colours[1]): Final[j][i] = colours[0] else: Final = copy.deepcopy(Shadows) im = Image.fromarray(Final.astype('uint8')).convert('RGBA') im.save('result_final_test.png') The final nested for loop is what I am interested in improving. This works fine but the iteration is a huge bottle neck. Is there anyway …
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50291600
has answer: http://stackoverflow.com/a/50291600
tagged with: arrays
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87669956
favorite count: 0
has comment: http://stackoverflow.com/comment/87533913
type: Question
has comment: http://stackoverflow.com/comment/87594418

http://stackoverflow.com/q/50282453
type: UnansweredQuestion
tagged with: python
tagged with: bots
score: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51584063
upvote count: 1
tagged with: discord
has title: Python Discord Bot Prune Command
favorite count: 0
type: Question
tagged with: discord.py
has body: I am creating a bot written in python for Discord. I want it to be able to delete specific user's messages, instead of just every message in the text channel. I saw another post on here that helped a bit, but I am having trouble figuring out how to do the 'specific user' part. Here's what I have: @client.command(pass_context = True) async def purge(ctx, number): number = int(number) #Converting the amount of messages to delete to an integer counter = 0 async for x in client.logs_from(ctx.message.channel, limit = number): if counter &lt; number: await client.delete_message(x) counter += 1

http://stackoverflow.com/q/50349562
favorite count: 0
has title: Python MySQL Connector: caching_sha2_password plugin
answer count: 5
has answer: http://stackoverflow.com/a/73055220
tagged with: mysql
has comment: http://stackoverflow.com/comment/132023110
has answer: http://stackoverflow.com/a/50578838
tagged with: mysql-connector
has answer: http://stackoverflow.com/a/52559110
type: Question
has comment: http://stackoverflow.com/comment/107986820
has answer: http://stackoverflow.com/a/52015669
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/62028813
tagged with: python
has body: I am trying to connect to MySQL (8.0.11) from Python (3.6) on Windows 7 with the following code: import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='root', password='*****', database='test') except mysql.connector.Error as err: print(err) else: cnx.close() However i get following error message: Authentication plugin 'caching_sha2_password' is not supported How can i avoid this error?

http://stackoverflow.com/comment/87655181
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50319600
type: AnswerComment
has text: The problem is the website is sending `ajax` request calling a different API and using JS to manipulate the data. Here I found this endpoint using the browser's network that have the information you need https://ws.alibaba.ir/api/v1/flights/domestic/available/MTc4NzYzNDE0LTAtNjM2NjE4MzUxNzI5Mjc2ODE3LTE= Just parse these `JSON`

http://stackoverflow.com/comment/136770445
type: AnswerComment
score: 2
has text: `json.dumps(asdict(ex), default=str)` will transform datetimes into str (default representation). It will do the same for all other types that aren't JSON serializable. https://docs.python.org/3/library/json.html#json.dump
comment on: http://stackoverflow.com/a/50380077
type: Comment

http://stackoverflow.com/comment/87707806
type: QuestionComment
has text: @DanielRoseman, yeah sorry for that, I was using Python 2.7, but even the code in documentation is same
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50345763

http://stackoverflow.com/comment/87741932
has text: @Primusa Thanks man that fixed it
type: QuestionComment
comment on: http://stackoverflow.com/q/50362707
score: 0
type: Comment

http://stackoverflow.com/a/50343827
has body: You can use web proxies that allow hotlinking or APIs, or you can use proxychains if you are on linux, or if you want to go for manual effort go for VPNs.
answers question: http://stackoverflow.com/q/50343736
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/87675693
type: Comment
comment on: http://stackoverflow.com/q/50329853
score: 0
has text: Join columns X,Y together to a tuple and do a simple Counter() from collections.
type: QuestionComment

http://stackoverflow.com/comment/87643026
type: AnswerComment
comment on: http://stackoverflow.com/a/50309651
has text: data_list gets clear for every iterations anyway then why does dictionary get printed correctly inside for loop?
type: Comment
score: 0

http://stackoverflow.com/comment/87527950
comment on: http://stackoverflow.com/q/50242285
type: Comment
score: 0
has text: Thank you, Ilja. I tested this and it works, but I noticed it doesn't work if I change the date string from "MM/DD/YYYY" to "YYYY-MM-DD". I'm just moving digits around and using hyphens instead of slashes, so I'm not sure why it wouldn't work. I'll update the original post.
type: QuestionComment

http://stackoverflow.com/comment/87651434
type: QuestionComment
has text: @user96 A ternary could work ;) But, more specifically, add to those `do_something` functions
comment on: http://stackoverflow.com/q/50317601
score: 1
type: Comment

http://stackoverflow.com/a/50237036
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87530092
has comment: http://stackoverflow.com/comment/87501569
has comment: http://stackoverflow.com/comment/87503711
accepted answer of: http://stackoverflow.com/q/50236637
type: Answer
has body: Maybe this is what you need: import itertools my_array = ['A','B','C'] combos = [] for i in range(1,len(my_array)): combos += itertools.combinations(my_array, i) result = [] for c1 in combos: curr = list(c1) for c2 in combos: if not any(i in curr for i in c2): result.append([curr, list(c2)]) result #[[['A'], ['B']], # [['A'], ['C']], # [['A'], ['B', 'C']], # [['B'], ['A']], # [['B'], ['C']], # [['B'], ['A', 'C']], # [['C'], ['A']], # [['C'], ['B']], # [['C'], ['A', 'B']], # [['A', 'B'], ['C']], # [['A', 'C'], ['B']], # [['B', 'C'], ['A']]]
answers question: http://stackoverflow.com/q/50236637
has comment: http://stackoverflow.com/comment/87492173
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87775921
has text: Isn't there an `{` missing in your `f` string?
comment on: http://stackoverflow.com/q/50379319
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50359667
tagged with: multithreading
has body: I was trying to set up a code of parallel jobs using multiprocessing module. I would like to terminate all the child job within 10 seconds. I made the following code using timeout argument in process join function. However, I found the termination time of all the jobs depend on both the values of the timeout and the number of jobs. How do I calculate the accurate time? import time from multiprocessing import Manager, Process def f(x, dic): time.sleep(60) print "Time: ", x dic[x] = "Done" mng = Manager() dic = mng.dict() jobs = [Process(target=f, args=(i, dic)) for i in range(50)] for job in jobs: job.start() for job in jobs: job.join(timeout=10) for job in jobs: job.terminate() for job in jobs: job.join() print dic.keys()
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50359874
has title: Fix time in timeout of multiprocessing process
answer count: 1
tagged with: timeout
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50359874

http://stackoverflow.com/comment/109236007
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50484727
type: Comment
has text: This is exactly what I was looking for. I though about the same solution but assumed there was a simpler way of doing it. Thanks!

http://stackoverflow.com/comment/87610370
type: Comment
comment on: http://stackoverflow.com/a/50295798
type: AnswerComment
has text: To my knowledge, it's not any better or worse. I thought it'd be better since allows for one line, but now that I look at it again the .assign may be less readable, so I'm switching that back.
score: 0

http://stackoverflow.com/q/50304156
has answer: http://stackoverflow.com/a/71352432
tagged with: memory
linked to: http://stackoverflow.com/q/35911252
has comment: http://stackoverflow.com/comment/87726941
has answer: http://stackoverflow.com/a/53528001
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55246936
score: 62
has answer: http://stackoverflow.com/a/73078670
has comment: http://stackoverflow.com/comment/87727077
downvote count: 0
has answer: http://stackoverflow.com/a/61760360
has answer: http://stackoverflow.com/a/75591721
tagged with: resnet
possible better answer: http://stackoverflow.com/a/55246936
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51367588
has answer: http://stackoverflow.com/a/63689843
has answer: http://stackoverflow.com/a/66438196
type: AnsweredQuestion
tagged with: keras-layer
has title: Tensorflow Allocation Memory: Allocation of 38535168 exceeds 10% of system memory
has answer: http://stackoverflow.com/a/54202348
has body: Using ResNet50 pre-trained Weights I am trying to build a classifier. The code base is fully implemented in Keras high-level Tensorflow API. The complete code is posted in the below GitHub Link. Source Code: Classification Using RestNet50 Architecture The file size of the pre-trained model is 94.7mb. I loaded the pre-trained file new_model = Sequential() new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weight_paths)) and fit the model train_generator = data_generator.flow_from_directory( 'path_to_the_training_set', target_size = (IMG_SIZE,IMG_SIZE), batch_size = 12, class_mode = 'categorical' ) validation_generator = data_generator.flow_from_directory( 'path_to_the_validation_set', target_size = (IMG_SIZE,IMG_SIZE), class_mode = 'categorical' ) #compile the model new_model.fit_generator( train_generator, steps_per_epoch = 3, validation_data = validation_generator, validation_steps = 1 ) and in the Training dataset, I have two folders dog and cat, each holder almost 10,000 images. When I compiled the script, I get the following error Epoch 1/1 2018-05-12 13:04:45.847298: W tensorflow/core/framework/allocator.cc:101] Allocation of 38535168 exceeds 10% of system memory. 2018-05-12 13:04:46.845021: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:47.552176: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:48.199240: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:48.918930: W tensorflow/core/framework/allocator.cc:101] Allocation of 37171200 exceeds 10% of system memory. 2018-05-12 13:04:49.274137: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory. 2018-05-12 13:04:49.647061: W tensorflow/core/framework/allocator.cc:101] Allocation of 19267584 exceeds 10% of system memory. 2018-05-12 13:04:50.028839: W…
upvote count: 62
answer count: 10
tagged with: python
accepted answer: http://stackoverflow.com/a/51367588
has comment: http://stackoverflow.com/comment/87726866

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/50361096

http://stackoverflow.com/comment/87754271
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50367337
has text: Apart from saying you are trying to access an element of a list that isn't there, this cannot be properly answered without a [mcve].

http://stackoverflow.com/comment/87584352
comment on: http://stackoverflow.com/q/50283992
score: 0
has text: for what `n` are you getting an overflow, if the number is more than a signed 64bit number you won't be able to store it in an array of `dtype='int64'`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50303508
favorite count: 0
type: Question
downvote count: 9
has title: Converting binary code to DNA code
score: -8
tagged with: python
type: AnsweredQuestion
has body: I am trying to write a python program for converting binary code to DNA code using the following data: A = 00, B = 10 , C = 01, D = 11. We input a 8 digit binary code and the program converts it to a 4 letter dna code using this data. What could the code for this program be?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87623414
has answer: http://stackoverflow.com/a/50303571
accepted answer: http://stackoverflow.com/a/50303571

http://stackoverflow.com/comment/87756479
has text: I don't know exactly how to solve your problem but i think that documentation would help https://docs.djangoproject.com/en/2.0/topics/testing/overview/
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50370312
type: QuestionComment

http://stackoverflow.com/a/50284876
has comment: http://stackoverflow.com/comment/87586099
has comment: http://stackoverflow.com/comment/87586116
has comment: http://stackoverflow.com/comment/87585985
has body: The root of your media, should include the BASE_DIR, like the following: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' You have a typo in your template, you'are accessing {{eachshirt.image.url}} without t. the correct is {{eachtshirt.image.url}} &lt;!-- with t : each tshirt --&gt;
score: 1
answers question: http://stackoverflow.com/q/50284845
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87585901
upvote count: 1

http://stackoverflow.com/comment/87650081
type: AnswerComment
has text: Nothing proves that characters are not consecutive.
comment on: http://stackoverflow.com/a/50317149
type: Comment
score: 0

http://stackoverflow.com/q/50363078
has comment: http://stackoverflow.com/comment/87742516
has comment: http://stackoverflow.com/comment/87742699
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50363762
tagged with: parsing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87742756
has comment: http://stackoverflow.com/comment/87743398
has comment: http://stackoverflow.com/comment/87742436
accepted answer: http://stackoverflow.com/a/50363762
tagged with: python
has body: Suppose I have json data like this. {"id": {"$oid": "57dbv34346"}, "from": {"$oid": "57dbv34346sbgwe"}, "type": "int"} {"id": {"$oid": "57dbv34345"}, "from": {"$oid": "57dbv34345sbgwe"}, "type": "int"} I wrote a script like this in python import json with open('klinks_buildson.json', 'r') as f: for line in f: distros_dict = json.dumps(json.loads(line), sort_keys=True, indent=4) print distros_dict['from'] print "\n" But It is giving me an error: print distros_dict['from'] TypeError: string indices must be integers, not str I want data of the from in both the lines.
has title: Can't access JSON loaded with json.dumps(json.loads(input))
has comment: http://stackoverflow.com/comment/87742662
has comment: http://stackoverflow.com/comment/87742410
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87742787

http://stackoverflow.com/a/61741031
upvote count: 8
answers question: http://stackoverflow.com/q/50231134
has body: There's an incompatibility version between pandas and your blaze package. It also does not have a fixed version, so the incompatibility can appear any time. You can downgrade two packages at once: conda install pandas==0.25 python==3.7 I'd uninstall blaze, downgrade pandas and try to reinstall blaze again. It is always a good practice to fix your package versions and commit them to your version control. Use this command: conda env export -f environment.yml It will save every version of your pandas and pip packages. Add it to your version control. BTW, I prefer to export using the option --from-history. It will export just the libs you explicitly installed, and not the dependencies: conda env export --from-history &gt; environment.yml It will prevent a lot of troubles. Note: for --from-history to work fine, you must have fixed your package version when installing packages: conda install pandas==0.25. Do not install without a version number: conda install pandas
type: Answer
score: 8
downvote count: 0

http://stackoverflow.com/comment/132494091
type: AnswerComment
comment on: http://stackoverflow.com/a/50328050
type: Comment
has text: Out of all these options: options.add_argument("window-size=2560,1440"), options.add_argument("--window-size=2560,1440"), options.add_argument("start-maximized"), driver.maximize_window() this is the only one that works with headless. Thank you.
score: 0

http://stackoverflow.com/q/50252213
has comment: http://stackoverflow.com/comment/87523020
upvote count: 0
answer count: 1
has body: great thanks but nnow when i do pip3 install pyplot it says: could not find a version that satisfies the requirement pyplot Sorry quite noob still in this area but willing to do great things :)
favorite count: 0
type: Question
tagged with: linux
type: UnansweredQuestion
score: -4
tagged with: python
has title: udemy course ai cannot continue installation matplotlib.pyplot
tagged with: ubuntu
has answer: http://stackoverflow.com/a/50252411
downvote count: 4

http://stackoverflow.com/comment/87665004
type: QuestionComment
score: 0
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!
type: Comment
comment on: http://stackoverflow.com/q/50324413

http://stackoverflow.com/q/50256606
has body: I am writing a simple program that reads new input being written to a file and displays it in popup windows. I am using PyQt5 for: A) File changes (QtCore) B) Window (QtWidgets) Note that I do actually have a working model using signals as per PyQt reference guide. But couldn't figured out the below, therefore I am not understanding how things works. While testing implementations i came across with multi-thread issues. This is a simplified example of my problem: from PyQt5 import QtWidgets import sys import threading def additem(window): """ generates label in window at bottom """ print("Adding label to window on thread {}".format(threading.currentThread())) row = window.layout().rowCount() + 1 btn = QtWidgets.QPushButton('button_' + str(row), window) window.layout().addWidget(btn,row,1) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() w.setLayout(QtWidgets.QGridLayout()) # set to timers after 3,6 will generate label in window threading.Timer(3,additem,args=(w,)).start() threading.Timer(6,additem,args=(w,)).start() w.show() sys.exit(app.exec_()) Output: Adding label to window QObject::setParent: Cannot set parent, new parent is in different thread I tried setting global queue to pass around objects but still same error. Although I now why the exception is raised, I do not understand how to avoid it. One attempt was to directly pass the top object "app" and then getting the window by index (app is the top parent): ... threading.Timer(3,additem,args=(app,)).start() ... def additem(app): w = app.allWidgets()[0] ... I know PyQt is a C library wrapped in python but I am not familiar with C. The app object is a pointer to the object in the memory heap, why it can't manipulate the object? is the object being copied in a new thread? (thought I could still "update" that object)
has title: Python PyQt dynamic widget generation using multithread
answer count: 0
tagged with: pyqt
tagged with: pyqt5
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/16501284
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/16501284
has comment: http://stackoverflow.com/comment/87531521
has comment: http://stackoverflow.com/comment/87531129
score: 0

http://stackoverflow.com/comment/87596881
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50285324
has text: That woked :) so is there any thing for multiple values like var_value1 & var_value2?
score: 0

http://stackoverflow.com/comment/87504399
score: 0
type: QuestionComment
type: Comment
has text: are you sure your proxy server is good?
comment on: http://stackoverflow.com/q/50242587

http://stackoverflow.com/q/50289484
tagged with: loops
has comment: http://stackoverflow.com/comment/87599819
has title: integrating cython and python Spyder anaconda
linked to: http://stackoverflow.com/q/17955194
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: spyder
has body: I'm new on python and Spyder and I'm trying to cythonize a for loop. I'm using Spyder 3.2.7 from anaconda navigator, so I run the code by just pushing the green triangular button. My pyx file looks like: import numpy as np def saluti(): print('hello world') def new_sum(double[:] X, double[:] beta, double[:,:] theta): cdef int N = X.shape[0] cdef double[:] Y = np.zeros(N) cdef int i, j for i in range(N): for j in range(i): Y[i] += beta[j] * np.exp(-theta[i, j]*(X[i] - X[j])) return Y While my py file: import numpy as np import pyximport pyximport.install() from prova_cythonn import saluti, new_sum def old_sum (x, beta, theta): N = x.shape[0] y = np.zeros(N) for i in range(N): for j in range(i): y[i] = y[i] + beta[j]*np.exp(-theta[i, j]*(x[i] - x[j])) return y ... do stuff (like print(np.sum(old_sum) or print(np.sum(new_sum)) ... When importing 'saluti' only, I get no error and obtain the 'hello world' message printed in the Ipython console. If I try to import the new_sum function I get ImportError: cannot import name 'new_sum' It seems to me that the problem is that if I modify and save the pyx savings are not 'read' when launching the py
tagged with: python
has comment: http://stackoverflow.com/comment/87605389
upvote count: 2
has comment: http://stackoverflow.com/comment/87604630
answer count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/87604663
tagged with: cython

http://stackoverflow.com/q/50308811
tagged with: valueerror
tagged with: lstm
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50309105
score: 0
has title: LSTM Cells, Input Shape Error
has answer: http://stackoverflow.com/a/50309105
answer count: 1
has body: I am trying to build LSTM Net with my input data with 41 fields. My idea is that current output is a function of current inputs as well as 49 previous inputs. I am trying to run following: CommonModel = Sequential() CommonModel.add(LSTM(50, return_sequences=True, input_shape=(None, 41))) CommonModel.add(LSTM(50, return_sequences=True)) CommonModel.add(LSTM(50)) CommonModel.add(Dense(20,activation='relu')) CommonModel.add(Dense(10,activation='relu')) CommonModel.add(Dense(1,activation='relu')) CommonModel.compile(loss = 'mse', optimizer = 'adam', metrics=['accuracy']) CommonModel.summary() Layer (type) Output Shape Param # dense_41 (Dense) (None, None, 50) 2100 dense_42 (Dense) (None, None, 20) 1020 dense_43 (Dense) (None, None, 10) 210 dense_44 (Dense) (None, None, 1) 11 Total params: 3,341 Trainable params: 3,341 Non-trainable params: 0 CommonModel.fit(Axis_X,Axis_Y,epochs=140,batch_size=64) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-90-f80115738f18&gt; in &lt;module&gt;() ----&gt; 1 CommonModel.fit(Axis_X,Axis_Y,epochs=140,batch_size=64) ~\Anaconda3\lib\site-packages\keras\models.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 961 initial_epoch=initial_epoch, 962 steps_per_epoch=steps_per_epoch, --&gt; 963 validation_steps=validation_steps) 964 965 def evaluate(self, x=None, y=None, ~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 1628 sample_weight=sample_weight, 1629 class_weight=class_weight, -&gt; 1630 batch_size=batch_size) 1631 # Prepare validation data. 1632 do_validation = False ~\Anaconda3\lib\site-packages\keras\engine\tr…
tagged with: keras
type: Question
tagged with: python

http://stackoverflow.com/q/50316997
type: UnansweredQuestion
has body: I'm using Django 1.10 and Python 3.5.3 In one of the views the user is sending a file and I'm reading it like that: def create(self, request, *args, **kwargs): file_serializer = self.get_serializer(data=request.data) file_serializer.is_valid(raise_exception=True) if file_serializer.is_valid(): if 'file' in request.data: # hash file hasher = hashlib.md5() read_file = request.data['file'].read() hasher.update(read_file) current_file_hash = hasher.hexdigest() My question is - Should I close the file afterwards? Seems like I don't actually open it.
tagged with: django
tagged with: python
score: 0
has title: Python should I close the file after reading
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/50317084
type: Question

http://stackoverflow.com/q/50361685
tagged with: histogram2d
has title: Issue with axes scaling when applying a filter to plt.imshow
answer count: 1
tagged with: gaussian
tagged with: imshow
type: AnsweredQuestion
score: 0
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/50362336
accepted answer: http://stackoverflow.com/a/50362336
type: Question
has body: I am trying to apply a gaussian filter to a 2dhistogram but the y-scale isn't fitting properly when I use my input data. If I run an example dataset it works fine. This is an example using random data. import matplotlib.pyplot as plt import random import numpy as np x = random.sample(range(80), 10) y = random.sample(range(80), 10) fig, ax = plt.subplots() plt.scatter(x,y) z,x,y,p = plt.hist2d(x,y, bins = 40, range = np.array([(0, 80), (0, 80)])) plt.imshow(z.T, interpolation = 'gaussian', origin = 'lower', cmap = 'jet', extent = [0,80,0,80]) Output: However, when I try to generate the same plot from my input data it doesn't work. See below. x = [29160, 30420, 30840, 31680, 31920, 32040, 33000, 33300, 33480, 34200] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] fig, ax = plt.subplots() plt.scatter(x,y) z,x,y,p = plt.hist2d(x,y, bins = 40, range = np.array([(29000, 35000), (0, 10)])) plt.imshow(z.T, interpolation = 'gaussian', origin = 'lower', cmap = 'jet', extent = [29000,35000,0,10])

http://stackoverflow.com/comment/87765132
comment on: http://stackoverflow.com/a/50374398
score: 0
type: Comment
has text: That's exactly what I was looking for but is there any other way to do it? Just wanted to know. Thank you!!!
type: AnswerComment

http://stackoverflow.com/comment/87609838
has text: @Wen How would you do this if you're looking for a value greater than or equal to? so for example in this data set I also have dates, I want anything from df2 that is after the date in df1
type: AnswerComment
comment on: http://stackoverflow.com/a/50293599
score: 0
type: Comment

http://stackoverflow.com/comment/87663034
type: QuestionComment
has text: So your second piece of code already works? consider posting to [codereview.se], but remember to read their help center before asking.
score: 0
comment on: http://stackoverflow.com/q/50323656
type: Comment

http://stackoverflow.com/a/50298046
answers question: http://stackoverflow.com/q/50297863
has comment: http://stackoverflow.com/comment/87613047
has comment: http://stackoverflow.com/comment/87612942
type: Answer
has body: The docs that you linked don't actually show subplot_kw being used in that way. What they show is calling dict(): fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True)) If you print the output of subplot_kw=dict(polar=True), you get: {'polar': True} Notice that polar has now become a string. subplot_kw={projection:'polar'}) does not define projection as a string, it's just a variable name that Python now has to look up (and it won't find it in this case, but it may find something else in other cases).
accepted answer of: http://stackoverflow.com/q/50297863
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/a/50310508
answers question: http://stackoverflow.com/q/50310228
type: Answer
has body: [c.name for c in SomeTable.__table__.columns] gives a list of column names.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50310228

http://stackoverflow.com/comment/87706697
score: 0
type: Comment
type: QuestionComment
has text: you need to understand *args and **kwargs in python (Read: https://learnbatta.com/blog/how-to-use-args-and-kwargs-in-python-3/)
comment on: http://stackoverflow.com/q/50345168

http://stackoverflow.com/comment/87744815
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50364048
has text: How much do you gain if you create a matrix that is `0.5*np.abs(x-0.5)`

http://stackoverflow.com/q/50247117
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50247253
has title: Meaning of defaultdict(lambda: defaultdict(dict))
has answer: http://stackoverflow.com/a/50247253
favorite count: 0
type: Question
upvote count: 2
has body: What is the meaning of the following line in Python? x = defaultdict(lambda: defaultdict(dict))
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87511761
tagged with: python
tagged with: defaultdict

http://stackoverflow.com/a/50315640
answers question: http://stackoverflow.com/q/50315615
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87647101
type: Answer
has body: mp3files = list(filter(lambda f: f.endswith('.txt') ,file)) Should work, since the file name do not match (==) to *.txt but rather end with that extension
accepted answer of: http://stackoverflow.com/q/50315615
score: 0

http://stackoverflow.com/a/50258697
has body: list.pop() takes in index, not a string; you are passing in one of the values from the list. If you want to produce items in random order, use random.shuffle(), then just pop from the end: randomised = lol[:] # create a copy random.shuffle(randomised) # put this in random order # each time you need a new value print(randomised.pop()) This is much more efficient than picking a random element each time and then removing that element. Note that instead of using random.randrange(), then use that as an index, you could also have used random.choice() to pick a single, random value. If random.shuffle() does not suit your specific needs, you should use: random_index = random.randrange(len(lol)) lol.pop(random_index) print(lol)
accepted answer of: http://stackoverflow.com/q/50258653
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50258653
has comment: http://stackoverflow.com/comment/87535929
score: 1

http://stackoverflow.com/comment/87662957
type: Comment
type: QuestionComment
has text: You've tagged web crawler, so have you search for web crawler Python libraries? Tried any?
comment on: http://stackoverflow.com/q/50323614
score: 1

http://stackoverflow.com/q/50327424
has comment: http://stackoverflow.com/comment/87678065
favorite count: 0
type: Question
has body: Running Python 2.7.6 in Windows 7. I have a little script that opens a socket, sends some data down it and waits for the response. I am trying to get Ctrl-C to exit the script instantly if it gets stuck trying to connect (for example the server is not listening). If I spam Ctrl-C the script eventually exits but not through my try/except. I was originally running this in PyCharm's Terminal but suspected the IDE might be messing up the Ctrl-C but I don't get any result in CMD either. Ctrl-Pause/Break does exit the script but I can't use that in PyCharm's Terminal. Am I doing something wrong or is this just how sockets work? import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: print("Trying to connect...") s.connect(("192.168.0.100", 80)) s.sendall("Hello world") except KeyboardInterrupt: print("Interrupted, exiting.") s.close() sys.exit(1) print("Waiting for response...") data = s.recv(1024) s.close() print(data)
type: UnansweredQuestion
tagged with: sockets
tagged with: python
score: 2
tagged with: pycharm
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/87677689
has title: Python KeyboardInterrupt not working with socket.connect
has comment: http://stackoverflow.com/comment/87671723
downvote count: 0

http://stackoverflow.com/comment/87766723
score: 0
type: Comment
has text: Sorry I misunderstood. So you're trying to insert data from one hive table into another another hive table?
type: AnswerComment
comment on: http://stackoverflow.com/a/50356692

http://stackoverflow.com/comment/87739740
comment on: http://stackoverflow.com/a/50361604
score: 0
type: Comment
has text: @chrisz For anything I'm not packaging for PyPI, I just `assert.version_info >= (3,6)` or whatever. That's good enough that if anyone complains "it doesn't work" and gives me any part of the error, I can tell them "Yeah, that's because Python 2.3 is not >= 3.6" instead of "That set comprehension looks perfectly valid, I don't know what to tell you without more information."
type: AnswerComment

http://stackoverflow.com/q/50262618
tagged with: python
has body: I'm modifying tensorboards example code for CNN's: https://www.tensorflow.org/tutorials/deep_cnn#launching_and_training_the_model I'm getting this error: DuplicateFlagError: The flag 'batch_sizes' is defined twice. First from D:/UofU/.../mycifar10.py, Second from D:/UofU/.../mycifar10.py. (Where both path names are the same) Description from first occurrence: Numbers of images to process in a batch. This is the jist of the code that must be producing the error: tf.app.flags.DEFINE_integer('batch_size', 49, """Numbers of images to process in a batch.""")
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50263202
tagged with: tensorflow
favorite count: 0
type: Question
has title: Tensorboard DuplicateFlagError
has comment: http://stackoverflow.com/comment/87544160
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/50316077
has comment: http://stackoverflow.com/comment/87648114
tagged with: server
linked to: http://stackoverflow.com/q/6823316
downvote count: 3
tagged with: python
favorite count: 0
has body: Guys and ladies. I am new to programming. I have written some script.It just checks whether some data is correct or not. I want that script to run 24*7 on Microsoft server at job (not on my PC). Please let me know how to do that. thanks in advance
upvote count: 0
type: UnansweredQuestion
answer count: 1
score: -3
has title: How to install and run python script on Microsoft server
has answer: http://stackoverflow.com/a/50316104
type: Question

http://stackoverflow.com/comment/87680466
score: 0
comment on: http://stackoverflow.com/q/50329848
type: QuestionComment
type: Comment
has text: @TomDalton I think the code freezes in line "result=....." and so even passing stderr could not help

http://stackoverflow.com/q/50348347
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/88338119
tagged with: python
has title: How to store multiple values in keys in dictionary in python?
has comment: http://stackoverflow.com/comment/87712530
has comment: http://stackoverflow.com/comment/87728344
tagged with: python-2.7
linked to: http://stackoverflow.com/q/48904041
has comment: http://stackoverflow.com/comment/87713140
has body: Maybe my question title is different from the question content. statuscode = [] statuscode.append(200) for x in find_from_sublister(hostname): x2 = x.strip() url = "http://"+ x2 try: req = requests.get(url) req1 = str(req.status_code) + " " + str(url) + '\n' req2 = str(req.status_code) req3 = str(url) dict = {req2 : req3} print " \n " + str(req1) except requests.exceptions.RequestException as e: print "Can't make the request to this Subdomain " + str(url) + '\n' for keys, values in dict.iteritems(): print "finding the url's whose status code is 200" if keys == statuscode[0]: print values else: print "po" I am using the code to do some following stuffs. It will find the subdomains from the Sub-lister (Locally) Then it will go to find the status code of each subdomain which was find by the sublister, with the help of for loop. for x in find_from_sublister(hostname): Note: find_from_sublister(hostname) is a function for finding the subdomain from the sublister. Then print the status code with the URL. Here print " \n " + str(req1) [All goes well, but the problem starts here ] Now what I want is to seperate the URLs which have 200 status code. so I heard then it can happen by using the dictionary in python. So, I try to use the dictionary. As you can see dict = {req2 : req3} Now I also make a list of index which have value 200 Then I compare the keys to list of index. here keys == statuscode[0] and if they match then it should print all the URL's which have 200 status code. But the result I am getting is below, finding the url's whose status code is 200 po You see the value po its else statment value, else: print "po" Now the problem is Why I am getting this else value why not the URL's which have status code 200? Hope I explained you clearly. And waiting for someone who talk to me on this. Thanks Note: I am Using Python 2.7 ver.
has comment: http://stackoverflow.com/comment/87727358
score: 0
has answer: http://stackoverflow.com/a/50348800
has comment: http://stackoverflow.com/comment/87712632
answer count: 1
accepted answer: http://stackoverflow.com/a/50348800

http://stackoverflow.com/a/50646740
accepted answer of: http://stackoverflow.com/q/50264760
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50264760
downvote count: 0
upvote count: 1
type: Answer
has body: When Gunicorn is called by Airflow, it uses ~\airflow\www\gunicorn_config.py as its config file.

http://stackoverflow.com/comment/87548948
type: Comment
comment on: http://stackoverflow.com/a/50265314
type: AnswerComment
score: 0
has text: Thanks! Is there a function to convert a series of date string to Period, analogs to pd.to_datetime?

http://stackoverflow.com/a/50365485
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88463729
accepted answer of: http://stackoverflow.com/q/50363291
has comment: http://stackoverflow.com/comment/87800643
answers question: http://stackoverflow.com/q/50363291
type: Answer
has body: Try this. The below script should fetch you the content from that table. To make it specific you should start your operation from the previous table (as it has got a unique ID) then using the appropriate method you can reach the content of your desired table. Here is what I did to achieve the same: import requests from bs4 import BeautifulSoup url = "http://ec.europa.eu/environment/ets/ohaDetails.do?returnURL=&amp;languageCode=en&amp;accountID=&amp;registryCode=&amp;buttonAction=all&amp;action=&amp;account.registryCode=&amp;accountType=&amp;identifierInReg=&amp;accountHolder=&amp;primaryAuthRep=&amp;installationIdentifier=&amp;installationName=&amp;accountStatus=&amp;permitIdentifier=&amp;complianceStatus=&amp;mainActivityType=-1&amp;searchType=oha&amp;resultList.currentPageNumber=1&amp;nextList=Next%C2%A0%3E&amp;selectedPeriods=" r = requests.get(url) soup = BeautifulSoup(r.text,"lxml") for items in soup.find(id="tblInstallationContacts").find_next_sibling().find_all("tr")[:-5]: data = [item.get_text(strip=True) for item in items.find_all("td")] print(data)
has comment: http://stackoverflow.com/comment/88295083
has comment: http://stackoverflow.com/comment/88439779
has comment: http://stackoverflow.com/comment/87800507
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87641377
has text: Ohh, that´s a good idea, but at the end I know that my teacher will request the file.
type: Comment
comment on: http://stackoverflow.com/a/50312501
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87679017
comment on: http://stackoverflow.com/q/50331018
type: Comment
type: QuestionComment
has text: ConectorSocket == ConectorClass ?
score: 0

http://stackoverflow.com/comment/87737596
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50360205
has text: Can you please add all code relevant to your question? People are usually not so keen on opening images. :)

http://stackoverflow.com/a/50231114
type: Answer
has comment: http://stackoverflow.com/comment/87479731
has body: r is a local variable, so each time begin() calls itself, that new begin() gets a new r. You can make r, we_list and you_list globals (declare them outside of begin() or with the global keyword) and it will save the values.
score: 0
answers question: http://stackoverflow.com/q/50230801
has comment: http://stackoverflow.com/comment/87481067

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/50271954

http://stackoverflow.com/q/50381448
has body: I have an array that looks like this: guest_list = ['P', 'r', 'o', 'f', '.', ' ', 'P', 'l', 'u', 'm', '\n', 'M', 'i', 's', 's', ' ', 'S', 'c', 'a', 'r', 'l', 'e', 't', '\n', 'C', 'o', 'l', '.', ' ', 'M', 'u', 's', 't', 'a', 'r', 'd', '\n', 'A', 'l', ' ', 'S', 'w', 'e', 'i', 'g', 'a', 'r', 't', '\n', 'R', 'o', 'b', 'o', 'c', 'o', 'p'] What I want is an array that looks like this: guest_list = ['Prof.Plum', 'Miss Scarlet', 'Col. Mustard', 'Al Sweigart', 'Robocop'] In other words, until '\n' appears, I want all of the string values to be combined into 1 value. Any suggestions? Edit #1: Here is part of my original code: ogl = open('guests.txt') #open guest list pyperclip.copy(ogl.read()) #open guest list copy guest_list = list(pyperclip.paste())
has comment: http://stackoverflow.com/comment/87779197
has comment: http://stackoverflow.com/comment/87779205
has comment: http://stackoverflow.com/comment/87779034
score: 1
has title: Array Combining Values
accepted answer: http://stackoverflow.com/a/50381462
has comment: http://stackoverflow.com/comment/87779092
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87779136
has answer: http://stackoverflow.com/a/50381462
has comment: http://stackoverflow.com/comment/87779265
type: AnsweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/87779223
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87779024
has comment: http://stackoverflow.com/comment/87779171
answer count: 1
has comment: http://stackoverflow.com/comment/87779043
has comment: http://stackoverflow.com/comment/87779067
favorite count: 0
type: Question

http://stackoverflow.com/comment/87561515
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50268923
has text: Sorry, my mistake, the regex didn't remove the characters, some I thought were `strong` weren't in fact normal text. Maybe I put the regex wrong.

http://stackoverflow.com/a/50318618
has comment: http://stackoverflow.com/comment/87653354
has comment: http://stackoverflow.com/comment/87660398
score: 2
downvote count: 0
type: Answer
has body: Why not use requests in lieu of pycurl, which would make your run method: def run(self): while True: try: url, filename = self.queue.get_nowait() except Queue.Empty: raise SystemExit with open(os.getcwd()+'/'+filename, "wb") as fp: #fp.write(requests.get(url).content) fp.write(requests.get(url, headers={'user-agent': 'CodeGuru'}).content I made a few other, stylistic changes.
answers question: http://stackoverflow.com/q/50318549
upvote count: 2
has comment: http://stackoverflow.com/comment/87653374
accepted answer of: http://stackoverflow.com/q/50318549
type: AcceptedAnswer

http://stackoverflow.com/a/52669966
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/92370311
has comment: http://stackoverflow.com/comment/92376587
has body: I've also met this problem, but I see in your code that you were wrong overriding render method. Class CSVRenderer's have render function which return string, not response. def render(self, data, media_type=None, renderer_context=None): ... """ Renders serialized *data* into CSV. For a dictionary: """ cause this function should return string, not response object. Actually there is one way to change the file name: just adding finaliez_response method (it's last method before returning response) into your API View def finalize_response(self, request, response, *args, **kwargs): response['Content-Disposition'] = 'attachment; filename="export.csv"' return super().finalize_response(request, response, *args, **kwargs) Hope that it will help who meet this problem!
has comment: http://stackoverflow.com/comment/92370351
type: Answer
answers question: http://stackoverflow.com/q/50289482
downvote count: 0

http://stackoverflow.com/a/50291769
has comment: http://stackoverflow.com/comment/87604670
accepted answer of: http://stackoverflow.com/q/50291028
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87603443
has comment: http://stackoverflow.com/comment/87602633
has comment: http://stackoverflow.com/comment/87622223
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50291028
upvote count: 1
has body: For me working: #remove duplicates sample data print (df) 0 1 2 3 4 0 1 01 ABC This is abc101 This is another abc101 1 1 01 DEF This is def101 This is another def101 2 1 02 ABC This is abc102 This is another abc102 3 1 02 DEF This is def102 This is another def102 4 1 02 GHI This is ghi102 This is another ghi102 5 2 01 ABC This is abc201 This is another abc201 6 2 01 DEF This is def201 This is another def201 7 2 01 GHI This is ghi201 This is another ghi201 8 2 03 GHI This is ghi203 This is another ghi203 9 3 02 ABC This is abc302 This is another abc302 10 4 01 ABC This is abc401 This is another abc401 11 4 02 DEF This is def402 This is another def402 #change headers to empty string and 2 for 'ABC','ABC_2','GHI','GHI_2' df.columns = ['ID1','ID2','Var_name','','2'] #unstack all columns df = df.set_index(['ID1','ID2', 'Var_name']).unstack() #excepted columns names for ordering variable_list = ['ABC','ABC_2', 'GHI', 'GHI_2'] #filter second level of MultiIndex df = df.loc[:, df.columns.get_level_values(1).isin(variable_list)] #flatten columns names df.columns = ['{}_{}'.format(j, i).strip('_') for i, j in df.columns] df = df.reindex(columns=variable_list).fillna('').reset_index() print (df) ID1 ID2 ABC ABC_2 GHI \ 0 1 01 This is abc101 This is another abc101 1 1 02 This is abc102 This is another abc102 This is ghi102 2 2 01 This is abc201 This is another abc201 This is ghi201 3 2 03 This is ghi203 4 3 02 This is abc302 This is another abc302 5 4 01 This is abc401 This is another abc401 6 4 02 GHI_2 0 1 This is another ghi102 2 This is another ghi201 3 This is another ghi203 4 5 6 #convert to lists L1 = [df.columns.tolist()] + df.values.tolist() print (L1[:3]) [['ID1', 'ID2', 'ABC', 'ABC_2', 'GHI', 'GHI_2'], [1, '01', 'This is abc101', 'This is another abc101', '', ''], [1, '02', 'This is abc102', 'This is another abc102', 'This is ghi102', 'This is another ghi102']]

http://stackoverflow.com/comment/87660208
comment on: http://stackoverflow.com/q/50321667
type: QuestionComment
has text: Have you tried closing the file first `f.close()`
score: 1
type: Comment

http://stackoverflow.com/q/50322595
has answer: http://stackoverflow.com/a/50324549
upvote count: 0
has title: pypyodbc.DatabaseError: (u'07002', u'[07002] [Microsoft][ODBC Microsoft Access \u9a71\u52a8\u7a0b\u5e8f] Too few parameters. Expected 1.'
downvote count: 2
answer count: 1
tagged with: ms-access
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: python
has body: I want to updata table 户结构查询结果 in access by python2 when I execute: cur.execute(u"UPDATE 户结构 SET 抽样数=(SELECT 抽样数 FROM 户结构查询结果 WHERE 户结构查询结果.行政区=户结构.行政区 AND 户结构查询结果.户结构=户结构.户规模)" ).commit() I get the following error: pypyodbc.DatabaseError: (u'07002', u'[07002] [Microsoft][ODBC Microsoft Access \u9a71\u52a8\u7a0b\u5e8f] Too few parameters. Expected 1.') my tables are following: enter image description here enter image description here all type of fields is text（255）

http://stackoverflow.com/comment/87605863
type: Comment
comment on: http://stackoverflow.com/q/50294151
type: QuestionComment
has text: Do you mean you want to get some unique identifier for each opened tab to be able to handle it after all tabs were opened?
score: 0

http://stackoverflow.com/q/50345708
type: Question
tagged with: smtplib
tagged with: mime-types
has answer: http://stackoverflow.com/a/50347130
accepted answer: http://stackoverflow.com/a/50347130
tagged with: python
has comment: http://stackoverflow.com/comment/87707973
has title: how can we join two different tables where no common column is present using pandas
upvote count: 2
type: AnsweredQuestion
score: 2
has body: I have two tables one with offerid and other with emailid .I want both to be merged and come in a table. import pandas as pd data = pd.read_csv("offer1.txt") data1 = pd.read_csv("offer2.txt") print data.merge(data1, left_on='listid', right_on='profile/emailid', how='left') I am getting output like this: listid profile/emailid 0 588001 NaN 1 614001 NaN 2 NaN rcruise295@yahoo.com 3 NaN 2282377983 I want like this listid profile/emailid 588001 rcruise295@yahoo.com 614001 2282377983 can any on help me
has comment: http://stackoverflow.com/comment/87709500
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/50375531
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50375504
has comment: http://stackoverflow.com/comment/87767648
answers question: http://stackoverflow.com/q/50375504
has body: This is an IPython magic. It controls how floats display: &gt;&gt;&gt; 1.2345 1.2345 &gt;&gt;&gt; %precision 2 '%.2f' &gt;&gt;&gt; 1.2345 1.23 Documented here. Note: It suggests your script was intended to be executed within an IPython runtime (such as a notebook). In a regular Python interpreter that will be a syntax error.
type: Answer
score: 11
upvote count: 11
downvote count: 0

http://stackoverflow.com/a/50337845
type: Answer
accepted answer of: http://stackoverflow.com/q/50334304
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Without a sample of the PDF you are parsing it's hard to say why the odd characters are appearing. I've also had problems using PyPDF2 in Python 3.x. I've found PyMuPDF to be superior for most PDF-related tasks. You could try extracting text with it to see if you have the same characters during text extraction.
answers question: http://stackoverflow.com/q/50334304
score: 1

http://stackoverflow.com/comment/87599710
has text: Just pass an argument to the function, like `any_or_all`, which is `any` or `all`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50291410
score: 0

http://stackoverflow.com/q/50317553
has title: Python 3: UnboundLocalError - local variable referenced before assignment
linked to: http://stackoverflow.com/q/9264763
has body: I get the error How often? 33 Traceback (most recent call last): File "main.py", line 20, in &lt;module&gt; main() File "main.py", line 17, in main won += 1 UnboundLocalError: local variable 'won' referenced before assignment when I try to run the following code: teller = 0 throw = int(input('How often?')) won = 0 def main(): pricedoor = round (3 * np.random.rand() + 0.5) if pricedoor == 4 : pricedoor = 3 choicedoor = round (3 * np.random.rand() + 0.5) if choicedoor == 4 : choicedoor = 3 sheepdoor = mf.quizmasteropens(pricedoor, choicedoor) #choicedoor = choicedoor if choicedoor == pricedoor: won += 1 while teller &lt; throw : main() teller = teller + 1 How can I fix this problem? Thanks in advance for the help!
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: function
has answer: http://stackoverflow.com/a/50317567
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/423379
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50317711
tagged with: python

http://stackoverflow.com/comment/87611109
score: 0
type: AnswerComment
has text: Why not embed the dashboard somewhere with `?standalone=true`?
comment on: http://stackoverflow.com/a/50295810
type: Comment

http://stackoverflow.com/comment/87626085
type: QuestionComment
score: 2
has text: The executable is `/usr/bin/python3`.
comment on: http://stackoverflow.com/q/50304901
type: Comment

http://stackoverflow.com/q/50316927
downvote count: 0
has comment: http://stackoverflow.com/comment/87755676
upvote count: 1
tagged with: python
has title: Conditional change value in cell in pandas dataframe
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
has body: I want to replace the NaN value for open, high and low to be same as close. However, this condition is applied only when the change is 0.00 Below is my code try: url = 'https://api.iextrading.com/1.0/stock/AAME/chart/1y' q_data = pd.read_json(url) if q_data.change == 0.00: q_data.open = q_data.close q_data.high = q_data.close q_data.low = q_data.close except Exception: print "No data" continue The issue is the try loop is bypassed and goes to except loop. How to change the data correctly?
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/50316982
score: 1
has answer: http://stackoverflow.com/a/50316982
type: Question
accepted answer: http://stackoverflow.com/a/50317094
answer count: 2
has answer: http://stackoverflow.com/a/50317094

http://stackoverflow.com/q/50305181
has comment: http://stackoverflow.com/comment/87626636
answer count: 0
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/87627584
downvote count: 1
favorite count: 0
has body: I am new to using databases and Firebase, and I made a function, restful API, that takes in 4 parameters. How would I route it to my Firebase database such that the address can take in the parameters? Also, when do I use the methods parameter when routing? I'm new to all of this and would appreciate some help. For example: db = firebase.FirebaseApplication("https://db.firebaseio.com") def foo(a, b, c, d): """code that PUT data from a b c d to Firebase""" And I want to route it so that I can do something like /foo/&lt;a&gt;/&lt;b&gt;/&lt;c&gt;/&lt;d&gt; and works with Firebase, any ideas ?
type: Question
type: UnansweredQuestion
tagged with: database
tagged with: python
tagged with: node.js
tagged with: firebase
has title: How to route functions with parameters in python using Firebase?

http://stackoverflow.com/q/50378567
score: 0
tagged with: python
type: Question
has title: Matching a string with Python RegEx negative lookahead
tagged with: regex-lookarounds
has body: I have a file with some content as wells as the two 'include' strings below: some string1 some string2 ... include: "base_pricing_app_model_my_deployment_id.model.lkml" include: "base_map_layers.model.lkml" ... some string3 ... Substring "my_deployment_id" is a token I need to add to the second 'include' string so file content looks like that: some string1 some string2 ... include: "base_pricing_app_model_my_deployment_id.model.lkml" include: "base_map_layers_my_deployment_id.model.lkml" ... some string3 I am running Python 3.5 and using its re library. Here is how I attempt to replace the second 'include' string: with fileinput.input(files=(rfi), inplace=True) as cmodf: for line in cmodf: match_no_dep_id = re.sub('^include:\s\"(?!my_deployment_id).*[.]model[.]lkml\"$', line.split('.')[0] + '_' + 'my_deployment_id' + 'model.lkml' + '"', line) print(match_no_dep_id, end='') However, both 'include' entries get modified and I end up with the following content: some string1 some string2 include: "base_pricing_app_model_my_deployment_id_my_deployment_id.model.lkml" include: "base_map_layers_my_deployment_id.model.lkml" some string3 ... So my negative lookahead regexp matches both strings, including the one which already contains the token I am negating. I am not sure what I am missing here. Please help. Thank you!
type: UnansweredQuestion
answer count: 1
tagged with: regex-negation
has answer: http://stackoverflow.com/a/50380631

http://stackoverflow.com/comment/87656090
score: 0
comment on: http://stackoverflow.com/q/50319877
type: Comment
type: QuestionComment
has text: same as @abarnert's answer. and don't send attack, stun, laser and so on to `super`

http://stackoverflow.com/comment/87559893
score: 0
type: AnswerComment
has text: @Saranya I'm glad it helped :)
comment on: http://stackoverflow.com/a/50270952
type: Comment

http://stackoverflow.com/comment/87673075
type: Comment
has text: I've edited the question. I think, the most logical way to invert colors is to apply it to whole canvas, or let's say part within specified coordinates.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50327186

http://stackoverflow.com/comment/87779854
has text: Thanks! I have a few cases with only 'www.abc.com/' and in these lines I received NaN at column main. How can I fix it? I will edit the question to add this case.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50381895
type: Comment

http://stackoverflow.com/comment/87577671
has text: I have searched for this, but I can only found how to order a list, but the problem here is that I have to order it by the alphabet just when the number is the same. So the Order is first by the numbers (I´ve reached that already), and then I have to order it but the alphabet when the numbers are the same.
score: 0
comment on: http://stackoverflow.com/q/50280423
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87616304
type: Comment
score: 0
type: AnswerComment
has text: Yes, you can tell `sympy` that certain symbols are real and positive by setting it here: `n1, n2, n3, n4, n5, nTot = sym.symbols('n1,n2,n3,n4,n5,nTot', positive=True, real=True)`. I've update the post above accordingly.
comment on: http://stackoverflow.com/a/50295760

http://stackoverflow.com/q/50352481
has comment: http://stackoverflow.com/comment/87724304
has comment: http://stackoverflow.com/comment/87721173
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49732826
has comment: http://stackoverflow.com/comment/87721126
accepted answer: http://stackoverflow.com/a/50353614
score: 5
possible better answer: http://stackoverflow.com/a/50352743
has title: Reading, editing, and writing over every 4th line in a text file
upvote count: 5
has comment: http://stackoverflow.com/comment/87721770
tagged with: python
has comment: http://stackoverflow.com/comment/87722014
has body: long time reader first time asker. I am working on some vtt (closed caption) files that I need to edit the timestamps for. The format of the file is as follows: 177 00:07:37.450 --&gt; 00:07:39.690 - [Liz] How would you suggest an organization devise 178 00:07:39.690 --&gt; 00:07:41.719 the accountabilities for culture? 179 00:07:41.719 --&gt; 00:07:43.690 - [Tamara] It is a shared accountability I have written the following code to read the file, calculate the new timestamps (5% slower) and spit out the new timestamps: from sys import argv script, filename = argv adjustment = input("Adjustment multiplier: ") video = open(filename, "r+") lines = video.readlines() video.seek(0) for l in lines: if l[:2] == "00": #here I've omitted a lot of calculations to turn the timestamps #into milliseconds, apply the adjustment multiplier, and turn them back into #minutes, seconds, and milliseconds. new_line = str(#concatenation of new values into timestamp format) video.write(new_line) video.close() The calculations work great, but the problem is that it dumps all the new lines into the start of the file instead of writing over each timestamp line and skipping the rest. I would love to hear what you guys think! I've been wrestling with this for a while and have tried a bunch of things but haven't quite been able to make it work. Thank you!
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87721316
has comment: http://stackoverflow.com/comment/87720979
has answer: http://stackoverflow.com/a/50353614
has answer: http://stackoverflow.com/a/50352743
has comment: http://stackoverflow.com/comment/87721346
downvote count: 0
linked to: http://stackoverflow.com/q/3277503

http://stackoverflow.com/a/50327522
type: Answer
has body: The distance to a circle is the same as the distance to the center minus the radius. Now, the distance from a rectangle to a point is found by considering the nine regions defined by the supporting lines of the sides. Depending on the region, the shortest distance is axis-aligned (from a side to the point) or oblique (from a corner to the point) and the formulas are easy. The discussion is even simpler for a rectangular hole or inner angle.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50324413
has comment: http://stackoverflow.com/comment/87702822
has comment: http://stackoverflow.com/comment/87700654
score: 1

http://stackoverflow.com/a/50281556
type: AcceptedAnswer
has body: I used Perl to solve the problem. First, it loads File2 into a hash table keyed by the char, pos, and nucleotide, the value is the number for the nucleotide. Then, the second file is processed. If there's non-zero value in the hash table for its char, pos, and nucleotide, it's not printed. #!/usr/bin/perl use warnings; use strict; my %gt0; open my $in2, '&lt;', 'File2.txt' or die $!; &lt;$in2&gt;; # Skip the header. while (&lt;$in2&gt;) { my %count; (my ($chr, $pos), @count{qw{ A C G T }}) = split; $gt0{$chr}{$pos}{$_} = $count{$_} for qw( A C G T ); } open my $in1, '&lt;', 'File1.txt' or die $!; while (&lt;$in1&gt;) { my ($chr, $pos, undef, $c4) = split; print unless $gt0{$chr}{$pos}{$c4}; }
downvote count: 0
has comment: http://stackoverflow.com/comment/87579857
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50281354
has comment: http://stackoverflow.com/comment/87579824
accepted answer of: http://stackoverflow.com/q/50281354
score: 1

http://stackoverflow.com/comment/87715741
has text: The guide you are using misstates that `in_reply_to_status_id` is necessary for a tweet to be present. Use `id` or `user`. Also, the tweet text may be in `tweet.text` or `tweet.full_text`, so check for both.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50342559
score: 0

http://stackoverflow.com/q/50229942
accepted answer: http://stackoverflow.com/a/50230080
has answer: http://stackoverflow.com/a/50230080
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/47896240
type: AnsweredQuestion
has body: When I run my script, Pandas gives the following: 'Future warning' FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. My script: import io data = io.StringIO('''A,B,M AM,1, AMC,2, ''') df = pd.read_csv(data) r=['CAR'] s=['CAR_M'] for i,j in zip(r,s): df=df.append([{'A':i,'M':j}], ignore_index=True) The same warning appear if "ignore_index=False". I don't know how to reindex?
tagged with: pandas
score: 3
upvote count: 3
duplicate of: http://stackoverflow.com/q/47896240
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Pandas: FutureWarning: Passing list-likes to .loc or []

http://stackoverflow.com/a/50282745
answers question: http://stackoverflow.com/q/50282420
type: Answer
score: -1
has body: I had the same problem as yours. I made use of the argmax function which fixed my problem. Try this piece of code (or similiar): cm = tf.confusion_matrix(labels=tf.argmax(y*np.arange(1,7), 1), predictions=tf.argmax(pred*np.arange(1,7))) #then check the result: with tf.Session() as sess: cm_reachable = cm.eval() print(cm_reachable) And check out this detailed instruction: Tensorflow confusion matrix using one-hot code
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/50282420
has comment: http://stackoverflow.com/comment/136920630

http://stackoverflow.com/a/50292745
has comment: http://stackoverflow.com/comment/87614502
has comment: http://stackoverflow.com/comment/87602980
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87602852
score: 1
has comment: http://stackoverflow.com/comment/87602109
has comment: http://stackoverflow.com/comment/87612600
has comment: http://stackoverflow.com/comment/87602147
accepted answer of: http://stackoverflow.com/q/50292678
has comment: http://stackoverflow.com/comment/87602166
has comment: http://stackoverflow.com/comment/87602817
has comment: http://stackoverflow.com/comment/87602888
has comment: http://stackoverflow.com/comment/87604461
has comment: http://stackoverflow.com/comment/87603139
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50292678
upvote count: 1
has comment: http://stackoverflow.com/comment/87602827
has body: I think need boolean indexing with ~ for inverse condition with isin for filter list of words with str.len for filter by length of words and if necessary chain conditions by |: autores_atuais = pd.DataFrame({'Ementa':['Estado','another','be','de','def','bax']}) print (autores_atuais) Ementa 0 Estado 1 another 2 be 3 de 4 def 5 bax m1 = autores_atuais['Ementa'].isin(['Estado','another','next']) m2 = autores_atuais['Ementa'].str.len() &lt; 3 s = autores_atuais.loc[~(m1 | m2), 'Ementa'] print (s) 4 def 5 bax Name: Ementa, dtype: object Similar alternative with &amp; for AND and inverse first condition by ~ and second by &gt;=: m1 = ~autores_atuais['Ementa'].isin(['Estado','another','next']) m2 = autores_atuais['Ementa'].str.len() &gt;= 3 s = autores_atuais.loc[m1 &amp; m2, 'Ementa'] print (s) 4 def 5 bax Name: Ementa, dtype: object wordcloud = WordCloud().generate(' '.join(s))
has comment: http://stackoverflow.com/comment/87602868

http://stackoverflow.com/q/50340754
has comment: http://stackoverflow.com/comment/87697918
has comment: http://stackoverflow.com/comment/87700376
has comment: http://stackoverflow.com/comment/87698155
tagged with: python
duplicate of: http://stackoverflow.com/q/33266430
has comment: http://stackoverflow.com/comment/87698281
has comment: http://stackoverflow.com/comment/87699478
tagged with: import
type: Question
tagged with: c++
has body: When I try to run the following python script from Qt I get this error. ImportError: No module named imapclient Python scripts will run just fine without the import statements. Does anyone know how to fix this? Thank you in advance for all your help. Qt doesn't seem to be using the same version of Python that is used by default on my terminal. Qt Code (widget.cpp) #include "widget.h" #include "ui_widget.h" #include "QDebug" #include &lt;QTimer&gt; #include &lt;QProcess&gt; #include &lt;QDir&gt; #include &lt;QTime&gt; Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui-&gt;setupUi(this); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(checkTexts())); timer-&gt;start(5000); } Widget::~Widget() { delete ui; } void Widget::checkTexts(){ QProcess *process = new QProcess(this); QStringList arguments { QCoreApplication::applicationDirPath() + "/../../../../../Monika/Qt Desktop Application/Monika/CheckText.py"}; process-&gt;startDetached("python", arguments); process-&gt;waitForFinished(-1); QString output = process-&gt;readAllStandardOutput(); qDebug() &lt;&lt; output; process-&gt;close(); } Python Code (CheckText.py) import imapclient import imaplib def getTexts(): imaplib._MAXLINE = 10000000 #increases the byte limit of how much python can remember imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) print ("done") getTexts()
has comment: http://stackoverflow.com/comment/87697985
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87702549
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87698068
tagged with: qt
linked to: http://stackoverflow.com/q/14117945
tagged with: importerror
has title: Qt ImportError when running a python script with imports
linked to: http://stackoverflow.com/q/33266430
score: 1

http://stackoverflow.com/q/50362679
possible better answer: http://stackoverflow.com/a/50362710
has title: Replacing numpy 2D array elements below an index array
favorite count: 0
has answer: http://stackoverflow.com/a/50362714
type: Question
tagged with: numpy
has body: I searched prior questions and didn't find one that quite fits this. I am setting the value of all cells in A's jth column to 0 whose row indeces are less than m[j]: import numpy as np n = 8 A = np.ones([n,n]) m = np.array([1,1,1,2,2,2,3,4]) for j in range(n): for i in range(m[j]): A[i,j] = 0 How do I rewrite that script without 'for' loops?
tagged with: arrays
downvote count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50362710
score: 3
answer count: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/50362714

http://stackoverflow.com/q/50309816
upvote count: 1
has comment: http://stackoverflow.com/comment/87635548
favorite count: 0
has body: I have hundreds of thousands of rows that look something like this (there's actually more data than just this, but I'm trying to simplify the idea I've been attempting)... index status location 0 infected area5 1 healthy area6 2 healthy area3 3 infected area8 4 healthy area1 5 healthy area8 6 healthy area5 7 healthy area2 8 healthy area4 9 healthy area10 10 .... .... I'm trying to update the status column, based on if an area is infected. So I basically made a list of the infected areas: infected_areas = ['area5', 'area8'] Then what I'm trying to do is look at all the rows (or really just the 'healthy' rows), and if any of those match to what is in my infected_areas list, to change that status to infected. So with my example above, the output should look like: index status location 0 infected area5 1 healthy area6 2 healthy area3 3 infected area8 4 healthy area1 5 infected area8 6 infected area5 7 healthy area2 8 healthy area4 9 healthy area10 10 .... .... here's what I've been working with, but not quite getting anywhere: `df[df['location'].isin(location)]['status'] = 'infected'
type: Question
has title: Python - Pandas replace a value in a column if another column has a value that is in a list
possible better answer: http://stackoverflow.com/a/50309979
has answer: http://stackoverflow.com/a/50309979
accepted answer: http://stackoverflow.com/a/50309873
tagged with: python
has answer: http://stackoverflow.com/a/50309873
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/87635516
tagged with: pandas
score: 1
downvote count: 0

http://stackoverflow.com/q/50379547
downvote count: 0
has comment: http://stackoverflow.com/comment/87775785
tagged with: minio
favorite count: 0
type: Question
has body: I'm trying to save file to bucket: if file and allowed_file(file.filename): filename = secure_filename(file.filename) try: minioClient.make_bucket("testbuck", location = "us-east-1") except BucketAlreadyOwnedByYou as err: pass except BucketAlreadyExists as err: pass except ResponseError as err: raise else: try: print(filename) minioClient.fput_object('testbuck', filename, image) except ResponseError as err: print(err) But get errors:Message: {0}'.format(error.message)) InvalidXMLError: InvalidXMLError: message: "Error" XML is not parsable. Message: syntax error: line 1, column 0 I'm newby in backend and flask and can't figure out what I am doing wrong! Thank for you patience
has title: How to save file from POST request in flask to localy-running Minio server?
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/53062299
score: 2
has comment: http://stackoverflow.com/comment/87785982
upvote count: 2
type: UnansweredQuestion
answer count: 1

modelica
tag name: modelica
tags question: http://stackoverflow.com/q/50250825
type: Tag

http://stackoverflow.com/a/50339674
has body: PyCharm (2018.1) does not support Pipenv at the time of writing this answer. You can vote for that here https://youtrack.jetbrains.com/issue/PY-26492.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50309076

http://stackoverflow.com/comment/87728552
has text: Cool! Will give this a shot today.
comment on: http://stackoverflow.com/a/50346246
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50359621
downvote count: 0
answers question: http://stackoverflow.com/q/50359334
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87736406
upvote count: 5
has comment: http://stackoverflow.com/comment/87736016
type: Answer
accepted answer of: http://stackoverflow.com/q/50359334
has body: There is no method in the python bindings to get the geckodriver version, you will have to implement it yourself, my first option would be subprocess # Mind the encoding, it must match your system's output = subprocess.run(['geckodriver', '-V'], stdout=subprocess.PIPE, encoding='utf-8') version = output.stdout.splitlines()[0].split()[-1]
score: 5

http://stackoverflow.com/a/50321380
has body: You need to test whether an input is a substring of either keys or values of values within your nested dictionary. If partial matches are acceptable, you can achieve this by using any with a generator expression: for key, value in addressBook.items(): if (searchString in key) or any(searchString in i for i in value.values()): print(...) A variation on this is to utilise collections.namedtuple, which makes more sense for structured data. This does involve a one-off transformation cost. from collections import namedtuple Contact = namedtuple('Contact', ['name', 'address', 'phone']) d = {k: Contact(**v) for k, v in addressBook.items()} for key, value in d.items(): if (searchString in key) or any(searchString in i for i in value): print(...)
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50321335
downvote count: 0

http://stackoverflow.com/comment/87561690
type: AnswerComment
has text: When you use the `.` it is looking for an attribute of the object. The `d[key]` syntax indicates you want to look up a key/value pair that will have different behaviour (e.g.: a KeyError if it's not found). Have a look at https://docs.python.org/2/library/stdtypes.html#mapping-types-dict.
comment on: http://stackoverflow.com/a/50260714
type: Comment
score: 0

pyinstaller
tags question: http://stackoverflow.com/q/50296638
tags question: http://stackoverflow.com/q/50234487
tags question: http://stackoverflow.com/q/50292748
tags question: http://stackoverflow.com/q/50299139
type: Tag
tags question: http://stackoverflow.com/q/50302229
tags question: http://stackoverflow.com/q/50243051
tag name: pyinstaller
tags question: http://stackoverflow.com/q/50360392
tags question: http://stackoverflow.com/q/50362043
tags question: http://stackoverflow.com/q/50337382
tags question: http://stackoverflow.com/q/50375963
tags question: http://stackoverflow.com/q/50282890
tags question: http://stackoverflow.com/q/50274273

http://stackoverflow.com/q/50284112
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/50284512
downvote count: 0
tagged with: python
has title: Tensorflow restore() missing 1 required positional argument: 'save_path'
has body: I am trying to make a neural network with Python that based on Irish dataset will predict the type of flower based on the array that I fed in. That how my NN looks like names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'species'] train = pd.read_csv(dataset, names=names, skiprows=1) test = pd.read_csv(test_dataset, names=names, skiprows=1) Xtrain = train.drop("species" , axis = 1) Xtest = train.drop("species" , axis = 1) ytrain = pd.get_dummies(train.species) ytest = pd.get_dummies(test.species) def create_train_model(hidden_nodes, num_iters): # Reset the graph tf.reset_default_graph() # Placeholders for input and output data X = tf.placeholder(shape=(120, 4), dtype=tf.float64, name='X') y = tf.placeholder(shape=(120, 3), dtype=tf.float64, name='y') # Variables for two group of weights between the three layers of the network W1 = tf.Variable(np.random.rand(4, hidden_nodes), dtype=tf.float64) W2 = tf.Variable(np.random.rand(hidden_nodes, 3), dtype=tf.float64) # Create the neural net graph A1 = tf.sigmoid(tf.matmul(X, W1)) y_est = tf.sigmoid(tf.matmul(A1, W2)) # Define a loss function deltas = tf.square(y_est - y) loss = tf.reduce_sum(deltas) # Define a train operation to minimize the loss optimizer = tf.train.GradientDescentOptimizer(0.005) train = optimizer.minimize(loss) # Initialize variables and run session init = tf.global_variables_initializer() saver = tf.train.Saver() sess = tf.Session() sess.run(init) # Go through num_iters iterations for i in range(num_iters): sess.run(train, feed_dict={X: Xtrain, y: ytrain}) loss_plot[hidden_nodes].append(sess.run(loss, feed_dict={X: Xtrain.as_matrix(), y: ytrain.as_matrix()})) weights1 = sess.run(W1) weights2 = sess.run(W2) print("loss (hidden nodes: %d, iterations: %d): %.2f" % (hidden_nodes, num_iters, loss_plot[hidden_nodes][-1])) save_path = saver.save(sess, model_path , hidden_nodes) print("Model saved in path: %s" % save_path) return weights1, weights2 # Plot the loss function over iterations nu…
score: 2
accepted answer: http://stackoverflow.com/a/50284540
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50284512
tagged with: deep-learning
has answer: http://stackoverflow.com/a/50284540
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/50308423
score: 1
downvote count: 0
tagged with: web-scraping
upvote count: 1
has title: Scraping with Beautiful results in jibberish
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I am trying to scrape a website using BeautifulSoup4, however everything after the body tag is gibberish, and breaks the terminal. The website is tagged with utf-8 so I have tried decoding and different html parsers, including html.parser and lxml. obsObj = BeautifulSoup(html.read().decode('utf-8','ignore'), "html5lib") print(bsObj.prettify()) Result: &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; }zƲu}y┴(M։ʖO┬┌;R° ─H$D◆P⎼^▒&amp;▒└⎻;\␍␍ (Q│P]]]U]]U£œ␉NG/?5˶ض&amp;±├;ӗ/D&amp;▒└⎻;·GW5Q߶/..(ڧ?ڗV*V┘┌[;≥⎻^N0T4ۓ┐'┴┘S7׏; њ#─K The relevant lines in the website are : &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da" dir="ltr" class="js"&gt;&lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;
has comment: http://stackoverflow.com/comment/87632782
has comment: http://stackoverflow.com/comment/87632826
tagged with: python
has answer: http://stackoverflow.com/a/50308600
possible better answer: http://stackoverflow.com/a/50308600
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50308511
accepted answer: http://stackoverflow.com/a/50308511

http://stackoverflow.com/q/50278213
has comment: http://stackoverflow.com/comment/87573189
score: 1
duplicate of: http://stackoverflow.com/q/12423614
duplicate of: http://stackoverflow.com/q/2295290
has comment: http://stackoverflow.com/comment/87573813
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/12423614
answer count: 0
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/3431676
has body: I found a interesting behavior of lambda function in Python. If I do, lambda_funcs = [] for i in range(10): lambda_func = lambda x:x[i] lambda_funcs.append(lambda_func) X = ['a', 'b', 'c'] print lambda_funcs[0](X) It throws an error: IndexError: list index out of range. This code aims to create 10 lambda functions each of which returns i-th element. But, all lambda_func in the above code attempts to retrieve 10th element. To make it work, I found that the following definition is a right way: lambda_func = (lambda j: lambda x: x[j])(i) Can anyone tell me what is going on inside lambda evaluation in Python?
has title: lambda function in Python
tagged with: python
tagged with: lambda
downvote count: 1
has comment: http://stackoverflow.com/comment/87573774
has comment: http://stackoverflow.com/comment/87573193
has comment: http://stackoverflow.com/comment/87573201

http://stackoverflow.com/comment/87499213
comment on: http://stackoverflow.com/q/50237213
type: Comment
type: QuestionComment
score: 0
has text: In python2, you should be able to send that XML block directly as a string. I would explore logs on the server to find out what's going wrong. Possibly the server is expecting something more: an additional CR-LF at the end maybe?

http://stackoverflow.com/a/50265416
has comment: http://stackoverflow.com/comment/87549137
has comment: http://stackoverflow.com/comment/87549890
has comment: http://stackoverflow.com/comment/87549752
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50265160
has comment: http://stackoverflow.com/comment/87548936
has comment: http://stackoverflow.com/comment/87549822
has comment: http://stackoverflow.com/comment/87549117
score: 1
has comment: http://stackoverflow.com/comment/87549415
has comment: http://stackoverflow.com/comment/87549586
has comment: http://stackoverflow.com/comment/87550267
type: Answer
has comment: http://stackoverflow.com/comment/87549635
has comment: http://stackoverflow.com/comment/87550280
has comment: http://stackoverflow.com/comment/87549015
has comment: http://stackoverflow.com/comment/87549215
has body: The issue comes from this line: banned_user = Banned_User.objects.create(profile=request.user.profile, report_reasons=request.report.report_reason) You're trying to access report inside request, whereas request doesn't have have this attribute. I suggest that you change your ForeignKey to ManyToManyField, since a user can have multiple reports. class Banned_User(models.Model): def __str__(self): return self.user.get_username profile = models.ForeignKey('Profile',on_delete=models.PROTECT, blank=False, null=False, related_name='banned_profile',) report_reasons = models.ManyToManyField('Report',blank=True) So you would have this: if hasattr(obj, 'user'): # This object is a Profile, so lookup the user obj = obj.user obj.is_active = False # email function banned_user = Banned_User.objects.create(profile=request.user.profile) banned_user.report_reasons.add(request.user.profile.user_reported_report.all()) # rest of code
has comment: http://stackoverflow.com/comment/87548926
has comment: http://stackoverflow.com/comment/87549071

http://stackoverflow.com/a/50382390
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87806713
type: Answer
answers question: http://stackoverflow.com/q/50381664
has body: I think you missed the actual reference of static. Change static to static.serve in urlpatterns from django.contrib import admin from django.urls import path, include from django.views import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls'), ), path('static/', static.serve, { 'document_root': 'C:/Users/USER1/PycharmProjects/untitled13/static' }), ] Reference : Serving files in development
accepted answer of: http://stackoverflow.com/q/50381664

http://stackoverflow.com/comment/87580021
type: QuestionComment
has text: The easiest solution is to create either a list of the three dicts, or a dict of the three dicts, and `json.dump` that.
score: 0
comment on: http://stackoverflow.com/q/50281750
type: Comment

http://stackoverflow.com/a/59049124
score: 3
type: Answer
upvote count: 3
downvote count: 0
has body: If this question is about listing all groups in django-channels 2: If django-channels 2 is configured for using Redis as the backend it stores all groups in Redis under the keys prefixed with: "asgi::group:". To list the groups the following code can be used: r = redis.Redis.from_url(REDIS_URL_USED_BY_CHANNELS_2) prefix = 'asgi::group:' groups = [key.decode('utf-8')[len(prefix):] for key in r.scan_iter(prefix + '*')]
answers question: http://stackoverflow.com/q/50282878

http://stackoverflow.com/q/50292880
linked to: http://stackoverflow.com/q/37010212
has title: Working with large networkx graph and Flask webserver
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: flask
favorite count: 0
accepted answer: http://stackoverflow.com/a/50293092
tagged with: networkx
tagged with: graph-theory
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50293092
tagged with: python
has comment: http://stackoverflow.com/comment/87605860
has body: I'm trying to create a Flask web app that can query a NetworkX graph, to return the shortest paths (using Dijkstra's algorithm, plus Yen's algorithm for the k-shortest paths). Here is my sample code (stripped of error handling et c., and only showing the Dijkstra implementation), which returns the path if you submit a GET request to localhost:3000/d?source=a&amp;target=b: import csv import json import networkx as nx from flask import Flask, request app = Flask(__name__) G = nx.Graph() @app.route('/d') def dijkstra(): global G source = request.args['source'].lower().strip() target = request.args['target'].lower().strip() path = nx.dijkstra_path(G, source, target, weight='weight') return json.dumps(path) if __name__ == '__main__': global G with open('nodes.csv', 'rb') as f: reader = csv.reader(f) node_list = list(reader) for i in nodes: G.add_node(i[0]) with open('edges.csv', 'rb') as f: reader = csv.reader(f) edge_list = list(reader) for i in edges: G.add_edge(i[0], i[1], weight=i[2]) app.run(host='0.0.0.0', port=3000, use_reloader=False) The graph is very large (one million nodes, twenty million edges), so I am currently populating from CSVs it as the app loads, rather than building it for every request. This takes about five minutes when run locally on my MacBook Pro (3GHz, 16GB RAM). Lookups take different amounts of time, but generally around fifteen seconds, and performance generally degrades after a certain amount of use, meaning I have to restart the app. Question one: as this is slow and pretty memory intensive, is there a way to store this graph so that I don't have to generate it every time, then hold it in memory? Question two: am I approaching it the right way, by using G as a global variable? I haven't worked with graphs this large before, so am aware my implementation is probably far from ideal, and would be grateful for any thoughts about how to make this perform better/more reliably!
type: Question

http://stackoverflow.com/q/50348914
has title: python debugger: initialising variables not interactively
linked to: http://stackoverflow.com/q/50065682
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87718305
score: 0
has comment: http://stackoverflow.com/comment/87717449
answer count: 0
has comment: http://stackoverflow.com/comment/87718456
tagged with: batch-processing
has comment: http://stackoverflow.com/comment/87718650
has comment: http://stackoverflow.com/comment/87717832
has body: I am running a code with pdb. The run is breaking at line 3, I insert setvars and some variables are changed. python -m pdb -c "b 3" -c c -c "alias setvars aaa=1;bbb=1" somecode.py 3 This does what I want interactively, but I would like to run this as a batch job, because I would like to run it on a cluster. So, I would like to set the variables aaa and bbb at breakpoint 3 and then continue without any user interaction. Is it possible? or maybe I am using the wrong tool to achieve this? NOTE: this is a follow-up question of python debugger initialising with file
tagged with: pdb
type: Question
has comment: http://stackoverflow.com/comment/87714837
has comment: http://stackoverflow.com/comment/87716323

http://stackoverflow.com/q/50295783
has comment: http://stackoverflow.com/comment/87608511
type: AnsweredQuestion
answer count: 3
linked to: http://stackoverflow.com/q/49442572
has comment: http://stackoverflow.com/comment/87609781
has comment: http://stackoverflow.com/comment/87609302
has comment: http://stackoverflow.com/comment/87608817
downvote count: 0
has comment: http://stackoverflow.com/comment/87608884
has answer: http://stackoverflow.com/a/50295893
has comment: http://stackoverflow.com/comment/87609560
has body: I have two spark dataframes: Dataframe A: |col_1 | col_2 | ... | col_n | |val_1 | val_2 | ... | val_n | and dataframe B: |col_1 | col_2 | ... | col_m | |val_1 | val_2 | ... | val_m | Dataframe B can contain duplicate, updated and new rows from dataframe A. I want to write an operation in spark where I can create a new dataframe containing the rows from dataframe A and the updated and new rows from dataframe B. I started by creating a hash column containing only the columns that are not updatable. This is the unique id. So let's say col1 and col2 can change value (can be updated), but col3,..,coln are unique. I have created a hash function as hash(col3,..,coln): A=A.withColumn("hash", hash(*[col(colname) for colname in unique_cols_A])) B=B.withColumn("hash", hash(*[col(colname) for colname in unique_cols_B])) Now I want to write some spark code that basically selects the rows from B that have the hash not in A (so new rows and updated rows) and join them into a new dataframe together with the rows from A. How can I achieve this in pyspark? Edit: Dataframe B can have extra columns from dataframe A, so a union is not possible. Sample example Dataframe A: +-----+-----+ |col_1|col_2| +-----+-----+ | a| www| | b| eee| | c| rrr| +-----+-----+ Dataframe B: +-----+-----+-----+ |col_1|col_2|col_3| +-----+-----+-----+ | a| wew| 1| | d| yyy| 2| | c| rer| 3| +-----+-----+-----+ Result: Dataframe C: +-----+-----+-----+ |col_1|col_2|col_3| +-----+-----+-----+ | a| wew| 1| | b| eee| null| | c| rer| 3| | d| yyy| 2| +-----+-----+-----+
favorite count: 0
type: Question
upvote count: 4
has title: How to update a pyspark dataframe with new values from another dataframe?
accepted answer: http://stackoverflow.com/a/50296778
linked to: http://stackoverflow.com/q/48427185
tagged with: pyspark
has answer: http://stackoverflow.com/a/50296778
possible better answer: http://stackoverflow.com/a/54293599
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/54293599
has comment: http://stackoverflow.com/comment/87608634
has comment: http://stackoverflow.com/comment/87608829

http://stackoverflow.com/comment/87771252
comment on: http://stackoverflow.com/q/50376697
score: 0
type: Comment
type: QuestionComment
has text: From your description I'm not able to completely imagine your hardware setup. Still, I would assume you are facing some kind of hardware layer incompatibility. Did you connected your RPI USART port to an RS485 device?

http://stackoverflow.com/comment/87661350
has text: Whatever errors you have should be edited into your post. Comments aren't the best place to debug broken code. By the way, I'd recommend trying to figure out what your data and your labels are, and slicing accordingly. I certainly don't know, because it isn't my data and I won't ssh into your system to find out.
comment on: http://stackoverflow.com/q/50322799
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50382353
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87782414
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87783056
has comment: http://stackoverflow.com/comment/87820606
has comment: http://stackoverflow.com/comment/133728318
has comment: http://stackoverflow.com/comment/133728284
type: Answer
has comment: http://stackoverflow.com/comment/87781195
accepted answer of: http://stackoverflow.com/q/50382256
has body: You can press the hotkey to get the debug console: Windows: Ctrl + Shift + D macOS: shift + command + Y Edit: In your project repo, find .vscode/launch.json file (create one if none exists) and add the following: { "version": "3.5", "configurations": [ { "type": "python", "request": "launch", "name": "Python: Current File", "program": "${file}", "console": "none" } ] } Then relaunch VSCode for the change to take effect.
has comment: http://stackoverflow.com/comment/87780770
answers question: http://stackoverflow.com/q/50382256

http://stackoverflow.com/comment/87581172
type: QuestionComment
has text: When I say "other reasons," I mean, that rounding is not acceptable. E.g., `Decimal(3.8)*Decimal(10)` returns 37.99999999999999822364316060. No bueno in a financial application.
comment on: http://stackoverflow.com/q/50282080
score: 0
type: Comment

http://stackoverflow.com/q/50370233
has title: How to turn Python Turtle to .exe
accepted answer: http://stackoverflow.com/a/50370355
type: Question
has comment: http://stackoverflow.com/comment/87756488
score: 0
has answer: http://stackoverflow.com/a/50370355
tagged with: turtle-graphics
answer count: 1
tagged with: py2exe
tagged with: python-3.x
type: AnsweredQuestion
has body: How do I turn my python turtle script to .exe? I tried py2exe and it did execute my script but the cmd showed up for like 1 milisecond. I think it is because I am using turtle graphics instead of normal python script. Is there any way to turn my turtle program into .exe?
tagged with: python

sockets
tags question: http://stackoverflow.com/q/50251765
tags question: http://stackoverflow.com/q/50360680
tags question: http://stackoverflow.com/q/50237213
tags question: http://stackoverflow.com/q/50321613
tags question: http://stackoverflow.com/q/50305321
tags question: http://stackoverflow.com/q/50301625
tags question: http://stackoverflow.com/q/50363682
tags question: http://stackoverflow.com/q/50294596
tags question: http://stackoverflow.com/q/50356320
tags question: http://stackoverflow.com/q/50306965
tags question: http://stackoverflow.com/q/50379072
tags question: http://stackoverflow.com/q/50295789
tags question: http://stackoverflow.com/q/50271308
tags question: http://stackoverflow.com/q/50265570
tag name: sockets
tags question: http://stackoverflow.com/q/50300307
tags question: http://stackoverflow.com/q/50281516
tags question: http://stackoverflow.com/q/50330849
tags question: http://stackoverflow.com/q/50382488
tags question: http://stackoverflow.com/q/50314151
tags question: http://stackoverflow.com/q/50376329
tags question: http://stackoverflow.com/q/50316521
type: Tag
tags question: http://stackoverflow.com/q/50327424
tags question: http://stackoverflow.com/q/50319187
tags question: http://stackoverflow.com/q/50273860
tags question: http://stackoverflow.com/q/50331018
tags question: http://stackoverflow.com/q/50243235

http://stackoverflow.com/a/50258470
downvote count: 0
has comment: http://stackoverflow.com/comment/87535485
answers question: http://stackoverflow.com/q/50258418
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87535002
has body: Your __init__ method should probably be: def __init__(self): print ("I m in __init__") self.tabControl = ttk.Notebook(root) self.tab1 = ttk.Frame(self.tabControl) self.tab2 = ttk.Frame(self.tabControl) You are missing the initial self. for each attribute.
upvote count: 2

pytest
tags question: http://stackoverflow.com/q/50268284
tags question: http://stackoverflow.com/q/50373916
tags question: http://stackoverflow.com/q/50370847
tag name: pytest
tags question: http://stackoverflow.com/q/50329629
tags question: http://stackoverflow.com/q/50239017
tags question: http://stackoverflow.com/q/50253429
tags question: http://stackoverflow.com/q/50252114
tags question: http://stackoverflow.com/q/50284208
tags question: http://stackoverflow.com/q/50370312
tags question: http://stackoverflow.com/q/50332266
tags question: http://stackoverflow.com/q/50251377
tags question: http://stackoverflow.com/q/50231627
tags question: http://stackoverflow.com/q/50248724
type: Tag

http://stackoverflow.com/comment/87682436
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50333067
has text: @HarvIpan Each folder has tons of .txt files with a bunch of words in a single column

http://stackoverflow.com/comment/87735718
type: AnswerComment
score: 0
type: Comment
has text: Is it correct to think of this like (string) interning?
comment on: http://stackoverflow.com/a/50338393

http://stackoverflow.com/q/50340211
tagged with: python
accepted answer: http://stackoverflow.com/a/50340263
type: AnsweredQuestion
score: 0
has body: I have two vectors: time and event. If one event is 1, the time at the same index should be assigned to func_for_event1. Otherwise, it goes to func_for_event0. import tensorflow as tf def func_for_event1(t): return t + 1 def func_for_event0(t): return t - 1 time = tf.placeholder(tf.float32, shape=[None]) # [3.2, 4.2, 1.0, 1.05, 1.8] event = tf.placeholder(tf.int32, shape=[None]) # [0, 1, 1, 0, 1] # result: [2.2, 5.2, 2.0, 0.05, 2.8] # For example, 3.2 should be sent to func_for_event0 because the first element in event is 0. How should I implement this logic in Tensorflow? Say tf.cond or tf.where?
has title: Calculate values in a vector based on the elements in another vector in Tensorflow
answer count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50340263

http://stackoverflow.com/comment/87630260
type: Comment
comment on: http://stackoverflow.com/a/50307026
score: 0
type: AnswerComment
has text: So is it not possible to do this with sockets?

http://stackoverflow.com/q/50290949
type: UnansweredQuestion
has body: I have to match the configuration of a filewall from a input file. In input file I'll specify a regex. This regex should match the output of the command from firewall. Suppose the firewall output is as below ssh 192.217.254.20 255.255.255.255 junk_string ssh 192.217.248.0 255.255.252.0 junk_string ssh 192.217.254.21 255.255.255.255 junk_string ssh 192.217.254.25 255.255.255.255 junk_string ssh 192.217.254.38 255.255.255.255 junk_string ssh 192.217.254.42 255.255.255.255 junk_string ssh 192.115.24.64 255.255.255.224 junk_string ssh 192.217.240.0 255.255.252.0 junk_string ssh 192.217.236.0 255.255.252.0 junk_string ssh 192.217.255.78 255.255.255.255 junk_string I want to match 9 lines as below regex. (sh 192.217.((254.(20|21|25|38|42)|255.78) 255.255.255.255|(240|248|236).0 255.255.252.0) [^ ]*\r\n?){9} But the rule will not match because of the 7th line when I use this regex with re.match or re.search. Is there any way to check this regex in any order. I mean it should match 9 lines, even if some unwanted lines are there in between. Update, This is how i use it if re.match(result_expected[command],actual_result,re.M|re.I): if verbose == "True": print("Command output and expected output Matched") result_expected - is our regex I have given above. actual_result - is the 10 lines which is output of the command executed on the firewall. ok. To make it more clear, my pattern works for the following 14 lines. pattern='(ssh 192.(168.((254.(2|6|20|21|25|38|42)|255.78|255.91|255.92) 255.255.255.255|(240|248|236).0 255.255.252.0)|115.24.64 255.255.255.224) [^ ]*\r?\n?){14}' ssh 192.168.240.0 255.255.252.0 junk_string ssh 192.168.248.0 255.255.252.0 junk_string ssh 192.168.236.0 255.255.252.0 junk_string ssh 192.168.254.42 255.255.255.255 junk_string ssh 192.168.254.25 255.255.255.255 junk_string ssh 192.168.254.21 255.255.255.255 junk_string ssh 192.168.255.78 255.255.255.255 junk_string ssh 192.168.254.20 255.255.255.255 junk_string ssh 192.168.254.38 255.255.255.255 junk_str…
tagged with: python
has comment: http://stackoverflow.com/comment/87602432
has comment: http://stackoverflow.com/comment/87598102
tagged with: python-2.7
score: 0
has title: Matching n number of lines in text to a regex any order using python
has comment: http://stackoverflow.com/comment/87598144
answer count: 1
tagged with: scripting
tagged with: regex
has comment: http://stackoverflow.com/comment/87599271
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50293561

http://stackoverflow.com/q/50362802
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: cython
upvote count: 17
has answer: http://stackoverflow.com/a/50368006
accepted answer: http://stackoverflow.com/a/50368006
favorite count: 0
type: Question
has body: If I have a generator function in Python, say: def gen(x): for i in range(x): yield(i ** 2) How do I declare that the output data type is int in Cython? Is it even worth while? Thanks. Edit: I read mentions of (async) generators being implemented in the changelog: http://cython.readthedocs.io/en/latest/src/changes.html?highlight=generators#id23 However there is no documentation about how to use them. Is it because they are supported but there is no particular advantage in using them with Cython or no optimization possible?
has title: How to type generator function in Cython?
tagged with: python
score: 17

http://stackoverflow.com/q/50285019
has comment: http://stackoverflow.com/comment/87593891
answer count: 0
tagged with: pandas
downvote count: 0
tagged with: gis
has comment: http://stackoverflow.com/comment/87587165
favorite count: 0
has title: Possible to render points plotted in Python with Matplotlib using a blending mode?
type: Question
has comment: http://stackoverflow.com/comment/87600532
tagged with: python-3.x
upvote count: 8
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87588154
has body: I'm plotting a series of overlapping points of various sizes using matplotlib in order from largest to smallest (smallest on top) but I am wondering if it is possible to configure the points to draw using a soft light blending mode so that you can see through stacks of points without using alpha blending. I'm loading my data using pandas and then plotting using the pandas plotting function (which uses matplotlib) like this simplified example: import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt roads = gpd.read_file('roads.shp') points = gpd.read_file('points.shp') f, ax = plt.subplots() roads.plot(ax=ax, linewidth=.5, color='#2D1B1B', zorder=1) points.plot(ax=ax, column='color', markersize=size, zorder=2) plt.axis('equal') plt.show() Here's how the plot looks: (I have exaggerated the overlap) Here's how I would like it to look: In this example each point is blended using a soft light blending mode, which makes it possible to 'see through' each point a bit without desaturating or adding transparency to points which are overlapping white. This makes it easy to see the larger, darker colored circles in the middle, without making the smaller, lighter colored circles on the white background harder to see the way alpha blending would. Difference from Alpha Blending: The most common method for blending overlapping points like this is to just make them transparent so that the overlapping points add up to a more intense color, but while this is desirable for visualizing density, it does not make sense in this context and looks washed out and bad: Is it possible to plot points using a soft light blending mode in matplotlib?
score: 8
has comment: http://stackoverflow.com/comment/87626783

http://stackoverflow.com/q/50341291
has comment: http://stackoverflow.com/comment/87698830
has comment: http://stackoverflow.com/comment/87698856
score: 2
has body: i have a data set as shown below Number of Number times of donated people 1 1885994 2 571213 3 298064 4 194252 5 140999 6 108091 7 86580 8 71330 9 59954 10 51590 11 44754 12 39711 and so on.. its around 100,000 data points. so, i wanted to try to plot a visualization, where i wanted to show how many percent of people donated 1 time, twice...and so on. which graph would be appropriate for this kind of data?
has comment: http://stackoverflow.com/comment/87698864
tagged with: visualization
answer count: 0
has comment: http://stackoverflow.com/comment/87828641
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87698810
has comment: http://stackoverflow.com/comment/87698776
upvote count: 2
has title: Which plot is best for showing per percentage data?
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
has comment: http://stackoverflow.com/comment/87698851
has comment: http://stackoverflow.com/comment/87698846

http://stackoverflow.com/a/78431138
answers question: http://stackoverflow.com/q/50355598
score: 0
has body: For a dask dataframe named df: df.compute().shape returns a tuple: (number of rows, number of columns)
type: Answer

http://stackoverflow.com/q/50371357
upvote count: 1
score: -1
accepted answer: http://stackoverflow.com/a/50374380
has title: Mathematical operations of user submitted equation
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87758588
answer count: 2
linked to: http://stackoverflow.com/q/2136556
has answer: http://stackoverflow.com/a/50374380
tagged with: python
has body: I am writing a program to take an equation from the user for example 2 * 56 and the program gives out the answer. this is working but for more than 2 function my code breaks equation = input('Enter an equation: ') def addition(): splited = equation.split('+') results = [float(i) for i in splited] results = results[0] + results[1] print(results) def subtraction(): splited= equation.split('-') results = [float(i) for i in splited] results = results[0] - results[1] print(results) def multiply(): splited= equation.split('*') results = [float(i) for i in splited] results = results[0] * results[1] print(results) def divide(): splited= equation.split('/') results = [float(i) for i in splited] results = results[0] / results[1] print(results) if ('+') in equation: addition() elif ('-') in equation: subtraction() elif ('*') in equation: multiply() elif ('/') in equation: divide() else: print('Error! Please only input + , - , * , /') this code easily works for equations containing only one operation but what if user inputs 2 + 2 - 9 * 6 how can i modify this code to work with every case possible
has comment: http://stackoverflow.com/comment/87758509
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/50371832
possible better answer: http://stackoverflow.com/a/50371832
has comment: http://stackoverflow.com/comment/87758500

http://stackoverflow.com/q/50341199
tagged with: pandas
has comment: http://stackoverflow.com/comment/87698706
has answer: http://stackoverflow.com/a/50341287
answer count: 2
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50342119
type: UnansweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87698566
type: Question
has comment: http://stackoverflow.com/comment/87698558
has title: Series data increasing numbers
tagged with: python
has body: In Pandas Dataframe, I input data unique key. For Example Inputs: time range 2018-03-04 00:00:06.520 0 2018-03-04 00:00:07.130 0 2018-03-04 00:00:07.850 1 2018-03-04 00:00:08.420 1 2018-03-04 00:00:09.210 2 2018-03-04 00:00:10.070 2 2018-03-04 00:00:10.840 3 2018-03-04 00:00:11.230 3 2018-03-04 00:00:11.980 4 2018-03-04 00:00:12.560 4 2018-03-04 00:00:13.120 0 2018-03-04 00:00:13.790 0 2018-03-04 00:00:14.330 1 2018-03-04 00:00:15.280 1 2018-03-04 00:00:15.960 2 2018-03-04 00:00:16.420 2 2018-03-04 00:00:17.090 3 I wanna Output dataFrame is here. time range Key 2018-03-04 00:00:06.520 0 1 2018-03-04 00:00:07.130 0 1 2018-03-04 00:00:07.850 1 1 2018-03-04 00:00:08.420 1 1 2018-03-04 00:00:09.210 2 1 2018-03-04 00:00:10.070 2 1 2018-03-04 00:00:10.840 3 1 2018-03-04 00:00:11.230 3 1 2018-03-04 00:00:11.980 4 1 2018-03-04 00:00:12.560 4 1 2018-03-04 00:00:13.120 0 2 2018-03-04 00:00:13.790 0 2 2018-03-04 00:00:14.330 1 2 2018-03-04 00:00:15.280 1 2 2018-03-04 00:00:15.960 2 2 2018-03-04 00:00:16.420 2 2 2018-03-04 00:00:17.090 3 2 ... I wanna using range &amp; Time get Key Values that increasing.. How can I do it?

http://stackoverflow.com/comment/87634849
score: 0
comment on: http://stackoverflow.com/q/50309299
has text: If you want to check if there is `@` or `de` at the end, use `re.search(r'@|de$', s)`. If you want to check for a sequence of them, try `re.search(r'@.*de$', s)`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50252474
score: 0
has body: I am not sure if I understand by "automatically". However, instead of plotting (which can be a hard task if you have many attributes for each sample), you can try to automatically group your samples using clustering techniques such as K-Means, Hierarchical clustering, SOM (or any clustering technique that fits to your problem). Then, for each group, you may extract any statistical information of interest.
answers question: http://stackoverflow.com/q/50248547
type: Answer

http://stackoverflow.com/comment/87685017
type: QuestionComment
comment on: http://stackoverflow.com/q/50333911
has text: According to https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.RandomState.html#numpy.random.RandomState, the default seed used is None, which in turn means it seeds from /dev/urandom, so the two notebooks should see different random data.
score: 1
type: Comment

http://stackoverflow.com/comment/87779867
type: Comment
has text: @bruna . .. That's interesting. There are two parameters inthe query and two in the list.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50381861

http://stackoverflow.com/comment/87506288
comment on: http://stackoverflow.com/q/50244270
score: 0
has text: Have you benchmarked your code? You can't improve it unless you know what you are trying to improve.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50293561
score: 0
has body: If you want to match a dot literally you should escape it \. or else it would mean to match any character. There is also a leading s missing, now it says sh. If you use an alternation and don't want to capture the values you could use a non capturing group (?: To to match all the lines except ssh 192.115.24.64 255.255.255.224 junk_string you might use findall. Without capturing groups you could match your lines with: ssh 192\.217\.(?:254\.(?:2[015]|38|42)|255\.78|24[08]\.0|236\.0) 255\.255\.(?:255\.255|252\.0) [^ ]*\r?\n|\r Demo Python
answers question: http://stackoverflow.com/q/50290949
type: Answer

http://stackoverflow.com/a/50313811
has comment: http://stackoverflow.com/comment/87644886
downvote count: 0
has comment: http://stackoverflow.com/comment/87643786
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87643687
has comment: http://stackoverflow.com/comment/87643720
has comment: http://stackoverflow.com/comment/87644211
has comment: http://stackoverflow.com/comment/87644498
accepted answer of: http://stackoverflow.com/q/50313785
answers question: http://stackoverflow.com/q/50313785
type: Answer
has comment: http://stackoverflow.com/comment/88590638
has body: Substitutions are not regular expressions, but a different pattern where you can use part of the original match, e.g.: re.sub(r"Google(.*)", r"\g&lt;0&gt;\n") Cf. http://www.regular-expressions.info/refreplacebackref.html for information about replacement placeholders. EDIT: As for your perceived lack of »global« substitution: re.sub will actually replace all matches in the string, but your regex actually matches from Google to the end of the string. Something like the following should work a bit better: re.sub(r"Google\((.*?)\)", r"\g&lt;0&gt;\n") Here .*? is »lazy«, so it will only match as much as possible to make the rest of the regex match as well, in this case up to the first closing parenthesis (instead of the last, as with the greedy match).

http://stackoverflow.com/a/50293509
answers question: http://stackoverflow.com/q/50283102
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: As suggested by @AndrewSvetlov, you can use an asyncio.Semaphore to enforce the limit: async def run_program(input): p = await asyncio.create_subprocess_exec(...) # ... communicate with the process ... p.terminate() return something_useful async def run_throttled(input, sem): async with sem: result = await run_program(input) return result LIMIT = 10 async def many_programs(inputs): sem = asyncio.Semaphore(LIMIT) results = await asyncio.gather( *[run_throttled(input, sem) for input in inputs]) # ...

http://stackoverflow.com/comment/105825819
has text: I assume [unittest.mock.patch](http://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)
comment on: http://stackoverflow.com/a/50251478
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87552087
comment on: http://stackoverflow.com/q/50254618
type: Comment
type: QuestionComment
has text: Yes I have Xcode on my mac. I'm a iOS developer for most time now
score: 0

http://stackoverflow.com/a/50359871
accepted answer of: http://stackoverflow.com/q/50359777
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: There are 2 improvements to your code: Compare objects of the same type, e.g. int with int. Use next(reader) to extract the first row before your for loop. This is one way you can refactor your logic: import csv with open('B.txt', 'r') as f: reader = csv.reader(f, delimiter=",") headers = next(reader) lineNumber = int(headers[1]) for row in reader: if int(row[0]) == lineNumber: print("Is equal") break
type: Answer
answers question: http://stackoverflow.com/q/50359777

http://stackoverflow.com/comment/87551333
has text: @PiyushRaut In that case, it's not the function's fault that everything comes out to be between 0.7 and 0.8, don't you think?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50266619

http://stackoverflow.com/a/50337885
upvote count: 2
answers question: http://stackoverflow.com/q/50306870
score: 1
has comment: http://stackoverflow.com/comment/119309284
type: AcceptedAnswer
downvote count: 1
has body: I believe you can do so with PyMuPDF. I've inserted text with the module before but not rotated text. There is a rotate parameter in the insertText method so hopefully it will work for you. It can be done as follows: import fitz doc = fitz.open(filename) page = doc[0] point = fitz.Point(x, y) # in PDF units (1 / 72 of an inch) page.insertText( point, text="Hello World", fontsize=8, fontname="Helvetica", # Use a PDF Base 14 Fonts, else check documentation color=(0, 0, 0), rotate=90 ) doc.save(filename, incremental=True) doc.close()
has comment: http://stackoverflow.com/comment/118291869
type: Answer
accepted answer of: http://stackoverflow.com/q/50306870

http://stackoverflow.com/q/50293850
upvote count: 1
score: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
type: Question
linked to: http://stackoverflow.com/q/11561258
tagged with: python
type: UnansweredQuestion
has title: Importing your R module in python scripts
has comment: http://stackoverflow.com/comment/87606918
has body: Let say I have script calc.R with a function add. add &lt;- function(x, y) { return(x+y) } Is it possible to import 'add' in a python script test.py ? (Had calc been a py script I could simply: from calc import add. Is there a soltuion for calc.R ?)
has comment: http://stackoverflow.com/comment/87604183
tagged with: python-import
has comment: http://stackoverflow.com/comment/87625460
answer count: 0
downvote count: 0

http://stackoverflow.com/a/50340870
score: 0
answers question: http://stackoverflow.com/q/50339997
type: Answer
has body: Strings are immutable in Python. replace() doesn't modify the string it was given, it returns a new string. So when you do: x = x.replace(x, y) in the first function, it's creating a new string and assigning that to the local variable x. The string in the original variable s is not affected. Also, function parameters are passed by value, not by reference. So assigning to x in the function doesn't assign to the outer variable s.

http://stackoverflow.com/q/50367594
has answer: http://stackoverflow.com/a/50367784
possible better answer: http://stackoverflow.com/a/50367784
tagged with: exists
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87754342
type: Question
has answer: http://stackoverflow.com/a/50367621
accepted answer: http://stackoverflow.com/a/50367621
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/2299454
tagged with: file
has comment: http://stackoverflow.com/comment/87751393
has title: Is there a way to find *.csv exists in python?
linked to: http://stackoverflow.com/q/12925288
favorite count: 0
has body: What is required? Test if any of *.csv file is generated in the current directory. Note that the csv file is named after date/time so its not possible to get the file name in this case. Problem Tried the os.path.isfile([exact_path_to_file]) and it works. However what we need to find is if any one of the .csv file is generated if so, assertTrue else assertFalse. In case of assertTrue, will delete the file. Is this possible with python? Reference The closest of this is using a regular expression like this post however for this simple check is it really required to go for a regular expression?
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: http://stackoverflow.com/tag/csv

marker
tag name: marker
tags question: http://stackoverflow.com/q/50360567
type: Tag

http://stackoverflow.com/a/50340641
type: Answer
has comment: http://stackoverflow.com/comment/87718519
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87721080
has comment: http://stackoverflow.com/comment/87716775
has body: The stop.wait() event is causing the problem. It is equivalent to time.sleep(). Remove stop should fix the problem. Programming Guide » Events and Properties » Main loop In Kivy applications, you have to avoid long/infinite loops or sleeping. Example main.py from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from multiprocessing import Process, Queue, Event kv = ''' &lt;InterfaceView&gt;: Button: text: 'teste' on_press: root.do_process() ''' def pprosess(message, q): q.put(message) Builder.load_string(kv) class InterfaceView(BoxLayout): def do_process(self): q = Queue() p = Process(target=pprosess, args=('any message', q)) p.daemon = True p.start() print('Read message') print('message: ', q.get()) p.join() print('Process closed') class SimpleApp(App): def build(self): return InterfaceView() if __name__ == '__main__': SimpleApp().run() Output
answers question: http://stackoverflow.com/q/50339895
downvote count: 0
has comment: http://stackoverflow.com/comment/87720700

http://stackoverflow.com/a/50299238
answers question: http://stackoverflow.com/q/50299172
has body: Interesting that you get that output. Running arange(0.0,0.6,0.2) I get: array([0. , 0.2, 0.4]) Regardless, from the numpy.arange docs: Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). Also from the docs: When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases The only thing I can suggest to achieve what you want is to modify the stop parameter and add a very small amount, for example np.arange(0.0, 0.6 + 0.001 ,0.2) Returns array([0. , 0.2, 0.4, 0.6]) Which is your desired output. Anyway, it is better to use numpy.linspace and set endpoint=True
score: 4
has comment: http://stackoverflow.com/comment/88029598
has comment: http://stackoverflow.com/comment/87615309
has comment: http://stackoverflow.com/comment/116832858
has comment: http://stackoverflow.com/comment/87615928
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/87615821
downvote count: 2

http://stackoverflow.com/q/50317305
score: 1
answer count: 1
has title: Using Numpy to find combination of rows in an array such that each column sums to the same value
has comment: http://stackoverflow.com/comment/87650427
has comment: http://stackoverflow.com/comment/87658478
tagged with: data-science
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50317587
accepted answer: http://stackoverflow.com/a/50317587
tagged with: python
tagged with: linear-algebra
has body: I'm trying to use numpy to find configurations of rows in a matrix such that summing the columns of the rows will result in the same value. As an example, for the matrix/array [[0,0,0,1], [1,0,1,0], [1,1,0,0], [0,1,0,0]] I would like to have the first, second, and last row as output, because 0,0,0,1 1,0,1,0 0,1,0,0 + ------- = 1,1,1,1 Is there any tools built into numpy that would assist me in acquiring this?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87670473
has comment: http://stackoverflow.com/comment/87652139
upvote count: 1

http://stackoverflow.com/q/50311415
favorite count: 0
type: Question
has title: Tkinter on Pydev Eclipse doesn't work
accepted answer: http://stackoverflow.com/a/50311429
has body: I tried to use Tkinter on eclipse, and it works for short codes such as this one: from tkinter import * root = Tk() mainloop() This code works on eclipse, but this one doesn't: from tkinter import Tk, Canvas, HIDDEN, NORMAL root = Tk() root.title('Snap') c = Canvas(root, width=400, height=400) shapes = [] circle = c.create_oval(35, 20, 365, 350, outline='black', fill='black', state=HIDDEN) shapes.append(circle) circle = c.create_oval(35, 20, 365, 350, outline='red', fill='red', state=HIDDEN) shapes.append(circle) circle = c.create_oval(35, 20, 365, 350, outline='green', fill='green', state=HIDDEN) shapes.append(circle) circle = c.create_oval(35, 20, 365, 350, outline='blue', fill='blue', state=NORMAL) shapes.append(circle) c.pack() This code should make a window appear and have a blue circle on it, but I tried running it but nothing happened.
score: 1
has answer: http://stackoverflow.com/a/50311429
tagged with: python
tagged with: eclipse
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
answer count: 1
downvote count: 1

http://stackoverflow.com/a/50245635
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50244301
has body: It would be ideal to programatically check for the length constraints. However, using Nested Conditional Regex, we could come up with the RIC regex as follows (please note that this could be a maintenance nightmare): Demo Regex: ^([A-Z0-9])? # first character is [A-Z0-9] (capture group 1) (?(1) # if capture group 1 is set \.[A-Za-z]{1,6} | # then check if there is min 1 and max 6 chars after the dot (total 7, including dot 8) ([A-Z0-9]{2})? # else check first 2 characters are [A-Z0-9] (capture group 2) (?(2) # if capture group 2 is set \.[A-Za-z]{1,5} | # then check if there is min 1 and max 5 chars after the dot (total 7, including dot 8) ([A-Z0-9]{3})? (?(3) \.[A-Za-z]{1,4} | ([A-Z0-9]{4})? (?(4) \.[A-Za-z]{1,3} | ([A-Z0-9]{5})? (?(5) \.[A-Za-z]{1,2} | ([A-Z0-9]{6})? # else check first 6 characters are [A-Z0-9] (capture group 6) (?(6) # if capture group 6 is set \.[A-Za-z] | # then check if there is 1 char after the dot (total 7, including dot 8) ([A-Z0-9][a-z])? (?(7) \.[A-Za-z]{1,5} | ([A-Z0-9][a-z]{2})? (?(8) \.[A-Za-z]{1,4} | ([A-Z0-9][a-z]{3})? (?(9) \.[A-Za-z]{1,3} | ([A-Z0-9][a-z]{4})? (?(10) \.[A-Za-z]{1,2} | ([A-Z0-9][a-z]{5})? (?(11) \.[A-Za-z] | ([A-Z0-9]{2}[a-z])? (?(12) \.[A-Za-z]{1,4} | ([A-Z0-9]{2}[a-z]{2})? (?(13) \.[A-Za-z]{1,3} | ([A-Z0-9]{2}[a-z]{3})? (?(14) \.[A-Za-z]{1,2} | ([A-Z0-9]{2}[a-z]{4})? (?(15) \.[A-Za-z] | ([A-Z0-9]{3}[a-z])? (?(16) \.[A-Za-z]{1,3} | ([A-Z0-9]{3}[a-z]{2})? (?(17) \.[A-Za-z]{1,2} | ([A-Z0-9]{3}[a-z]{3})? (?(18) \.[A-Za-z] | ([A-Z0-9]{4}[a-z])? (?(19) \.[A-Za-z]{1,2} | ([A-Z0-9]{4}[a-z]{2})? (?(20) \.[A-Za-z] | ([A-Z0-9]{5}[a-z])? (?(21) \.[A-Za-z] ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )$

http://stackoverflow.com/comment/87554734
has text: Possible duplicate of [Opening csv file in Python: builtins. AttributeError AttributeError: '\_io.BytesIO' object has no attribute 'file'](https://stackoverflow.com/questions/44005053/opening-csv-file-in-python-builtins-attributeerror-attributeerror-io-bytesi)
comment on: http://stackoverflow.com/q/50268055
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87655865
type: Comment
comment on: http://stackoverflow.com/a/50319866
type: AnswerComment
has text: I still think that the OP wanted trailing spaces removed based on their example, so [`df.Description = df.Description.str.replace(r'[-#*\d]+ ?, '')`](https://regex101.com/r/2I4ZmD/2/) may be better suited for the OP's desired behavior.
score: 1

http://stackoverflow.com/comment/87682960
type: QuestionComment
comment on: http://stackoverflow.com/q/50332735
has text: What language? `phynton` ? Is that python?
score: 1
type: Comment

http://stackoverflow.com/q/50365473
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87747401
has comment: http://stackoverflow.com/comment/87747584
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
score: 1
type: Question
has title: How can I simply count how many Multiprocesses are currently running in python?
answer count: 0
has body: My script runs a process called load, it takes more than 30 seconds to finish. The connection to the proxy means that the processes take different amounts of time to complete each time they run. I need my code to look like this while running == true: if not 25 multiprocesses running: start enough processes to reach 25 running here's what my code looks like now, it just starts 10 processes and then ends as a test: import random, time from selenium import webdriver from selenium.webdriver.common.proxy import * from fake_useragent import UserAgent import multiprocessing def load(): proxy = "falcon.proxyrotator.com:8080" profile = webdriver.ChromeOptions() profile.add_argument('headless') profile.add_argument('--proxy-server=http://%s' % proxy) profile.add_argument('--user-agent=' + UserAgent().random) driver = webdriver.Chrome(chrome_options=profile) driver.get('https://ipchicken.com') print ('done') time.sleep(30) driver.quit() if __name__ == '__main__': for i in range(10): time.sleep(7) print ('start') P = multiprocessing.Process(target=load) P.start()

http://stackoverflow.com/a/61148430
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/50291923
type: Answer
has body: I have a slightly modified example that worked really well for me: app.py: link_chart_data = { "type": "LinkChart", "items": [{ "type": "node", "id": "ac1", "u": "static/icons/bank.png", "t": "45081063" }] } @app.route('/link_chart') def covid(): return render_template("link_chart/index.html", flask_data=link_chart_data) Then in templates/link_chart/index.html: &lt;script&gt; const parsedData = JSON.parse(''); const unparsedData = '{{ flask_data }}' console.log('parsed', parsedData) console.log('unparsed', unparsedData) &lt;/script&gt; Which yields: parsed, items: Array(1) 0: id: "ac1" t: "45081063" type: "node" u: "static/icons/bank.png" __proto__: Object length: 1 __proto__: Array(0) type: "LinkChart" ^^This is what I want. a new JSON object and: unparsed {&amp;#39;type&amp;#39;: &amp;#39;LinkChart&amp;#39;, &amp;#39;items&amp;#39;: [{&amp;#39;type&amp;#39;: &amp;#39;node&amp;#39;, &amp;#39;id&amp;#39;: &amp;#39;ac1&amp;#39;, &amp;#39;u&amp;#39;: &amp;#39;static/icons/bank.png&amp;#39;, &amp;#39;t&amp;#39;: &amp;#39;45081063&amp;#39;}]} ^^Which I really don't want. The |tojson jinja template un-asciis the variable so that it gets passed as the same format it came from python (flask). the JSON.parse() javascript function is what converts it from a string to a JSON object in javascript. I hope this helps.
has comment: http://stackoverflow.com/comment/118634035

del
tag name: del
tags question: http://stackoverflow.com/q/50322795
type: Tag

http://stackoverflow.com/q/50244016
linked to: http://stackoverflow.com/q/49559003
has answer: http://stackoverflow.com/a/50244115
tagged with: python
duplicate of: http://stackoverflow.com/q/49559003
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87505744
accepted answer: http://stackoverflow.com/a/50244115
has body: When I print out sys.path in python it apparently always starts with apostrophes denoting an empty string '', why is that? import sys print(sys.path) # ['', and/some/other/paths]
answer count: 1
has title: Why does sys.path start with an empty string?
type: Question

http://stackoverflow.com/q/50274807
has title: How to combine two lists of tuples to create a nested dictionary?
answer count: 3
has answer: http://stackoverflow.com/a/50275210
type: UnansweredQuestion
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/50274902
has body: I have two lists of tuples like: tin = [ ('a1', 'meow'), ('b1', 'woof'), ('c1', 'mooo'), ('d1', 'oink'), ] rop = [ ('b1', 'forest'), ('a1', 'home'), ('d1', 'shed'), ] How can I combine them into one dictionary so that the result looks like: full = [ {'a1' : {'sound': 'meow', 'place': 'home'} {'b1' : {'sound': 'woof', 'place': 'forest'} {'c1' : {'sound': 'mooo', 'place': None} {'d1' : {'sound': 'oink', 'place': 'shed'} ] I have it working like this: my_dict = {} for k, v in tin : if not my_dict.get(k): my_dict[k] = {} my_dict[k]['sound'] = v else: my_dict[k]['sound'] = v for k, v in rop: if not my_dict.get(k): my_dict[k] = {} my_dict[k]['place'] = v else: my_dict[k]['place'] = v But is is very verbose and I think there should be something more pythonic.
has answer: http://stackoverflow.com/a/50274878
type: Question
score: 0

http://stackoverflow.com/comment/87724407
comment on: http://stackoverflow.com/q/50354041
score: 0
type: Comment
type: QuestionComment
has text: Please include an example of `dict` that gives some of the results. I'm not sure where those strings of lists are coming from - are they to be split into their own columns? Also, are you on Windows? Is this Python 2 or 3 (changes how you get rid of the blank lines). And finally, it's not a good idea to call your own variables `dict`

http://stackoverflow.com/comment/87735890
score: 0
has text: Thank you it was exactly wat I needed :)
comment on: http://stackoverflow.com/a/50349972
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50355334
score: 0
has comment: http://stackoverflow.com/comment/87727100
answer count: 2
has body: I have multiple .txt files inside folder/subfolders as shown below: States (folder) Arizona (subfoler) file1.txt file2.txt file3.txt Alaska (subfolder) file1.txt file2.txt file3.txt file4.txt Arkansas (subfolder) file1.txt file2.txt I need to convert all the files to csv and combine csv files per folder (such as arizona_files.csv, alaska_files.csv). I tried to use the code below and there was no output. Any idea what I am doing wrong? import os import csv for root, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith('.txt'): txt_file = ('*.txt') csv_file = ('*.csv') in_txt = csv.reader(open(filename, "rb"), delimiter = '\t') out_csv = csv.writer(open('*.csv', 'wb')) out_csv.writerows(filename)
has comment: http://stackoverflow.com/comment/87727312
has comment: http://stackoverflow.com/comment/87727621
has answer: http://stackoverflow.com/a/50355763
has answer: http://stackoverflow.com/a/50355776
type: Question
has comment: http://stackoverflow.com/comment/87727578
tagged with: http://stackoverflow.com/tag/csv
has title: Convert multiple text file to csv using os.walk
possible better answer: http://stackoverflow.com/a/50355776
accepted answer: http://stackoverflow.com/a/50355763
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/50307866
score: 1
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/87632307
has answer: http://stackoverflow.com/a/51989860
favorite count: 0
has comment: http://stackoverflow.com/comment/87632273
type: Question
has comment: http://stackoverflow.com/comment/87631896
has comment: http://stackoverflow.com/comment/87632210
type: UnansweredQuestion
has title: LightFM recommendation: Inconsistent error with interaction data
tagged with: python
has comment: http://stackoverflow.com/comment/87632577
tagged with: collaborative-filtering
has body: I have the following basic code with the LightFM recommendation module: # Interactions A=[0,1,2,3,4,4] # users B=[0,0,1,2,2,3] # items C=[1,1,1,1,1,1] # weights matrix = sparse.coo_matrix((C,(A,B)),shape=(max(A)+1,max(B)+1)) # Create model model = LightFM(loss='warp') # Train model model.fit(matrix, epochs=30) # Predict scores = model.predict(1, np.array([0,1,2,3])) print(scores) This returns the following error: &gt; C:\Program &gt; Files\Python\Python36\lib\site-packages\numpy\core\_methods.py:32: &gt; RuntimeWarning: invalid value encountered in reduce return &gt; umr_sum(a, axis, dtype, out, keepdims) Traceback (most recent call &gt; last): File "run.py", line 15, in &lt;module&gt; &gt; model.fit(matrix, epochs=100) File "C:\Program Files\Python\Python36\lib\site-packages\lightfm\lightfm.py", line 476, &gt; in fit &gt; verbose=verbose) File "C:\Program Files\Python\Python36\lib\site-packages\lightfm\lightfm.py", line 580, &gt; in fit_partial &gt; self._check_finite() File "C:\Program Files\Python\Python36\lib\site-packages\lightfm\lightfm.py", line 410, &gt; in _check_finite &gt; raise ValueError("Not all estimated parameters are finite," ValueError: Not all estimated parameters are finite, your model may &gt; have diverged. Try decreasing the learning rate or normalising feature &gt; values and sample weights Strangely enough, making some changes in the interaction data makes it work, as with: # Interactions A=[0,1,2,3,4,4] B=[0,0,1,2,2,10] # notice the 10 here C=[1,1,1,1,1,1] Could anyone help me with that please?
tagged with: recommendation-engine

http://stackoverflow.com/comment/87637341
type: Comment
type: QuestionComment
has text: Use https://regex101.com/ to debug it.
comment on: http://stackoverflow.com/q/50310656
score: 0

http://stackoverflow.com/comment/87527758
comment on: http://stackoverflow.com/q/50255096
score: 3
type: Comment
type: QuestionComment
has text: what is your expected out put ?

http://stackoverflow.com/q/50260158
linked to: http://stackoverflow.com/q/39805675
tagged with: nltk
has title: Error from importing TextBlob
answer count: 1
tagged with: laravel
accepted answer: http://stackoverflow.com/a/50266210
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50266210
tagged with: textblob
tagged with: python
has body: I am having a problem when running a Python script within my Laravel project. I do not get this problem when running the python script using virtualenv and without. I am using Win 10 64-bit. When running the python script within Laravel using Symfony/Process, I am getting this error: """ The command "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\Scripts\activate &amp;&amp; py C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\main.py" failed.\n ◀ \n Exit Code: 1(General error)\n \n Working directory: C:\xampp\htdocs\projects\laravel-project\public\n \n Output:\n ================\n \n \n Error Output:\n ================\n Traceback (most recent call last):\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\main.py", line 10, in &lt;module&gt;\r\n from textblob import TextBlob\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\textblob\__init__.py", line 2, in &lt;module&gt;\r\n ◀ from .blob import TextBlob, Word, Sentence, Blobber, WordList\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\textblob\blob.py", line 28, in &lt;module&gt;\r\n import nltk\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\nltk\__init__.py", line 160, in &lt;module&gt;\r\n from nltk.downloader import download, download_shell\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\nltk\downloader.py", line 2237, in &lt;module&gt;\r\n ◀ _downloader = Downloader()\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\nltk\downloader.py", line 443, in __init__\r\n ◀ self._download_dir = self.default_download_dir()\r\n File "C:\xampp\htdocs\projects\laravel-project\scripts\sentiment\env\lib\site-packages\nltk\downloader.py", line 954, in default_download_dir\r\n ◀ raise ValueError("Could not find a default download directory")\r\n ValueError: Could not find a def…
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/70906837
type: Answer
score: 0
has body: I created a similar python script to @Chankey above but mine does repos and not gists and shows a little bit more info (shows ahead and behind commits as well). I wanted to know the same as OP for any fork because some repos can just get out of hand with the number of forks and forks of forks (Can github do anything with that to show the user better information?). Let me know what everyone thinks of the script - I'm definitely open to suggestions. It was something I threw together: https://github.com/ikwyl6/git-diff-forks
answers question: http://stackoverflow.com/q/50258835

http://stackoverflow.com/q/50337886
has body: I have two classes as follows: class Buttons(): def __init__(self, dDict): self.TCT = Tool() self.dDict = dDict def btnName(self): # I will use both self.TCT and self.dDict here a = self.dDict['setup'] class Switch(Buttons): def __init__(self): self.TCT =Tool() I need to instantiate Switch class, but I need to provide dDict so that Buttons class will have the data it is looking for. What is the right way to instantiate the class Switch?
tagged with: python
type: AnsweredQuestion
score: 0
has title: How to inherit from a class with __init__ and take input parms
upvote count: 2
downvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/50721803
accepted answer: http://stackoverflow.com/a/50337947
has answer: http://stackoverflow.com/a/50337947
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87730506
comment on: http://stackoverflow.com/a/50356670
has text: I have checked css selector provided by me is generic. and would work if scroll down is performed.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/50365138
tagged with: string
has body: Here is the simple code: OS.write(ip+re.search(version,data).group(0).rjust(25)+'\n') All I want is to have the output like this: 10.102.19.1 version=6.40.7 10.102.41.1 version=6.40.7 10.102.3.1 version=6.40.8 But have the right string absolutely doesnt want to be aligned and I always get this: 10.102.19.1 version=6.40.7 10.102.41.1 version=6.40.7 10.102.3.1 version=6.40.8 What I'm doing wrong?
accepted answer: http://stackoverflow.com/a/50365207
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Rjust method alignment
answer count: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50365207
tagged with: text-align

http://stackoverflow.com/q/50362088
has answer: http://stackoverflow.com/a/79040317
has answer: http://stackoverflow.com/a/60478942
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87740607
has body: Hi~I have got a ModuleNotFoundError saying "No module named 'captcha.fields'" when I run manage.py in my Django project. I confirm that django-simple-captcha has been installed and successfully imported into my programme. But I check the captcha package and I haven't found any definition for captcha.fields. Could anyone help me, please? Thank you.
has answer: http://stackoverflow.com/a/78210999
type: UnansweredQuestion
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/87743434
score: 3
upvote count: 3
tagged with: captcha
downvote count: 0
has answer: http://stackoverflow.com/a/59600403
has title: No module named 'captcha.fields'

python-curses
tag name: python-curses
type: Tag
tags question: http://stackoverflow.com/q/50279114
tags question: http://stackoverflow.com/q/50273301

http://stackoverflow.com/a/52787541
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/104621032
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50266753
score: 2
has body: The convolution inner loop does macc of uint8 values. There is also a smaller outer loop for computing the z-offset portions of the macc. At the end of each kernel convolution you will need to downscale from the int32 accumulator to the 8 bit uint8 range using a downscale multiplier that is input_scale * kernel_scale / output_scale. Those three scale values were learned during training, and are in the tflite inference file. This paper explains the operations. http://openaccess.thecvf.com/content_cvpr_2018/papers/Jacob_Quantization_and_Training_CVPR_2018_paper.pdf
answers question: http://stackoverflow.com/q/50266753

http://stackoverflow.com/comment/87533272
type: Comment
comment on: http://stackoverflow.com/q/50257656
score: 1
type: QuestionComment
has text: I'll give you a couple of tips before your question gets downvoted. First fix the formatting, your error is unreadable. Second, take your time to elaborate a question and describe it the best possible way, as I don't understand what your problem is and others won't either. Third, explain what have you tried when it was working, and what changed now that it's not working. Cheers ~

http://stackoverflow.com/q/50368744
has comment: http://stackoverflow.com/comment/87764920
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: File "src/gevent/greenlet.py", line 705, in gevent._greenlet.Greenlet.run File "/home/interview/BEMOSS3.5/volttron/platform/auth.py", line 147, in zap_loop time = gevent.core.time AttributeError: 'module' object has no attribute 'core' 2018-05-16T09:52:00Z &lt;Greenlet "Greenlet-0" at 0x7f37102cd998: &lt;bound method AuthService.zap_loop of &lt;volttron.platform.auth.AuthService object at 0x7f3718630050&gt;&gt;(&lt;volttron.platform.vip.agent.core.Core object at 0)&gt; failed with AttributeError 2018-05-16 15:22:06,815 wheel INFO: creating '/tmp/tmpPCrbeW/pkg/dist/bacnet_proxyagent-0.1-py2-none-any.whl' and adding '.' to it 2018-05-16 15:22:06,816 wheel INFO: adding 'bacnet_proxy/rough.py' 2018-05-16 15:22:06,816 wheel INFO: adding 'bacnet_proxy/__init__.py' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxy/agent.py' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/DESCRIPTION.rst' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/entry_points.txt' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/metadata.json' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/top_level.txt' 2018-05-16 15:22:06,817 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/WHEEL' 2018-05-16 15:22:06,818 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/METADATA' 2018-05-16 15:22:06,818 wheel INFO: adding 'bacnet_proxyagent-0.1.dist-info/RECORD' clear: error: 'gevent._event.AsyncResult' object has no attribute 'ident' Unpacking to: /home/interview/.volttron/agents/cd699ad7-934b-4e78-8ff8-68ab3d54a592/bacnet_proxyagent-0.1 Installed /home/interview/.volttron/packaged/bacnet_proxyagent-0.1-py2-none-any.whl as cd699ad7-934b-4e78-8ff8-68ab3d54a592 bacnet_proxyagent-0.1 VOLTTRON_HOME=/home/interview/.volttron clear: error: 'gevent._event.AsyncResult' object has no attribute 'ident' Unpacking to: /home/interview/.volttron/agents/b50a12ee-2602-4622-b943-f78380d450ae/VIPagent-3.0 Insta…
tagged with: volttron
has comment: http://stackoverflow.com/comment/87784073
tagged with: cassandra
downvote count: 0
score: 1
upvote count: 1
tagged with: cassandra-3.0
has answer: http://stackoverflow.com/a/50580799
favorite count: 0
has title: Error while running the bemoss, I am getting AttributeError: 'gevent._event.AsyncResult' object has no attribute 'ident'
type: Question

http://stackoverflow.com/comment/87725593
score: 0
comment on: http://stackoverflow.com/q/50354482
type: Comment
type: QuestionComment
has text: Why is this tagged “machine-learning”? If you really want an ML solution, just train the network on a bunch of examples with that list of book titles, and it should (a) come up with a heuristic that covers most cases (e.g., a string in Book Title Case is a book, or maybe only _Title Case in Italics_, or however they appear in your source text), and (b) learn the most common exceptions. Then you don’t need to keep checking that list. But it’s may be a lot less reliable than a rule-based system rather than more. And it will definitely be less reliable than explicit checking.

http://stackoverflow.com/a/50338339
has body: Don't use np.ndarray until you are older and wiser! I couldn't even use it without rereading the docs. arr1d = np.array([1,2,3,4,5]) is the correct way to construct a 1d array from a list of numbers. Also don't use np.append. I won't even add the 'older and wiser' qualification. It doesn't work in-place; and is slow when used in a loop. A good way of building a 2 array from 1d arrays is: alist = [] for i in ....: alist.append(&lt;alist or 1d array&gt;) arr = np.array(alist) provided all the sublists have the same size, arr should be a 2d array. This is equivalent to building a 2d array from np.array([[1,2,3], [4,5,6]]) that is a list of lists. Or a list comprehension: np.array([predictions(i) for i in range(10)]) Again, predictions must all return the same length arrays or lists.
has comment: http://stackoverflow.com/comment/87770506
answers question: http://stackoverflow.com/q/50337236
type: Answer
has comment: http://stackoverflow.com/comment/87747083
score: 2
accepted answer of: http://stackoverflow.com/q/50337236
has comment: http://stackoverflow.com/comment/87747374
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87605418
type: Comment
comment on: http://stackoverflow.com/a/50291070
type: AnswerComment
has text: @JonadriBundo this stuff is probably to advacned for me. But this was my guess
score: 0

http://stackoverflow.com/a/50322654
has body: Seems like you're using python2 and you can print out the result so why not print out the type of the the dictionary-like object and find out its type.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50322294
type: Answer

http://stackoverflow.com/q/50260971
tagged with: elasticsearch-dsl
has comment: http://stackoverflow.com/comment/87544268
has body: I am looking for ways to use elasticsearch_dsl to query for multiple strings on a single field. When I try using wildcard option, it just lists last string found For example, I need to look for following strings in field called cars_model “honda_accord” “honda_crv” “honda_civic” … etc So the query I am forming is from elasticsearch import Elasticsearch from elasticsearch_dsl import Search client = Elasticsearch([{'host': MY_HOST, 'port': MY_PORT, 'timeout': TIME_OUT}]) s = Search(using=client,index=“myIndex”).query("wildcard",cars_model=“honda*”).execute() Here, Its returning only listing for “honda_crv” , which I am assuming last data. I’ve tried using following options after doing some research body = {'query_string': {'query': ‘honda*’, 'default_operator': 'or', 'analyze_wildcard': True}} s = Search(using=client, index=“myIndex”).query(body).execute() Even tried multi_match option which still gives me last query found. from elasticsearch_dsl.query import MultiMatch, Match s = Search(using=client, index=“my_index”).query("multi_match", query="wildcard", cars_model=[“honda_accord”,“honda_crv”, “honda_civic” ]) Logically, it should list all the cars model that matches "honda*" Any help is appreciaited.
tagged with: elasticsearch-dsl-py
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87544015
type: Question
has comment: http://stackoverflow.com/comment/87562909
tagged with: kibana
has comment: http://stackoverflow.com/comment/87543661
has title: Search for more than one string in a field using elasticsearch_dsl
tagged with: elasticsearch
tagged with: python

eval
tag name: eval
tags question: http://stackoverflow.com/q/50267780
tags question: http://stackoverflow.com/q/50353972
type: Tag

kivy
tags question: http://stackoverflow.com/q/50339895
tags question: http://stackoverflow.com/q/50289370
type: Tag
tags question: http://stackoverflow.com/q/50358110
tag name: kivy
tags question: http://stackoverflow.com/q/50302593
tags question: http://stackoverflow.com/q/50374631
tags question: http://stackoverflow.com/q/50317173
tags question: http://stackoverflow.com/q/50235265
tags question: http://stackoverflow.com/q/50292748
tags question: http://stackoverflow.com/q/50316560
tags question: http://stackoverflow.com/q/50320922
tags question: http://stackoverflow.com/q/50380542
tags question: http://stackoverflow.com/q/50261988
tags question: http://stackoverflow.com/q/50343129
tags question: http://stackoverflow.com/q/50263705
tags question: http://stackoverflow.com/q/50343100
tags question: http://stackoverflow.com/q/50290053
tags question: http://stackoverflow.com/q/50269698
tags question: http://stackoverflow.com/q/50344429
tags question: http://stackoverflow.com/q/50314646
tags question: http://stackoverflow.com/q/50308757
tags question: http://stackoverflow.com/q/50266390
tags question: http://stackoverflow.com/q/50314617
tags question: http://stackoverflow.com/q/50362476

http://stackoverflow.com/comment/87662144
comment on: http://stackoverflow.com/q/50323005
type: QuestionComment
has text: This may be a time when `is` is the correct operator (but perhaps not the indexing); note that both `x` and `y` iterate over `a`. But mixing `is` and `==` deserves a comment at least, they are not complementary (in which case `else` would do anyway).
type: Comment
score: 1

http://stackoverflow.com/comment/87493466
score: 0
comment on: http://stackoverflow.com/q/50238070
has text: what is `scramble_list`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87749932
score: 1
type: Comment
type: AnswerComment
has text: @ashishpal I mean, neither of those results is wrong. It depends on whether you want the first or last encountered equal length longest. Changing the `>` to a `>=` will solve that.
comment on: http://stackoverflow.com/a/50366567

http://stackoverflow.com/comment/119732652
type: AnswerComment
has text: @MiguelGonzalez No, it shouldn't Miguel, if you used the exact format of %d/%m/%Y. The error of flopping will not occur.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50372326

while-loop
tags question: http://stackoverflow.com/q/50323005
tags question: http://stackoverflow.com/q/50350944
type: Tag
tags question: http://stackoverflow.com/q/50230801
tags question: http://stackoverflow.com/q/50317635
tags question: http://stackoverflow.com/q/50255995
tags question: http://stackoverflow.com/q/50267427
tags question: http://stackoverflow.com/q/50309338
tags question: http://stackoverflow.com/q/50269718
tags question: http://stackoverflow.com/q/50373842
tags question: http://stackoverflow.com/q/50379319
tags question: http://stackoverflow.com/q/50307812
tags question: http://stackoverflow.com/q/50231746
tags question: http://stackoverflow.com/q/50342348
tags question: http://stackoverflow.com/q/50375825
tags question: http://stackoverflow.com/q/50342318
tags question: http://stackoverflow.com/q/50320095
tags question: http://stackoverflow.com/q/50378610
tag name: while-loop
tags question: http://stackoverflow.com/q/50315394
tags question: http://stackoverflow.com/q/50325598
tags question: http://stackoverflow.com/q/50283547
tags question: http://stackoverflow.com/q/50361325

http://stackoverflow.com/comment/87657889
type: AnswerComment
score: 0
type: Comment
has text: So, how should I solve the problem with the elif statement. I need to differentiate this 4 case.
comment on: http://stackoverflow.com/a/50320942

http://stackoverflow.com/q/50353078
has comment: http://stackoverflow.com/comment/87723969
has comment: http://stackoverflow.com/comment/87723648
tagged with: python
has comment: http://stackoverflow.com/comment/87723479
has comment: http://stackoverflow.com/comment/87723736
type: Question
has answer: http://stackoverflow.com/a/50355161
has comment: http://stackoverflow.com/comment/87724514
answer count: 1
tagged with: machine-learning
has title: Keras convolution rank inconsistent with 1 filter
tagged with: keras
has body: Keras convolutions seem to be being too clever for my network - my final convolutional layer has 1 filter, and Keras seems to be squeezing the output shape to remove the filter axis. Unfortunately, it only does this at train time: model.summary() shows the filter axis where it should be. I need to concatenate this output on the filter axis to another input, but if I trust the model summary I get a train time error: ValueError: Error when checking target: expected leaky_re_lu_6 to have 4 dimensions, but got array with shape (5, 112, 112). Planting a Reshape((1,112,112)) after the LeakyReLU doesn't help. If I instead use keras.backend.expand_dims(resized_output,1) to force the size I want, I get a compile-time error: ValueError: A 'Concatenate' layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 3, 448, 448), (None, 1, 1, 448, 448)] Relevant section of model.summary(): conv2d_6 (Conv2D) (None, 1, 112, 112) leaky_re_lu_6 (LeakyReLU) (None, 1, 112, 112) conv2d_6[0][0] conv2d_6[1][0] full_input (InputLayer) (None, 3, 16, 448, 448) lambda_1 (Lambda) (None, 3, 448, 448) full_input[0][0] up_sampling2d_5 (UpSampling2D) (None, 1, 448, 448) leaky_re_lu_6[1][0] concatenate_1 (Concatenate) (None, 4, 448, 448) lambda_1[0][0] up_sampling2d_5[0][0] Model definition snippet: data_format = "channels_first" C3 = lambda filter_size: Conv3D( filter_size, (3, 3, 3), data_format=data_format, activation="relu", padding="same") def P3(shape=(2, 2, 2)): return MaxPooling3D( shape, data_format=data_format) C2 = lambda filter_size: Conv2D( filter_size, (3,3), data_format=data_format, padding="same") U2 = lambda: UpSampling2D(data_format=data_format) coarse_architecture = [ # encoder #112, 16 C3(64), P3(), #56 , 8 C3(128), P3(), #28 , 4 C3(256), C3(256), P3(), #14 , 2 C3(512), C3(512), P3(), #7 , 1 # decoder Reshape((512,7,7)), C2(256), LeakyReLU(0.001), U2(), #14 C2(128), LeakyReLU(0.001), U2(), #28 C2(64), LeakyReLU(0.001), U2(), #56 C2(32), Leaky…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50355161
score: 0

http://stackoverflow.com/comment/87709421
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50346390
has text: Ah, found it. never mind!

http://stackoverflow.com/comment/87560612
type: QuestionComment
comment on: http://stackoverflow.com/q/50270930
score: 0
has text: I have updated the post, thanks @NarendraR
type: Comment

http://stackoverflow.com/a/50334867
has comment: http://stackoverflow.com/comment/87754323
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50316789
has body: tf.estimator.LinearClassifier instances return a dictionary of values you can use. You're only using pred[ 'classes' ] in your code but you also have the probability values are in pred[ 'probabilities' ]. You can also just print( pred ) which will output something similar to this (with dummy data): {'logits': array([1.4264423], dtype=float32), 'logistic': array([0.80634636], dtype=float32), 'probabilities': array([0.19365363, 0.80634636], dtype=float32), 'class_ids': array(1), 'classes': array([b'1'], dtype=object) } so you can see you also have access to the logits and class_ids. The probability of class 1 is the second value in pred[ 'probabilities' ], which is what you want to use as I understand.
answers question: http://stackoverflow.com/q/50316789
type: Answer
has comment: http://stackoverflow.com/comment/87754731

http://stackoverflow.com/a/50337847
type: Answer
has comment: http://stackoverflow.com/comment/87805917
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/87776606
answers question: http://stackoverflow.com/q/50337598
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87729588
has comment: http://stackoverflow.com/comment/87729782
has comment: http://stackoverflow.com/comment/87803777
accepted answer of: http://stackoverflow.com/q/50337598
has comment: http://stackoverflow.com/comment/87730593
has body: use the after_idle function with your function as the callback function in this order from threading import Thread workout1 = Tk() thread = Thread(target = SpeechRecognition1) workout1.after_idle(thread.start) workout1.mainloop()
has comment: http://stackoverflow.com/comment/87809435
has comment: http://stackoverflow.com/comment/87800580

http://stackoverflow.com/comment/87656300
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50319185
type: AnswerComment
has text: Thanks joseph, instead of using spawn_n we can also use spawn with wait directly, ex: t1 = eventlet.spawn(square, 10).wait() works as well.

http://stackoverflow.com/q/50235673
linked to: http://stackoverflow.com/q/45416626
has comment: http://stackoverflow.com/comment/87488784
upvote count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/45416626
tagged with: python
score: -1
has body: I'm writing a program that estimates the value of pi. I want to implement that you in the command line can specify when the result have the specified number of correct decimals. Example: python est_pi.py 3 should end the script when the estimation is 3.141... Is it possible to have a variable real_pi = 3.14159... and then index into the number of decimals or is there any other solution to this problem?
has comment: http://stackoverflow.com/comment/87488886
tagged with: pi
answer count: 1
linked to: http://stackoverflow.com/q/13479163
has title: Index number of decimals in float - python
downvote count: 1
has answer: http://stackoverflow.com/a/50235749
has comment: http://stackoverflow.com/comment/87488678
favorite count: 0
linked to: http://stackoverflow.com/q/455612
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/50241023
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50240187
type: Answer
has body: You can use interpolate(method='nearest'), ffill() and bfill() and finally groupby(). Short version: &gt;&gt; series = pd.Series(x).interpolate(method='nearest').ffill().bfill() &gt;&gt; series.groupby(series).apply(lambda k: k/len(k)) [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0] To illustrate what's happening, create your df df = pd.DataFrame() df["x"] = x where x is the series you gave. Now: &gt;&gt;&gt; df["inter"] = df.x.interpolate(method='nearest').ffill().bfill() &gt;&gt;&gt; df["inter"] = df.groupby("inter").inter.apply(lambda k: k/len(k)) &gt;&gt;&gt; df x inter 0 NaN 2.0 1 NaN 2.0 2 NaN 2.0 3 12.0 2.0 4 NaN 2.0 5 NaN 2.0 6 NaN 2.0 7 NaN 2.0 8 10.0 2.0 9 NaN 2.0 10 NaN 2.0 11 NaN 2.0 12 NaN 2.0 13 8.0 2.0 14 NaN 2.0 15 6.0 3.0 16 NaN 3.0
accepted answer of: http://stackoverflow.com/q/50240187
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/50255669
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50255556
has body: You should use a dictionary to store a function with a given name. In general, you should not create a function name from a string. You can use ast.literal_eval to safely evaluate a computation provided as a string. Here is one example: from ast import literal_eval mystr = input('Enter a calculation:\n') # 'define f1 3 + 5' _, name, calc = mystr.split(None, 2) d = {name: literal_eval(calc)} print(d['f1']) # 8
type: Answer
answers question: http://stackoverflow.com/q/50255556

http://stackoverflow.com/comment/135007334
type: AnswerComment
has text: Not necessary, we are already on 3.11. Thank you
type: Comment
comment on: http://stackoverflow.com/a/50671638
score: 0

http://stackoverflow.com/q/50307018
has body: pysfml is a library I love, but it has not been maintained for a while now, and is not available with pip. I am using windows 10 and visual C++ 2015. The setup.py is this one: https://github.com/Sonkun/python-sfml/blob/master/setup.py I edited line 60, but I still have an error since I did not specific .lib files. I also edited line 81 like so: library_dirs=[os.path.join('extlibs', 'libs-msvc-universal', arch)]+[os.path.join('C:\\_code\\libs\\SFML-2.5.0\\lib')] if sys.hexversion &gt;= 0x03050000 else [], setup.py finishes, but when I import it in python it says ImportError: DLL load failed: The specified module could not be found. I even add the dlls in the .egg file it generated in /dist and installed the .egg manually with the same error.
has answer: http://stackoverflow.com/a/50320850
tagged with: windows
tagged with: python
tagged with: visual-studio
type: AnsweredQuestion
score: 0
has title: How to specify C++ header and library folder in a setup.py (pySFML)?
has comment: http://stackoverflow.com/comment/87631555
accepted answer: http://stackoverflow.com/a/50320850
tagged with: sfml
answer count: 1
tagged with: pip
type: Question

oop
tags question: http://stackoverflow.com/q/50260632
tags question: http://stackoverflow.com/q/50246236
tags question: http://stackoverflow.com/q/50254839
tags question: http://stackoverflow.com/q/50349653
tags question: http://stackoverflow.com/q/50263510
tags question: http://stackoverflow.com/q/50260717
tag name: oop
tags question: http://stackoverflow.com/q/50333012
tags question: http://stackoverflow.com/q/50230802
tags question: http://stackoverflow.com/q/50335812
tags question: http://stackoverflow.com/q/50259303
tags question: http://stackoverflow.com/q/50308919
type: Tag
tags question: http://stackoverflow.com/q/50312503
tags question: http://stackoverflow.com/q/50239003
tags question: http://stackoverflow.com/q/50353476
tags question: http://stackoverflow.com/q/50360539

http://stackoverflow.com/q/50351625
possible better answer: http://stackoverflow.com/a/50354909
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50354909
tagged with: odoo-10
tagged with: odoo
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87748715
favorite count: 0
has body: I'm trying to modify the default search engine of the existing model mail.message. If you look for the word Hello, the search returns you all the messages whose record_name field contains Hello. But I need that it returns all the messages whose body contains Hello. mail.thread model has a One2many field pointing to mail.message, and a lot of models inherit from mail.thread. For example, sale.order. Therefore, in the search view of sale.order you can do an advanced search and look for Messages. But as I wrote above, it's returning you the messages whose "title" (field record_name) contains the word you have wrote in the search textbox. To change that, I did this: @api.model def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None): result = super(MailMessage, self)._name_search( name=name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid ) mms = self.env['mail.message'].search([]).filtered( lambda r: name in r.body ) l = [(r.id, r.record_name) for r in mms] return l So far it's working OK, but I don't trust it's working OK in all cases, and I'm pretty sure that there must be a much better way to manage it. Any ideas?
has title: How to change the default search field of a model in Odoo 10?
type: Question
accepted answer: http://stackoverflow.com/a/50367090
has comment: http://stackoverflow.com/comment/87749428
has comment: http://stackoverflow.com/comment/87749110
has answer: http://stackoverflow.com/a/50367090
has comment: http://stackoverflow.com/comment/87750454
upvote count: 1
tagged with: python

http://stackoverflow.com/tag/tar
tags question: http://stackoverflow.com/q/50375544
tag name: tar
type: Tag
tags question: http://stackoverflow.com/q/50379970

http://stackoverflow.com/q/50298599
answer count: 1
tagged with: arduino
upvote count: 1
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50335719
has comment: http://stackoverflow.com/comment/133897689
has answer: http://stackoverflow.com/a/50335719
tagged with: python
has body: I'm currently trying to send 1024 bytes of data to an Arduino with external EEPROM. But when running these code, the transmission often stopped before EOF is reached, and the whole process was just weird. My code is as below: import binascii import os import serial import time ser = serial.Serial('/dev/ttyUSB0',9600) recv = -1 counter = 0 totalcount = 0 with open('TestCard.txt', 'rb') as f: hexdata = binascii.hexlify(f.read()) hexlist = map(''.join, zip(*[iter(hexdata)]*2)) f.close while(1): #Wait for arduino to ask for address if(ser.readline()=="address\n"): ser.write("0") print "written 0 \n" #Give arduino address I wanted to write break for a in hexlist: ser.write("srq\n") #Check if arduino is good to revcieve data while(ser.readline() != "OK\n"): if(ser.readline() == "write\n"): print "write\n" ser.write("srq\n") print "srq\n" while(ser.readline() != "read\n"): if(ser.readline() == "read\n"): print "sok\n" ser.write("SOK\n") break print "sok\n" ser.write("SOK\n") #Send data ser.write(a.encode()) print "written " + a.encode() counter = counter + 1 totalcount = totalcount + 1 #else: #while(ser.readline()!="Next Block\n" and ser.readline()!="Done\n"): #continue if(counter == 16 ): print "\n\n16 bytes\n\n" counter = 0 ser.write("EOF\n") print "\nEOF\n" ser.close() And my arduino sketch: #include &lt;Wire.h&gt; #include &lt;SoftwareSerial.h&gt; byte buff[16]; int addr=-1; int count=0; char readed[5]; char srq[4] = "srq\n"; char eof[4] = "EOF\n"; char sok[4] = "SOK\n"; byte recv; bool ended = false; void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data ) { int rdata = data; Wire.beginTransmission(deviceaddress); Wire.write((int)(eeaddress &gt;&gt; 8)); // MSB Wire.write((int)(eeaddress &amp; 0xFF)); // LSB Wire.write(rdata); Wire.endTransmission(); } // WARNING: address is a page address, 6-bit end will wrap around // also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes void i2c_eeprom_write_page( i…
favorite count: 0
type: Question
has title: Python serial to Arduino
tagged with: pyserial
score: 0

http://stackoverflow.com/a/50383047
downvote count: 0
score: 1
type: Answer
has body: You're reading a blog post from 2013, which contains a link to a urllib3 Github issue, which was fixed about a month later, and support was added to requests shortly afterward, and is there in all 2.x versions. So, you're looking for a workaround for a problem that was solved almost 5 years ago. To use an HTTPS proxy, you just configure it the same way as an HTTP proxy: proxies = { 'https': 'http://10.10.1.10:12345', } page = requests.get('https://example.org', proxies=proxies) If you, e.g., run nc -kl 1080 on 10.10.1.10, you'll see this: CONNECT example.org:443 HTTP/1.0 And if you run an actual HTTPS proxy there, it will just work. You also claim that urllib doesn't handle HTTPS proxies, but it always has. It's slightly more painful to set up, but still not that hard: ph = urllib.request.ProxyHandler({'https': '192.168.42.100:1080'}) op = urllib.request.build_opener(p) page = op.open('https://example.com') … or, if you want to use it for everything rather than a single request: ph = urllib.request.ProxyHandler({'https': '192.168.42.100:1080'}) urllib.request.install_opener(urllib.request.build_opener(p)) page = urllib.request.open('https://example.com') And of course if you have your default proxy settings configured in the appropriate way for your platform, you don't even need to do this much; both requests and urllib will just use them.
upvote count: 1
answers question: http://stackoverflow.com/q/50382727

http://stackoverflow.com/comment/87534631
comment on: http://stackoverflow.com/a/50258136
has text: Browser I am using is IE
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87762112
type: Comment
has text: Man... Don't do that. Ubuntu needs python and uninstalling the packages can break your system.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50372907

http://stackoverflow.com/q/50241742
accepted answer: http://stackoverflow.com/a/50241804
answer count: 3
has answer: http://stackoverflow.com/a/50241830
has title: Python 3.6 Split() Not enough values to unpack workaround?
downvote count: 0
has comment: http://stackoverflow.com/comment/87501206
has comment: http://stackoverflow.com/comment/87529819
duplicate of: http://stackoverflow.com/q/20270871
favorite count: 0
has comment: http://stackoverflow.com/comment/87501132
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50241804
has body: I keep getting an error in Python when I try to split a single word. From what I read, this is because the default split() command looks for whitespace. The problem is, I want the second assigned variable (asset in this case) to return nothing or null. This is what I am working with: slack_text.startswith("!help"): command, asset = slack_text.split() if asset != "": if asset == "commandlist": slack_reply = "Available Commands: !addme, !getBalance, !buy &lt;asset&gt; &lt;quantity&gt;" elif asset == "ships": slack_reply = getAllShips() elif asset == "buildings": slack_reply = getAllBuildings() elif shipExists(asset): slack_reply = getShip(asset) elif buildingExists(asset): slack_reply = getBuilding(asset) else: slack_reply = "Not a valid asset." else: slack_reply = "Available help modifiers are: commandlist, &lt;ship_name&gt;, &lt;building_name&gt;. (!help &lt;modifier&gt;)" So with this code, I can type '!help ships' in Slack and cast no error and return the getAllShips() function. But if I type simply '!help', Python casts an error. I basically want to be able to return a statement if there is no modifier. However, not having a modifier casts an error. Is there something else I can do to approach this problem? Can someone point me in the right direction here?
tagged with: python
possible better answer: http://stackoverflow.com/a/50242048
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/20270871
has answer: http://stackoverflow.com/a/50242048
has comment: http://stackoverflow.com/comment/87501113
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12265451

http://stackoverflow.com/comment/87690383
type: QuestionComment
has text: Anyway, have you read [Reference Count Details](https://docs.python.org/3/c-api/intro.html#reference-count-details) in the docs? Because some of what you're asking is directly answered there. And, while I love learning by segfault, it's usually easier to read the docs too.
score: 0
comment on: http://stackoverflow.com/q/50336978
type: Comment

http://stackoverflow.com/q/50372479
type: Question
upvote count: 2
score: 2
has title: Use multiple filters in Scapy's "sniff" function
type: UnansweredQuestion
tagged with: scapy
answer count: 1
downvote count: 0
has body: A friend and I are currently making a sniffing application in Python using the Scapy library. We have a GUI interface where we can choose filters and protocols. We want to sniff the network using one or more filters but don't know how to do. For now we tried the following code : capture=scapy.sniff(filter="tcp and udp",timeout=5) print(capture) It works well but it sniffs using only the first filter (tcp filter in this case). We also tried with the following code but same : capture1=scapy.sniff(filter="tcp",timeout=5) capture2=scapy.sniff(filter="udp",timeout=5) print(capture1) print(capture2) So, is it possible to sniff using more than one filter and if so, do you have any idea ? Thanks
tagged with: spyder
tagged with: python
tagged with: sniffing
has answer: http://stackoverflow.com/a/50390963
favorite count: 0

http://stackoverflow.com/q/50336049
downvote count: 0
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/87689367
has body: I have just started integrating Django with Scrapy. Upon receiving the variable(that is Website url) on the Django side, I want to pass it to the scrapy part so as to crawl it. This is the code snippet I wrote on the backend. def post(self, request, format=None): ... serializer = self.serializer_class(data=data) if serializer.is_valid(): site = serializer.create(data) domain = urlparse(site.url).netloc site_id = site.id settings = { 'unique_id': unique_id, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } task = scrapyd.schedule('default', 'icrawler', settings=settings, url=url, domain=domain) task = { 'task_id': task, 'unique_id': target_id, 'status': 'started' } resp = { 'task': task, 'data': serializer.data, 'status': status.HTTP_201_CREATED } return Response(resp) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have created spider on the Django project called icrawler.py. class IcrawlerSpider(CrawlSpider): name = 'icrawler' allowed_domains = ['https://google.com'] start_urls = ['http://https://google.com/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): i = {} return i As you can see, there is allowed_domains = ['https://google.com'] and start_urls = ['http://https://google.com/'] in the spider. But I want to replace it with variable passed from Django and start running crawler, upon receiving the variable on the django side. I am not sure how I can implement it.
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: How to pass variable from Django to Scrapy?
answer count: 0
score: 1

http://stackoverflow.com/q/50372509
has answer: http://stackoverflow.com/a/50373282
downvote count: 0
upvote count: 18
favorite count: 0
type: Question
has title: Why are attributes lost after copying a Pandas DataFrame
has answer: http://stackoverflow.com/a/50373364
has body: Why is it not possible to pass attributes of an instance through a copy? I want to pass the name attribute to another dataframe. import copy df = pd.DataFrame([1,2,3]) df.name = 'sheet1' df2 = copy.deepcopy(df) print(f'df.name: {df.name}') &gt;&gt; df.name: sheet1 print(f'df2.name: {df2.name}') &gt;&gt; AttributeError ... 'DataFrame' object has no attribute 'name' Similarly, why does this also not work, when creating a class and inheriting from it? class DfWithName(pd.DataFrame): def __init__(self, *args, **kwargs): self.__init__ = super().__init__(*args, **kwargs) print('lol') @property def name(self): return self._name @name.setter def name(self, value): self._name = value and using the same code: import copy df = DfWithName([1,2,3]) df.name = 'sheet1' df2 = copy.deepcopy(df) print(f'df.name: {df2.name}') &gt;&gt; AttributeError ... 'DataFrame' object has no attribute 'name'
linked to: http://stackoverflow.com/q/14688306
has comment: http://stackoverflow.com/comment/87761771
score: 18
has comment: http://stackoverflow.com/comment/87761910
has comment: http://stackoverflow.com/comment/87762190
tagged with: python
has answer: http://stackoverflow.com/a/50373155
accepted answer: http://stackoverflow.com/a/50373364
has comment: http://stackoverflow.com/comment/87762053
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50373282
has answer: http://stackoverflow.com/a/50373021
has comment: http://stackoverflow.com/comment/87762187

http://stackoverflow.com/q/50243181
has comment: http://stackoverflow.com/comment/87504563
type: UnansweredQuestion
tagged with: python
has body: I have following data user_id session_id youtube_id 1 1 2342 1 1 3523 1 2 3325 2 1 3423 2 1 2352 2 1 3333 2 2 2351 2 2 9876 2 3 2388 Goal is to group by user_id and calculate both total_sessions, total_views per user and hence average views per session. user_id, total_sessions, total_views, average_view_per_session 1, 2, 3, 1.5 2, 3, 6, 2 result_df['avg'] = df.groupby('user_id').agg({ 'session_id':lambda x : x.nunique(), 'youtube_id': 'count'}).apply(lambda x : x['total_views']/x['total_sessions'] Two problems with above: the resulting columns are still named session_id and youtube_id though they are aggregations how to carry out the division to get the average_view_per_session? The above approach gives a key error which could be due to using the original column name for aggregated columns.
has title: pandas groupby and aggregate two columns for respective totals, then calculate ratio - summarize the summary
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/87504498
tagged with: summary
tagged with: aggregate
answer count: 1
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/50283292
favorite count: 0
has answer: http://stackoverflow.com/a/50243332
type: Question
linked to: http://stackoverflow.com/q/19078325

http://stackoverflow.com/a/50599188
has comment: http://stackoverflow.com/comment/88208465
has body: I ran into the same problem and I believe the issue is that you're initializing a new Dataset object rather than initializing the Iterator that was saved with the model. Try: make_iter = model.get_operation_by_name("YOURPREFIX/MakeIterator") sess.run(make_iter, feed_dict) model.infer(some_numpy_array)
answers question: http://stackoverflow.com/q/50354306
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/50342809
has body: I replace 'mysqldb' with 'pymysql' and it works.Thank everyone.
answers question: http://stackoverflow.com/q/50327160
has comment: http://stackoverflow.com/comment/108698547
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/50302205
has title: How can I avoid using path name in my Python scripts?
has comment: http://stackoverflow.com/comment/87659487
favorite count: 0
type: Question
has body: In my Python scripts, I write the specific path name. It will not work if I were to use it on another computer or folder. ex: df = pd.read_csv('C:/VerySpecificNameForDocuments/test.csv', 'wb') I have seen the use of: %/... How can I re-write this to be usable in other computers/directories?
upvote count: 2
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/87620851
has comment: http://stackoverflow.com/comment/87683273
tagged with: python
has answer: http://stackoverflow.com/a/50302372
linked to: http://stackoverflow.com/q/1854
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/50302547

http://stackoverflow.com/q/50321335
tagged with: dictionary
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/50321380
upvote count: 3
favorite count: 0
type: Question
tagged with: python-3.x
has title: Trying to understand searching through a nested dict
has body: I have a list of contact information stored in a nested dict: addressBook = {'Jim': {'name': 'James Marsh', 'address': '32 Morris Ave', 'phone': '654-987-3217'}, 'Leanne': {'name': 'Leanne Moss', 'address': '37 Shamrock Lane', 'phone': '123-456-7890'}, 'Chris': {'name': 'Christopher Philips', 'address': '49 Langley Court', 'phone': '321-654-9870'}, 'Tim': {'name': 'Timothy Morris', 'address': '49 Langley Court', 'phone': '321-654-9870'}} and I'm trying to write a function which will search through each entry for a user-entered search string. def searchAllFields(addressBook): searchString = input("Enter a string to search for (enter to cancel): ") if searchString == "": return else: for key, value in addressBook.items(): inside = False for v in value.values(): if searchString in v: inside = True break if searchString in key or inside: print("The following contacts were found: ") print(addressBook[key]['name']) print(addressBook[key]['address']) print(addressBook[key]['phone'] + '\n') else: print("No contact matching the string {} was found.".format(searchString)) return My function iterates through the dictionary nicely, but it only finds the search string in the keys. For example, if my search string in Jim, I can find James' information, but if my search string is Lang I want to be able to find Chris. I would have thought that for key, value in addressBook.items(): would look through the values as well as the keys. Why doesn't it? How could I fix this?
answer count: 2
accepted answer: http://stackoverflow.com/a/50321351
downvote count: 0
has answer: http://stackoverflow.com/a/50321351
has answer: http://stackoverflow.com/a/50321380
tagged with: python

http://stackoverflow.com/comment/87507021
score: 0
comment on: http://stackoverflow.com/q/50243600
type: Comment
type: QuestionComment
has text: `haven::read_sas()` has a (although experimental) `cols_only` parameter, you could try loading only a few columns and see what happens.

http://stackoverflow.com/comment/87526379
has text: Hi criterion for removing is if it occurs only once. I've tried a count function but it doesn't work as expected. I tried a time range so if '64' appears for less then 25 seconds using a time difference i.e. between 33 then it ignores it , but failed to work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50254107
score: 0

http://stackoverflow.com/comment/87693384
comment on: http://stackoverflow.com/a/50336827
type: Comment
type: AnswerComment
has text: if you come up with something let me know it would be highly appreciated
score: 0

http://stackoverflow.com/q/50350624
has body: I have created a PIL Image and I want to send it to a server over requests. My code looks like this, but I am not able to get it working as I get no errors. import requests from PIL import Image from io import BytesIO img = Image.new('RGB', (25, 25), color = (120, 120, 20)) byte_io = BytesIO() img.save(byte_io, 'png') byte_io.seek(0) requests.post( url('/media/upload'), files={ 'files[]': ( '1.png', byte_io, 'multipart/form-data' ) }, ) print files gives me {'files[]': ('1.png', &lt;_io.BytesIO object at 0x105b69290&gt;, 'multipart/form-data')} and it does not error out.
downvote count: 0
tagged with: python-requests
answer count: 1
favorite count: 0
type: Question
tagged with: python-imaging-library
has title: Sending PIL Image over request in Python
accepted answer: http://stackoverflow.com/a/50350750
tagged with: python
has comment: http://stackoverflow.com/comment/130972424
upvote count: 10
has answer: http://stackoverflow.com/a/50350750
score: 10
type: AnsweredQuestion

http://stackoverflow.com/a/50284167
has comment: http://stackoverflow.com/comment/87584749
answers question: http://stackoverflow.com/q/50284143
has comment: http://stackoverflow.com/comment/87584694
type: Answer
has comment: http://stackoverflow.com/comment/87584661
upvote count: 3
score: 3
downvote count: 0
has body: You just need to create your name file by concatenating name and the string ".txt", which you can do with the + operator: name=input("please type the name you would like: ") f = open(name + '.txt','r') message = f.read() print(message) f.close() Or, to make it more consise, the following is completely equivalent: name=input("please type the name you would like: ") with open(name + '.txt', 'r') as f: print(f.read())

http://stackoverflow.com/a/50278108
type: Answer
accepted answer of: http://stackoverflow.com/q/50277490
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Try this. For my case it worked df = df.apply(pd.to_numeric, errors='coerce')
answers question: http://stackoverflow.com/q/50277490
score: 1

http://stackoverflow.com/q/50266585
downvote count: 0
tagged with: activation-function
tagged with: sigmoid
accepted answer: http://stackoverflow.com/a/50266619
has body: I am trying to implement a simple neural network for XOR function. The activation function I am using is Sigmoid function. The code for the sigmoid function is: def ActivationFunction(a) e = 2.671 # Sigmoid Function expo = e ** a val = expo / (1 + expo) return val My problem is that this function is always returning a value between 0.7 and 0.8. This problem is showing a major effect in the output process. Any suggestions would be appriciated.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50266619
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Implementing sigmoid function in python
score: 1
answer count: 1

http://stackoverflow.com/q/50303403
has comment: http://stackoverflow.com/comment/87660840
tagged with: raspberry-pi3
tagged with: flask
has comment: http://stackoverflow.com/comment/87624948
linked to: http://stackoverflow.com/q/14384739
type: Question
has title: Using Flask with Core Applications written in Python
tagged with: python
has comment: http://stackoverflow.com/comment/87660845
has body: I am new to Flask and am trying to think how I want to approach an idea. I am building an Aquarium Controller on the Raspberry Pi using Python. I have already built one that works quite well on the Arduino but would like to move to Raspberry Pi and add a web interface. My approach was to right the Python code along with Flask in the same application. But when I ran the code I had to have the browser open to the web server before the app would actually execute. I need the base code to run irrespective of what is happening on the web server. Because I am controlling things like the topoff pumps, main pumps, and heater, I need the application to run continuously regardless of the webserver. My question is, can Flask be configured to run as a passive function to allow for the critical part of the code to work without the web server? I also thought I could export the web server data to a file then, write a separate application for the webserver. The limitation here is I would like to be able to interact with the core application from the browser (i.e. turn pumps on/off from the browser). from flask import Flask, render_template import datetime import RPi.GPIO as GPIO #use Channel numbering for rpi pins GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #import time import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 # Software SPI configuration: CLK = 18 # physical pin 12 MISO = 23 # physical pin 16 MOSI = 24 # physical pin 18 CS = 25 # physical pin 25 mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI) # Setup Relays Relay_Ch1 = 26 # physical pin 37 Relay_Ch2 = 20 # physical pin 38 Relay_Ch3 = 21 # physical pin 40 GPIO.setup(Relay_Ch1,GPIO.OUT) GPIO.setup(Relay_Ch2,GPIO.OUT) GPIO.setup(Relay_Ch3,GPIO.OUT) #Initialize Relays to OPEN GPIO.output(Relay_Ch1,GPIO.HIGH) GPIO.output(Relay_Ch2,GPIO.HIGH) GPIO.output(Relay_Ch3,GPIO.HIGH) #Optical Switch Setup OptSw1 = 17 # physical pin 11 OptSw2 = 27 # physical pin 13 GPIO.setup(OptSw1, GPIO.IN) GPIO.setup(OptSw…
score: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/50269141
has body: This can't possibly work. global in Python means "within a single module"; there is no way[*] to define a global variable in the shell that would affect an imported script. You should make efgh a parameter to the function. [*] well, you could monkey-patch, but don't do that.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50268960

http://stackoverflow.com/q/50230918
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87479294
favorite count: 0
has comment: http://stackoverflow.com/comment/87479549
type: Question
score: 1
has body: For a project: package\ │ └───┐ package\ │ ├──── __init__.py └───┐ subpackage\ │ ├──── __init__.py └──── spam.py in subpackage\__init__.py I can import spam via: from package.subpackage.spam import eggs, beans ...or... from .spam import eggs, beans The latter is robust to changing the name of the package, which is useful in my current case of a project in early development. The problem arises when I don't want to actually export anything from spam, I just want it to perform its initialisation logic. For instance, the following does not work. import .spam (I am using PyCharm, which identifies the error, if this is relevant.) Is there an alternative or standard way to import in this case?
tagged with: python
has answer: http://stackoverflow.com/a/50266118
has comment: http://stackoverflow.com/comment/87479686
has title: Relative import module

http://stackoverflow.com/comment/87642344
type: QuestionComment
comment on: http://stackoverflow.com/q/50311856
type: Comment
has text: 2.3 GB, that's big. But I will try. Thanks for your help eyllanesc. I'll see if it can solve the problem.
score: 1

http://stackoverflow.com/comment/87770173
has text: Getting 404 error on your files. Can you add a short excerpt to the question itself?
score: 0
comment on: http://stackoverflow.com/q/50372558
type: Comment
type: QuestionComment

http://stackoverflow.com/a/69061002
answers question: http://stackoverflow.com/q/50344721
type: Answer
score: 3
has body: just place get_destination_display withoput () in fields. like this: class TransferCostSerializer(serializers.ModelSerializer): class Meta: model = TransferCost fields = ('id', 'get_destination_display', 'total_cost', 'is_active',)
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/99082863
score: 0
type: Comment
has text: @NLR And what does `mean_test_score` sounds like? Emphasis on `mean`. I never said that it is an average of all `mean_test_score` values. I said its an average of values from all test folds.
comment on: http://stackoverflow.com/a/50233868
type: AnswerComment

http://stackoverflow.com/a/50278032
answers question: http://stackoverflow.com/q/50277574
upvote count: 1
has body: I like Julien's Answer as it feels less like magic. All of these are efforts to set a 2 level multiindex. set_index with empty arrays i = np.array([]) a = pd.DataFrame().set_index([i, i]) a.loc[(1, 2), 2] = 0 a 2 1.0 2.0 0.0 Slightly more concise a = pd.DataFrame().set_index([np.array([])] * 2) a.loc[(1, 2), 2] = 0 pd.concat a = pd.concat([pd.DataFrame()] * 2, keys=[1, 2]) a.loc[(1, 2), 2] = 0 a 2 1 2 0.0
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/54065166
answers question: http://stackoverflow.com/q/50321278
has comment: http://stackoverflow.com/comment/115329738
score: 20
type: Answer
has comment: http://stackoverflow.com/comment/115327869
has body: Solution: from selenium import webdriver fp = webdriver.FirefoxProfile('/home/gabriel/.mozilla/firefox/whatever.selenium') driver = webdriver.Firefox(fp) I struggled until I found this issue which is now solved but was helpful because it shows some commands. first version, not working because I could not connect with selenium afterward: from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.desired_capabilities import DesiredCapabilities options = Options() options.add_argument("-profile") options.add_argument("/home/gabriel/.mozilla/firefox/whatever.selenium") firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = True driver = webdriver.Firefox(capabilities=firefox_capabilities, firefox_options=options) I am sure that this loads the profile "whatever.selenium" because if I go to about:profiles I can read: Profile: selenium This is the profile in use and it cannot be deleted. Even though "whatever.selenium" is not the default profile on my system. Remark: at least one the profile parameters is overridden by selenium (or geckodriver?): Preferences > Privacy and Security > "Block pop-up windows" is always reseted to off. So use about:profiles to make assertions on which profile you are running. notes: firefox_capabilities might not be needed in above code. tested under Firefox 60.4.0esr (64-bit), geckodriver 0.23.0 ( 2018-10-04), selenium 3.141.0 with Python 3.5.3
upvote count: 21
downvote count: 1

http://stackoverflow.com/comment/87622023
type: QuestionComment
has text: With only that information it's impossible to answer your question. What exactly did you do?
comment on: http://stackoverflow.com/q/50302807
score: 0
type: Comment

http://stackoverflow.com/q/50265145
has body: I have a PHP file which calls a Python script to then return the value that outputs to PHP. $price = system("/usr/local/bin/python3 /full/path/script.py", $retval); For testing purposes due to this error, I commented everything out of the Python script except for printing a string to be returned. If I have it like this, it returns that string, but if I uncomment the line from bs4 import BeautifulSoup then it fails. The other imports that I have, which are for sys and requests, work without any issue but when I have BeautifulSoup imported then nothing is returned and I get a $retval of 1. Running the full Python script from command line works perfectly but when I do it with PHP the command fails. What would be keeping this from working properly in PHP but it works fine when done in the command line? I have ensured that bs4 is installed with pip but I knew that anyway since it works fine from the command line.
score: 1
has comment: http://stackoverflow.com/comment/87548949
upvote count: 1
tagged with: php
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/87549450
tagged with: python
has comment: http://stackoverflow.com/comment/87548867
has comment: http://stackoverflow.com/comment/87550174
type: Question
has answer: http://stackoverflow.com/a/50357467
has title: Issue calling a Python script in PHP that imports BeautifulSoup4
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50331587
upvote count: 2
has comment: http://stackoverflow.com/comment/87680977
accepted answer of: http://stackoverflow.com/q/50330090
type: Answer
has comment: http://stackoverflow.com/comment/87684896
has body: If I understand correctly, you're looking for groupby + sample and then some indexing stuff First sample by the probabilites: n_samples = 3 df_samples = df.groupby('NAME').apply(lambda x: x'NAME', 'POSITION' \ .sample(n_samples, replace=True, weights=x.PROB)) \ .reset_index(drop=True) Now add the extra columns: df_samples['SAMPLE'] = df_samples.groupby('NAME').cumcount() df_samples['PROB'] = 1 print(df_samples) NAME POSITION SAMPLE PROB 0 X 1 0 1 1 X 0 1 1 2 X 1 2 1 3 Y 1 0 1 4 Y 1 1 1 5 Y 1 2 1 6 Z 2 0 1 7 Z 0 1 1 8 Z 0 2 1 Note that this doesn't include the 0 probability positions for each sample as requested in the initial question but it is a more concise way of storing the information. If we want to also include the 0 probability positions we can merge in the other positions as follows: domain = df'NAME', 'POSITION'.drop_duplicates() df_samples.drop('PROB', axis=1, inplace=True) df_samples = pd.merge(df_samples, domain, on='NAME', suffixes=['_sample', '']) df_samples['PROB'] = (df_samples['POSITION'] == df_samples['POSITION_sample']).astype(int) df_samples.drop('POSITION_sample', axis=1, inplace=True)
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50330090

http://stackoverflow.com/comment/87747846
type: QuestionComment
has text: With correct parameters
score: 0
comment on: http://stackoverflow.com/q/50358448
type: Comment

http://stackoverflow.com/a/50337853
has body: While your headline testcase is flawed, x being just a reference, your observation stands if less extreme for &gt;&gt;&gt; timeit(lambda: x[a], number=1000000) 1.8212362979538739 &gt;&gt;&gt; timeit(lambda: x.copy(), number=1000000) 1.2187692462466657 What we are seeing here is the cost of advanced indexing. "Conventional" slice indexing costs significantly less but still has an overhead: &gt;&gt;&gt; np.all(x[:20] == x[a]) True &gt;&gt;&gt; timeit(lambda: x[:20].copy(), number=1000000) 0.7956113098189235
type: Answer
answers question: http://stackoverflow.com/q/50337632
accepted answer of: http://stackoverflow.com/q/50337632
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50353506
downvote count: 0
has comment: http://stackoverflow.com/comment/87744752
has comment: http://stackoverflow.com/comment/87831489
has answer: http://stackoverflow.com/a/50356050
accepted answer: http://stackoverflow.com/a/50356050
has body: I am working to get C++ class enum to python enum using swig. I have the following implementation in example.h file. namespace colors{ enum class Color{ RED = 0, BLUE = 1, GREEN = 2 }; } My Swig interface file is %module api %{ #include "example.h" %} %include "example.h" But after using swig tool the interface provides the following usage import pywarp_example as impl impl.RED The question arise here is that is it possible to access enum like below thats the way we use in python? impl.Color.RED Or impl.Color.RED.value
has comment: http://stackoverflow.com/comment/87723179
has comment: http://stackoverflow.com/comment/87827650
has title: SWIG- Convert C++ enum to Python enum
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87723621
tagged with: swig
tagged with: enums
linked to: http://stackoverflow.com/q/13269393
linked to: http://stackoverflow.com/q/16471213
tagged with: python
upvote count: 4
score: 4
possible better answer: http://stackoverflow.com/a/50365059
tagged with: c++
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50365059

http://stackoverflow.com/comment/87734923
type: Comment
type: QuestionComment
score: 0
has text: How are you actually producing the first image? It looks like you're using `matplotlib` to display the image. If that's the case, link #1 to remove all of the borders and axes: https://stackoverflow.com/questions/9295026/matplotlib-plots-removing-axis-legends-and-white-spaces. Link #2 to actually obtain the image data from the window: https://stackoverflow.com/questions/23345165/python-how-to-get-the-data-from-an-plt-imshow.
comment on: http://stackoverflow.com/q/50358964

http://stackoverflow.com/q/50285037
has body: I am not able to get the dates in correct form in my output.It is concerned with plottng of 3 stock data (opening price) for 4 days on single axis. My code is # Import matplotlib.pyplot import matplotlib.pyplot as plt from datetime import date from nsepy import get_history avenue_df=get_history(symbol='DMART',start=date(2018,5,6),end=date(2018,5,10)) avenue_df.Open.plot(color='green', label='DMART') shriram_df = get_history(symbol='SRTRANSFIN',start=date(2018,5,6),end=date(2018,5,10)) shriram_df.Open.plot(color='red', label='SHRI') infy_df = get_history(symbol='INFY',start=date(2018,5,6),end=date(2018,5,10)) infy_df.Open.plot(color='blue', label='INFY') # Add a legend in the top left corner of the plot plt.legend(loc='upper left') # Display the plot plt.show() My output is
type: Question
accepted answer: http://stackoverflow.com/a/50287685
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50287685
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/87588760
has title: Why am I not able to get proper dates in my graph?
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87589238

http://stackoverflow.com/comment/87772095
type: QuestionComment
has text: I think it's your context stuff rather than psycopg2. Try `yield iter(cur)` instead of plain cur.
score: 0
comment on: http://stackoverflow.com/q/50377100
type: Comment

http://stackoverflow.com/comment/87617498
comment on: http://stackoverflow.com/a/50300341
has text: What code would then actually go to `Your code here`? The ` ` content?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87756579
has text: do we need to create a url in urls.py file for '/download' ? The error I am getting at server side is 'Not Found: /download' and client side 'Failed to load resource: the server responded with a status of 404 (Not Found)'
comment on: http://stackoverflow.com/a/50369972
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50315365
type: Answer
score: 9
type: AcceptedAnswer
downvote count: 0
has body: The site is probably using a self signed SSL certificate, you can turn off SSL verification (although you should understand the security risks first), add this code before br.open(): import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context Source: Disable ssl certificate validation in mechanize So in your case the code would end up being: import mechanize import ssl ssl._create_default_https_context = ssl._create_unverified_context br = mechanize.Browser() br.set_handle_robots(False) br.open("https://192.168.10.3/connect/PortalMain") for f in br.forms(): print f Should work but I've not tested it.
accepted answer of: http://stackoverflow.com/q/50315334
upvote count: 9
answers question: http://stackoverflow.com/q/50315334

http://stackoverflow.com/comment/87548648
score: 1
comment on: http://stackoverflow.com/q/50265297
type: Comment
has text: Hi Noobis! What line does this error occur at? Could you try executing the Python one line at a time in your interpreter and tell us where the actual error happens? Thanks!
type: QuestionComment

http://stackoverflow.com/comment/87478263
has text: you wanna to get size of files using Python ?
comment on: http://stackoverflow.com/q/50230487
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87710928
type: Comment
has text: Possible duplicate of [Limit number of threads in numpy](https://stackoverflow.com/questions/30791550/limit-number-of-threads-in-numpy)
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/50347484

http://stackoverflow.com/comment/87640495
type: Comment
type: AnswerComment
has text: This will accept `100.5,0` which might be allowed, OP doesn't specify restrictions on comma use.
score: 0
comment on: http://stackoverflow.com/a/50311993

http://stackoverflow.com/a/50341851
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50341471
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50341471
has body: Here is program which might help you: x = range(60, 70) y = range(0,5) z = ["type1", "type2"] ans = [] for i in x: for j in y: for k in z: ans.append([i, j, k, f(i, j, k)]) print(ans)

http://stackoverflow.com/comment/87559955
type: QuestionComment
score: 1
type: Comment
comment on: http://stackoverflow.com/q/50271439
has text: https://askubuntu.com/questions/156484/how-do-i-install-python-imaging-library-pil - relevant?

http://stackoverflow.com/q/50279960
has title: Issue finding a string in scripts using xpath/selenium/python
score: 0
linked to: http://stackoverflow.com/q/47811895
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/87577177
linked to: http://stackoverflow.com/q/47770144
has body: I'm scanning a website to check if a certain script exists on the site. I have been successful in extracting this information from most sites but there are a few which is causing trouble for me eg. 247sports.com, where I'm unable to get this information the DOM looks like this ... ... ... ... I'm using Firefox Webdriver to look for the "agkn" string in src="https://js.agkn.com/prod..." Python code: x = Webdriver.find_elements_by_xpath("(//iframe|//script|//img|//a)[contains(text(),'agkn') or contains(@src,'agkn') or contains(.,'agkn') or contains(@id,'utag_81') ]") the length of x is always 0. does the have something to do with this?.
type: Question
tagged with: xpath
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50280344

http://stackoverflow.com/q/50296546
has comment: http://stackoverflow.com/comment/87610018
has answer: http://stackoverflow.com/a/50296625
tagged with: python
has title: Increase variable in comprehension with if statement?
tagged with: list-comprehension
possible better answer: http://stackoverflow.com/a/50296788
has answer: http://stackoverflow.com/a/50296678
has answer: http://stackoverflow.com/a/50296647
type: AnsweredQuestion
tagged with: python-3.x
has body: I'm trying to learn Python comprehensions, but I'm stuck. I'm trying to increase my count variable when the condition is True, and return that count after the loop. Here is my code: list = [1,2,4,5,7,8,10] d = 3 count = 0 return [count for x in range(len(list)) if list[x] + d in list and list[x] + 2 * d in list] It's returning "0" each time my condition is True. When I try to add count += 1 in the comprehension it's giving me a SyntaxError.
tagged with: list
accepted answer: http://stackoverflow.com/a/50296680
has answer: http://stackoverflow.com/a/50296788
answer count: 5
upvote count: 3
has answer: http://stackoverflow.com/a/50296680
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87610062
has comment: http://stackoverflow.com/comment/87610156
score: 3
has comment: http://stackoverflow.com/comment/87610036

http://stackoverflow.com/q/50309079
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87653576
score: 0
tagged with: pywin32
has body: Based on this popular Python PyWin32 system tray icon script: http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html How can I set the menu_options tuple and/or the relevant functions for accepting multi parameters functions for menu entries actions? i.e. menu_options = ( ('Complex Function', None, complex_function(a,b,c,d)), ) as as-it-is it only seems to accept function names with no directly-passed parameters although the function's definition must include sysTrayIcon.
answer count: 1
has answer: http://stackoverflow.com/a/50353464
has title: SysTrayIcon.py menu actions with multi parameters functions

openssl
tags question: http://stackoverflow.com/q/50264247
tags question: http://stackoverflow.com/q/50246699
tags question: http://stackoverflow.com/q/50271295
tags question: http://stackoverflow.com/q/50374610
type: Tag
tags question: http://stackoverflow.com/q/50246084
tags question: http://stackoverflow.com/q/50354231
tag name: openssl

http://stackoverflow.com/a/50343394
answers question: http://stackoverflow.com/q/50343117
score: 1
has comment: http://stackoverflow.com/comment/87703419
downvote count: 0
type: Answer
upvote count: 1
has body: Based on your syntax and content, I assume you are using BeautifulSoup package and want to find files by multiple classes. Using .find_all(): files = bsObj.find_all("div", {"class":['row','No','4']}) for file in files: print (file.get_text()) On the other hand, If you go for selectors then you need to use dot . to join multiple classes: Using .select(): files = bsObj.select("div.row.No.4") for file in files: print (file.get_text())

http://stackoverflow.com/a/50309396
accepted answer of: http://stackoverflow.com/q/50304718
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50304718
downvote count: 0
has body: I agree with the sentiments of @quamrana on this matter, but let's solve what could be a difficult problem. With a bit of trickery. First, your consolidated function has to take four argument as the order argument to circle() isn't related to the order argument to fract(). We'll rename the first of these to sides() as that's what it represents. Second, your fract() function isn't completely recursive, it uses iteration internally. I'm going to follow that same pattern in my solution. Finally, we need a bit of hidden information to work with -- you could use a defaulted fifth argument that changes internally but instead I'm going to play with the type of sides to achieve this result: import turtle as t def fract(t, sides, order, size): if order == 0: t.forward(size) elif sides is not None: for _ in range(sides): fract(t, None, order, size) t.right(360 / sides) else: for angle in (60, -120, 60, 0): fract(t, None, order - 1, size / 3) t.left(angle) t.speed('fastest') # because I have no patience fract(t, 4, 2, 300) t.hideturtle() t.exitonclick() I believe this achieves your desired result with minimal change to your original code. In addtion to the fract(t, 4, 2, 300) invocation, which produces your original figure, we can also do variations like fract(t, 3, 3, 300): The next problem you might want to tackle is how to center these images on the screen so that fract(t, 5, 1, 300) doesn't fall off the edge.
score: 1
upvote count: 1

http://stackoverflow.com/q/50360012
score: 4
has answer: http://stackoverflow.com/a/50360923
has answer: http://stackoverflow.com/a/74685773
tagged with: jupyter-notebook
type: Question
upvote count: 4
has body: I am trying to run below code in jupyter notebook. import argparse parser = argparse.ArgumentParser(description='Example with non-optional arguments') parser.add_argument('count', action="store", type=int) parser.add_argument('units', action="store") print(parser.parse_args()) but this gives this gives below error usage: ipykernel_launcher.py [-h] count units ipykernel_launcher.py: error: argument count: invalid int value: 'C:\\Users\\Kwan Lee\\AppData\\Roaming\\jupyter\\runtime\\kernel-76bf5bb5-ea74-42d5-8164-5c56b75bfafc.json' An exception has occurred, use %tb to see the full traceback. SystemExit: 2 c:\users\kwan lee\anaconda2\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py:2971: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) I am just trying to learn what argparse is but I don't get this error.
has comment: http://stackoverflow.com/comment/87737097
type: UnansweredQuestion
downvote count: 0
has title: Python argparse error: error: argument count: invalid int value
favorite count: 0
has comment: http://stackoverflow.com/comment/87737859
answer count: 3
tagged with: argparse
has answer: http://stackoverflow.com/a/74852799
tagged with: python
linked to: http://stackoverflow.com/q/30656777

http://stackoverflow.com/comment/87587596
comment on: http://stackoverflow.com/q/50285686
type: Comment
type: QuestionComment
score: 0
has text: File "/Users/umair/Documents/Untitled.py", line 8 print clf.predict([[160,0]])

http://stackoverflow.com/comment/88048098
comment on: http://stackoverflow.com/q/50312305
score: 0
type: Comment
type: QuestionComment
has text: related: [Interleaving two lists in Python](https://stackoverflow.com/q/7946798/4279) and [Most pythonic way to interleave two strings](https://stackoverflow.com/q/34756145/4279)

http://stackoverflow.com/comment/87775755
has text: Thought about that, but what I wrote is actually the simplified version where a actually = (1-delta)/alpha and b = delta (e.g. delta and alpha are what I'm actually solving for.)
comment on: http://stackoverflow.com/q/50379644
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87649254
has text: use pandas to manage the records and export it as a csv.
comment on: http://stackoverflow.com/q/50316737
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50255229
tagged with: regex
tagged with: python-3.6
score: -5
answer count: 3
has comment: http://stackoverflow.com/comment/87528194
has answer: http://stackoverflow.com/a/63016506
upvote count: 3
has body: I am currently getting started with python. I have a server log file for the pages I visited over a period of time. How do I write a python program to find out which IP address was visited most? Will I have to use dictionary? I have done this but I am not sure how to use regex to fetch IP addresses. import re openFile = open('text.txt', "r") readLines = openFile.read() # pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") wordfreq = {} for word in readLines.split(): if word not in wordfreq: wordfreq[word] = 1 else: wordfreq[word] += 1 print(wordfreq) # wordList = [(v,k) for k,v in wordfreq.items()] # wordList.sort(reverse=True) # # print(wordList) PS: I don't want to use counter from python module. I am figuring out to do this with dictionary.
has answer: http://stackoverflow.com/a/50255517
has comment: http://stackoverflow.com/comment/87547099
has comment: http://stackoverflow.com/comment/87528292
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to use python regex to extract IP address from server log files?
has answer: http://stackoverflow.com/a/50255655
downvote count: 8
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50262296
type: Question
accepted answer: http://stackoverflow.com/a/50268299
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50267416
has body: It is not clear for me how to use Gtk.SpinnerCellRenderer in a Gtk.TreeView with a Gtk.ListStore as model. In this example the spinner is shown but it is inactive. It doesn't spin. #!/usr/bin/env python3 import random import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class TreeView(Gtk.TreeView): def __init__(self): # model self.model = Gtk.ListStore.new([bool, int]) for i in range(5): self.model.append([random.choice([True, True, False]), i]) # view Gtk.TreeView.__init__(self, self.model) # column bool (as spinner) self.spinner_renderer = Gtk.CellRendererSpinner.new() col_bool = Gtk.TreeViewColumn('bool', self.spinner_renderer, active=0) self.append_column(col_bool) # column int col_int = Gtk.TreeViewColumn('int', Gtk.CellRendererText(), text=1) self.append_column(col_int) class Window(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title='Mein Gtk-Fenster') self.set_default_size(100, 120) self.view = TreeView() self.add(self.view) self.connect('destroy', Gtk.main_quit) self.show_all() if __name__ == '__main__': win = Window() Gtk.main()
has comment: http://stackoverflow.com/comment/87552970
has comment: http://stackoverflow.com/comment/87553535
tagged with: gtktreeview
tagged with: python
has comment: http://stackoverflow.com/comment/87553451
possible better answer: http://stackoverflow.com/a/50267416
tagged with: gtk
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50268299
tagged with: pygobject
has title: Spinner in a PyGObject Gtk.TreeView does not spin
has comment: http://stackoverflow.com/comment/87554290

http://stackoverflow.com/q/50248548
linked to: http://stackoverflow.com/q/49826003
favorite count: 0
has comment: http://stackoverflow.com/comment/87515278
has comment: http://stackoverflow.com/comment/87517817
tagged with: pandas
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87515648
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87515833
tagged with: for-loop
has title: python categorizing for loop
has body: Hi i want ask about python for loop logic. here is some data. art1 = ["A",'B','C','D','E','F'] quote = ["",'A','A','C','C','A'] g2 = pd.DataFrame({"Article":art1,"Quote":quote}) A is quoted by B,C,F and C is quoted by D and E. So I wrote a for loop. dic = [] dic2 = [] for i in range(0,len(art1)) : dic.append(art1[i]) dic2.append("") for j in range(1,len(quote)): if art1[i] == quote[j]: dic2.append(art1[j]) dic.append("") g3 = pd.DataFrame(OrderedDict({"Article":dic,"Quote":dic2})) But C quoted A. D and E quoted C. So I want to put D and E in category A. please...How do I code it? This is the format I want.
answer count: 0
has comment: http://stackoverflow.com/comment/87517484
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/87519214
has comment: http://stackoverflow.com/comment/87524153
upvote count: 1

http://stackoverflow.com/comment/87660972
type: Comment
type: AnswerComment
has text: It works!!! Thanks. Sorry forgot to launch 'from dask.distributed import Client client = Client('xxxxx')' Thanks again for the help! Christian
score: 0
comment on: http://stackoverflow.com/a/50321019

http://stackoverflow.com/comment/87613114
type: QuestionComment
has text: Really? That works perfect for me using your exact data! What version of pandas?: `print(pd.__version__)`
comment on: http://stackoverflow.com/q/50297439
type: Comment
score: 1

http://stackoverflow.com/comment/87622844
has text: Noted, thanks again.
type: QuestionComment
comment on: http://stackoverflow.com/q/50302994
type: Comment
score: 0

http://stackoverflow.com/q/50320281
tagged with: function
type: UnansweredQuestion
has body: So I am working on an assignment that requires me to work on two separate python files, one with my main code, and another with two functions, one that encrypts a file, another one that decrypts it. This is what the main code file looks like: import sys sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7') from assgn7 import encrypt_file, decrypt_file file_in = 'Sample.txt' print('Encrypting input file', file_in) enc_dict = encrypt_file(file_in) print('-' * 20) print('Decrypting input file', file_in) decrypt_file(enc_dict, file_in + '.enc') I am supposed to modify this code so that decrypt_file() is called only if encrypt_file() does not return None. How can I go about this? I was thinking of maybe using exception handling but didn't know what kind of error this would need to catch.
has comment: http://stackoverflow.com/comment/87656510
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/50320302
type: Question
has answer: http://stackoverflow.com/a/50320383
tagged with: python-3.x
has title: Only Call a Function if another Function does not return None
answer count: 2
tagged with: exception

http://stackoverflow.com/comment/87575368
has text: I understand it better. You have bytes and not string. Can you try to use base64.encodestring()?
type: AnswerComment
comment on: http://stackoverflow.com/a/50273699
type: Comment
score: 0

http://stackoverflow.com/comment/87479053
type: Comment
comment on: http://stackoverflow.com/a/50230908
type: AnswerComment
has text: Double quotes will always be balanced and never escaped.
score: 0

http://stackoverflow.com/comment/87679286
type: QuestionComment
has text: How do you expect a static property to work? You might want to look at defining a property on the metaclass.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50331601

http://stackoverflow.com/q/50382554
tagged with: postgresql
has comment: http://stackoverflow.com/comment/87781270
has answer: http://stackoverflow.com/a/50386649
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am new Flask and Postgres... I am following this tutorial: https://auth0.com/blog/using-python-flask-and-angular-to-build-modern-apps-part-1/ I have created a Entity like this: from marshmallow import Schema, fields from sqlalchemy import Column, String, Boolean, Date from .entity import Entity, Base class Strategy(Entity, Base): __tablename__ = 'strategies' name = Column(String) description = Column(String) startDate = Column(Date) endDate = Column(Date) allowTeamToVote = Column(Boolean) votingDeadline = Column(Date) isActive = Column(Boolean) def __init__(self, name, description, startDate, endDate, allowTeamToVote, votingDeadline, created_by): Entity.__init__(self, created_by) self.name = name self.description = description self.startDate = startDate self.endDate = endDate self.allowTeamToVote = allowTeamToVote self.votingDeadline = votingDeadline self.isActive = True class StrategySchema(Schema): id = fields.Number() name = fields.Str() description = fields.Str() startDate = fields.DateTime() endDate = fields.DateTime() allowTeamToVote = fields.Boolean() votingDeadline = fields.DateTime() isActive = fields.Boolean() created_at = fields.DateTime() updated_at = fields.DateTime() last_updated_by = fields.Str() and a Post Method: @app.route('/strategies', methods=['POST']) @requires_auth def add_strategy(): # mount Strategy object print(request.get_json()) posted_strategy = StrategySchema(only=('name', 'description', 'startDate', 'endDate', 'allowTeamToVote', 'votingDeadline', 'isActive'))\ .load(request.get_json()) print(posted_strategy.data) strategy = Strategy(**posted_strategy.data, created_by="HTTP post request") # persist Strategy session = Session() session.add(strategy) session.commit() # return created Strategy new_strategy = StrategySchema().dump(Strategy).data session.close() return jsonify(new_strategy), 201 What doesn't getting converted when .load(request.get_json()) method is called is all three datetime values. I get the following error: __init__()…
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
score: 1
tagged with: flask
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/87781646
has title: Missing required positional argument (datetime)

http://stackoverflow.com/q/50313107
has title: How to set filter in the bs4 soup on the basis of the file extension?
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50313161
tagged with: beautifulsoup
type: Question
has body: I successfully wrote to get every file detail from a wiki category by beautiful soup4 in python. The category contains .jpg and .pdf file extensions. How can i filter to get details of the pdf-files only? The code ;- #!/usr/bin/env python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup rUrl = u'https://commons.wikimedia.org/wiki/Category:பண்டிதர் க. அயோத்திதாசர்' #getting all the data from above the category url rData = requests.get(rUrl) soup = BeautifulSoup(rData.content, 'lxml') #getting files name only for item in soup.find_all('div', class_='gallerytext'): fileTags = item.a print(fileTags.text) #getting pdfs name only Its output ;- Oru paisa tamilan 1.jpg Oru paisa tamilan 2.jpg ஒரு பூர்வ பௌத்தனின் சாட்சியம்-அயோத்திதாசரின் சொல்லாடல்.pdf க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-1.pdf க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-2.pdf க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-4.pdf க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-அரசியல்-சமூகம்.pdf பண்டிதரின் கொடை-விகிதாச்சார உரிமை எனும் சமூகநீதிக் கொள்கை.pdf How can filter pdf files only?
answer count: 1
accepted answer: http://stackoverflow.com/a/50313161

http://stackoverflow.com/a/50276953
answers question: http://stackoverflow.com/q/50276202
type: Answer
has comment: http://stackoverflow.com/comment/87576571
score: 1
downvote count: 0
upvote count: 1
has body: In case anyone has the same problem and needs a quick fix, here's my hacky solution: from tkinter import Tk, Checkbutton, IntVar class MyGUI: def __init__(self, window): self.var = IntVar() self.c = Checkbutton( window, text="Enable Tab", command=lambda:self.toggle(self.var)) self.c.pack() def toggle(self, var): var.set(not var.get()) root = Tk() gui = MyGUI(root) root.mainloop()

http://stackoverflow.com/comment/87713839
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50348303
has text: `new_string = old_string.replace('.\b','')`
score: 0

http://stackoverflow.com/q/50243512
downvote count: 1
answer count: 1
has title: exporting output to csv file?
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
has body: I have a code to get a tweet from its ID and I want to export the output to csv file. Code as below: import tweepy from tweepy import OAuthHandler import csv consumer_key = '???' consumer_secret = '???' access_token = '???' access_secret = '???' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) tweet = api.get_status(/id of tweet/) print(tweet.text) print(tweet.id) print(tweet.created_at) I tried this code I get it from other code and it doesn't work: with open('tweet1212.csv', 'w',encoding='utf-8') as csvfile: fieldnames = ['info.'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(tweet) It gets me: TypeError: 'Status' object is not iterable please help me if you could.
tagged with: python
tagged with: twitter
upvote count: 2
tagged with: export
tagged with: export-to-csv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50275307
accepted answer: http://stackoverflow.com/a/50275307
has comment: http://stackoverflow.com/comment/87541933
score: 1

http://stackoverflow.com/comment/87521663
has text: You can just use bash directly instead of having to summon Python at all: https://stackoverflow.com/questions/13280131/hexadecimal-to-decimal-in-shell-script
type: Comment
comment on: http://stackoverflow.com/a/50252192
type: AnswerComment
score: 1

http://stackoverflow.com/a/50379094
has comment: http://stackoverflow.com/comment/87774444
downvote count: 0
has body: Option 1 Set the index then pipe df.set_index(['Timestamp', 'id']).pipe( lambda d: pd.Series(d.values.tolist(), d.index).unstack() ) id a b Timestamp 665047 [30.50842, -84.37288199999999] [30.491882, -84.372938] 665348 [30.50842, -84.37288199999999] None 2055292 None [30.491899, -84.372938] 2058714 None [30.492026, -84.372938] Option 2 cols = ['Timestamp', 'id', 'lat', 'long'] pd.Series({ t[:2]: list(t[2:]) for t in df[cols].itertuples(index=False) }).unstack() a b 665047 [30.50842, -84.37288199999999] [30.491882, -84.372938] 665348 [30.50842, -84.37288199999999] None 2055292 None [30.491899, -84.372938] 2058714 None [30.492026, -84.372938]
accepted answer of: http://stackoverflow.com/q/50378759
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50378759
upvote count: 2
score: 2

rounding
tags question: http://stackoverflow.com/q/50382591
tags question: http://stackoverflow.com/q/50320813
tag name: rounding
tags question: http://stackoverflow.com/q/50264155
type: Tag
tags question: http://stackoverflow.com/q/50374779
tags question: http://stackoverflow.com/q/50308057

http://stackoverflow.com/comment/87613176
has text: I need logic sir.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50285073
score: 0

bdd
tag name: bdd
tags question: http://stackoverflow.com/q/50246929
type: Tag

http://stackoverflow.com/a/50271563
has comment: http://stackoverflow.com/comment/87560851
has comment: http://stackoverflow.com/comment/87560588
has comment: http://stackoverflow.com/comment/87565100
type: Answer
has comment: http://stackoverflow.com/comment/87563020
upvote count: 4
answers question: http://stackoverflow.com/q/50271399
has comment: http://stackoverflow.com/comment/87560556
has comment: http://stackoverflow.com/comment/87564923
has comment: http://stackoverflow.com/comment/87565575
has comment: http://stackoverflow.com/comment/87565379
has comment: http://stackoverflow.com/comment/87565060
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50271399
has comment: http://stackoverflow.com/comment/87560196
has comment: http://stackoverflow.com/comment/87560597
type: AcceptedAnswer
has body: This could be faster, using itertools.izip but in your case (if you don't cast it to numpy array) comprehension does the best job: [(sum(x)*1.0)/len(x) for x in itertools.izip(*lis)] The *1.0 is due to python 2.x division. lis = [[random.randint(1,50) for j in range(50)] for i in range(1400)] %timeit np.mean(lis, axis=0) 100 loops, best of 3: 3.67 ms per loop %timeit [(sum(x)*1.0)/len(x) for x in itertools.izip(*lis)] 100 loops, best of 3: 1.07 ms per loop %timeit [(sum(x)*1.0)/len(x) for x in lis] #NOTE: equivalent to np.mean(lis,axis=1) 100 loops, best of 3: 660 µs per loop lisnp = np.array(lis) %timeit np.mean(lisnp, axis=0) 100 loops, best of 3: 132 µs per loop lisnp = np.array(lis, dtype=np.float64) %timeit np.mean(lisnp, axis=0) 100 loops, best of 3: 67.3 µs per loop
has comment: http://stackoverflow.com/comment/87565001
score: 4

http://stackoverflow.com/comment/87823443
type: Comment
has text: The advice **recompile with -fPIC** is right on the screen, that's why the question is a dup.
score: 0
comment on: http://stackoverflow.com/q/50384771
type: QuestionComment

http://stackoverflow.com/comment/87702804
type: AnswerComment
has text: @AlexanderFraser sounds like you're not returning at the end of the clause.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50343011

http://stackoverflow.com/comment/87749632
comment on: http://stackoverflow.com/q/50365433
score: 0
type: Comment
type: QuestionComment
has text: Hmm well that makes sense. In your second example though I guess that is just undefined behaviour since `1,234.6E2` is not scientific format.

http://stackoverflow.com/comment/87601687
has text: I tried, it still gives some erroneous results. Try this array([1.2 , 1.21, 1.2 , 1.19, 1.21, 1.22, 2.47, 2.53, 2.49, 2.39, 2.28, 2.16, 2.07, 1.99, 1.91, 1.83, 1.74, 1.65, 1.57, 1.5 , 1.45, 1.41, 1.38, 1.35, 1.33, 1.29, 1.24, 1.19, 1.14, 1.11, 1.07, 1.04, 1. , 0.95, 0.91, 0.87, 0.84, 0.8 , 0.77, 0.74, 0.72, 0.7 , 0.68, 0.66, 0.63, 0.61, 0.59, 0.57, 0.55, 0.52, 0.5 , 0.48, 0.45, 0.43, 0.41, 0.39, 0.38, 0.37, 0.37, 0.36, 0.35, 0.34, 0.34, 0.33])
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50292662
type: AnswerComment

http://stackoverflow.com/q/50233302
has comment: http://stackoverflow.com/comment/87485059
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87485343
has title: Pandas compare rows to row with similar partial multi-index
answer count: 0
has comment: http://stackoverflow.com/comment/87485187
tagged with: pandas
score: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87484827
has body: Problem description I have a multi-index pandas dataframe with the column 'value' as on of the columns: index name value ('cat1', 'subcat1') henk 6 ('cat2', 'subcat1') klaas 7 ('cat3', 'subcat1') jan 10 ('cat1', 'subcat2') piet 7 ('cat2', 'subcat2') joris 8 ('cat3', 'subcat2') corneel 9 I want to select all rows r with index (index0,index1) where the following holds: r['value'] &gt; ref['value'] Where ref has the same first index as r , and 'subcat1' as second index: r.index0 == ref.index0 AND ref.index1 == 'subcat1' This would result in: index name value ('cat1', 'subcat2') piet 7 ('cat2', 'subcat2') joris 8 So in short, how can i compare the values of the rows based on it's own multi-level index. Code i have so far So far i got code for selecting values larger than a reference index, but only with a complete index import pandas as pd indices = [['cat1','cat2','cat3','cat1','cat2','cat3'],['subcat1','subcat1','subcat1','subcat2','subcat2','subcat2']] df = pd.DataFrame([ {'value' : 6,'name' : 'henk'}, {'value' : 7,'name' : 'klaas'}, {'value' : 10,'name' : 'jan'}, {'value' : 7,'name' : 'piet'}, {'value' : 8,'name' : 'joris'}, {'value' : 9,'name' : 'corneel'}, ],index=indices) result = df[(df['value'] &gt; df.loc[('cat1','subcat1')]['value'])] Missing in this code The values are compared to a fixed index row, instead of selecting the reference row based on part of it's own index
type: UnansweredQuestion

http://stackoverflow.com/comment/87707651
has text: Yes exactly, when I refer to memory location it is id
type: Comment
comment on: http://stackoverflow.com/a/50345836
type: AnswerComment
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/50238150
tags question: http://stackoverflow.com/q/50258694
tags question: http://stackoverflow.com/q/50239268

http://stackoverflow.com/a/50283923
has comment: http://stackoverflow.com/comment/87584318
accepted answer of: http://stackoverflow.com/q/50283745
has comment: http://stackoverflow.com/comment/87584459
has body: Based on your current code, f_descriptor_T appears on a different row because you are providing the f_descriptor_T in a different writerow call to the rest of the data (every call to writerow creates a new row). Note that the writerow function takes the data-to-insert as a single parameter in the form of a list. If you want them in the same row, you will need to provide them in the same call. To do it in the way you show in your 'Desired Output' image, you'll need to do provide the writer with a single, flat list. Since you have two different data types (the img_id is a string, and f_descriptor_T contains numbers), I recommend doing this by creating an array containing your img_id, and then adding the contents of f_descriptor_T to it. You will need to convert f_descriptor_T into a normal Python List. For the conversion, you can use the list function. Here is a minimal set of examples to demonstrate the behaviour. You want to do it like example 4. It is similar to example 2, but includes an example of how to convert a numpy array into an ordinary List. import csv import numpy as np #example 1 with open("output_different_rows.csv", "w") as f: writer = csv.writer(f) writer.writerow(['foo']) writer.writerow(['bar']) #example 2 with open("output_same_row.csv", "w") as f: writer = csv.writer(f) writer.writerow(['foo'] + ['bar']) #example 3 with open("output_same_row_with_array.csv", "w") as f: writer = csv.writer(f) writer.writerow([['foo', 'bar'], 'too']) #example 4 numpy_array = np.arange(0,9) listified_array = list(numpy_array) with open("output_same_row_numpy.csv", "w") as f: writer = csv.writer(f) writer.writerow(['foo'] + listified_array)
has comment: http://stackoverflow.com/comment/87587736
has comment: http://stackoverflow.com/comment/87586849
has comment: http://stackoverflow.com/comment/87589067
answers question: http://stackoverflow.com/q/50283745
type: Answer
has comment: http://stackoverflow.com/comment/87588259
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/87584575
has comment: http://stackoverflow.com/comment/87589485
downvote count: 0
has comment: http://stackoverflow.com/comment/87598402
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87589366

http://stackoverflow.com/comment/87737370
comment on: http://stackoverflow.com/a/50359577
type: Comment
has text: Thank you so much! The `source_dir` fixed it, though I actually found two more mistakes I was making before I could get it to run: the `'tracknumber'` needed to be a string - so it was `str(count + 1)` - and the `file.save()` part was undefined and unnecessary, as it turned out, so I just removed it.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50370501
possible better answer: http://stackoverflow.com/a/50370706
tagged with: concatenation
accepted answer: http://stackoverflow.com/a/50370821
has answer: http://stackoverflow.com/a/50370706
type: AnsweredQuestion
score: 0
tagged with: cat
answer count: 3
tagged with: file
has comment: http://stackoverflow.com/comment/87756997
has answer: http://stackoverflow.com/a/50380037
has comment: http://stackoverflow.com/comment/87757068
type: Question
has comment: http://stackoverflow.com/comment/87757072
has answer: http://stackoverflow.com/a/50370821
tagged with: python
tagged with: merge
has body: I have thousands of files inside a directory with this pattern YYYY/MM/DD/HH/MM: 201801010000.txt 201801010001.txt 201801010002.txt I want to keep just the hours, so I need to merge 60 files into one for every hour of every day. I don't know how to search into the filename to get the 60 files that i want. This is what I wrote def concat_files(path): file_list = os.listdir(path) with open(datetime.datetime.now(), "w") as outfile: for filename in sorted(file_list): with open(filename, "r") as infile: outfile.write(infile.read()) How do I name the file to keep the date? I'm using datetime now but it override the current filename. With my code I'm merging all files into one, I should merge every % 60 into a different file.
has title: Python merging files in directory
linked to: http://stackoverflow.com/q/20684640

http://stackoverflow.com/comment/87583754
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50283411
has text: @Jared Correct! That's the output I want. Thank you.

http://stackoverflow.com/a/50322549
has body: The problem is with the line if (bolivia == "La Paz" or "Sucre"): or "Sucre" will always evaluate to true. You need to check if (bolivia == "La Paz" or bolivia == "Sucre"):
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50322529

http://stackoverflow.com/q/50367789
has title: Python: How do I convert file to custom base number and back?
has comment: http://stackoverflow.com/comment/87752867
has comment: http://stackoverflow.com/comment/87752341
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87752288
score: 0
linked to: http://stackoverflow.com/q/30079879
accepted answer: http://stackoverflow.com/a/50398767
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: radix
has comment: http://stackoverflow.com/comment/87751985
tagged with: python-3.x
has body: I have a file that I want to convert into custom base (base 86 for example, with custom alphabet) I have try to convert the file with hexlify and then into my custom base but it's too slow... 8 second for 60 Ko.. def HexToBase(Hexa, AlphabetList, OccurList, threshold=10): number = int(Hexa,16) #base 16 vers base 10 alphabet = GetAlphabet(AlphabetList, OccurList, threshold) #GetAlphabet return a list of all chars that occurs more than threshold times b_nbr = len(alphabet) #get the base out = '' while number &gt; 0: out = alphabet[(number % b_nbr)] + out number = number // b_nbr return out file = open("File.jpg","rb") binary_data = file.read() HexToBase(binascii.hexlify(binary_data),['a','b'],[23,54]) So, could anyone help me to find the right solution ? Sorry for my poor English I'm French, and Thank's for your help !
tagged with: python
has answer: http://stackoverflow.com/a/50398767

http://stackoverflow.com/q/50373123
has comment: http://stackoverflow.com/comment/87763149
type: Question
tagged with: python
tagged with: regex
has body: What is the pattern to extract string between 2 strings and fetch to the end if 2nd string not found? For example: to retrieve value assigned to foo (value contains white spaces) import re s1 = 'quz=1, 2, 3 and foo=4, 5, 6 and bar=7, 8, 9' m = re.match(pattern=r'^.*foo=(.*)\sand', string=s1) assert m.group(1) == '4, 5, 6' s2 = 'quz=1, 2, 3 and foo=4, 5, 6' m = re.match(pattern=r'^.*foo=(.*)', string=s2) assert m.group(1) == '4, 5, 6' Thanks
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/50376586
possible better answer: http://stackoverflow.com/a/50376586
has comment: http://stackoverflow.com/comment/87762655
answer count: 2
has answer: http://stackoverflow.com/a/50373210
accepted answer: http://stackoverflow.com/a/50373210
has comment: http://stackoverflow.com/comment/87764300
has title: Extract string between 2 strings and fetch to the end if 2nd string not found
has comment: http://stackoverflow.com/comment/87763772

http://stackoverflow.com/comment/87596865
type: QuestionComment
comment on: http://stackoverflow.com/q/50281108
score: 0
has text: Add else condition for this if str(response.status)[0] in ("4", "5") in complete_callback and yield corresponding item to see if anyitem you scraped fall in this case.
type: Comment

http://stackoverflow.com/q/50249012
has comment: http://stackoverflow.com/comment/87515371
tagged with: python
has comment: http://stackoverflow.com/comment/87515397
has title: AttributeError: '_io.TextIOWrapper' object has no attribute 'tk'
score: 0
has comment: http://stackoverflow.com/comment/87515628
tagged with: tkinter
answer count: 0
type: Question
tagged with: python-3.x
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/87516475
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87515436
has body: def shop1(): kitchen_shopping = Toplevel() kitchen_shopping.title('Kitchen Shelves, Shelves, Shelves...!') kitchen_shopping = open('Static Pages/kitchenshelf.html', 'r') kitchen_list_items = Text(kitchen_shopping, width = 30, height = 10, borderwidth = 2, relief = 'groove') kitchen_list_items.pack(kitchen_shopping) kitchen_items = findall(r'&lt;title&gt;\s&lt;!\[CDATA\[(.*?)\]\]&gt;', kitchen_shopping.read()) return print(kitchen_items) So my problem is that I'm trying to read a HTML document and return all the 'Titles'. Obviously in future I want this to be formatted into the text box "kitchen_list_items" but for now i'm just trying to get it to print. What is going wrong?

http://stackoverflow.com/q/50315615
type: AnsweredQuestion
has body: import os, glob file = os.listdir("my directory: example") mp3files = list(filter(lambda f: f == '*.txt',file)) print(mp3files) This code is giving me only : []
tagged with: filenames
tagged with: glob
has answer: http://stackoverflow.com/a/50315643
accepted answer: http://stackoverflow.com/a/50315640
tagged with: python
has answer: http://stackoverflow.com/a/50316033
has title: Find all files named *.txt in directory
linked to: http://stackoverflow.com/q/3964681
answer count: 4
favorite count: 0
type: Question
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87647059
duplicate of: http://stackoverflow.com/q/3964681
downvote count: 0
possible better answer: http://stackoverflow.com/a/50316067
has answer: http://stackoverflow.com/a/50315640
has comment: http://stackoverflow.com/comment/87647194
has answer: http://stackoverflow.com/a/50316067

http://stackoverflow.com/q/50378547
tagged with: bluetooth-gatt
has comment: http://stackoverflow.com/comment/126859242
tagged with: raspberry-pi
answer count: 0
has body: I've been working on a simple bluetooth GATT server app working on a Raspberry pi 3 model B. This app uses Bluez (version 5.49) to advertise services and characteristics. The app is based on the following example: https://github.com/Jumperr-labs/python-gatt-server So far I have almost ended the server: clients can read and write in characteristics and services are advertised. The problem appears when the clients attempt to disconnect to the server. The server seems to be rejecting disconnections so the client cannot disconnect. The only way that one can disconnect a client is either shutting down the server or disabling the bluetooth adapter on the client. The client is a Xamarin app using the following bluetooth library: https://github.com/aritchie/bluetoothle . Client issues have been discarded because the problem also apprears testing with bluetooth le testing apps like LightBlue (https://itunes.apple.com/us/app/lightblue-explorer/id557428110?mt=8). The base GATT server is the following: from __future__ import print_function import dbus import dbus.exceptions import dbus.mainloop.glib import dbus.service import array try: from gi.repository import GObject except ImportError: import gobject as GObject import advertising import gatt_server import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-a', '--adapter-name', type=str, help='Adapter name', default='') args = parser.parse_args() adapter_name = args.adapter_name dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() mainloop = GObject.MainLoop() advertising.advertising_main(mainloop, bus, adapter_name) gatt_server.gatt_server_main(mainloop, bus, adapter_name) mainloop.run() if __name__ == '__main__': main() In advertising: from __future__ import print_function import dbus import dbus.exceptions import dbus.mainloop.glib import dbus.service import functools import exceptions import adapters BLUEZ_SERVICE_NAME = 'org.bluez' LE_ADVERTISING_MANAGER_IFACE = 'org.bl…
score: 1
has title: Python Bluez GATT server - client cannot disconnect
downvote count: 0
upvote count: 1
tagged with: bluez
favorite count: 0
type: Question
tagged with: raspbian
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87551015
has text: @DanMašek where is part 2 ??!!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50244613
type: AnswerComment

http://stackoverflow.com/a/50245071
upvote count: 2
answers question: http://stackoverflow.com/q/50243373
type: Answer
has body: It sounds like you are missing at least two basic concepts: The search path: when you issue a command that is not a shell function or built-in and that has an unqualified name (one with no / characters), the shell searches a list of zero or more directories for a matching executable file. This list of directories is the "path", and it is stored in the PATH environment variable. You can change it if you wish. This is how the shell finds the git program when you do not specify a path to it. Executable scripts: Python, shell, Perl, etc. programs that must be run via an interpreter can be made executable by name alone by including an appropriate shebang line as the very first line and assigning an executable mode. You include an appropriate shebang line in your example Python program, in fact, but you seem not to understand its significance, because you explicitly launch the script via the python3 command. The shebang line is just another comment to Python, but it is meaningful to the system. It seems like you probably also are missing some other concepts, like the fact that your script doesn't need to be in the current working directory for you to run it via the python3 launcher, path notwithstanding. Just specify its full pathname. Alternatively, Python has its own variation on a path, PYTHONPATH, by which it can locate modules and packages. These are alternatives, however -- the first two points are enough to achieve your apparent objective. Specifically, Keep the shebang line in your script, though your default python is probably v2.7, so if you really want to run it specifically via python3 then modify the shebang line to say so: #!/usr/bin/env python3 Make sure the file has executable mode. For example, chmod 0755 /Users/urn/bin/SCRIPT.py Then you should be able to execute the script from anywhere via its full pathname. To access it from anywhere via its simple name, ensure that the directory containing it is in your path. For this purpose, it would be wise to cho…
score: 2
downvote count: 0

http://stackoverflow.com/comment/87641403
type: Comment
has text: Thanks @cᴏʟᴅsᴘᴇᴇᴅ, that's a bit cleaner!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50312608

http://stackoverflow.com/q/50361352
tagged with: pandas
upvote count: 2
has title: Give default datetime object value to pandas.to_datetime()
downvote count: 0
answer count: 1
favorite count: 0
has body: I have some dates in string with different formats that I convert to datetime objects using to_datetime(). However, the list of strings also has some garbage values that I want to convert to default date. import pandas as pd import datetime as dt print(df) dates 0 2018-02-12 1 2018-03-19 2 12-24-2018 3 garbage I use errors='coerece' to avert to throw exception. It produces NaT, that I want to convert to a default date 2018-12-31, in my case. df['dates'] = pd.to_datetime(df['dates'], errors='coerce') Below result. dates 0 2018-02-12 1 2018-03-19 2 2018-12-24 3 NaT Approach: I am checking if the given value is a valid datetime or not. If not, put the default datetime object. But for some reason, it produces all default values. df['dates'].apply(lambda x: dt.datetime(2018,12,31) if x is not dt.datetime else x) Current Output dates 0 2018-12-31 1 2018-12-31 2 2018-12-31 3 2018-12-31 Expected Output: dates 0 2018-02-12 1 2018-03-19 2 2018-12-24 3 2018-12-31 Is there a way to give a default date to to_datetime() function so that, it won't produce NaT? If not, how do I put default dates afterwards?
type: Question
accepted answer: http://stackoverflow.com/a/50361383
tagged with: datetime
has answer: http://stackoverflow.com/a/50361383
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/87548179
type: AnswerComment
has text: i like that it's a list comprehension, although this separates the integers. So '3 13' would become [3,1,3] when i need it to do [3, 13]. Do you know a way to do this in a list compression and without any modules?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50263164

http://stackoverflow.com/q/50334755
has body: I read that feature columns in tensorflow are used to define our data but how and why? How do feature columns work and why they even exist if we can make a custom estimator without them too? And if they are necessary, why libraries like keras don't use them?
type: AnsweredQuestion
score: 2
upvote count: 3
has title: How feature columns work in tensorflow?
answer count: 1
downvote count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50334977
accepted answer: http://stackoverflow.com/a/50334977

http://stackoverflow.com/q/50340428
has comment: http://stackoverflow.com/comment/87697341
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87697170
has comment: http://stackoverflow.com/comment/87697097
has comment: http://stackoverflow.com/comment/87697216
favorite count: 0
has body: hi i was hoping if someone can help me , i was trying to cluster data set that consists of tweets of health care of several news channel (e.g bbc, cnn , everydayhealth, foxnewshealth, gdnhealthcare, goodhealth, KaiserHealthNews, latimeshealth, msnhealthnews, NBChealth, nprhealth, nytimeshealth, reuters_health, usnewshealth, wsjhealth) now the data set is separated by |, but this symbol is repeated two time before the tweet is presented, for example a sample from the data set: 585978391360221184|Thu Apr 09 01:31:50 +0000 2015|Breast cancer risk test devised http://bbc.in/1CimpJF using regular expression i was able to separate each of the previous line with the | but i remove the first 2 parameters and keep the tweet to use it in clustering. i was able to find a code that separates the first 2 parameters import re x = "585978391360221184|Thu Apr 09 01:31:50 +0000 2015|Breast cancer risk test devised http://bbc.in/1CimpJF" d = print(re.split('\|', x).pop(-1)) and it provided the output i needed Breast cancer risk test devised http://bbc.in/1CimpJF however, when when i applied it on the entire data set it came with this output; it is sort of a collection of the tweets from the news agencies files: ["C. diff 'manslaughter' inquiry call ", 'Health Canada to stop sales of small magnets ', "Robin Roberts' cancer diagnosis ", 'Americans die sooner and are sicker than those in other high-income countries. Does this worry you? ', 'Clinton Kelly’s fresh and #fruity take on #holiday dishes #HappyThanksgiving', '"The biggest challenge facing my department, but also the NHS as a whole, is the lack of money." ', 'RT @MSNHealth: The Mediterranean? The Volumetrics? Or maybe the DASH? U.S. Newsâ€™ Best Overall Diet Plans of 2011: ', "Health law's promise of coverage not resonating with Miami's uninsured. ", 'O.B. Ultra tampons are coming back, and the company apologizes with a song ', 'Mental Illness Affects Women, Men Differently, Study Finds: ', "Why it's so hard to get the flu vacc…
type: Question
has title: separate using regular expression on a data set PYTHON
has comment: http://stackoverflow.com/comment/87697210
has comment: http://stackoverflow.com/comment/87697036
tagged with: python
tagged with: twitter
tagged with: regex
has comment: http://stackoverflow.com/comment/87697057
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87697298
tagged with: dataset

http://stackoverflow.com/q/50362923
score: 18
tagged with: python-unittest
tagged with: python-unittest.mock
upvote count: 18
has comment: http://stackoverflow.com/comment/87742680
has answer: http://stackoverflow.com/a/79320566
has comment: http://stackoverflow.com/comment/87815115
tagged with: python
answer count: 2
has comment: http://stackoverflow.com/comment/87892476
has title: Avoid type warnings when mocking objects in unit tests?
has comment: http://stackoverflow.com/comment/87920273
has comment: http://stackoverflow.com/comment/87844338
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: mypy
has comment: http://stackoverflow.com/comment/87742227
has body: Assuming I have a function that takes a complex object and does something with it: def foo(bar: SomeComplexObject): ... In unit tests bar will be replaced by a mock object, but that of courses now raises type warnings. Should I simply ignore or suppress these or is there a proper way to deal with them (without changing the original function signature of course)? Update: I've seen now that this is an open issue on mypy, but its been in that state for over two years. Has any consensus emerged on how to work around this?
has comment: http://stackoverflow.com/comment/87742318
has comment: http://stackoverflow.com/comment/87742185
has answer: http://stackoverflow.com/a/61951048

http://stackoverflow.com/comment/87734953
score: 2
type: Comment
type: QuestionComment
has text: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000108710-Matplotlib-support-failed People either rolled back to matplotlib 2.1.2 or possibly updated their Pycharm to version 2018.1.2
comment on: http://stackoverflow.com/q/50346498

http://stackoverflow.com/q/50381134
has body: Well, hello everybody. this is my very first piece of code i've ever written, but i am willing to learn. basically i want to generate random numbers/passwords. The script should ask at first some things (have not implemented all right now). length = length of generated passwords (fixed value) pmaximum = amount of generated passwords chars = which chars should be used for generating (i want to short this one so i can choose between LC, UC and numbers) Choosing between: string.letters[0:52] + string.digits + string.punctuation this is my code right now, generating a valueerror; #! /usr/bin/python import string, random #=============== Router Password Generator ============== print 'Welcome to passwordlist generator' length=input('length of generated passwords: ') pmaximum=input('maximum amount of generated passwords: ') chars=raw_input('which chars to use: ') string='' filename = raw_input('assign wordlist name: ') f_extns = filename.split('.') for count in xrange(0,pmaximum): for x in random.sample(chars,length): string+=x file.write(string+'\n') string='' file.close() print 'Done' #================ RPG END =============== i've wrote this using snippets from the web, i have a bit understanding of coding but i am here to learn, if someone could've explain some things i would be very happy so i can understand this code better if it works.
has comment: http://stackoverflow.com/comment/87779791
has comment: http://stackoverflow.com/comment/87778705
score: 0
has comment: http://stackoverflow.com/comment/87779961
has comment: http://stackoverflow.com/comment/87778639
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87779693
tagged with: random
answer count: 0
type: UnansweredQuestion
has title: Generating fixed length random numbers

http://stackoverflow.com/a/50282306
downvote count: 0
has body: Try string_value .... python uses the field names, not the type name.
accepted answer of: http://stackoverflow.com/q/50277963
type: Answer
score: 4
answers question: http://stackoverflow.com/q/50277963
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/50355825
type: Question
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/87728092
has answer: http://stackoverflow.com/a/50355949
has body: Sorry for a somewhat basic question, pretty new to python / pandas. I'm trying to create a column from my database that returns True or False as to whether another column contains any (not all) string from a list of strings. Currently my code looks like this: keywords_list = ["foo, bar, ..etc] df['relevant'] = df['Description'].isin(keywords_list) I know that my 'Description' column contains some of the values in the list, but it is returning all as false. I've looked at similar stackoverflow questions (see below), and they all say to do what I am doing. But the pandas documentation (also below) says that isin only works if it contains all the values in the list. Is there a function I can use that will return if the column includes any of the values in the list? Please help! Filter out rows based on list of strings in Pandas https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html
has answer: http://stackoverflow.com/a/50355989
linked to: http://stackoverflow.com/q/28914078
has title: Pandas - using isin to return if column contains any values in a list, rather than all
favorite count: 0

http://stackoverflow.com/q/50336493
has comment: http://stackoverflow.com/comment/87690823
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/88610021
tagged with: apache
has title: Fullcalendar unable to locate /data feed
accepted answer: http://stackoverflow.com/a/50813438
has comment: http://stackoverflow.com/comment/88631557
tagged with: flask
answer count: 1
has answer: http://stackoverflow.com/a/50813438
has comment: http://stackoverflow.com/comment/87693200
has comment: http://stackoverflow.com/comment/87690572
has body: I am trying to use Fullcalendar to render events returned from another application written in Python using Flask. I have managed to query the application and return JSON to Fullcalendar on my test setup (local to my laptop) which works fine. When I tried to deploy the same code to the server (CentOS 7 with Apache), Apache logs the following error: AH00128: File does not exist: /etc/httpd/htdocs/data An extract from the calendar.html template is as follows: &lt;script&gt; $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,listWeek' }, defaultView: 'listWeek', editable: false, eventLimit: true, // allow "more" link when too many events events: { url: 'data', error: function() { $('#script-warning').show(); } }, loading: function(bool) { $('#loading').toggle(bool); } }); }); &lt;/script&gt; I have identified that the url: 'data' line appears to be controlling the path, but I have been unable to set anything there that works. I cannot see anywhere else in the code where I can set a path - clearly /etc/httpd/htdocs/data/ is invalid - how can I configure the path so that the data is rendered? EDIT: I believe this is an Apache problem - my conf file is as follows: &lt;virtualhost *:443&gt; ServerName server.example.com LogLevel info SSLEngine On SSLProtocol all -SSLv2 -SSLv3 WSGIDaemonProcess fs_calendar user=apache group=apache threads=5 home=/var/www/fs_calendar/ WSGIScriptAlias /fs_calendar /var/www/fs_calendar/calendar.wsgi &lt;directory /var/www/fs_calendar&gt; WSGIProcessGroup fs_api WSGIApplicationGroup %{GLOBAL} WSGIScriptReloading On WSGIPassAuthorization On Order deny,allow Allow from all &lt;/directory&gt; Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/server.example.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/server.example.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateChainFile /etc/letsencrypt/liv…
type: Question
has comment: http://stackoverflow.com/comment/88631804
tagged with: javascript
tagged with: python
tagged with: fullcalendar
has comment: http://stackoverflow.com/comment/87690713

http://stackoverflow.com/q/50361464
has title: TypeError while trying to pass Maxcor into L-BFGS-B minimizer
answer count: 1
has answer: http://stackoverflow.com/a/50362306
downvote count: 1
favorite count: 0
tagged with: optimization
has body: I got the below error when i tried to specify the maxcor kwarg in L-BFGS-B method. The optimization line is shown below, minimizer_kwargs = {"method": "L-BFGS-B", "bounds": bounds, "maxcor": 190} BH_result=optimize.basinhopping(obj_Basinhopping, initial_guess, minimizer_kwargs=minimizer_kwargs, accept_test=mybounds,callback=printx, disp=True) I got the below error, TypeError: minimize() got an unexpected keyword argument 'maxcor' I am very sure i am making a silly mistake here. Anyone please help.
type: AnsweredQuestion
tagged with: python
score: -1
tagged with: scipy
type: Question
tagged with: nonlinear-optimization
accepted answer: http://stackoverflow.com/a/50362306
upvote count: 0

http://stackoverflow.com/comment/87558887
has text: you missed closing `)` at the line immidiate before error line
type: Comment
score: 3
comment on: http://stackoverflow.com/q/50270844
type: QuestionComment

http://stackoverflow.com/q/50253560
has body: I have a python script that currently runs on my desktop. It takes a csv file with roughly 25 million lines (Maybe 15 or so columns) and performs line by line operations. For each line of input, multiple output lines are produced. The results are then output line by line into a csv file, the output ends up at around 100 million lines. Code looks something like this: with open(outputfile,"a") as outputcsv: with open(inputfile,"r") as input csv: headerlist=next(csv.reader(csvfile) for row in csv.reader(csvfile): variable1 = row[headerlist.index("VAR1")] variableN = row[headerlist.index("VARN")] while calculations not complete: do stuff #Some complex calculations are done at this point outputcsv.write(stuff) We're now trying to convert the script to run via Hadoop, using pyspark. I have no idea how to even start. I'm trying to work out how to iterate through an RDD object but don't think it can be done. Is a line by line calculation like this suitable for distributed processing?
score: 0
has comment: http://stackoverflow.com/comment/87524361
tagged with: apache-spark
has answer: http://stackoverflow.com/a/50254406
has comment: http://stackoverflow.com/comment/87524903
tagged with: python
type: Question
tagged with: hadoop
has title: Converting Python script to be able to run in Spark/Hadoop
type: UnansweredQuestion
tagged with: pyspark
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87525036
favorite count: 0
tagged with: hive

http://stackoverflow.com/comment/87580484
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50281946
has text: @MonicaHeddneck I absolutely disagree with that, but it's down to personal preference I guess. Have you ever tried parsing JSON?

http://stackoverflow.com/comment/87593730
type: Comment
comment on: http://stackoverflow.com/a/50288876
type: AnswerComment
has text: Right, but he says explicit
score: 1

pyopenssl
tags question: http://stackoverflow.com/q/50246699
tag name: pyopenssl
tags question: http://stackoverflow.com/q/50374610
type: Tag

http://stackoverflow.com/a/50309835
answers question: http://stackoverflow.com/q/50309668
accepted answer of: http://stackoverflow.com/q/50309668
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87635589
type: Answer
score: 7
has comment: http://stackoverflow.com/comment/87635736
downvote count: 0
has comment: http://stackoverflow.com/comment/87635804
has body: Ok, so I went and downloaded a sample of the data. Each row is something like: 0.000000000000000000e+00,9.439358860254287720e-02,1.275558676570653915e-02 ... Each individual number seems to have 25 character overall, and actually, 26 or so if you include the comma. So that's one byte per character, so about 25 bytes. Using a binary representation of a 64-bit floating point numbers will require ... 64 bits i.e. 8 bytes per number. So You should expect the binary file to be less than 1/3 the size, so this seems correct: 5.2/3 = 1.73... A better estimate would be about 26 characters per number (including commas and line-breaks), so: In [2]: (8/26)*5.2 Out[2]: 1.6 Seems legit.
has comment: http://stackoverflow.com/comment/87646041
upvote count: 7

http://stackoverflow.com/comment/87648603
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50316414
has text: did you try to write some code to do it? show it, so we can help.
score: 0

http://stackoverflow.com/q/50273517
score: 0
tagged with: python-3.x
tagged with: tkinter
type: Question
has body: I am making a game with levels and in each level, I will need to be using different operators and/or different ranges. My problem is that I don't know how to change the variables in a function from a different class. I would like to do this so I don't need to copy and paste my code making it lengthy. I'd like to use self.Answer and self.strQuestion for mulitple scope. The code below is just to make the classes functional. from tkinter import * import tkinter as tk import random from Tkinter import messagebox class BattleMaths(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, levelone, leveltwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) lvl1_button = Button(self, text="LEVEL 1", command=lambda: controller.show_frame(levelone)) lvl1_button.place(relx=0.5, rely=0.5, anchor='center') I want to put the questions def into class leveltwo while changing it to self.Answer = int(numOne) * int(numTwo) and self.strQuestion = "{} x {}".format(str(numOne), str(numTwo)) class levelone(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) def widgets(self): #widgets here def question(self): self.UserAnswer = '' numOne = random.randrange(1,10) numTwo = random.randrange(1,10) self.Answer = int(numOne) + int(numTwo) #change this self.strQuestion = "{} + {}".format(str(numOne), str(numTwo)) #and change this def answer(self): #answer checker class leveltwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) #question def here root = BattleMaths() root…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87563910
has title: How do you change the variable in a function from a different class and call it back?
tagged with: python
has answer: http://stackoverflow.com/a/50274451
answer count: 1
tagged with: class
has comment: http://stackoverflow.com/comment/87564080
linked to: http://stackoverflow.com/q/7546050

http://stackoverflow.com/q/50328377
has title: Parsing XML using minidom in Python
type: AnsweredQuestion
score: 0
tagged with: xml-parsing
has body: I'm new to Python and need a little advice on one of my project from the experts. I have a xml file that i need to parse and then sort . Below is the example of the xml file <Product_Key Name="Visio Professional 2002" KeyRetrievalNote=""> 12345-67890 </Product_Key> <Product_Key Name="Visio Professional 2008" KeyRetrievalNote=""> 23456-78901 </Product_Key> <Product_Key Name="Visio Professional 2012" KeyRetrievalNote=""> 34567-89012 </Product_Key> <Product_Key Name="Visio Professional 2016” KeyRetrievalNote=""> 45678-90123 </Product_Key> Below is the output that i'm trying to achieve Visio Professional 2002: 12345-67890 Visio Professional 2008: 23456-78901 Visio Professional 2012: 34567-89012 Visio Professional 2016: 45678-90123 I'm trying to get the name of the product and in front of it the corresponding product key. I can get the output like below however that is not what I'm looking for. Visio Professional 2002 Visio Professional 2008 Visio Professional 2012 Visio Professional 2016 12345-67890 23456-78901 34567-89012 45678-90123 The snip of the code that i used is below . import xml.dom.minidom def main(): doc = xml.dom.minidom.parse("keysexport.xml") names = doc.getElementsByTagName("Product_Key") keys = doc.getElementsByTagName("Key") for name in names: print(name.getAttribute("Name")) for key in keys: print(key.firstChild.nodeValue) if __name__ == "__main__": main();
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50329967
tagged with: minidom
has answer: http://stackoverflow.com/a/50329967
tagged with: python

google-colaboratory
tags question: http://stackoverflow.com/q/50354158
tags question: http://stackoverflow.com/q/50299153
tags question: http://stackoverflow.com/q/50315989
tags question: http://stackoverflow.com/q/50317371
type: Tag
tag name: google-colaboratory
tags question: http://stackoverflow.com/q/50270540

http://stackoverflow.com/q/50319663
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/50320141
accepted answer: http://stackoverflow.com/a/50320141
has answer: http://stackoverflow.com/a/50319744
has body: i'm trying to scrape a website this is the target div look like this Mots-clefs : A Gray State 4, A Gray State 3, A Gray State 2, ` i'm trying to scrape the text using this method myurl = 'http://agb.xyz' uclient = uReq(myurl) page_html =uclient.read() uclient.close() pag_soup = soup(page_html, "html.parser") tags = pag_soup.find_all("div",{"class":"entry-footer"}) finaltags = tags[0].text.replace('/n',' ') print(finaltags)` the resulat i got ! https://i.sstatic.net/LbWlh.jpg but what i want is to text look like this Mots-clefs : A Gray State 4, A Gray State 3, A Gray State 2, i want to replace retur to line with space
has title: remove return to line from scraped website using python
type: Question
has comment: http://stackoverflow.com/comment/87655047
has answer: http://stackoverflow.com/a/50320488
possible better answer: http://stackoverflow.com/a/50320488

http://stackoverflow.com/a/50335122
has comment: http://stackoverflow.com/comment/87686513
accepted answer of: http://stackoverflow.com/q/50335057
upvote count: 4
has comment: http://stackoverflow.com/comment/87686459
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87686477
has body: You can do this using the in operator. For example: users = ['john', 'adam', 'susan'] exists = 'john' in users # will be true exists2 = 'robert' in users # will be false # for 1 or 0 output exists = int(exists) exists2 = int(exists2)
type: Answer
answers question: http://stackoverflow.com/q/50335057
score: 4

asynchronous
tags question: http://stackoverflow.com/q/50267890
tags question: http://stackoverflow.com/q/50373051
tags question: http://stackoverflow.com/q/50269036
tags question: http://stackoverflow.com/q/50310231
tags question: http://stackoverflow.com/q/50233238
tags question: http://stackoverflow.com/q/50280247
type: Tag
tags question: http://stackoverflow.com/q/50369868
tags question: http://stackoverflow.com/q/50299749
tag name: asynchronous
tags question: http://stackoverflow.com/q/50299695
tags question: http://stackoverflow.com/q/50248559
tags question: http://stackoverflow.com/q/50303797
tags question: http://stackoverflow.com/q/50371266

http://stackoverflow.com/comment/87655266
type: Comment
has text: If the whole array has a pattern of duplicates, it's possible to use some striding tricks to avoid 'copies'. But where the pattern is irregular, no. The data for the array is stored in a flat (1d) buffer. It's the striding and shape that makes it multidimensional.
score: 0
comment on: http://stackoverflow.com/q/50319677
type: QuestionComment

http://stackoverflow.com/q/50347159
answer count: 1
favorite count: 0
tagged with: keras
tagged with: tensorflow
type: Question
tagged with: gpu
has comment: http://stackoverflow.com/comment/87710459
tagged with: python
has title: Keras does not use GPU - how to troubleshoot?
tagged with: cuda
has answer: http://stackoverflow.com/a/50359157
accepted answer: http://stackoverflow.com/a/50359157
upvote count: 12
type: AnsweredQuestion
score: 12
has comment: http://stackoverflow.com/comment/87710275
downvote count: 0
has body: I'm trying to train a Keras model on the GPU, with Tensorflow as backend. I have set everything up according to https://www.tensorflow.org/install/install_windows. This is my setup: I'm working in a Jupyter notebook in a virtualenv environment. The current virtualenv environment has tensorflow-gpu installed. I have CUDA 9.1 and cudaDNN for CUDA 9.1 installed. cuDNN64_7.dll is at a location which is accessible via the PATH variable. I have an NVIDIA GeForce GTX 780 on my computer with the latest drivers. However, Tensorflow does not see any usable GPU: from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 5275203639471190827 ] Keras neither: from keras import backend as K K.tensorflow_backend._get_available_gpus() [] How can I debug this? How can I find out where the problem is?

http://stackoverflow.com/q/50344006
has comment: http://stackoverflow.com/comment/87707431
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50346682
possible better answer: http://stackoverflow.com/a/50344387
has answer: http://stackoverflow.com/a/50346682
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50344387
score: 1
linked to: http://stackoverflow.com/q/42599924
has title: Python Tkinter - Name of objects created by function
has body: I am creating a set of buttons via this function: from tkinter import * from random import randint window = Tk() window.title("Test") window.geometry('200x200') color = ["red","blue","green","yellow","black","purple","orange"] RandInt = 0 j = 0 h = 0 def ButtonDef(xvar = 0,yvar = 0): btn = Button(command =lambda:[RandomColor()]) btn.grid() btn.place(x = xvar*50, y = yvar*50, width = 50, height = 50) def RandomColor(): RandInt = randint (0,6) btn.configure(bg = color[RandInt]) while j in range (4): i = 0 j += 1 while i in range (4): ButtonDef(i,h) i += 1 if i == 4: h += 1 window.mainloop() However, my RandomColor() function is changing only the color of the very button i have pressed - that is fun too, but i wonder how i can make it randomly change the color of all buttons. When being created by a function, i would have guessed that all buttons that were created are named "btn" since thats the only name i have given them. How could i address all (or one specific) buttons, out of a group of created-by-function buttons? Or to put it simply, what name do all of those buttons have? Do they share the name "btn"? Are they assigned a hidden ID?
has comment: http://stackoverflow.com/comment/87705614
favorite count: 0
type: Question
tagged with: tkinter
answer count: 2
has comment: http://stackoverflow.com/comment/87703931
tagged with: function
downvote count: 0

http://stackoverflow.com/comment/89540538
score: 0
type: Comment
type: QuestionComment
has text: @TomKeeler yes , I just set up coursework and also want to setup courses.
comment on: http://stackoverflow.com/q/50372024

http://stackoverflow.com/comment/87697036
type: Comment
type: QuestionComment
score: 0
has text: Why do you need to use `re`? It's just a literal string, not a regular expression pattern, so just use `x.split('|')`
comment on: http://stackoverflow.com/q/50340428

http://stackoverflow.com/q/50257174
has comment: http://stackoverflow.com/comment/87532594
tagged with: logging
favorite count: 0
has answer: http://stackoverflow.com/a/50258017
type: Question
has comment: http://stackoverflow.com/comment/87776720
has comment: http://stackoverflow.com/comment/87780442
score: -2
tagged with: python
tagged with: formatting
tagged with: date
possible better answer: http://stackoverflow.com/a/50258017
has comment: http://stackoverflow.com/comment/87798498
has comment: http://stackoverflow.com/comment/87780577
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50395896
has answer: http://stackoverflow.com/a/50395896
downvote count: 3
has title: Logging format with multiple timestamps?
has comment: http://stackoverflow.com/comment/87539790
has body: Due to specific requirements of my application, I need to have the same timestamp added to a single logging entry but with different formats for each timestamp. These two timestamps are NOT adjacent to one another, so other log record fields are between them. Since datefmt is passed as a second parameter against format in the formatter, I've yet to figure out how you can provide two different date formats for a single logging entry. The ONLY question I'm asking is if this possible with Python WITHOUT custom formatters or filters.
upvote count: 1

http://stackoverflow.com/q/50288105
answer count: 1
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/87593976
type: Question
has title: Data science : correlation between quantitative and qualitative variables (in python)
tagged with: python
type: UnansweredQuestion
has body: I want to know if it is possible to measure the correlation between a quantitative variable (in my case the average daily consumption of households) and a qualitative variable (in my case the month : 1, 2, ..., 12) in python ? month | avg_daily_consumption ------------------------------------------ 1 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| 12.11836586156116 2 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|11.713968603585668 3 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|11.902829015188159 4 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|10.12066900094302 5 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|8.879703717271864 6 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|8.384419625257689 7 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|8.146453593663365 8 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|7.961394876525876 9 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|8.748848024841289 10 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|9.820944144869841 11 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|11.247017177860053 12 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|12.069888731716086 Thanks.
tagged with: correlation
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50288862

http://stackoverflow.com/comment/87531257
comment on: http://stackoverflow.com/a/50256577
score: 0
type: AnswerComment
has text: ['a', 'close', 'up', 'of', 'a', 'person', 'holding', 'a', 'pair', 'of', 'scissors'] ['a', 'close', 'up', 'of', 'a', 'person', 'on', 'a', 'pair', 'of', 'skis'] ['a', 'close', 'up', 'of', 'a', 'person', 'holding', 'a', 'pair', 'of', 'skis']
type: Comment

http://stackoverflow.com/comment/87483115
score: 0
type: Comment
type: QuestionComment
has text: How are you trying to assign more values to `args` and what's the issue in doing so?
comment on: http://stackoverflow.com/q/50232893

http://stackoverflow.com/q/50285824
answer count: 2
tagged with: pytorch
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/19339
tagged with: python
has body: I'm trying to construct new observation and applying it into DQN. I use pytorch DQN algorithm with my observation code. its not finished yet, so data is not clear. I changed some line in whole code as follows. import sys, math import random as rd import numpy as np import matplotlib import matplotlib.pyplot as plt ###################################### from collections import namedtuple from itertools import count from PIL import Image import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import torchvision.transforms as T Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward')) class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args): """Saves a transition.""" if len(self.memory) &lt; self.capacity: self.memory.append(None) self.memory[self.position] = Transition(*args) self.position = (self.position + 1) % self.capacity def sample(self, batch_size): return rd.sample(self.memory, batch_size) def __len__(self): return len(self.memory) class DQN(nn.Module): def __init__(self): super(DQN, self).__init__() self.l1 = nn.Linear(5, 16) self.l2 = nn.Linear(16, 12) self.l3 = nn.Linear(12, 20) self.head = nn.Linear(20, 1) def forward(self, x): x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = F.relu(self.l3(x)) return self.head(x.view(x.size(0), -1)) BATCH_SIZE = 5 GAMMA = 0.999 EPS_START = 0.9 EPS_END = 0.05 EPS_DECAY = 200 TARGET_UPDATE = 5 policy_net = DQN() target_net = DQN() target_net.load_state_dict(policy_net.state_dict()) target_net.eval() optimizer = optim.RMSprop(policy_net.parameters()) memory = ReplayMemory(10000) def optimize_model(): if len(memory) &lt; BATCH_SIZE: return transitions = memory.sample(BATCH_SIZE) # Transpose the batch (see http://stackoverflow.com/a/19343/3343043 for # detailed explanation). batch = Transition(*zip(*transitions)) print("batch = ", batch, "\n") # …
has comment: http://stackoverflow.com/comment/87603447
has title: Pytorch modified DQN algorithm error "the derivative for ' ' is not implemented"
has answer: http://stackoverflow.com/a/57407341
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50318079
favorite count: 0
type: Question

http://stackoverflow.com/comment/87759312
type: Comment
has text: First off `in my_own_m2m.ids` is enough, no need for `mapped`. And then the other thing. It could work with a domain like `[('my_own_m2m.ids', '=', ref('some_external_id'))]` but depends if `ref()` is usable in `attrs` domains, which i dont know at exact his moment ;-)
type: AnswerComment
comment on: http://stackoverflow.com/a/50369937
score: 0

http://stackoverflow.com/comment/87766589
comment on: http://stackoverflow.com/a/50375035
has text: OK so basically `fmod` reduces the chance of this error occurring... or how should I interpret this? I'm actually looking to avoid these cases, not just reduce the chance of them occurring.
type: Comment
score: 0
type: AnswerComment

connexion
tag name: connexion
type: Tag
tags question: http://stackoverflow.com/q/50260276

http://stackoverflow.com/comment/87777789
has text: Unfortunatly, I am not very experienced with python. I don't know what a list or dict is.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50380804
type: AnswerComment

http://stackoverflow.com/q/50298705
downvote count: 1
has body: So, i'm reading a xlsx file with pandas, then parsing the datetime (excel's a float) Then I need to parse it into Json, and I'm running into some problems. STEP 1 (Before parsing with to_json()) df = pandas.read_excel('test.xlsx', names=['date', 'value', 'source']) df['date'] = pandas.to_datetime(df['date'], format='%b %d %Y.%f') print(df) the return is date value source 0 2012-05-22 1 xxxxxxxxxxxxxxxxxxxx 1 2012-05-25 1 xxxxxxxxxxxxx 2 2012-05-30 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 3 2012-06-01 1 xxxxxxxxxx 4 2012-06-08 1 xxxxxxxxxxxxxxxxx Everything seems fine, then I got o to_json payload = df.to_json() And the return is {"date":{"0":1337644800000,"1":1337904000000,"2":1338336000000,"3":1338508800000,"4":1339113600000},"value":{"0":1,"1":1,"2":1,"3":1,"4":1},"source":{"0":"xxxxxxxxxxxxxxx","1":"xxxxxxxxxx","2":"xxxxxxxxxxx","3":"xxxxxxxxxxxxxxxx","4":"xxxxxxxxxxxxxxx"}} So what am I doing wrong? Am I missing args on to_json()? Halp pls :c I needed it to be like this: [{"date":"2012-05-22","value":1,"source":"xxxxxxxxxxxxxxxxxxxx"}, {"date":"2012-05-25","value":1,"source":"xxxxxxxxxxxxxxxxxxxx"}, {"date":"2012-05-30","value":1,"source":"xxxxxxxxxxxxxxxxxxxxx"}, {"date":"2012-06-01","value":1,"source":"xxxxxxxxxxxxxxxxxxxx"}, {"date":"2012-06-08","value":1,"source":"xxxxxxxxxxxxxxxxxxxxxx"}]
tagged with: string
has comment: http://stackoverflow.com/comment/87614209
has comment: http://stackoverflow.com/comment/87614365
favorite count: 0
has title: pandas DataFrame to list of dicts using to_json()
has comment: http://stackoverflow.com/comment/87614419
type: Question
has answer: http://stackoverflow.com/a/50298809
accepted answer: http://stackoverflow.com/a/50298809
tagged with: datetime
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50298830
possible better answer: http://stackoverflow.com/a/50298830
has comment: http://stackoverflow.com/comment/87614308
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/87487409
type: Comment
comment on: http://stackoverflow.com/q/50235020
score: 0
has text: Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response)
type: QuestionComment

http://stackoverflow.com/comment/87738831
type: Comment
type: QuestionComment
has text: field is a field from a pyodbc cursor row.
score: 0
comment on: http://stackoverflow.com/q/50360671

http://stackoverflow.com/comment/87627378
comment on: http://stackoverflow.com/q/50304323
type: Comment
score: 0
has text: Could you please edit the post to include sample text that gets copied to clipboard?
type: QuestionComment

http://stackoverflow.com/comment/87493098
type: Comment
type: QuestionComment
has text: (Can't help but notice that installing third-party packages to the system Python is not a great idea; a virtualenv makes things much easier to control and understand.)
score: 0
comment on: http://stackoverflow.com/q/50237237

http://stackoverflow.com/a/50399584
type: Answer
has body: One option is to implement this mapping using functions that return True if the x,y pair is inside said zone and False otherwise. Working with pandas, this function can be easily implemented. Below there are examples of some of these functions (credit for the triangle function to How to determine if a point is in a 2D triangle?): def triangle(x,y,verts): p0x,p0y = verts[0]; p1x,p1y = verts[1]; p2x,p2y = verts[2]; area = 0.5 *(-p1y*p2x + p0y*(-p1x + p2x) + p0x*(p1y - p2y) + p1x*p2y); s = 1/(2*area)*(p0y*p2x - p0x*p2y + (p2y - p0y)*x + (p0x - p2x)*y); t = 1/(2*area)*(p0x*p1y - p0y*p1x + (p0y - p1y)*x + (p1x - p0x)*y); return (s&gt;0) &amp; (t&gt;0) &amp; (1-s-t&gt;0) def upper_square(x,y): return (x&gt;4) &amp; (y&gt;4) def circle(x,y): return ((x-2)**2+(y-2)**2)&lt;1 Then, you can loop over each zone in order to assign the values to the new column. One example using the above functions would be using a dict to map the zone function to the zone id: # define data df = pd.DataFrame(np.random.random((10000,2))*5,columns=['lat','lon']) t1 = ((0,0),(0,3),(1,0)) t2 = ((4,4),(4,2),(2,4)) # define relation between zone id and zone function zones = {1:upper_square,2:lambda x,y: triangle(x,y,t1),3:lambda x,y: triangle(x,y,t2),4:circle} df['zone']=0 # this will serve as everything else zone # loop over zones and update df.zone column for zone,zone_fun in zones.items(): mask = zone_fun(df.lat,df.lon) df.loc[mask,'zone'] = zone Here, we have 5 zones, one square, 2 triangles, one circle and everything else. We can check whether the assignation worked or not with the following plot, that will plot the points with a different color depending on their df.zone value: plt.scatter(df.lat,df.lon,c = df.zone,s=10,cmap='plasma') plt.gca().set_aspect('equal') Which yields:
score: 0
answers question: http://stackoverflow.com/q/50379732

http://stackoverflow.com/comment/87806095
score: 0
comment on: http://stackoverflow.com/q/50379732
has text: Yes, there would be a new column in the dataframe with zone id included. Trying to figure out first how to divide the region into a grid, and then secondly assign the data points to distinct zones within that grid.
type: Comment
type: QuestionComment

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/50238812

http://stackoverflow.com/comment/87729241
has text: Try `commentcount = '{0:.1f}k'.format(commentcount/1000)` in your if statement.
comment on: http://stackoverflow.com/q/50356402
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52371928
has body: You can publish and subscribe to a different server at the same time using the same code as well, according to this example from ZMQ import zmq import time context = zmq.Context() subscriber = context.socket (zmq.SUB) subscriber.connect ("tcp://192.168.55.112:5556") subscriber.connect ("tcp://192.168.55.201:7721") subscriber.setsockopt (zmq.SUBSCRIBE, "NASDAQ") publisher = context.socket (zmq.PUB) publisher.bind ("ipc://nasdaq-feed") while True: message = subscriber.recv() publisher.send (message) So you are a subscriber connected to those two servers subscriber.connect ("tcp://192.168.55.112:5556") subscriber.connect ("tcp://192.168.55.201:7721") at the same time you are broadcasting as a publisher publisher.send (message) This is how you would build a peer-to-peer distributed system, every server a subscriber and publisher
answers question: http://stackoverflow.com/q/50301625
type: Answer
score: 0

http://stackoverflow.com/comment/87723192
score: 0
comment on: http://stackoverflow.com/a/50352616
type: Comment
has text: if i do idx_first_empty_row = np.where(reading_book.iloc[:, 0].isnull().values == True) then the result is - (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype=int64),)
type: AnswerComment

http://stackoverflow.com/q/50239522
tagged with: math
accepted answer: http://stackoverflow.com/a/50239885
possible better answer: http://stackoverflow.com/a/50239637
upvote count: 1
has answer: http://stackoverflow.com/a/50239885
tagged with: permutation
downvote count: 1
has body: Using python I have to get all the permutations of given subset using python. I used itertools.permutation but result is a bit different. Think of a machine and it has a maximum capacity, and we have products can be produced together, and we have to fill the capacity of machine. Output format is not important, I used a dictionary to describe it. I will make a calculation after getting this combinations. For example : products = {'x','y','z','a'} machine_capcacity = 8 #required output as follows: {'x':5,'y':1,'z':1,'a':1} {'x':4,'y':2,'z':1,'a':1} {'x':4,'y':1,'z':2,'a':1} {'x':4,'y':1,'z':1,'a':2} {'x':3,'y':3,'z':1,'a':1} {'x':3,'y':1,'z':3,'a':1} {'x':3,'y':1,'z':1,'a':3} {'x':3,'y':2,'z':2,'a':1} {'x':3,'y':2,'z':1,'a':2} {'x':3,'y':1,'z':2,'a':2} {'x':2,'y':4,'z':1,'a':1} # ... {'x':6,'y':1,'z':1} # This can't be in results,since need at least 1 element of product {'x':4,'y':1,'z':1,'a':1} # This can't be in results,since we need to fill the capacity And we dont want repeating elements: {'x':5,'y':1,'z':1,'a':1} and {'a':1,'y':1,'z':1,'x':5} is same thing for us.
favorite count: 0
type: Question
has title: Permutation of items with quantities
tagged with: python
has answer: http://stackoverflow.com/a/50239637
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/87527273
type: Comment
comment on: http://stackoverflow.com/a/50254791
type: AnswerComment
has text: Nice method also. I like the shift. +1
score: 2

http://stackoverflow.com/q/50300412
has comment: http://stackoverflow.com/comment/87685089
favorite count: 0
type: Question
tagged with: random-forest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87617878
tagged with: python
score: 4
upvote count: 4
has body: I'm facing a weird issue, appreciate any assistance. My training dataset objects are pure float32 numpy arrays which are populated by a vectorizer. The issue has to be one of the parameters I feed into the RandomForestClassifier because I was able to get through it without any parameters passed. I'm positive there are no strings present in my inputs: X_train memmap([0.25173673, 0.01420455, 0.00684149, ..., 0. , 0. , 0. ], dtype=float32) y_train memmap([ 0., 0., 0., ..., -1., 1., 1.], dtype=float32) However when I run a RandomForest fit on the dataset I get the following result: model_RandomForest = ek.RandomForestClassifier(n_estimators = 200, max_depth = 'auto', n_jobs = 1, random_state = 5,max_features = 'auto',min_samples_leaf = 100, verbose=1) result_RandomForest = model_RandomForest.fit(X_train[train_rows], y_train[train_rows]) Trace Output: ~\Anaconda3\envs\emberenv\lib\site-packages\sklearn\ensemble\forest.py in fit(self, X, y, sample_weight) 326 t, self, X, y, sample_weight, i, len(trees), 327 verbose=self.verbose, class_weight=self.class_weight) --&gt; 328 for i, t in enumerate(trees)) 329 330 # Collect newly grown trees ~\Anaconda3\envs\emberenv\lib\site-packages\sklearn\externals\joblib\parallel.py in __call__(self, iterable) 777 # was dispatched. In particular this covers the edge 778 # case of Parallel used with an exhausted iterator. --&gt; 779 while self.dispatch_one_batch(iterator): 780 self._iterating = True 781 else: ~\Anaconda3\envs\emberenv\lib\site-packages\sklearn\externals\joblib\parallel.py in dispatch_one_batch(self, iterator) 623 return False 624 else: --&gt; 625 self._dispatch(tasks) 626 return True 627 ~\Anaconda3\envs\emberenv\lib\site-packages\sklearn\externals\joblib\parallel.py in _dispatch(self, batch) 586 dispatch_timestamp = time.time() 587 cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self) --&gt; 588 job = self._backend.apply_async(batch, callback=cb) 589 self._jobs.append(job) 590 ~\Anaconda3\envs\emberenv\lib\sit…
has comment: http://stackoverflow.com/comment/87627387
has title: TypeError: '<' not supported between instances of 'float' and 'str' in tree.py
has comment: http://stackoverflow.com/comment/87619326
has comment: http://stackoverflow.com/comment/87623892
answer count: 0
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/a/50234121
has body: First of all you should install virtualenv using python3.5. there is a tricky way that I use, I add some lines to the .bashrc file like this: export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3.5 alias v.activate="source /usr/local/bin/virtualenvwrapper.sh" so whenever I want to change my virtualenv to be on python3.5 I run the v.activate command, and then create my virtual environment with python3.5. remember this that: 1.I use virtualenvwrapper instead of virtualenv 2.Dont forget to run source .bashrc after you add those lines to bashrc
has comment: http://stackoverflow.com/comment/87507031
has comment: http://stackoverflow.com/comment/87485830
has comment: http://stackoverflow.com/comment/87485778
answers question: http://stackoverflow.com/q/50232728
has comment: http://stackoverflow.com/comment/87509306
score: 0
has comment: http://stackoverflow.com/comment/87508454
type: Answer

http://stackoverflow.com/comment/87481618
has text: i mean when you click on my program, i dont want any prompt or window or anything to be shown, just the process be activated on background and do its job
score: 0
comment on: http://stackoverflow.com/q/50231913
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50283235
has body: You can use unpacking: data = [None]+[i.strip('\n') for i in open('filename.txt')] def group_data(d): while len(d) &gt; 2: a, b, c, *d1 = d yield [a, b, c] d = [b, c]+d1 print(list(group_data(s))) Output: [[None, 'line1', 'line2'], ['line1', 'line2', 'line3'], ['line2', 'line3', 'line4']]
score: -1
answers question: http://stackoverflow.com/q/50283152
upvote count: 0
downvote count: 1
type: Answer

http://stackoverflow.com/a/50352565
score: 2
has body: Create a dict of values:colors, and then create a new column in your dataframe. Here is a simplified example: df = pd.DataFrame(data={"col1":[0, 1, 2, 3, 1, 2, 3]}) colors = {0: "brown", 1: "green", 2: "blue", 3: "purple"} df["color"] = df["col1"].apply(lambda c: colors[c])
upvote count: 2
has comment: http://stackoverflow.com/comment/87722452
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50352335
type: Answer
has comment: http://stackoverflow.com/comment/87722032
answers question: http://stackoverflow.com/q/50352335
has comment: http://stackoverflow.com/comment/87721324

http://stackoverflow.com/q/50360981
has body: I am building a notification model with Redis as database. With every addition to a particular key in the database, I notify the remote client(written with Redis-py) using Redis's pubsub feature and also a HTTP based notification. While running performance test and comparing the times between Redis PUBSUB notification and HTTP Response are fairly close( redis still being faster than HTTP by a few ms. Example. Redis notification takes 47 ms and HTTP notification takes 56 ms). I was assuming Redis PUBSUB would be much faster than HTTP. Is this the expected performance of redis notification over HTTP ? Is there a faster way to push notifications from Redis db (faster than HTTP)?
tagged with: http
type: Question
tagged with: testing
tagged with: redis
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50368728
tagged with: python
has comment: http://stackoverflow.com/comment/87771571
has title: Redis Pubsub performance for remote clients
score: 0
tagged with: notifications
answer count: 1

http://stackoverflow.com/a/50326863
has comment: http://stackoverflow.com/comment/87669522
has comment: http://stackoverflow.com/comment/87669727
has comment: http://stackoverflow.com/comment/87669773
has body: You're going to have to keep a record of the previous line and compare the values. There's a couple of ways of doing this. One simple way is like so previous = None increased = True with open('dataset') as f: for line in f: line = line.strip() if not line: continue # ignore blank lines if line.isnumeric(): if previous is not None and increased: # if increased is currently True, see if it is still True increased = float(line) &gt; float(previous) previous = line else: # Now prints out country name print('GDP for {} increased every year: {}'.format(line, increased)) increased = True previous = None Output from your example GDP for Australia increased every year: False GDP for Azerbaijan increased every year: False
has comment: http://stackoverflow.com/comment/87669473
downvote count: 0
has comment: http://stackoverflow.com/comment/87669491
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87669686
answers question: http://stackoverflow.com/q/50326706

http://stackoverflow.com/a/50230388
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87611533
has body: This is one way using pd.DataFrame.apply. Note that np.nan == np.nan evaluates to False, we can use this trick in our function to determine when to apply removal logic. import pandas as pd, numpy as np df = pd.DataFrame({'Main': ['Sri playnig well cricket', 'sri went out', 'Ram is in' ,'Ram went to UK,US'], 'substring': ['cricket', np.nan, np.nan, 'UK,US']}) def remover(row): sub = row['substring'] if sub != sub: return row['Main'] else: lst = row['Main'].split() return ' '.join([i for i in lst if i!=sub]) df['Main'] = df.apply(remover, axis=1) print(df) Main substring 0 Sri playnig well cricket 1 sri went out NaN 2 Ram is in NaN 3 Ram went to UK,US
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50230233
score: 1
answers question: http://stackoverflow.com/q/50230233

http://stackoverflow.com/comment/87640509
score: 0
comment on: http://stackoverflow.com/q/50309166
type: Comment
has text: Okay then. I just checked anyway and your syntax is wrong. You have `arrayFilters` "inside" the update and not `array_filters` the "option". Also needs to be a "list" as per my answer on the linked duplicate.
type: QuestionComment

http://stackoverflow.com/a/50316298
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/50316154
has body: You don't need a separate URL or view for the list. Just include the queryset in the context of your get_name view. posts = Eintrag.objects.all() return render(request, 'form/name.html', {'form': form, 'posts': posts})

http://stackoverflow.com/a/50347788
score: 0
type: Answer
has body: The script expects a file name to be passed as a command line argument. Apparently you are not passing a file name, so the variable fileName = sys.argv[1:] will be empty. Then tempassign will also be an empty string and the file name will be just "txt/.txt". Of course such file does not exist and you get the FileNotFound error.
answers question: http://stackoverflow.com/q/50347084
has comment: http://stackoverflow.com/comment/87714026

http://stackoverflow.com/comment/87783770
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50383690
has text: ok. In your question you did not say anything about r2 being the source code of page 1. Does the code wait for the page to finish loading before fetching `r2`? If yes, did you really check that?

http://stackoverflow.com/a/50369521
downvote count: 0
type: AcceptedAnswer
upvote count: 6
score: 6
accepted answer of: http://stackoverflow.com/q/50367661
answers question: http://stackoverflow.com/q/50367661
has comment: http://stackoverflow.com/comment/129863536
has comment: http://stackoverflow.com/comment/104417976
type: Answer
has comment: http://stackoverflow.com/comment/129864137
has body: At issue is the metaclass used by typing.NamedTuple; this metaclass ignores all base classes and just generates a collections.namedtuple() class with added annotation information (copying across any additional attributes directly defined on the class). You can define your own metaclass (which must be a subclass of typing.NamedTupleMeta), that adds your additional base classes after generating the named tuple class: import typing NamedTuple = typing.NamedTuple if hasattr(typing.NamedTuple, '__mro_entries__'): # Python 3.9 fixed and broke multiple inheritance in a different way # see https://github.com/python/cpython/issues/88089 NamedTuple = typing._NamedTuple class MultipleInheritanceNamedTupleMeta(typing.NamedTupleMeta): def __new__(mcls, typename, bases, ns): if NamedTuple in bases: base = super().__new__(mcls, '_base_' + typename, bases, ns) bases = (base, *(b for b in bases if not isinstance(b, NamedTuple))) return super(typing.NamedTupleMeta, mcls).__new__(mcls, typename, bases, ns) class Base1(metaclass=MultipleInheritanceNamedTupleMeta): def foo(self): print(self.__annotations__) class Test1(NamedTuple, Base1): x: int y: int Note that this won't let you inherit fields! That's because you must generate a new namedtuple class for any combination of fields. The above produces the following structure: Test1, inherits from _base_Test1 - the actual typing.NamedTuple generated namedtuple tuple Base1 and this works as required: &gt;&gt;&gt; x = Test1(1, 2) &gt;&gt;&gt; x.foo() {'x': &lt;class 'int'&gt;, 'y': &lt;class 'int'&gt;} Technically speaking, you’ll only need the above in Python versions up to Python 3.10. Python 3.9 has a refactored NamedTuple implementation that fixes the specific metaclass issue underlying this problem, but then introduced a different problem by explicitly raising a TypeError stating that multiple inheritance is not supported. This TypeError was raised as a bug, as there are valid use-cases for using multiple inheritance with NamedTuple, a…

http://stackoverflow.com/a/50233444
answers question: http://stackoverflow.com/q/50231621
has comment: http://stackoverflow.com/comment/87531665
has comment: http://stackoverflow.com/comment/87566586
score: 0
has comment: http://stackoverflow.com/comment/87486773
type: Answer
has body: You can see which keys are currently being pressed using the pygame.key.get_pressed() method. It returns a list of boolean values on which keys are currently being pressed. while True: keys = pygame.key.get_pressed() A, S, D = keys[K_a], keys[K_s], keys[K_d] # add right hand dots as well braille_dict = {'a': D, 'b': D and S,} # and so on for every combination You'll need to then check for each combination of keystrokes to make the different braille letters by using the logical 'and' operator. So if 2 keys are being pressed at the same time, it might make a different braille letter than the 2 being pressed one after the other. Once you see which combination is being pressed, you can then print it You can't limit the keystrokes that one is typing, but you can ignore the ones that the program does not require (keys apart from the home row?).

http://stackoverflow.com/comment/87628161
comment on: http://stackoverflow.com/q/50305976
has text: It also states, at the end of article, that arrays scale much better. On small test-cases, list can outperform array (like your case -10000). For the benchmark test on 10^7, array is the winner.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50350268
accepted answer: http://stackoverflow.com/a/50352206
answer count: 1
tagged with: django
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50352206
tagged with: python
has body: In part of my django API I have the following, to update old notes: old_note = request.databaseSession.query(Tmemo).\ filter(Tmemo.memosern1 == serial).\ one() This query works without any problem as I am using it many other places. The weird problem comes with: old_note.memotext = newtext Then when I commit the following errors happens: ProgrammingError: (pyodbc.ProgrammingError) ('42000', u'[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The data types text and text are incompatible in the equal to operator. (402) (SQLExecDirectW)') [SQL: u'UPDATE tmemo SET memotext=? WHERE tmemo.memosern1 = ? AND tmemo.memosern2 = ? AND tmemo.memotype = ? AND tmemo.memotext = ?'] [parameters: ('asassasasasaassaassaasas2121', u'P03000000060445', u'MEMO', u'5', u'asassasasasaassaassaasas')] (Background on this error at: http://sqlalche.me/e/f405) Tmemo is just a table with column for a serial number memosern1 and memosern2, type with memotype and the notes itself as memotext, serials and type are varchar and memotext as text. I really don't understand what text and text are incompatible means really, it makes no sense, also I am just filtering the serial number, nothing else, so what is up with this weird query? And I can perfectly create another row in the table with the exact same variables being used (newtext), I just can't update an existent one. Any ideias? I can provide more info
tagged with: python-2.x
tagged with: sqlalchemy
has title: SQL Alchemy the data types text and text are incompatible in the equal operator

http://stackoverflow.com/comment/87626404
comment on: http://stackoverflow.com/q/50304941
type: Comment
type: QuestionComment
has text: Having mixed types is actually [well documented](https://docs.scipy.org/doc/numpy/user/basics.rec.html), and super awesome.
score: 0

http://stackoverflow.com/q/50384771
has title: theano import error in linux using python3.6 when using cpu as config device
answer count: 0
has comment: http://stackoverflow.com/comment/87786218
score: 1
upvote count: 1
tagged with: cpu
has comment: http://stackoverflow.com/comment/87822359
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/28511138
tagged with: linux
tagged with: theano
type: UnansweredQuestion
has body: I have installed theano with python3.6 using pip install theano and Getting below error while importing theano even though I configured theano to run with cpu. /usr/bin/ld: /usr/local/lib/libpython3.6m.a(abstract.o): relocation R_X86_64_32S against `_Py_NotImplementedStruct' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libpython3.6m.a: error adding symbols: Bad value collect2: error: ld returned 1 exit status Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 75, in raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 92, in raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.6/site-packages/theano/init.py", line 66, in from theano.compile import ( File "/usr/local/lib/python3.6/site-packages/theano/compile/init.py", line 10, in from theano.compile.function_module import * File "/usr/local/lib/python3.6/site-packages/theano/compile/function_module.py", line 21, in import theano.compile.mode File "/usr/local/lib/python3.6/site-packages/theano/compile/mode.py", line 10, in import theano.gof.vm File "/usr/local/lib/python3.6/site-packages/theano/gof/vm.py", line 662, in from . import lazylinker_c File "/usr/local/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 127, in preargs=args) File "/usr/local/lib/python3.6/site-packages/theano/gof/cmodule.py", line 2316, in compile_str (status, compile_stderr.replace('\n', '. '))) Exception: Compilation failed (return status=1): /usr/bin/ld: /usr/local/lib/libpython3.6m.a(abstract.o): relocation R_X86_64_32S against `_Py_NotImplementedStruct' can not be used when making a shared object; recompile with -fPIC. /usr/local/lib/libpytho…
downvote count: 0
has comment: http://stackoverflow.com/comment/87823443
tagged with: pip
has comment: http://stackoverflow.com/comment/90145298
tagged with: python

http://stackoverflow.com/comment/87596715
has text: yes, it is working. And a side question, if I wish to assign this column a new name, then what should be the ideal thing??
comment on: http://stackoverflow.com/a/50290186
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87941225
has text: Hum, I think that `unique_together` or `through model` with signals are the only solutions to solve his issue.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50463785
type: Comment

http://stackoverflow.com/comment/87748114
score: 0
type: QuestionComment
has text: Could you please verify that replacing `href` value with `{% url 'file-format-error' %}` works fine?
type: Comment
comment on: http://stackoverflow.com/q/50365436

http://stackoverflow.com/a/50314516
answers question: http://stackoverflow.com/q/50314492
has body: d['a'] is a list. To add a single element to that list, either use append() or call extend() with an iterable (such as a list or a tuple): d['a'].append(34) d['a'].extend([34]) For further background, see What exactly are iterator, iterable, and iteration?
upvote count: 1
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87644929

http://stackoverflow.com/comment/87531773
comment on: http://stackoverflow.com/a/50256666
score: 0
has text: added in your refactor in the first bit
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87548842
score: 0
comment on: http://stackoverflow.com/q/50265399
type: Comment
has text: what is `component`?
type: QuestionComment

http://stackoverflow.com/comment/87525415
comment on: http://stackoverflow.com/a/50253808
score: 0
type: AnswerComment
has text: Now I receive this error `----> 3 nfkd_form = unicodedata.normalize('NFKD', input_str)` `TypeError: normalize() argument 2 must be unicode, not str`
type: Comment

http://stackoverflow.com/comment/87565671
type: Comment
type: AnswerComment
has text: @kasi_VN in vanilla Python?
comment on: http://stackoverflow.com/a/50274394
score: 0

http://stackoverflow.com/comment/87756968
type: Comment
score: 0
type: AnswerComment
has text: @ebong I have updated my answer to format big numbers.
comment on: http://stackoverflow.com/a/50365901

http://stackoverflow.com/comment/87615218
type: AnswerComment
comment on: http://stackoverflow.com/a/50298971
score: 0
has text: I believe that for his needs, `pandas` is a much better way to read the data from the csv files
type: Comment

http://stackoverflow.com/comment/87760699
comment on: http://stackoverflow.com/q/50370513
type: Comment
has text: No, that's not how binary programs work @BusyTraveller. Cython will generate a python extension which is loaded into the interpreter. Of course the interpreter is in the picture, it is responsible for loading the binary code. The C code is what interfaces with C library. The binary is an extension to the interpreter. Have a look at the Python standard library. It is written in C. It defines Python objects in C that allocate C data structures when the python object is created by the interpreter. Those same C data structures are de-allocated when the python object is garbage collected.
score: 1
type: QuestionComment

ibm-watson
tags question: http://stackoverflow.com/q/50366496
tag name: ibm-watson
type: Tag

http://stackoverflow.com/comment/87587617
type: QuestionComment
comment on: http://stackoverflow.com/q/50283031
has text: @ImportanceOfBeingErnest You are right, the point in 2D is a line in the 3D, but it has only finite number of intersections with the surface. Usually only one or two. I want to pick the one, which is closest to the viewer. Well, the Matplotlib seems to be able to resolve this properly, as it displays the desired coordinates in the bottom right corner of the window.
score: 0
type: Comment

http://stackoverflow.com/q/50371551
has title: How to Efficiently Scrape page results from a paginated list of links returned by a website's search functionality
answer count: 0
downvote count: 0
upvote count: 1
has body: I am trying to scrape the pages of an online retailer through their search functionality. As an example, when a request is sent to the url www.example.com/search the page returns a paginated list of links to all of the website's products. Every product page is more or less the same and as such relatively simple to scrape. The problem is that there are roughly 40,000 product page links returned and I want to scrape all of them initially loading up a database and then scheduling a scraper to run daily to add any new products. I want to know what a good approach would be to efficiently scrape those 40,000 product pages using scrapy. Right now my code is along the lines of: ExampleSpider(scrapy.Spider): next_page = 1 last_page = 100 start_urls = ['example.com/search?page={}'.format(next_page)] parse(self, response): yield scrapy.Request(response.url, callback=self.follow_product_links) yield scrapy.Request(response.url, callback=self.follow_pagination_links) follow_product_links(self,response): for href in selector_that_gets_all_the_product_links: yield response.follow(href, callback=self.parse_product) parse_product(self,response): # Scrape the product page and yield an item # details are not relevant to my problem follow_pagination_links(self,response): self.next_page += 1 if self.next_page &lt; self.last_page: url = 'example.com/search?page={}'.format(self.next_page) scrapy.Request(url, callback=self.parse) This isn't runnable code, but it should give you the idea of what I am trying to do. I know Scrapy is asynchronous which should certainly help, but are there any better techniques I could be using? As an aside I was hoping the website exposed a public API for querying their database, but sadly they do not.
tagged with: scrapy
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/comment/87776129
comment on: http://stackoverflow.com/a/50379840
has text: If I understand how your code is supposed to work, just move your initialization of `first_value` and `fifth_value` to right above and at the same level of indentation as your while statement.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87699762
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50341598
has text: Can we have [MCVE]?
score: 1

http://stackoverflow.com/comment/87669689
comment on: http://stackoverflow.com/a/50320846
has text: Yes, I agree. I just suggested a way to get what @Gayathri needs.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50318876
tagged with: python
has body: I am training (and saving) a very simple model in eager mode as follows: import os import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() NUM_EXAMPLES = 2000 training_inputs = tf.random_normal([NUM_EXAMPLES]) noise = tf.random_normal([NUM_EXAMPLES]) outputs = training_inputs * 3 + 2 + noise class Model(tf.keras.Model): def __init__(self): super(Model, self).__init__() self.W = tfe.Variable(5., name="weight") self.b = tfe.Variable(0., name="bias") def predict(self, input): return self.W * input + self.b def loss(model, inputs, outputs): error = model.predict(inputs) - outputs return tf.reduce_mean(tf.square(error)) def grad(model, inputs, outputs): with tf.GradientTape() as tape: loss_value = loss(model, inputs, outputs) return tape.gradient(loss_value, [model.W, model.b]) if __name__ == "__main__": model = Model() optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) for i in range(300): gradients = grad(model, training_inputs, outputs) optimizer.apply_gradients(zip(gradients, [model.W, model.b]), global_step=tf.train.get_or_create_global_step()) checkpoint_dir = './checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") root = tfe.Checkpoint(optimizer=optimizer, model=model, optimizer_step=tf.train.get_or_create_global_step()) root.save(file_prefix=checkpoint_prefix) The only ways I found to save/restore (with Checkpoint or Saver) imply having access to the Model class to load it elsewhere, for instance: model = Model() checkpointer = tfe.Checkpoint(model=model) checkpointer.restore(tf.train.latest_checkpoint('checkpoints/')) print(model.predict(7)) The save method from tf.keras.Model doesn't seem to be implemented yet for Eager mode: model.save("keras_model") &gt;&gt;&gt; NotImplementedError Is there another way to save and load the model without having to instantiate a new Model object?
has title: Restoring TF Eager model without using training code
score: 2
answer count: 0
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91911006
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/87685352
type: QuestionComment
has text: Very important to note, *Python doesn't have private attributes*. As the answers have notes, this has nothing to do with "bypassing a setter". Even in languages like Java with strongly enforeced private access modifiers, if your attribute is an object that you mutate then that change will be seen in the instance that attribute belongs to.
score: 0
comment on: http://stackoverflow.com/q/50333012
type: Comment

http://stackoverflow.com/a/50241487
score: 0
has body: If you're not planning on doing any fancy cross-validation and are basically looking to split the data into train and test sets, below is one way to do it. Caveats: I'm randomly generating data so I may be working around issues you won't be facing like datatype casting. Take-away: manually shuffle your data before-hand, use train_test_split (from sklearn) and set shuffle=False, then slice the numpy datasets to cut out the string columns and pass the numeric to the classifier. The slicing makes this example look ugly which is why I'd personally use pandas. Alternative way: slightly more advanced but you could use a pipeline and a custom transformer to select the numeric data from the overall data (not shown below). import numpy as np from scipy.stats import bernoulli import string, random from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split ### making up data, don't need to understand this part ### size = 10000 fnames = np.array([''.join(random.choices(string.ascii_letters, k=5)) for i in range(size)]) lnames = np.array([''.join(random.choices(string.ascii_letters, k=5)) for i in range(size)]) identifier = np.array([''.join(random.choices(string.ascii_letters, k=2)) for i in range(size)]) rand_ints = np.random.randint(0, 20, (size,10)) data = np.column_stack((fnames, lnames, identifier, rand_ints)) answers = bernoulli.rvs(0.3, size=size) ###---------------------------end----------------------### np.random.shuffle(data) # an in-place operation X_train, X_test, y_train, y_test = train_test_split( data, answers, test_size=0.10, random_state=42, shuffle=False) clf = MLPClassifier(solver='lbfgs', alpha=1e-5) clf.fit(X_train[:, 3:].astype('int16'), y_train) score = clf.score(X_test[:, 3:].astype('int16'), y_test) print('Test score: {}'.format(score)) pred = clf.predict(X_test[:, 3:].astype('int16')) X_train_result = np.column_stack((X_train[:, :3], y_train, clf.predict(X_train[:, 3:].astype('int16')))) X_test_result = np.col…
answers question: http://stackoverflow.com/q/50238979
type: Answer

http://stackoverflow.com/q/50375511
has answer: http://stackoverflow.com/a/50384540
has answer: http://stackoverflow.com/a/50397406
downvote count: 0
has comment: http://stackoverflow.com/comment/87767460
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87768326
tagged with: nginx
tagged with: uwsgi
favorite count: 0
type: Question
has body: I have I python-flask script running under uwsgi + nginx deployment configuration. My uwsgi.ini file: [uwsgi] pythonpath=/usr/bin/python3 socket=/tmp/grace.sock chmod-socket = 666 vacuum = true uid = www-data gid = www-data plugin= python3 chdir= /home/grace/pyRep/beta_grace module= app:app enable-threads= true master= true processes= 3 #cheaper= 1 logto = /home/grace/pyRep/beta_grace/uwsgi.log lazy-apps = true single-interpreter=true now, inside my script I have a function like this: from uwsgidecorators import * @timer(60) def foo(): global_var += 1 print(global_var) Looking at my logs i find: global_var: 1 global_var: 1 global_var: 1 In my opinion this is due to the lazy-apps options enabled, so after fork i have three copies of this task running and after some time I find: global_var: 34 global_var: 32 global_var: 32 I tried with the @lock and @postfork decorator before @timer decorator but nothing changes. If I take out lazy-apps option I have problems connecting to the mongoDB engine and other weird behaviours so I think that I have to keep it. The only solution I found is to limit processes to 1 but this obiouvsly decreases performances. Any advice?!
type: UnansweredQuestion
tagged with: python
tagged with: flask
has title: nginx + uwsgi + flask and multiprocess
answer count: 2

http://stackoverflow.com/q/50311985
tagged with: python
has comment: http://stackoverflow.com/comment/87640480
score: 0
has comment: http://stackoverflow.com/comment/87640565
has title: Does the Python interpreter check indents to be space or tab characters?
answer count: 1
has comment: http://stackoverflow.com/comment/87640577
has comment: http://stackoverflow.com/comment/87640573
type: Question
has comment: http://stackoverflow.com/comment/87640535
has comment: http://stackoverflow.com/comment/87640599
has answer: http://stackoverflow.com/a/50311998
has body: For example are 4 space characters equivalent to 1 tab character for new line indents? Or will it only scan for just one and not the other?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87640527

http://stackoverflow.com/comment/87644840
has text: https://en.wikipedia.org/wiki/Ordinal_data_type
score: 0
comment on: http://stackoverflow.com/q/50314440
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87776444
has text: @jhamman the main use case I have in mind is to store a word embedding model as an xarray with words as row labels.
score: 0
comment on: http://stackoverflow.com/q/50344033
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50295085
tagged with: subprocess
answer count: 1
upvote count: 1
downvote count: 1
has title: -regex: No such file or directory
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87606799
accepted answer: http://stackoverflow.com/a/50295182
has body: I tested a command to look for odt files in the current directory, find . -regex "*\.odt" -type f -maxdepth 1 The command works well on the terminal. When I tried using python subprocess as such subprocess.run(["find" , dirPath, " -regex", '".*\.odt"', "-type", "f", "-maxdepth", "1" ]) Where dirPath is the path to the directory I want to search in. The result, however, shows me the list of files in the directory and returns the error find: -regex: No such file or directory find: ".*level2\.odt": No such file or directory
has answer: http://stackoverflow.com/a/50295182
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50240057
has comment: http://stackoverflow.com/comment/89713856
upvote count: 10
score: 10
tagged with: python
has answer: http://stackoverflow.com/a/52322744
has title: Django Rest Framework custom schema for view in viewset
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89712199
has comment: http://stackoverflow.com/comment/89765897
downvote count: 0
answer count: 1
has body: I have an API built using Django and Django REST Framework. I have a model that returns some JSON that is built that doesn't correspond to a typical Django model. So the auto-documentation feature that seems to utilize knowledge about Django models doesn't work for some of my views. In particular, I have a viewset that returns some typical API views (like a list of objects), and some views that return some of my custom objects. I'd like to build documentation for these custom objects, but I am not sure how to override the schema for a particular endpoint within a viewset. How can I override the schema generated for a single view in a DRF viewset? DRF seems to provide this functionality for views, but I want to do the same for Viewsets.
tagged with: django
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/52322744
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/50303654
has body: I'm doing web scraping (I'm using miniconda) and I need to import the data that I got it using scrapy to a Mysql database but when I execute my program in Python 2.7 using Scrapy it says: no module name MySQLdb but I've installed the connection python mysql already so I don't know what is the problem... Connector/Python 8.0.11 Windows (x86, 64-bit), MSI Installer Python 2.7 I went to shell python and I executed >>import MySQLdb to verify if it's installed correctly and it says Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import MySQLdb ImportError: No module named MySQLdb I've looking for other solution and I installed a lot of other versions of this connector mysql but it doesn't work thanks in advance.
has comment: http://stackoverflow.com/comment/87624360
has title: no module name MySQLdb
score: 0
has comment: http://stackoverflow.com/comment/87635861
has comment: http://stackoverflow.com/comment/87624338
has comment: http://stackoverflow.com/comment/87624326
answer count: 0
has comment: http://stackoverflow.com/comment/87637821
tagged with: mysql-python
tagged with: mysql
tagged with: web-scraping
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/87624445
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87623695
tagged with: python

http://stackoverflow.com/q/50345780
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87707363
has body: I have many features that I need to vectorize and apply functions down the road. Rather than manually making copies of each DF, filtering down, then applying my various functions, I'd rather dynamically create new DF's based on the values contained with specified columns. Take my code down below for example. I'd like to take Column B and create three new dataframes. df_A, df_B, df_C. I've scoured a few dozen posts, but these are the closest I can find: Create new dataframe in pandas with dynamic names also add new column I wasn't able to get this to work, throwing an error at this bit dict_of_df[key_name] = copy.deepcopy(df) TypeError: unhashable type: 'numpy.ndarray' https://datascience.stackexchange.com/questions/29825/create-new-data-frames-from-existing-data-frame-based-on-unique-column-values I don't want to print lists, I want actual dataframes. Here's some different code I tried to put together, but is throwing an error with the range function, though I'm not sure why... import pandas as pd data = {'Column A': [100,200,300,400,500], 'Column B': ["A","A","B","B","C"]} df = pd.DataFrame(data, columns=['Column A','Column B']) df for i in range(len(df['Column B'].unique())): for item in df['Column B'].unique(): new_df[i] = df[df['Column B'] == item] new_df ValueError: Wrong number of items passed 2, placement implies 1 EDIT: Per the link that @jezrael provided in this post (the duplicate), his solution in that post met the need: for i, x in df.groupby('Column B'): globals()['dataframe' + i] = x
favorite count: 0
linked to: http://stackoverflow.com/q/40973687
has comment: http://stackoverflow.com/comment/87708027
linked to: http://stackoverflow.com/q/45114945
answer count: 0
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/87708051
duplicate of: http://stackoverflow.com/q/45114945
tagged with: dataframe
tagged with: loops
type: Question
has title: Dynamically create new Pandas dataframes from existing dataframe based on unique column values
has comment: http://stackoverflow.com/comment/87707473
has comment: http://stackoverflow.com/comment/87707575
type: UnansweredQuestion

http://stackoverflow.com/comment/87541944
comment on: http://stackoverflow.com/q/50261759
score: 0
type: Comment
type: QuestionComment
has text: Yes that it exactly it

http://stackoverflow.com/a/50292101
accepted answer of: http://stackoverflow.com/q/50291963
has body: Yes! You can use boto3 to interact with Athena. Particularly, you're going to probably want the start_query_execution method. http://boto3.readthedocs.io/en/latest/reference/services/athena.html#Athena.Client.start_query_execution
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50291963
has comment: http://stackoverflow.com/comment/87664715
has comment: http://stackoverflow.com/comment/87600309
upvote count: 8
type: Answer
score: 8
downvote count: 0

http://stackoverflow.com/a/50324319
answers question: http://stackoverflow.com/q/50323654
has body: Try the following code: df is your first dataframe, df1 is the second one res = pd.DataFrame() for text in df1.TEXT_DATA: res = res.append( df[df.apply(lambda row: row.KEYWORD in text or text in row.KEYWORD, axis=1)] ) print(res) Output: KEYWORD TICKET 0 Burst of bit errors 89814 3 wires stop passing traffic 60245 Here is another way to do it to get exactly the same as your expected output: res = pd.DataFrame(columns=['KEYWORD', 'TICKET', 'sentenced_data']) # create an empty dataframe to store the answer for text in df1.TEXT_DATA: # loop-through the second dataframe bools = df.apply(lambda row: row.KEYWORD in text or text in row.KEYWORD, axis=1) # return a boolean series if KEYWORD contains(by the "in" keyword in python) text or text contains KEYWORD if (bools.any()): # filter the df by the boolean series, append it to res, append the text to second column res = res.append(df[bools]) res.iloc[-bools.sum():, 2] = text res = res'KEYWORD', 'sentenced_data', 'TICKET' print(res) Output: KEYWORD sentenced_data TICKET 0 Burst of bit errors Burst of bit errors due to 89814 3 wires stop passing traffic stop passing traffic 60245 in keyword in python would return True if two string are partially match or 100% match; otherwise it return False.
has comment: http://stackoverflow.com/comment/87664807
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87664915
has comment: http://stackoverflow.com/comment/87666168
has comment: http://stackoverflow.com/comment/87666743
has comment: http://stackoverflow.com/comment/87665740
has comment: http://stackoverflow.com/comment/87665135
score: 1
has comment: http://stackoverflow.com/comment/87665840
type: Answer

http://stackoverflow.com/a/51248616
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50371607
type: Answer
has body: I'd suggest instantiating both app/db in app/init.py, so that app/db can be imported from a single place. After you've instantiate your manager, import the manager in run.py which is outside of the app directory and switch it between app.run()/ manager.run() model.py from app import db class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key = True) username = db.Column(db.String(120), unique = True, nullable = False) project/app/init.py def create_app(): app = Flask(__name__) return app app = create_app() # import this db to your model. db = SQLAlchemy(app) manager = Manager(app) manager.add_command('db', MigrateCommand) project/run.py # Placed from app import manager right above main block. from app import manager if __name__ == '__main__': # switch between run/manager based on your need. #manager.run() # for DB migration app.run(threaded=True, debug=True)

http://stackoverflow.com/q/50271807
has body: I'm trying to plot the predicted mean data from Gaussian process regression into a 3-D contour. I've followed Plot 3D Contour from an Image using extent with Matplotlib and mplot3d example code: contour3d_demo3.py threads. Following is my code: import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm x_train = np.array([[0,0],[2,2],[3,3]]) y_train = np.array([[200,321,417]]) xvalues = np.array([0,1,2,3]) yvalues = np.array([0,1,2,3]) a,b = np.meshgrid(xvalues,yvalues) positions = np.vstack([a.ravel(), b.ravel()]) x_test = (np.array(positions)).T kernel = C(1.0, (1e-3, 1e3)) * RBF(10) gp = GaussianProcessRegressor(kernel=kernel) gp.fit(x_train, y_train) y_pred_test = gp.predict(x_test) fig = plt.figure() ax = fig.add_subplot(projection = '3d') x=y=np.arange(0,3,1) X, Y = np.meshgrid(x,y) Z = y_pred_test cset = ax.contour(X, Y, Z, cmap=cm.coolwarm) ax.clabel(cset, fontsize=9, inline=1) plt.show() After running the above code, I get following error on console: I want x and y-axis as 2-D plane and the predicted values on the z-axis.The sample plot is as follows: What is wrong with my code? Thank you!
score: 3
upvote count: 3
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/18817110
accepted answer: http://stackoverflow.com/a/50285551
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/50285551
favorite count: 0
tagged with: mplot3d
type: Question
has title: How to plot regression predicted data in 3-D contour plot?
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/87648574
comment on: http://stackoverflow.com/q/50315982
type: QuestionComment
has text: It's also not clear what you mean by "most of values situated near 0.5" (for a distribution with `mean=0`).
type: Comment
score: 2

http://stackoverflow.com/comment/87715971
type: Comment
comment on: http://stackoverflow.com/q/50349559
score: 0
type: QuestionComment
has text: https://flask-migrate.readthedocs.io/en/latest/

http://stackoverflow.com/comment/87624774
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50304106
score: 0
has text: how were you trying to install it? It is not at all clear from your question

http://stackoverflow.com/comment/87678145
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50330066
has text: I have already tried passing x, y, z. That does not work. Python takes its x as an argument, not the value in it.
type: AnswerComment

http://stackoverflow.com/comment/87501206
has text: The whole point of errors is that you can `try/except` them and recover appropriately...
comment on: http://stackoverflow.com/q/50241742
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/50338278
has comment: http://stackoverflow.com/comment/87692842
downvote count: 0
has answer: http://stackoverflow.com/a/50338393
has body: I am confused about the slice operation. &gt;&gt;&gt; s = "hello world" &gt;&gt;&gt; y = s[::] &gt;&gt;&gt; id(s) 4507906480 &gt;&gt;&gt; id(y) 4507906480 # they are the same - no new object was created &gt;&gt;&gt; z = s[:2] &gt;&gt;&gt; z 'he' &gt;&gt;&gt; id(z) 4507835488 # z is a new object What allocation rule does slice operation follow?
has comment: http://stackoverflow.com/comment/87693594
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87692782
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50338393
linked to: http://stackoverflow.com/q/50037548
upvote count: 1
score: 1
tagged with: slice
favorite count: 0
type: Question
has title: Does slice operation allocate a new object always?

http://stackoverflow.com/comment/88743925
has text: Hi Jezreal. PLease can you look into this - https://stackoverflow.com/questions/50859373/convert-all-data-within-the-json-to-csv-using-pandas-or-python Thanks in advance :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50384929
score: 0
type: Comment

http://stackoverflow.com/comment/87549284
comment on: http://stackoverflow.com/q/50265439
score: 3
has text: And which operating system do you use? This is hard to solve on Windows, but on linux / ios you can use `pexpect`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87708666
score: 0
has text: @kazemakase Oh ok ;) btw, is there a short `numpy` way to zero-pad an array to the next power of 2?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50346006

http://stackoverflow.com/q/50354360
answer count: 1
has body: i have two list, one is column names and another one is data type and i would like to form a json. sample code: columnNameList = ["name", "age"] dataTypeList = ["string", "int"] colDataList = [{"colName": k, "dataType": v} for k, v in zip(columnNameList, dataTypeList)] colDataDict = {"schema": colDataList} print(colDataDict) The above code gives me the below output, but everything is enclosed with single quotes, why is that? also is this the best way of doing it? sample output: { 'schema':[ { 'colName':'name', 'dataType':'string' }, { 'colName':'age', 'dataType':'int' } ] }
has comment: http://stackoverflow.com/comment/87725111
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: list
score: -5
has answer: http://stackoverflow.com/a/50354451
has comment: http://stackoverflow.com/comment/87725078
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87725192
downvote count: 5
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87725104
has title: merge two lists to form a json
accepted answer: http://stackoverflow.com/a/50354451
upvote count: 0
linked to: http://stackoverflow.com/q/26745519

http://stackoverflow.com/q/50271245
downvote count: 1
has comment: http://stackoverflow.com/comment/87560276
has comment: http://stackoverflow.com/comment/87560351
has comment: http://stackoverflow.com/comment/87559935
has body: I am writing a discord bot, I want players to earn a daily reward, however I am not sure how I can allow the user to receive their reward every 24+hrs. I have tried many solutions but have come up with none. (Rewrite, EXT) Points to note: The bot will use json files to store the time in which the user claimed their daily bonus. There will be many users executing this pretty much at the same time so the feature must be able to be used by multiple people. Thanks to anyone who helps, even if it isn't too helpful.
has comment: http://stackoverflow.com/comment/87560192
has comment: http://stackoverflow.com/comment/87559606
has comment: http://stackoverflow.com/comment/87560570
has answer: http://stackoverflow.com/a/50280058
has comment: http://stackoverflow.com/comment/87560510
score: -1
has comment: http://stackoverflow.com/comment/87560117
has title: Daily reward help, Discord Bot
favorite count: 0
type: Question
tagged with: discord.py
has comment: http://stackoverflow.com/comment/87560242
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87576656
has comment: http://stackoverflow.com/comment/87560050
has comment: http://stackoverflow.com/comment/87560706
answer count: 1
tagged with: clock
has comment: http://stackoverflow.com/comment/87560301
has comment: http://stackoverflow.com/comment/87559978
tagged with: python
has comment: http://stackoverflow.com/comment/87560402
has comment: http://stackoverflow.com/comment/87559674
tagged with: counting
has comment: http://stackoverflow.com/comment/87560744

http://stackoverflow.com/q/50382094
upvote count: 6
has answer: http://stackoverflow.com/a/53938392
has answer: http://stackoverflow.com/a/62827521
has title: How to use Bootstrap 4 in Flask-Bootstrap?
tagged with: flask-bootstrap
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
score: 6
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87781541
tagged with: flask
has body: The automatic supplied css file of Flask-bootstrap is like this: &lt;link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"&gt; It is version 3. Is there any way to use bootstrap4 in flask-bootstrap? For now, I just change the css and js files to version 4 in my base template. But I am wondering if this will make some subtle problems.

http://stackoverflow.com/q/50284226
tagged with: sas
answer count: 0
type: UnansweredQuestion
has title: SPEDIS (SAS) equivalent in Python
has body: Would appreciate help in finding a Python equivalent of SAS's SPEDIS function, which compares the spelling distance between two strings. e.g. spedis('abc', 'abc')=0. Thank you!
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/87596395
has comment: http://stackoverflow.com/comment/104623471
upvote count: 3
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87756942
type: AnswerComment
has text: Thank you, this a very detailed and well implemented solution to the problem I was having.
type: Comment
comment on: http://stackoverflow.com/a/50362882
score: 0

pexpect
tags question: http://stackoverflow.com/q/50311564
tag name: pexpect
type: Tag

http://stackoverflow.com/comment/87773421
score: 1
has text: is df a sub-selection of a larger dataframe? In that case that sub-selection is still linked to the larger dataframe and you are not just changing a column of df, but also trying to change the slice of that bigger dataframe. Easy solution, wherever you define df = bigger_df[ix:ix] use: df = bigger_df[ix:ix].copy()
comment on: http://stackoverflow.com/q/50378594
type: QuestionComment
type: Comment

http://stackoverflow.com/q/50238397
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to send query to telegrambot by clicking a link, not a button?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/62913938
has body: I built a telegrambot in Python. I managed to send a keyboard with a message (allowing me to send callback queries to the bot) using this example. Now, if I only have one option, these buttons are a bit large in my opinion which is why I'd like to find another solution to send a callback query to the bot. Is there a way to send such a query by clicking a link inside a message? From the docs, I don't see an obvious way to do that. To provide more context: I built a command /reminder to schedule and send reminders (as Telegram messages, see attached screenshot). When a reminder is scheduled, the bot will send a message saying that the reminder was scheduled. In this message, I'd like to append a link "Delete" in the text (not as InlineKeyboardButton, because such a button would make this "FYI, I scheduled the reminder, just as you requested" message too large in my opinion) and clicking this link shall send a query to the bot which I then can use to remove the correct reminder from the jobqueue and database. The last message in the screenshot (when the reminder is actually sent and can be rescheduled via buttons) is only to show that the buttons indeed significantly increase the vertical space of such a message.
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-telegram-bot

http://stackoverflow.com/comment/87622378
type: Comment
score: 0
type: QuestionComment
has text: I see! Sorry still quite new to programming but getting there thanks to your help :)
comment on: http://stackoverflow.com/q/50302951

regex-lookarounds
tags question: http://stackoverflow.com/q/50280191
tag name: regex-lookarounds
type: Tag
tags question: http://stackoverflow.com/q/50374496
tags question: http://stackoverflow.com/q/50378567

http://stackoverflow.com/comment/87720183
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50350890
score: 0
has text: @iamkhush do you mind sharing some more details?

http://stackoverflow.com/comment/87539502
type: QuestionComment
comment on: http://stackoverflow.com/q/50260451
type: Comment
has text: I need not first value. I need sum all values _c by _b=3 for all _a
score: 0

http://stackoverflow.com/comment/87648493
type: Comment
comment on: http://stackoverflow.com/a/50315142
score: 0
type: AnswerComment
has text: toolz is really new for me. Thankyou so much. I was thinking to use float with itemgetter() but did not know that we can give 2 arguments like this.

http://stackoverflow.com/q/50342601
type: AnsweredQuestion
has body: I am running the following sparql in my code but I get an error. def get_parents_of_node(node): sparql = """select ?superclass where {{ :{0} rdfs:subClassOf* ?superclass }}""".format(node) q = g.query(sparql) for row in q: print row get_parents_of_node('http://cccc.com#LaptopHighPerformance') The error message is Traceback (most recent call last): File "C:\Code\Python\RDF Parser\RDF_Parser.py", line 244, in &lt;module&gt; get_parents_of_node('http://cccc.com#LaptopHighPerformance') File "C:\Code\Python\RDF Parser\RDF_Parser.py", line 68, in get_parents_of_node q = g.query(sparql) File "C:\Python27\lib\site-packages\rdflib\graph.py", line 1085, in query query_object, initBindings, initNs, **kwargs)) File "C:\Python27\lib\site-packages\rdflib\plugins\sparql\processor.py", line 74, in query parsetree = parseQuery(strOrQuery) File "C:\Python27\lib\site-packages\rdflib\plugins\sparql\parser.py", line 1058, in parseQuery return Query.parseString(q, parseAll=True) File "C:\Python27\lib\site-packages\pyparsing.py", line 1632, in parseString raise exc pyparsing.ParseException: Expected {SelectQuery | ConstructQuery | DescribeQuery | AskQuery} (at char 36), (line:2, col:9) [Finished in 3.8s with exit code 1] [shell_cmd: python -u "C:\Code\Python\RDF Parser\RDF_Parser.py"]
score: 1
accepted answer: http://stackoverflow.com/a/50342732
tagged with: python
has answer: http://stackoverflow.com/a/50342732
type: Question
tagged with: rdflib
has title: pyparsing.ParseException: Expected {SelectQuery | ConstructQuery | DescribeQuery | AskQuery}
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50355412
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50355846
accepted answer: http://stackoverflow.com/a/50355843
has comment: http://stackoverflow.com/comment/87727502
has answer: http://stackoverflow.com/a/50355843
has title: finding gappy sublists within a larger list
tagged with: python
possible better answer: http://stackoverflow.com/a/50355846
tagged with: list
answer count: 2
has body: Let's say I have a list like this: [['she', 'is', 'a', 'student'], ['she', 'is', 'a', 'lawer'], ['she', 'is', 'a', 'great', 'student'], ['i', 'am', 'a', 'teacher'], ['she', 'is', 'a', 'very', 'very', 'exceptionally', 'good', 'student']] Now I have a list like this: ['she', 'is', 'student'] I want to query the larger list with this one, and return all the lists that contain the words within the query list in the same order. There might be gaps, but the order should be the same. How can I do that? I tried using the in operator but I don't get the desired output.
score: 0
has comment: http://stackoverflow.com/comment/87727884
type: Question

http://stackoverflow.com/comment/87508493
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50240925
has text: I guess you are using client.get method in other places. `request.POST` Only handles form data. http://www.django-rest-framework.org/tutorial/2-requests-and-responses/
type: Comment

http://stackoverflow.com/q/50255454
tagged with: jinja2
type: Question
accepted answer: http://stackoverflow.com/a/51125187
has answer: http://stackoverflow.com/a/51125187
tagged with: wtforms
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: I'm trying to make a form to populate a calendar. The calendar can be five or seven days long, and I'd like to pass the number of days as an argument to the form. My form is defined like so: class LoadForecastForm(Form): def __init__(self, n_days, *args, **kwargs): self.n_days = n_days super(LoadForecastForm, self).__init__(*args, **kwargs) self.day_values = FieldList(SelectField('Day Values', coerce=str, choices=[('low', 'Low'), ('medium', 'Medium'), ('high', 'High'), ('holiday', 'Holiday')]), min_entries=n_days, max_entries=n_days) self.send = SubmitField('Send Calendar') It's rendered like so: &lt;form role="form" action="" method="POST"&gt; {{ form.hidden_tag() }} &lt;div class="form-group row"&gt; {% for field in form.day_values %} &lt;div class="col-sm-2"&gt; &lt;div class="form-group{% if field.errors %} error {% endif %}"&gt; {% if label %} {{ field.label }} {% endif %} {{ field(**kwargs) }} {% for error in field.errors %} &lt;span class="help-inline"&gt;[{{error}}]&lt;/span&gt;&lt;br&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; {{ form.send }} The form page is failing to render; the traceback ends with: File "project/populate_schedule.tpl.html", line 25, in block "page_content" {% for field in day_values %} TypeError: 'UnboundField' object is not iterable n_days used to be hardcoded, and the fields were defined as class variables with no __init__() function, and there were no errors. How do I correctly define the field programmatically? I am using Python 2.7.
tagged with: flask-wtforms
has title: How can I render a FieldList of variable length in WTForms?
answer count: 1

http://stackoverflow.com/comment/87581257
type: AnswerComment
comment on: http://stackoverflow.com/a/50282270
type: Comment
score: 0
has text: The solution looks promising. However, if I run your code, it removes column D entirely and all columns containing numeric values.

http://stackoverflow.com/a/50347017
has comment: http://stackoverflow.com/comment/87710229
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87710115
has body: As commented above, I'd recommend reading in all rows as rows of a dataframe, structured in two columns named frequency and loss: df = pd.read_table(_filepath_, sep=' [@GHz=dB ]+', header=None, usecols=[1,2], names=['frequency', 'Loss per inch'], engine='python') In: df Out: frequency Loss per inch 0 2.5 -0.474 1 5.0 -0.838 2 7.5 -0.955
accepted answer of: http://stackoverflow.com/q/50346449
has comment: http://stackoverflow.com/comment/87709956
has comment: http://stackoverflow.com/comment/87709882
has comment: http://stackoverflow.com/comment/87710584
type: Answer
has comment: http://stackoverflow.com/comment/87751954
answers question: http://stackoverflow.com/q/50346449
has comment: http://stackoverflow.com/comment/87710485
has comment: http://stackoverflow.com/comment/87711090
has comment: http://stackoverflow.com/comment/87711064
has comment: http://stackoverflow.com/comment/87710026
has comment: http://stackoverflow.com/comment/87711128
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/50297337
favorite count: 0
has answer: http://stackoverflow.com/a/50297397
type: Question
tagged with: python
has title: return new instance of current class
possible better answer: http://stackoverflow.com/a/50297397
tagged with: class
has body: i'd like to return a new instance of the current class, when an inherited class return it will return the base class instead of the current class class class1: def __init__(self): self.foo = 1 self.bar = 2 def new(self): return class1() class class2(class1): def __init__(self): super().__init__() c1 = class1() c2 = class2() print(c1.new()) print(c2.new()) this returns &lt;main.class1 object at 0x0000027B681E57F0> &lt;main.class1 object at 0x0000027B681E57F0> desired result &lt;main.class1 object at 0x0000027B681E57F0> &lt;main.class2 object at 0x0000027B681E57F0>
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50297390
accepted answer: http://stackoverflow.com/a/50297431
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50297431
tagged with: inheritance

http://stackoverflow.com/comment/87560213
score: 0
has text: like this : aver =[5.2 1.8 9 2 6.3 ... ]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50271399

http://stackoverflow.com/a/50280635
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50280193
type: AcceptedAnswer
has body: When you do this: Directed_G=nx.from_pandas_dataframe(data, 'from', 'to') it creates a graph from the pandas dataframe and assigns that result to the name Directed_G. It doesn't go and check first what sort of graph Directed_G was previously. So it creates a graph using the default type (which is Graph) and the previous graph that was stored in Directed_G is overwritten, lost to the great garbage collector in the sky. Then the command to find the cycles dies because it can't handle an undirected graph. Add the optional argument create_using=DiGraph to your call to from_pandas_dataframe. You should be aware that in the latest version of networkx from_pandas_dataframe has been removed: https://networkx.github.io/documentation/networkx-2.0/release/release_2.0.html Previously, the function from_pandas_dataframe assumed that the dataframe has edge-list like structures, but to_pandas_dataframe generates an adjacency matrix. We now provide four functions from_pandas_edgelist, to_pandas_edgelist, from_pandas_adjacency, and to_pandas_adjacency.
type: Answer
answers question: http://stackoverflow.com/q/50280193
upvote count: 2

http://stackoverflow.com/q/50308951
favorite count: 0
accepted answer: http://stackoverflow.com/a/50310620
has answer: http://stackoverflow.com/a/50309413
tagged with: conv-neural-network
has body: I'm trying to understand the transformation performed by tf.layers.conv2d. The mnist tutorial code from the TensorFlow website includes the convolution layer: # Computes 64 features using a 5x5 filter. # Padding is added to preserve width and height. # Input Tensor Shape: [batch_size, 14, 14, 32] # Output Tensor Shape: [batch_size, 14, 14, 64] conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) However, my expectation is that the 32 input images would be multiplied by the number of filters, as each filter is applied to each image, to give an output tensor of [batch_sz, 14, 14, 2048]. Clearly this is wrong, but I don't know why. How does the transformation work? The API documentation tells me nothing about how it works. What would be the output if the input tensor was [batch_size, 14, 14, 48]?
type: Question
has answer: http://stackoverflow.com/a/50310620
tagged with: python
tagged with: tensorflow
linked to: http://stackoverflow.com/q/42883547
has title: Understanding input/output tensors from tf.layers.conv2d
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50309413

http://stackoverflow.com/comment/87631554
has text: what do you mean by 'unread' ?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50307812

http://stackoverflow.com/q/50380295
has title: Remove rows with dates older than "today"
favorite count: 0
type: Question
score: 3
tagged with: pandas
tagged with: datetime
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50380338
has answer: http://stackoverflow.com/a/50380338
type: AnsweredQuestion
has body: I have been searching around here and google and have found many examples that show how to remove old dates based on a non moving date variable but can not figure out how to remove rows of data based on today's date going forward. In the example below, how would I go about removing anything older than today's date (should be one value removed) then save it? The real source file will continue to get new data everyday and I will need to be removing everything older than 'today' date. from datetime import datetime import pandas as pd data = {'date': ['2001-04-10 18:47:05.069722', '2018-05-16 18:47:05.119994', '2018-05-16 18:47:05.178768', '2018-05-16 18:47:05.230071', '2018-05-16 18:47:05.230071', '2018-05-16 18:47:05.280592', '2018-05-16 18:47:05.332662', '2018-05-16 18:47:05.385109', '2018-05-16 18:47:05.436523', '2018-05-16 18:47:05.486877'], 'battle_deaths': [34, 25, 26, 15, 15, 14, 26, 25, 62, 41]} df = pd.DataFrame(data, columns = ['date', 'battle_deaths']) df date battle_deaths 0 2001-04-10 18:47:05.069722 34 1 2018-05-16 18:47:05.119994 25 2 2018-05-16 18:47:05.178768 26 3 2018-05-16 18:47:05.230071 15 4 2018-05-16 18:47:05.230071 15 5 2018-05-16 18:47:05.280592 14 6 2018-05-16 18:47:05.332662 26 7 2018-05-16 18:47:05.385109 25 8 2018-05-16 18:47:05.436523 62 9 2018-05-16 18:47:05.486877 41
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/87615780
type: QuestionComment
has text: @Andersson Hah! It is inside an iframe!
score: 0
comment on: http://stackoverflow.com/q/50298553
type: Comment

http://stackoverflow.com/a/50379950
has body: You question is similar to this one. From the multiprocessing programming guidelines. Explicitly pass resources to child processes ... it is better to pass the object as an argument to the constructor for the child process. Apart from making the code (potentially) compatible with Windows ... On Windows, you need to pass the shared objects to the Process constructor list of arguments. Otherwise, the child process will get a brand new copy instead of the parent's one. That's why you get the impression the Semaphore isn't working. The two processes are creating their own distinct Semaphore object instead of sharing the same one. To pass a Semaphore object to a Pool on Windows you need to struggle a bit but not too much. As you cannot pass the Semaphore object to the writenum function directly, you need to rely on the Pool initializer. from multiprocessing import Semaphore, Pool mutex = None def initializer(semaphore): """This function is run at the Pool startup. Use it to set your Semaphore object in the child process. """ global mutex mutex = semaphore def writenum(args): with mutex: print "[+] - " + str(number) def main(): semaphore = Semaphore() pool = Pool(initializer=initializer, initargs=[semaphore]) numbers = range(50) pool.map(writenum, numbers) EDIT: just noticed I wrote about Lock instead of Semaphore. The core reasoning remains the same.
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/50379009
has comment: http://stackoverflow.com/comment/87799536
has comment: http://stackoverflow.com/comment/87836886
accepted answer of: http://stackoverflow.com/q/50379009
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87799806
has comment: http://stackoverflow.com/comment/87800238
score: 5

http://stackoverflow.com/comment/87813728
type: AnswerComment
has text: @Nazan Yes, perfectly. If you're only looking for integers, you can drop the non-capture group as well.
score: 0
comment on: http://stackoverflow.com/a/50360704
type: Comment

http://stackoverflow.com/comment/87590322
score: 0
has text: I don't see clear question.
comment on: http://stackoverflow.com/q/50283552
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50277490
has answer: http://stackoverflow.com/a/50278344
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50278108
has title: How to determine correlation from dataframe with Nan?
answer count: 2
has answer: http://stackoverflow.com/a/50278108
tagged with: pandas
score: 1
downvote count: 0
tagged with: nan
favorite count: 0
type: Question
has body: I use method DataFrame.corr() from Pandas. As result it return matrix of correlation, but it removes columns where were even one Nan value. Is possible to compute correlation in DataFrame with Nan?
tagged with: correlation
possible better answer: http://stackoverflow.com/a/50278344
upvote count: 1
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/70260077
has comment: http://stackoverflow.com/comment/130456085
score: 13
has comment: http://stackoverflow.com/comment/132633094
type: Answer
has comment: http://stackoverflow.com/comment/130542756
upvote count: 13
answers question: http://stackoverflow.com/q/50246304
has body: The third-party retry module is an option for this purpose. You can also pass the list of exceptions to retry for, number of retries, delays, maximum delay, exponential back-off, etc. $ pip install retry Example usage: from retry import retry @retry(ZeroDivisionError, tries=3, delay=2) def make_trouble(): '''Retry on ZeroDivisionError, raise error after 3 attempts, sleep 2 seconds between attempts.'''
has comment: http://stackoverflow.com/comment/134992091
downvote count: 0

http://stackoverflow.com/comment/87723621
score: 0
comment on: http://stackoverflow.com/q/50353506
type: QuestionComment
has text: SWIG predates Python `enum`s by quite a bit. The maintainers will have to add support for `enum`s before you can do that. As far as I know that hasn't happened yet.
type: Comment

http://stackoverflow.com/a/50359846
answers question: http://stackoverflow.com/q/50359777
score: 1
upvote count: 1
has body: import csv lineNumber = 0 with open('test', 'r') as f: reader = csv.reader(f, delimiter=",") for row in reader: if row[0] == 'Line number': lineNumber = row[1] else: if row[0] == lineNumber: print 'isEqual for row ',row
downvote count: 0
type: Answer

http://stackoverflow.com/comment/106589535
comment on: http://stackoverflow.com/a/50518676
type: AnswerComment
has text: @myfunnyfella, how could you explain more how you did that?
score: 0
type: Comment

http://stackoverflow.com/comment/87814710
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50377510
has text: Is there any way to save features for an entire dataset or should i extract one image at time?

http://stackoverflow.com/comment/87508526
has text: If you don’t provide a value for content_type, the values in data will be transmitted with a content type of multipart/form-data. https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client.post
type: AnswerComment
comment on: http://stackoverflow.com/a/50240925
score: 0
type: Comment

http://stackoverflow.com/q/50283619
type: Question
score: -2
has body: Write a binary_search function which at each step prints the list being searched as in the following output. It shows both the sublist currently being searched and then how that gets split into two parts around the midpoint. This is what I have tried, but still struggle to find the solution: def binary_search(a_list, item): print(a_list) # just to show the search area if a_list == []: return False midpoint = len(a_list) // 2 element = a_list[midpoint] if item == element: return True elif item &lt; element: # first half return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1:], item) Given Input: test_list = [0,1,2,8,13,17,19,32,42] binary_search(test_list,3) binary_search(test_list,13) Expected output: [0, 1, 2, 8, 13, 17, 19, 32, 42] [0, 1, 2, 8] 13 [17, 19, 32, 42] [0, 1, 2, 8] [0, 1] 2 [8] [8] [] 8 [] [] [0, 1, 2, 8, 13, 17, 19, 32, 42] [0, 1, 2, 8] 13 [17, 19, 32, 42]
has title: Python Hashing binary search
tagged with: python
has answer: http://stackoverflow.com/a/50283662
accepted answer: http://stackoverflow.com/a/50283662
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87583691
has comment: http://stackoverflow.com/comment/87583638
favorite count: 0

http://stackoverflow.com/comment/87632559
comment on: http://stackoverflow.com/a/50307477
type: Comment
has text: Ho Jerzael,, i imported csv file to dataframes so they have same columns name .. `'EMPLOYEE_NUMBER', 'LAST_NAME', 'FIRST_NAME', 'MIDDLE_NAME', 'BRANCH', 'DEPARTMENT', 'LEVEL', 'POSITION', 'EMAIL_ADDRESS'` is list column name. Values in column is text and number.. Thanks
type: AnswerComment
score: 0

http://stackoverflow.com/a/50301728
score: 1
upvote count: 1
has body: You don't need many changes to your code. Main restructuring involves to move all exceptions like repetition of names and no input to the top of the loop. More explanations are integrated in the comments. def function(): x = [] #no need to keep track of the number of members, the list length will give us this information #infinite loop that will be interrupted, when no input is given while True: #determine length of list, +1 because Python index starts with 0 n = len(x) + 1 #ask for input, format prints the number into the bracket position name = input("{}. Enter a member: ".format(n)) #check if name already in list if name in x: #if name in list, ignore the input and start while loop again continue #no input - print out members and stop if not name: print("Members:") #get for each member the index number i for i, member in enumerate(x): #print index in position {0} and member name in position {1} print("{0}. {1}".format(i + 1, member)) #leave function() return #append name and sort list x.append(name) x.sort() #print list print("Names:", x) function()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50301594

http://stackoverflow.com/q/50336562
tagged with: anaconda
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54987221
tagged with: conda
score: 2
has answer: http://stackoverflow.com/a/52279683
upvote count: 2
answer count: 2
downvote count: 0
has body: I'm trying to run conda env create command in terminal, but I'm getting the following error: `(base) *******-MBP:Tensorflow-Bootcamp-master ******$ conda env create -f tfdl_env.yml Solving environment: failed ResolvePackageNotFound: - libpng==1.6.30=vc14_1 - six==1.10.0=py35_1 - tk==8.5.18=vc14_0 - openssl==1.0.2l=vc14_0 - icu==57.1=vc14_0 - wincertstore==0.2=py35_0 - zlib==1.2.11=vc14_0 - vs2015_runtime==14.0.25420=0 - jpeg==9b=vc14_0 - win_unicode_console==0.5=py35_0 - qt==5.6.2=vc14_6` I've tried updating Conda, but that's not working. Do I need to manually install each of these packages? I tried manually installing zlib, but it didn't remove it from the list of packages. Thanks!
has title: Conda ResolvePackageNotFound Error
favorite count: 0
type: Question

http://stackoverflow.com/q/50366883
has comment: http://stackoverflow.com/comment/87750338
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/49757899
has body: I am trying to find a good way to calculate mean values from values in a dataframe. It contains measured data from an experiment and is imported from an excel sheet. The columns contain the time passed by, electric current and the corresponding voltage. The current is changed in steps and then held for some time (the current values vary a little bit, so they are not exactly the same for each step). Now I want to calculate the mean voltage for each current step. Since it takes some time after the voltage gets stable after a step, I also want to leave out the first few voltage values after a step. Currently I am doing this with loops, but I was wondering wether there is a nicer way with the usage of the groupby function (or others maybe). Just say if you need more details or clarification. Example of data: s [A] [V] 0 6.0 -0.001420 0.780122 1 12.0 -0.002484 0.783297 2 18.0 -0.001478 0.785870 3 24.0 -0.001256 0.793559 4 30.0 -0.001167 0.806086 5 36.0 -0.000982 0.815364 6 42.0 -0.003038 0.825018 7 48.0 -0.001174 0.831739 8 54.0 0.000478 0.838861 9 60.0 -0.001330 0.846086 10 66.0 -0.001456 0.851556 11 72.0 0.000764 0.855950 12 78.0 -0.000916 0.859778 13 84.0 -0.000916 0.859778 14 90.0 -0.001445 0.863569 15 96.0 -0.000287 0.864303 16 102.0 0.000056 0.865080 17 108.0 -0.001119 0.865642 18 114.0 -0.000843 0.866434 19 120.0 -0.000997 0.866809 20 126.0 -0.001243 0.866964 21 132.0 -0.002238 0.867180 22 138.0 -0.001015 0.867177 23 144.0 -0.000604 0.867505 24 150.0 0.000507 0.867571 25 156.0 -0.001569 0.867525 26 162.0 -0.001569 0.867525 27 168.0 -0.001131 0.866756 28 174.0 -0.001567 0.866884 29 180.0 -0.002645 0.867240 .. ... ... ... 242 1708.0 24.703866 0.288902 243 1714.0 26.469208 0.219226 244 1720.0 26.468838 0.250437 245 1726.0 26.468681 0.254972 246 1732.0 26.468173 0.271525 247 1738.0 26.468260 0.247282 248 1744.0 26.467666 0.296894 249 1750.0 26.468085 0.247300 250 1756.0 26.468085 0.247300 251 1762.0 26.467808 0.261096 252 1768.0 26.467958 0.259615 253 1774.0 26.467828…
has title: Calculate mean values from pandas dataframe
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: mean
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/90421731
type: Question
has answer: http://stackoverflow.com/a/50366994
has comment: http://stackoverflow.com/comment/87750046

http://stackoverflow.com/q/50266568
type: Question
upvote count: 2
tagged with: python-3.x
downvote count: 2
has title: How to increment a list in python containing both numbers and characters?
has comment: http://stackoverflow.com/comment/87552753
has comment: http://stackoverflow.com/comment/87550921
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/50266626
tagged with: python
has body: I have a list as [1,2,3,a,b,M] and need to increment every variable by 1 . I have tried for number I can use as : a = [1,2,3] for i in range(len(a)): a[i] += 1 print a Also for characters I can use : ch = 'M' x = chr(ord(ch) + 1) print ("The incremented character value is : ") print (x) But together I am not able to club it. Is there anyway by which i can club it?
favorite count: 0
has comment: http://stackoverflow.com/comment/87551072
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/87551491

http://stackoverflow.com/a/50374857
answers question: http://stackoverflow.com/q/50362074
score: 0
has body: You can use recursion: d = [{'A': ['B', 'C', 'D']}, {'B': ['E', 'F']}, {'C': ['E']}, {'F': ['G', 'H']}] d1 = dict(list(i.items())[0] for i in d) def flatten_structure(d, root = 'A'): if root: return {root:flatten_structure(d1[root], None)} return {i:flatten_structure(d1[i], None) if i in d1 else None for i in d} print(flatten_structure(d1['A'])) Output: {'A': {'B': {'E': None, 'F': {'G': None, 'H': None}}, 'C': {'E': None}, 'D': None}}
type: Answer

http://stackoverflow.com/comment/87774098
has text: What output are you expecting?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/50378928

http://stackoverflow.com/comment/87520658
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50251705
type: Comment
has text: @BcK, from python3.6 they maintain insertion order, https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation. So they will be always ordered.

http://stackoverflow.com/q/50331539
tagged with: python
has title: plot multiple processes graph in python
tagged with: graph
accepted answer: http://stackoverflow.com/a/50331962
has answer: http://stackoverflow.com/a/50331962
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I am trying to plot multiple processes data against each process name in the form of the line. A line represents the time the process was alive and the gap represents the time process was idle. x_axis_data1 = [1,2,3,4,5,6,7,8] x_axis_data2 = [1,2,3,4,5,6,7,8] x_axis_data3 = [1,2,3,4,5,6,7,8] alive_for_time = 6 sleep_for_time = 2 plt.plot(x_axis_data1, "process1", dashes = [alive_for_time, sleep_for_time]) plt.plot(x_axis_data2, "process2", dashes = [alive_for_time, sleep_for_time]) plt.plot(x_axis_data3, "process3", dashes = [alive_for_time, sleep_for_time]) plt.show() I am not sure how to plot against a string in pyplot. Now, I have this error: ValueError: Illegal format string "process1"; two marker symbols
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/a/50331511
score: 5
type: AcceptedAnswer
downvote count: 0
has body: You should increment the value of a regardless of if it's a multiple of 3 or 5 while( a &lt;= 1000): if (a%3 == 0 or a%5 == 0): suma = suma + a a = a + 1 Currently, it is never getting past a = 1 because 1 is neither a multiple of 3 nor 5 so it never increments
accepted answer of: http://stackoverflow.com/q/50331475
has comment: http://stackoverflow.com/comment/87764916
upvote count: 5
answers question: http://stackoverflow.com/q/50331475
type: Answer

pip
tags question: http://stackoverflow.com/q/50374464
tags question: http://stackoverflow.com/q/50380624
tags question: http://stackoverflow.com/q/50315645
tags question: http://stackoverflow.com/q/50360615
tags question: http://stackoverflow.com/q/50277848
tags question: http://stackoverflow.com/q/50274084
tags question: http://stackoverflow.com/q/50344114
tags question: http://stackoverflow.com/q/50251435
tags question: http://stackoverflow.com/q/50363356
tags question: http://stackoverflow.com/q/50376990
tags question: http://stackoverflow.com/q/50351567
tags question: http://stackoverflow.com/q/50249571
tags question: http://stackoverflow.com/q/50347920
tags question: http://stackoverflow.com/q/50316939
tags question: http://stackoverflow.com/q/50305112
tags question: http://stackoverflow.com/q/50361217
tags question: http://stackoverflow.com/q/50352396
tags question: http://stackoverflow.com/q/50380899
tags question: http://stackoverflow.com/q/50247464
tags question: http://stackoverflow.com/q/50316006
tags question: http://stackoverflow.com/q/50344228
type: Tag
tags question: http://stackoverflow.com/q/50250345
tags question: http://stackoverflow.com/q/50343626
tags question: http://stackoverflow.com/q/50266110
tags question: http://stackoverflow.com/q/50250310
tags question: http://stackoverflow.com/q/50355080
tags question: http://stackoverflow.com/q/50243762
tags question: http://stackoverflow.com/q/50248524
tags question: http://stackoverflow.com/q/50263933
tags question: http://stackoverflow.com/q/50266075
tags question: http://stackoverflow.com/q/50307018
tags question: http://stackoverflow.com/q/50283741
tags question: http://stackoverflow.com/q/50281510
tags question: http://stackoverflow.com/q/50361143
tags question: http://stackoverflow.com/q/50285525
tags question: http://stackoverflow.com/q/50288006
tag name: pip
tags question: http://stackoverflow.com/q/50249629
tags question: http://stackoverflow.com/q/50365651
tags question: http://stackoverflow.com/q/50325986
tags question: http://stackoverflow.com/q/50294552
tags question: http://stackoverflow.com/q/50269943
tags question: http://stackoverflow.com/q/50336667
tags question: http://stackoverflow.com/q/50378639
tags question: http://stackoverflow.com/q/50246442
tags question: http://stackoverflow.com/q/50235010
tags question: http://stackoverflow.com/q/50356168
tags question: http://stackoverflow.com/q/50281252
tags question: http://stackoverflow.com/q/50339918
tags question: http://stackoverflow.com/q/50384771
tags question: http://stackoverflow.com/q/50364980
tags question: http://stackoverflow.com/q/50356741
tags question: http://stackoverflow.com/q/50368390

http://stackoverflow.com/comment/87751294
type: Comment
type: AnswerComment
has text: @RickyRobinson - Pretty much. Blame it on the way built-ins are implemented. If you really find it too annoying, you can always override the `len()` built-in to check if the target object has `__len__()` and call that, otherwise revert to the built-in `len()`.
comment on: http://stackoverflow.com/a/50367338
score: 0

http://stackoverflow.com/comment/87598910
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50287717
type: Comment
has text: @PrakashGanesan input should work under linux - figuring out why it doesn't is probably the solution you actually want. In terms of filtering, check `keystate`: http://python-evdev.readthedocs.io/en/latest/apidoc.html#evdev.events.KeyEvent

http://stackoverflow.com/comment/87484685
has text: The function above works, yet If I add more values after **kwargs it will have syntax error, so I would like to know what to do
comment on: http://stackoverflow.com/q/50232893
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50294471
has body: code_null.loc[:,'code'] = code_null['blockname'].apply(__f,args=(code_name,)).copy()
type: Answer
has comment: http://stackoverflow.com/comment/87638843
score: 0
answers question: http://stackoverflow.com/q/50293524

http://stackoverflow.com/q/50374236
type: Question
tagged with: image-recognition
has body: I am trying to implement LeNet-5 in tensorflow right now, as described in http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf. I am having a little bit of trouble defining C3 (7 page last paragraph-8 page first paragraph) since I don't know how to specifically tell the network which feature maps from S2 are connected to which from C3 (i.e. I only know how to connect all the feature maps). My code is: def LeNet(x): # Hyperparameters for initliazitation of weights mu = 0 sigma = 0.1 #This is the first convolutional layer C1 #Initialize weights for the first convolutional layer. 6 feature maps connected to #one (1) 5x5 neighborhood in the input. 5*5*1*6=150 trainable parameters C1_w = tf.Variable(tf.truncated_normal(shape = [5,5,1,6],mean = mu, stddev = sigma)) #Bias for each feature map. 6 parameters, with the weights we have 156 parameters C1_b = tf.Variable(tf.zeros(6)) #Define the convolution layer with the weights and biases defined. C1 = tf.nn.conv2d(x, C1_w, strides = [1,1,1,1], padding = 'VALID') + C1_b #LeCun uses a sigmoidal activation function here. #This is the sub-sampling layer S2 #Subsampling (also known as average pooling) with 2x2 receptive fields. 12 parameters. S2 = tf.nn.avg_pool(C1, ksize = [1,2,2,1], strides = [1,2,2,1], padding = 'VALID') #The result is passed to a sigmoidal function S2 = tf.nn.sigmoid(S2) #Another convolutional layer C3. #Initlialize weights. 16 feature maps connected connected to 5*5 neighborhoods C3_w = tf.Variable(tf.truncated_normal(shape = [5,5,6,16], mean = mu, stddev = sigma)) #This is the line I would want to change. C3_b = tf.Variable(tf.zeros(16)) Right know the code is working (of course with the rest of the code attached, just showing the important part), but I am not doing what the paper describes and I would want to follow it more closely. I have 5x5x6x16=2400+16=2416 trainable parameters in C3 and the network is supposed to have 1516 trainable parameters here. Maybe is it possible to define C3_w as a matrix where …
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50375457
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
tagged with: deep-learning
score: 1
answer count: 1
has title: TensorFlow: Implementing Networks where all if one layer's feature map is not connected to all of the next layer's feature map
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/87657566
type: Comment
comment on: http://stackoverflow.com/a/50320835
type: AnswerComment
score: 1
has text: You beat me to it, but I used: `r'\bz\b'` for my RE (imagine "buzz"). Possibly helpful t give the meaning of `\b`?

http://stackoverflow.com/q/50236637
has body: I am trying to find a nice Pythonic way for finding all possible combinations of splitting a list into two groups, as in the following example: my_array = [A,B,C] The output should be: [[[A],[B]] [[A],[B,C]] [[A],[C]] [[A,B],[C]] [[A,C],[B]] [[B],[A]] [[B],[A,C]] [[B],[C]] [[B,C],[A]] [[C],[A]] [[C],[A,B]] [[C],[B]]] Thanks!
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50237036
score: 1
has comment: http://stackoverflow.com/comment/87490770
tagged with: grouping
has answer: http://stackoverflow.com/a/50237036
tagged with: python
has comment: http://stackoverflow.com/comment/87490774
type: AnsweredQuestion
has title: Python - finding all possible grouping of elements in a list
tagged with: list
has comment: http://stackoverflow.com/comment/87490689
has comment: http://stackoverflow.com/comment/87490893
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50324789
accepted answer: http://stackoverflow.com/a/50324890
has title: Python check for duplicate and null values in two list and map them
has answer: http://stackoverflow.com/a/50324890
type: AnsweredQuestion
score: 0
answer count: 3
has body: I have two list of name and numbers which contains some blank and duplicate entries phone = ['918222822','92929129','','92929129','','12345678','12345678','1727398',''] name = ['jhon', 'ele', '' , 'ele', '' , 'rock','rock','','burh'] If you see most of the numbers map to a name. There is a case where I have entry for number for blank for name or vice-versa. This is what is have tried so far: phone = ['918222822','92929129','','92929129','','12345678','12345678','1727398',''] name = ['jhon', 'ele', '' , 'ele', '' , 'rock','rock','','burh'] phone = set(phone) name = set(name) for na, ph in zip(name,phone): if na is None: na = ph elif ph is None: #do something pass print(na,ph) What I am trying to get as output is: Output jhon 918222822 ele 92929129 rock 12345678 1727398 1727398 # if number found but not name then put number in name # if only name found but no corresponding number then delete entries in both list
possible better answer: http://stackoverflow.com/a/50324810
tagged with: python
has answer: http://stackoverflow.com/a/50324810
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50324968

http://stackoverflow.com/comment/87771649
comment on: http://stackoverflow.com/q/50372481
score: 0
has text: Nothing is written...Well, try the Fortran [`flush`](https://software.intel.com/en-us/node/679280) intrinsic, maybe. Or try writing with the [`iomsg`](https://software.intel.com/en-us/node/680026) specifier or other error indicators to return a msg about possible issues.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87770231
type: QuestionComment
comment on: http://stackoverflow.com/q/50376329
has text: please cover your print statement with closing parenthesis like `print(s)`.
type: Comment
score: 0

http://stackoverflow.com/a/50336024
has body: Using list compresion and adding a new function: def match_with_set(string_a, set_b, threshold=0.8): for string in set_b: if match(string_a, string, threshold): return True return False intersection_set = set([ string for string in set_a if match_with_set(string, set_b)])
answers question: http://stackoverflow.com/q/50335886
type: Answer
score: 0

http://stackoverflow.com/comment/87606552
type: QuestionComment
has text: The `global` directive is used inside functions, to allow them to assign to global names. But there are no functions in your code, and a `global` directive in the global scope does nothing.
type: Comment
comment on: http://stackoverflow.com/q/50294906
score: 3

http://stackoverflow.com/q/50260499
type: Question
has comment: http://stackoverflow.com/comment/87541967
linked to: http://stackoverflow.com/q/11411681
tagged with: python
linked to: http://stackoverflow.com/q/13640298
has comment: http://stackoverflow.com/comment/87542373
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/10894706
score: 0
answer count: 0
has title: sqlAlchemy to access blob via a hybrid propery?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87543056
has body: I'm trying to add a block of text into a sqlAlchemy table, which I want to compress to save space with it. Looking through various answers I came up with what I think should be working, but is not. I'm working with a sqlite database. Updated: Was pointed out I was attempting to use mysql on sqlite which I wasn't aware that was what was happening. I adjusted to use zlib instead and it works to a degree, which gives me a new error that I do not understand. # proper imports and stuff to make this work from sqlalchemy import func class Data(Base): __tablename__ = 'data' # ... text_blobbed = Column('text', BLOB) @hybrid_property def text(self): # return func.decompress(self.text_blobbed) return self.text_blobbed.decode("zlib") @text.setter def text(self, stuff): # self.text_blobbed = func.compress(stuff) self.text_blobbed = stuff.encode("zlib") old error from func. sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such function: compress [SQL: ...... ] I can now add in the text via Data.text = "a really big block of text" But when I go to query for this like session.query(Data.text).filter(Data.id.like(2)).first() I get an error: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Data.text_blobbed has an attribute 'decode' Doing this is fine. r = session.query(Data).filter(Data.id.like(2)).first() print r.text I've also looked at the text_blobbed which is a set(). And I can do this that works: r = session.query(Data.text_blobbed.filter( ... ).first()[0].decode("zlib") print r But if I move that [0] into the hybrid_property for ... return self.text_blobbed[0].decode("zlib") and query: r = session.query(Data.text).filter( ... ).first() I get the error: NotImplementedError: Operator 'getitem' is not supported on this expression So, I'm a bit confused still. I've been looking at these things: SQLAlchemy - Writing a hybrid method for child count mysql Compress() with sqlalchemy SELECT UNCOMPRESS(text) FROM with sqlalche…

http://stackoverflow.com/comment/87777564
score: 0
has text: @MartinPrikryl i have now updated the question :D
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50371683

cqlengine
tags question: http://stackoverflow.com/q/50260368
type: Tag
tag name: cqlengine

http://stackoverflow.com/q/50334685
type: Question
score: 1
has body: I'm trying to take a file with a format like: # Comments # More comments 1,foo,bar,1 1,foo,bar,2 21,foo,bar,8 end_of_file and process it into a list like: listing = [[1,'foo','bar',1], [1,'foo','bar',2], [21,'foo','bar',8]] Currently, I'm running something similar to: listing = [] with open('foo_file.cfg','r') as f: for line in f: if line[0].isDigit: listing.append(line) # i've also tried listing.append([line]) Obviously, I'm ending up with: [['1,foo,bar,1'],['1,foo,bar,2'],['21,foo,bar,8']] I know I can split the line by comma, rebuild a new list, then append the list to listing. I'm definitely willing to do that if it's the proper way, but I thought their might be something cleaner. I know the csv module would read the whole file into a proper format, but I'm not sure how it would deal with selectively removing certain data, such as the comments.
tagged with: python
answer count: 4
accepted answer: http://stackoverflow.com/a/50334760
has title: How can I selectively place line from File into List
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
has answer: http://stackoverflow.com/a/50334760
upvote count: 2
has answer: http://stackoverflow.com/a/50335014
possible better answer: http://stackoverflow.com/a/50334807
downvote count: 1
has answer: http://stackoverflow.com/a/50334807
favorite count: 0
has answer: http://stackoverflow.com/a/50334886

http://stackoverflow.com/a/50363417
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50358481
has body: At the model level, you can override the clean() method of your model to implement that check every time a University instance is saved. def clean(self): if self.sister_university.id == self.id: raise ValidationError('A university object can never be its own sister_university.')
answers question: http://stackoverflow.com/q/50358481
score: 0

http://stackoverflow.com/comment/87770531
has text: with global size, you say how many work-items you want to have. It can be a 1d, 2d or 3d tuple, e.g. you want to change the brightness of a 320x240px image -> just use (320, 240) as global size. With local size, you say how many work-items you want to put in a work-group, i.e. you partition your work-items. Items in a work-group can work together, e.g. they can share fast local memory. Because you partition your global size with your local size into groups, both must have the same dimension, e.g. g.s=(1,10) and l.s.=(1,2) gives 5 groups. If you don't care about work-groups, just put None.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50373589

http://stackoverflow.com/a/50274601
type: Answer
has comment: http://stackoverflow.com/comment/87566445
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/87566027
has body: np.split and np.flatnonzero The point here is to create a boolean array that identifies where the value changes among being negative, positive, or zero while also not being zero. This will find the beginnings of groups. a = np.sign(df.x.values) b = np.append(False, a[:-1] != a[1:]) splits_dict = dict(enumerate(np.split(df, np.flatnonzero(a.astype(bool) &amp; b)))) pd.concat(splits_dict) x y 0 0 -5 25 1 -7 32 2 -3 33 3 0 22 1 4 1 16 5 6 10 6 3 36 7 0 22 8 0 55 2 9 -10 24 10 -9 32 11 -8 5 3 12 11 4 13 17 9 14 13 88 15 0 14 16 0 12 17 0 0 18 0 10 19 0 96 4 20 -1 492 21 -9 -440 22 -3 34 set_index If the intention is to embed the information back into the dataframe, we could have just done: a = np.sign(df.x.values) b = np.append(False, a[:-1] != a[1:]) c = (a.astype(bool) &amp; b).cumsum() df.set_index([c, df.index]) x y 0 0 -5 25 1 -7 32 2 -3 33 3 0 22 1 4 1 16 5 6 10 6 3 36 7 0 22 8 0 55 2 9 -10 24 10 -9 32 11 -8 5 3 12 11 4 13 17 9 14 13 88 15 0 14 16 0 12 17 0 0 18 0 10 19 0 96 4 20 -1 492 21 -9 -440 22 -3 34
answers question: http://stackoverflow.com/q/50274268

http://stackoverflow.com/q/50278120
score: 0
has title: Converting a cURL command to a python request
linked to: http://stackoverflow.com/q/35939761
answer count: 1
linked to: http://stackoverflow.com/q/3252851
has answer: http://stackoverflow.com/a/50278928
has comment: http://stackoverflow.com/comment/87573577
has body: I am new to cURL; I wanted to convert a curl command of this structure: curl -X POST "http://127.0.0.1:8881/models/faewrfaw/v1/predict" -H "Content-Type:multipart/form-data" -F "data={\"key\": \"Path\"};type=application/json" -F "Path=@C:\Users\rtam\Music\1 2 3\TEST123.jpg" to a python request. I used https://curl.trillworks.com/ to assist me and got this as the output: import requests headers = { 'Content-Type': 'multipart/form-data', } files = { 'data': (None, '{"key": "Path"};type'), 'Path': ('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', open('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', 'rb')), } response = requests.post('http://127.0.0.1:8881/models/faewrfaw/v1/predict', headers=headers, files=files) However, when testing the response in python I got a bad request/request the server did not understand. I noticed the trillworks website did not account for the type (application/json) in its formatting, does it need to be in the python script?
tagged with: curl
type: Question
has comment: http://stackoverflow.com/comment/87573247
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10588644
has comment: http://stackoverflow.com/comment/87573966
tagged with: python

http://stackoverflow.com/q/50331029
upvote count: 0
score: -5
tagged with: pandas
has comment: http://stackoverflow.com/comment/87678186
answer count: 1
favorite count: 0
type: Question
has title: aggregating the table using pandas
downvote count: 5
has body: Below is the input. X Y Z AP 1 1 1 Karnataka 0 1 0 Goa 1 1 0 Tamilnadu 0 1 0 AP 0 1 1 Goa 0 0 0 Tamilnadu 0 1 1 Goa 0 0 0 AP 1 0 0 Tamilnadu 0 1 0 Tamilnadu 1 1 0 Goa 0 1 1 Karnataka 0 0 0 Karnataka 0 1 0 Calculations to be performed: number of states present in column A number of 1's present in column X divided by count of each state in column A The code should be dynamic,as the number of columns and rows may vary. Expected output: Total AP Karnataka Goa Tamilnadu Total Sample 14 3 3 4 4 X 0.2857 0.6667 0.0000 0.2500 0.2500 Y 0.7143 0.6667 0.6667 0.5000 1.0000 Z 0.2857 0.6667 0.0000 0.2500 0.2500
tagged with: python
has answer: http://stackoverflow.com/a/50334329
accepted answer: http://stackoverflow.com/a/50334329
type: AnsweredQuestion

http://stackoverflow.com/comment/87632480
type: Comment
comment on: http://stackoverflow.com/a/50307890
type: AnswerComment
has text: first, I declare the string structure. that is shown by "%s/%s". the "%s" means that a string variable will come there. so, in the structure, i pointed out that I wanted two string variables with a slash (/) between them. after that, I put the strings I want in the right order, which are `base_path` and `i`.
score: 0

http://stackoverflow.com/a/50274763
type: AcceptedAnswer
has body: a="aaaarggh" d={} for char in set(a): d[char]=a.count(char) print(d) output {'a': 4, 'h': 1, 'r': 1, 'g': 2}
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50274685
answers question: http://stackoverflow.com/q/50274685
upvote count: 1

http://stackoverflow.com/q/50353592
has comment: http://stackoverflow.com/comment/87723636
has comment: http://stackoverflow.com/comment/87723960
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/50353720
tagged with: updates
favorite count: 0
type: Question
has title: pandas - Update only specific DataFrame column values based on a 'key' value
has body: I have the two following DataFrames, stats: player_id player_name gp ab run hit 28920 S. Smith 1 2 1 3 33351 T. Mancini 0 0 0 0 30267 C. Gentry 0 0 0 0 34885 H. Kim 1 0 0 0 31988 J. Schoop 0 0 0 0 5908 J.J. Hardy 1 3 0 0 &amp; game: player_id player_name gp ab run hit 28920 S. Smith 1 4 1 1 33351 T. Mancini 1 1 0 1 34885 H. Kim 1 1 2 0 5908 J.J. Hardy 1 4 0 0 I want to update the statistics only for the players who've been active in the last game, based on the player_id, so that the final statistics DataFrame looks like this: player_id player_name gp ab run hit 28920 S. Smith 2 6 2 4 33351 T. Mancini 1 1 0 1 30267 C. Gentry 0 0 0 0 34885 H. Kim 2 1 2 0 31988 J. Schoop 0 0 0 0 5908 J.J. Hardy 2 7 0 0 Thank you for your time and help!
accepted answer: http://stackoverflow.com/a/50353720
tagged with: python
linked to: http://stackoverflow.com/q/17398216
tagged with: merge
type: AnsweredQuestion

http://stackoverflow.com/q/50246672
has body: I need to label each contour with numbers so that with the help of following code i can extract the coordinates of that particular contour. Here is the image: import numpy as np import cv2 THRESHOLD = 55 CONTOUR = 55 im = cv2.imread("ceramic.bmp") imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,THRESHOLD,255,0) _th,contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) print "Number of contours detected = %d" % len(contours) cv2.drawContours(im,contours,CONTOUR,(1,70,255)) area = cv2.contourArea(contours[CONTOUR]) print (area) cv2.imshow("Contours",im) np.set_printoptions(threshold=np.inf) coords = np.array2string(contours[CONTOUR]) open("contour_%d.txt" % CONTOUR, "w").write(coords) cv2.waitKey(0) cv2.destroyAllWindows()`
tagged with: python
has comment: http://stackoverflow.com/comment/87627464
type: Question
has comment: http://stackoverflow.com/comment/87587959
has comment: http://stackoverflow.com/comment/87521354
tagged with: contour
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87561766
answer count: 1
has answer: http://stackoverflow.com/a/50309210
has title: Labelling the contours with numbers and then extracting the coordinates of any numbered contour
has comment: http://stackoverflow.com/comment/87537877
tagged with: opencv
has comment: http://stackoverflow.com/comment/87626848
score: 0
has comment: http://stackoverflow.com/comment/87634323

http://stackoverflow.com/comment/87679302
has text: You can change the list to have integers instead of strings, but integers can't have leading zeros
type: Comment
comment on: http://stackoverflow.com/a/50305284
score: 0
type: AnswerComment

http://stackoverflow.com/q/50305223
tagged with: scikit-learn
tagged with: text-classification
favorite count: 0
has answer: http://stackoverflow.com/a/50314857
accepted answer: http://stackoverflow.com/a/50314857
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28160335
tagged with: python
has body: I am pretty new in machine learning, so I still don't understand how I can visualize the border between 2 classes in bag of words case. I found the following exaplpe to plot data plot a document tfidf 2D graph from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.decomposition import PCA from sklearn.pipeline import Pipeline import matplotlib.pyplot as plt newsgroups_train = fetch_20newsgroups(subset='train', categories=['alt.atheism', 'sci.space']) pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ]) X = pipeline.fit_transform(newsgroups_train.data).todense() pca = PCA(n_components=2).fit(X) data2D = pca.transform(X) plt.scatter(data2D[:,0], data2D[:,1], c=newsgroups_train.target) plt.show() In my project I use SVC estimator clf = SVC(random_state=241, kernel = 'linear') clf.fit(X,newsgroups_train.target) I have tried to use the example http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html but it didn't work in text clasification case So how can I add the border of two classes to this plot? Thank you!
tagged with: svm
has title: How can I visualize border/decision function of two classes using scikit-learn
type: Question
score: 5
upvote count: 5
answer count: 1
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/a/74921066
score: 0
has body: If you are still in development and can take the pain of filling out the db data again then here's what all you need to know!. you need to first delete all the files related with db(including sqlite.py if it exists), you can do this by the help of below following ways. find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete Now either delete the entire data,tables of your DB or just Drop the db and make a new one and do the migrations separately for each app and migrate it. python manage.py makemigrations appname python manage.py migrate appname then if you get any error for the session like "ProgrammingError: relation "django_session" does not exist" then follow these steps below: python manage.py migrate --fake sessions zero then your sessions migrate will be python manage.py showmigrations sessions [ ] 0001_initial then migrate with --fake-initial again python manage.py migrate --fake-initial now do try to the runserver again and the problem must have been by gone now, if not then please let me know,I'll try my best possible way to solve it. Thanks for looking at this.
answers question: http://stackoverflow.com/q/50324561
type: Answer

image
tags question: http://stackoverflow.com/q/50300282
tags question: http://stackoverflow.com/q/50352528
tags question: http://stackoverflow.com/q/50268092
tags question: http://stackoverflow.com/q/50358964
tags question: http://stackoverflow.com/q/50301752
tags question: http://stackoverflow.com/q/50314242
tags question: http://stackoverflow.com/q/50244202
tags question: http://stackoverflow.com/q/50353836
tags question: http://stackoverflow.com/q/50263155
tags question: http://stackoverflow.com/q/50317614
tags question: http://stackoverflow.com/q/50251719
tags question: http://stackoverflow.com/q/50365453
tags question: http://stackoverflow.com/q/50276488
tags question: http://stackoverflow.com/q/50280640
tags question: http://stackoverflow.com/q/50378543
tag name: image
tags question: http://stackoverflow.com/q/50345786
tags question: http://stackoverflow.com/q/50265888
tags question: http://stackoverflow.com/q/50370236
tags question: http://stackoverflow.com/q/50368612
tags question: http://stackoverflow.com/q/50289882
tags question: http://stackoverflow.com/q/50239066
tags question: http://stackoverflow.com/q/50309671
tags question: http://stackoverflow.com/q/50297176
tags question: http://stackoverflow.com/q/50252468
type: Tag
tags question: http://stackoverflow.com/q/50325261
tags question: http://stackoverflow.com/q/50381372
tags question: http://stackoverflow.com/q/50272801
tags question: http://stackoverflow.com/q/50294263
tags question: http://stackoverflow.com/q/50330601

http://stackoverflow.com/comment/87536458
has text: Unfortunately not so simple. I tried implementing this before writing this question but I got an error: StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
type: AnswerComment
comment on: http://stackoverflow.com/a/50245961
type: Comment
score: 0

http://stackoverflow.com/comment/87718212
comment on: http://stackoverflow.com/a/50351070
score: 0
type: AnswerComment
has text: I want the values 0, 1, 2, etc. to appear **in between** grid lines.
type: Comment

http://stackoverflow.com/q/50315780
linked to: http://stackoverflow.com/q/43966427
tagged with: python
linked to: http://stackoverflow.com/q/32137396
score: -1
has body: in the following code only the plot is drawn but the head is not printed why? import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("file.csv") df.set_index("id", inplace=True) plt.plot(df) plt.show() # this draws plof of entire df form csv print(df.head(10)) # this does not print the first 10 rows of the dataframe
has comment: http://stackoverflow.com/comment/87647404
tagged with: pycharm
tagged with: pandas
has title: Drawing plot and displaying head at the same time - PyCharm
tagged with: matplotlib
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50316010
answer count: 2
has answer: http://stackoverflow.com/a/50315791
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50313960
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50314029
answer count: 1
has comment: http://stackoverflow.com/comment/87643948
type: Question
tagged with: python
has title: What happens if threading.stack_size() is used to set stack size beyond the allocated stack size for python application?
has body: The stack size limit on python application on my system is limit stacksize 40960 kbytes. If threading.stack_size() is used to set the thread stack size to a value higher than 40960KB, will the stack size allocated to python application increase automatically? Thanks

http://stackoverflow.com/comment/87641116
has text: You have circular dependencies, `a` cant import `b` if `b` imports `a`. Also in python, there is no reason to split up your code into so many different files, unlike java you can multiple classes per file.
comment on: http://stackoverflow.com/q/50312470
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/87631432
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50307722
score: 3
has text: it is `len` not `Len`. And you 2nd point is incorrect. `len('a' + 'b') == 2`

http://stackoverflow.com/q/50344911
answer count: 2
has title: pandas can't parse the following txt file into a pandas dataframe, just got one column
has body: I have a txt file format like this: [{ "lng": "111.68389897298637", "odometer": 0, "busSpeed": "0.00", "relativeLocation": 0, "realTimeStatus": "0", "driverUuid": "28b3ea130a6ad049a10b041037e2550d80f5", "posUuid": "8eba1ae2fd014eaf948b", "cursorOverGround": "0", "posIsInStation": "", "sationName": "", "distanceToPrePosition": 0, "lineUuid": "c2e0313000fba04c940a4be0f9edb9c521c8", "drvIcCard": "3168310624", "lineType": "0", "isOffset": "1", "driverName": "贾爱俊", "gatherTime": 1506468898000, "allAlarms": "7", "busUuid": "9d9648ff0375a04702080cc03a4c20377ea8", "lat": "40.86856137377131", "devUuid": "3d16fedb858842199cb3", "sationUuid": "" }， { "lng": "111.68364330061954", "odometer": 0, "busSpeed": "11.00", "relativeLocation": 0, "realTimeStatus": "0", "driverUuid": "28b3ea130a6ad049a10b041037e2550d80f5", "posUuid": "ff42c6cca2e14583b84f", "cursorOverGround": "280", "posIsInStation": "", "sationName": "", "distanceToPrePosition": 0, "lineUuid": "c2e0313000fba04c940a4be0f9edb9c521c8", "drvIcCard": "3168310624", "lineType": "0", "isOffset": "1", "driverName": "贾爱俊", "gatherTime": 1506468919000, "allAlarms": "7", "busUuid": "9d9648ff0375a04702080cc03a4c20377ea8", "lat": "40.868510932496115", "devUuid": "3d16fedb858842199cb3", "sationUuid": "" }] When I want to import it into a dataframe, I only get one column: But when I choose some list of the txt I can get the right answer: Can anyone tell me how I would do it correctly with the txt file? Any help appreciated! Thanks.
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/50345302
has comment: http://stackoverflow.com/comment/87755458
tagged with: pandas
has answer: http://stackoverflow.com/a/50344973
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
score: -1
favorite count: 0
type: Question

gyroscope
tags question: http://stackoverflow.com/q/50313135
type: Tag
tag name: gyroscope

http://stackoverflow.com/q/50312047
score: 0
has comment: http://stackoverflow.com/comment/87726964
answer count: 1
has body: I've been following this tutorial https://www.youtube.com/watch?v=COlbP62-B-U to run an object detection program from jupyter notebook. When I open the object-detection tutorial, it shows me the following error: could not find 'cudart64_90.dll'. tensorflow requires that this dll be installed in a directory that is named in your %path% environment variable. I've already installed CUDA 9.0 developer kit, and the file 'cudart64_90.dll' exists in my NVIDIA directory. Is the .dll file in the right place? Why am I getting this problem?
tagged with: tensorflow
tagged with: jupyter-notebook
type: Question
tagged with: python
has title: CUDA library not found error with object detection API
has answer: http://stackoverflow.com/a/50845873
accepted answer: http://stackoverflow.com/a/50845873
type: AnsweredQuestion

http://stackoverflow.com/q/50343129
has body: Getting an error that Kivy module is not found after installing Kivy for Python 3.6 using pip3 and brew. Please advise.
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/50352715
has title: Module not found error Kivy Python 3.6 Mac OS High Sierra
has answer: http://stackoverflow.com/a/50352715
type: AnsweredQuestion
score: 0
tagged with: kivy
has comment: http://stackoverflow.com/comment/87721321
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87718570
type: Question

http://stackoverflow.com/q/50295870
has comment: http://stackoverflow.com/comment/87652364
duplicate of: http://stackoverflow.com/q/44404349
has body: I have a program that involves both pyQt and opencv. I installed opencv with anaconda and installed pyqt separately a while ago. I run anaconda python2.7 on an OSX machine. The example code is below, it is supposed to have a button that switch on openCV camera, and put the image to self.video_frame, which is a QLable() from PyQt4 import QtGui from PyQt4.QtGui import QImage,QPixmap import PyQt4.QtCore as QtCore import cv2,sys, time class QtCapture(QtGui.QWidget): def __init__(self, *args): self.app = QtGui.QApplication(sys.argv) super(QtGui.QWidget, self).__init__() self.layout = QtGui.QGridLayout() self.w = QtGui.QWidget() # Main gui object self.w.setMinimumHeight(480) self.capture = None self.frame = None self.video_frame = QtGui.QLabel() self.button_start = QtGui.QPushButton('Camera Connect') self.button_start.setFixedWidth(300) self.button_start.clicked.connect(lambda: self.start()) self.w.setLayout(self.layout) self.layout.addWidget(self.button_start, 0, 0) self.layout.addWidget(self.video_frame, 0, 1, 16, 1) self.w.show() print "Init" def nextFrameSlot(self): try: previous_frame = self.current_frame ret, self.frame = self.cap.read() self.current_frame = self.frame frame_diff = cv2.absdiff(self.current_frame, previous_frame) qformat= QImage.Format_Indexed8 if len(self.frame.shape) == 3: if self.frame.shape[2] == 4: qformat=QImage.Format_RGBA8888 else: qformat=QImage.Format_RGB888 img = QtGui.QImage(self.frame, self.frame.shape[1], self.frame.shape[0], self.frame.strides[0], qformat) self.video_frame.setPixmap(QtGui.QPixmap.fromImage(img)) self.video_frame.setScaledContents(True) except Exception, e: print "Failed" self.timer.stop() def start(self): print "button_start pressed. " try: self.cap = cv2.VideoCapture(0) self.start_time = time.time() self.timer = QtCore.QTimer() ret, self.current_frame = self.cap.read() self.timer.timeout.connect(self.nextFrameSlot) self.timer.start(1./10.) except Exception, e: print "failed" def closeEvent(self, event): print "Closing…
has comment: http://stackoverflow.com/comment/87618095
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/87617228
type: UnansweredQuestion
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/87608962
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87616206
favorite count: 0
has comment: http://stackoverflow.com/comment/87652376
has title: pyQt and opencCV s pyQt both exists and crashes the program
tagged with: qt
tagged with: opencv
has comment: http://stackoverflow.com/comment/87618098
linked to: http://stackoverflow.com/q/44404349
has comment: http://stackoverflow.com/comment/87616387
score: 1
tagged with: python

syntactic-sugar
tags question: http://stackoverflow.com/q/50309409
type: Tag
tag name: syntactic-sugar

http://stackoverflow.com/comment/87565902
has text: @Emily The code above completes that task. In the route, a simple list is created which is passed as a jsonified object to the `ajax` response function. Let me know how this works.
comment on: http://stackoverflow.com/a/50244965
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/95273596
comment on: http://stackoverflow.com/q/50243600
has text: I think that solution may be simple if you stop to solve it directly. SAS never load the whole file into the memory. It's old good system and the most SAS procedures works in LIMITED memory (!) R load ALL data in memory. It' a problem. You will not be able to work with such file in R anyway. R is not for DIG DATA. Possible use data.table package, but... Suggest some ideas: 1) load the file into some database and work with it from R using connection and SQL 2) use SAS to split the file for some smaller files 3) drop unused information from the SAS file
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87634063
comment on: http://stackoverflow.com/q/50302418
score: 0
has text: I edited my question with the function, but I don't think that that function is the problem, because I checked in local MySQL and all the records were created without any problem, even my system list the new records but only after clicking the link on my option lists
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87485718
has text: Are you willing to use `pandas`? It would make this pretty fast and easy
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50234065

http://stackoverflow.com/comment/87638843
type: AnswerComment
has text: still got the warnning "SettingWithCopyWarning"
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50294471

http://stackoverflow.com/comment/87480120
type: AnswerComment
comment on: http://stackoverflow.com/a/50230709
score: 0
type: Comment
has text: I like the second one a lot! And the speed is important for my program so the faster the better. Thanks for spending time on this!

http://stackoverflow.com/a/50304123
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50304103
answers question: http://stackoverflow.com/q/50304103
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87626244
upvote count: 2
has body: I think need DataFrame.nlargest with column A for top 5 rows and then select column B: df = pd.DataFrame({'A':[4,5,26,43,54,36,18,7,8,9], 'B':range(10)}) print (df) A B 0 4 0 1 5 1 2 26 2 3 43 3 4 54 4 5 36 5 6 18 6 7 7 7 8 8 8 9 9 9 print (df.nlargest(5, 'A')) A B 4 54 4 3 43 3 5 36 5 2 26 2 6 18 6 a = df.nlargest(5, 'A')['B'] print (a) 4 4 3 3 5 5 2 2 6 6 Name: B, dtype: int64 Alternative solution with sorting: a = df.sort_values('A', ascending=False)['B'].head(5) print (a) 4 4 3 3 5 5 2 2 6 6 Name: B, dtype: int64
type: AcceptedAnswer

drag-and-drop
tags question: http://stackoverflow.com/q/50232639
tag name: drag-and-drop
type: Tag

http://stackoverflow.com/q/50325848
has body: I previously trained and saved a keras model for a Neural Network, but whenever I try to load it I get this error. Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "C:\Users\gio-c\PycharmProjects\NN\venv\lib\site-packages\keras\models.py", line 260, in load_model f = h5py.File(filepath, mode='r') File "C:\Users\gio-c\PycharmProjects\NN\venv\lib\site-packages\h5py\_hl\files.py", line 269, in __init__ self._swmr_mode = True File "C:\Users\gio-c\PycharmProjects\NN\venv\lib\site-packages\h5py\_hl\files.py", line 99, in make_fid else: File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper File "h5py\h5f.pyx", line 78, in h5py.h5f.open OSError: Unable to open file (file signature not found) In the code, I just load keras and import the file. I already tried to recreate the file and nothing happened. Any ideas on how to solve the problem?
type: Question
has comment: http://stackoverflow.com/comment/95969792
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87667391
has comment: http://stackoverflow.com/comment/87674742
has comment: http://stackoverflow.com/comment/87667423
has comment: http://stackoverflow.com/comment/87670354
tagged with: machine-learning
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/87669141
has comment: http://stackoverflow.com/comment/87697295
has comment: http://stackoverflow.com/comment/87668345
score: 0
has answer: http://stackoverflow.com/a/53162956
answer count: 1
has title: Can't load keras model
linked to: http://stackoverflow.com/q/38089950
has comment: http://stackoverflow.com/comment/87669309

http://stackoverflow.com/a/50372569
answers question: http://stackoverflow.com/q/50372272
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/119579093
has body: This is one way: df2 = df.join(pd.DataFrame(columns=['b'])) The advantage of this method is you can add an arbitrary number of columns without explicit loops. In addition, this satisfies your requirement of df.empty evaluating to True if no data exists.
has comment: http://stackoverflow.com/comment/119565016
has comment: http://stackoverflow.com/comment/119687559
has comment: http://stackoverflow.com/comment/119569722
type: Answer
upvote count: 6

http://stackoverflow.com/q/50294443
tagged with: smtplib
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has body: import smtplib server = smtplib.SMTP('smtp-mail.outlook.com', 587) server.ehlo() server.starttls() server.login("user1@outlook.com", "pass") body = 'Subject: Mail test .\n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Initials' server.sendmail("user1@outlook.com","user2@outlook.com",body) server.quit() I can see the mail sent in user1 sent items but user2 is in bcc list not in to as to shows unknown and mail is not received in user 1 account. Please help me as what i am doing wrong here
favorite count: 0
type: Question
has title: Unable to receive mails using smtplib as recipient is getting added in bcc list
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50294915

http://stackoverflow.com/comment/87717271
type: Comment
comment on: http://stackoverflow.com/q/50348306
type: QuestionComment
score: 0
has text: Instead of re-implementing a Twitch API client from scratch, I strongly recommend to use an existing package. For example this one: https://github.com/tsifrer/python-twitch-client. These will already have solved the issues you are battling here.

http://stackoverflow.com/comment/87543483
score: 0
has text: You need to import whichever ones you use, if any.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50262722

http://stackoverflow.com/comment/88799991
has text: @RobertN please, mark the answer if its helpful to you. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/50307936
type: Comment
score: 2

http://stackoverflow.com/q/50379541
possible better answer: http://stackoverflow.com/a/50379875
has body: I have the following column in a pyspark dataframe, of type Array[Int]. +--------------------+ | feature_indices| +--------------------+ | [0]| |[0, 1, 4, 10, 11,...| | [0, 1, 2]| | [1]| | [0]| +--------------------+ I am trying to pad the array with zeros, and then limit the list length, so that the length of each row's array would be the same. For example, for n = 5, I expect: +--------------------+ | feature_indices| +--------------------+ | [0, 0, 0, 0, 0]| | [0, 1, 4, 10, 11]| | [0, 1, 2, 0, 0]| | [1, 0, 0, 0, 0]| | [0, 0, 0, 0, 0]| +--------------------+ Any suggestions? I looked at pyspark rpad function, but it only operates on string type columns.
tagged with: pyspark
tagged with: dataframe
tagged with: python
score: 6
upvote count: 6
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50379688
downvote count: 0
has answer: http://stackoverflow.com/a/50379875
favorite count: 0
has title: Pyspark: Pad Array[Int] column with zeros
type: Question
accepted answer: http://stackoverflow.com/a/50379688

http://stackoverflow.com/q/50273322
tagged with: python-3.x
has body: I am using python-3.x, and I am trying to generate an initial population that contains random real numbers between 0 and 1 where these numbers should be one of the following: 0, 0.33333, 0.666667 or 1 That means the difference between these numbers is 0.33333 (1/3). I tried to modify this code in many ways but their no luck import numpy as np import random from random import randint from itertools import product pop_size = 7 i_length = 2 i_min = 0 i_max = 1 level = 2 step = ((1/((2**level)-1))*(i_max-i_min)) def individual(length, min, max): return [ randint(min,max) for x in range(length) ] def population(count, length, min, max): return [ individual(length, min, max) for x in range(count) ] population = population(pop_size, i_length, i_min, i_max) ##count: the number of individuals in the population ##length: the number of values per individual ##min: the minimum possible value in an individual's list of values ##max: the maximum possible value in an individual's list of values ##this code was taken from :https://lethain.com/genetic-algorithms-cool-name-damn-simple/ I did this lines which works very well for me: population2 = np.array(list(product(np.linspace(i_min, i_max, 2**level), repeat=2))) population3 = [j for j in product(np.arange(i_min, i_max+step, step), repeat=2)] but the problem it will list all the possible values which are not what I want. I want random numbers where the population size will be given the result I want to see is smailar to (numpy array or list): population = [[0, 1], [0, 0.3333], [0.3333, 1], [1, 0.6667], [0.3333, 0.6667], [0.6667, 0], [0.3333, 0.3333]] keep in mind the: level = 2 where I can calculat the the step value: step = ((1/((2**level)-1))*(i_max-i_min)) for example, if I changed the level = 2 to level = 3 then it is no more using the 0.3333 it will change to 0.1428 1/7) which I will get different values. Any advice would be much appreciated
score: 5
upvote count: 5
tagged with: python
has title: Python - Generate random real number between range with a step size
accepted answer: http://stackoverflow.com/a/50273566
tagged with: numpy
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50273675
has answer: http://stackoverflow.com/a/50273566
tagged with: random
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50273675
favorite count: 0
type: Question

http://stackoverflow.com/comment/87777971
type: Comment
score: 0
type: AnswerComment
has text: You could also use set union, although I'm not sure if it would be any faster.`if len(set(list1) | set(list2)) == len(list1) + 2:`
comment on: http://stackoverflow.com/a/50380853

http://stackoverflow.com/q/50254906
has title: Django TemplateDoesNotExist at account/signup/
upvote count: 1
favorite count: 0
type: Question
score: -2
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
has body: Can someone please help me? I created a sign up form under: blog/templates/regitsration/singup.html # This is the template blog/templates/regitsration/login.html blog/templates/blog/*** blog/views.py blog/urls.py blog/forms.py views def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) The site isn't working correctly. It says: TemplateDoesNotExist at accounts/signup/ registration/signup.html
type: AnsweredQuestion
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/50255161
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/50255161

http://stackoverflow.com/comment/87597740
type: Comment
score: 0
type: QuestionComment
has text: @staz you're welcome, don't forget to mark it as solved (so that the green tick appeared on the answer). Thank you!
comment on: http://stackoverflow.com/q/50288583

http://stackoverflow.com/comment/87599271
type: QuestionComment
has text: A quick glance shows that input string contains `ssh` while you are trying to match `sh`.
score: 0
comment on: http://stackoverflow.com/q/50290949
type: Comment

http://stackoverflow.com/comment/87564288
score: 0
type: AnswerComment
has text: No problem, glad it was helpful :)
comment on: http://stackoverflow.com/a/50271119
type: Comment

http://stackoverflow.com/comment/87589746
has text: @RickyAguilar - I change answer, can you check it?
comment on: http://stackoverflow.com/a/50286266
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87502069
comment on: http://stackoverflow.com/a/50242225
type: Comment
score: 0
type: AnswerComment
has text: Do you have an (counter)example of that?

http://stackoverflow.com/comment/87506079
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50243600
type: QuestionComment
has text: Can you do some manipulation of the file in SAS first? It is in a wide format currently, e.g. `DX1`-`DX25` for each diagnosis running across the page. This could be stored in one long diagnosis table and probably save you 50% of the filesize if most cases only have a handful of diagnoses.

http://stackoverflow.com/comment/87583584
type: QuestionComment
comment on: http://stackoverflow.com/q/50283547
has text: … and if I fix that problem, and type `N`, the `break` works just fine. Of course if I type `n`, it doesn't. Maybe that's the problem you're seeing? If so, the problem is that `'N'` and `'n`' aren't the same string; you probably want `appDownCon = input(…).upper()`.
type: Comment
score: 0

http://stackoverflow.com/q/50360567
tagged with: errorbar
has answer: http://stackoverflow.com/a/50361035
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
upvote count: 3
has title: Python errorbar with varied marker size
has body: I used python errorbar to make a plot, however the arguments markersize can only be a scalar not an array, which means all the data points have the same marker size. I am wondering how can I assign different markersize to different data points? ax.errorbar(x,y,xerr=[xlow,xup],yerr=[ylow,yup],color='r',ls='None',marker='o',markersize=5.) If I create the marker size to be 5.0*y, how can I make it work?
answer count: 1
downvote count: 1
tagged with: marker
type: Question
accepted answer: http://stackoverflow.com/a/50361035

http://stackoverflow.com/comment/87555405
score: 0
comment on: http://stackoverflow.com/q/50268691
type: Comment
type: QuestionComment
has text: Could you provide some sample data from your dataset?

http://stackoverflow.com/a/71345223
type: Answer
score: 0
has body: You can use Numba to parallel process the array. I don't know exactly what kind of processing you are planning to do. But it's likely possible to speed up with numba. from numba import njit, prange @njit(parallel=True) def process(array): m, n, o, p = array.shape for i in prange(m): # process slices individually # or do something else return result You might also want to look into numbas vecorize, guvectorize or stencil depending on your use case.
answers question: http://stackoverflow.com/q/50270346

http://stackoverflow.com/comment/87707033
type: Comment
has text: @ytpillai while your solution on pastebin works to a point. I'm not looking to have the user keep guessing until they get the number correct, as appears to happen in your solution
comment on: http://stackoverflow.com/a/50343011
type: AnswerComment
score: 0

http://stackoverflow.com/q/50347675
has title: Error installing mply library. Fatal error: gsl/gsl_sf.h: No such file or directory
tagged with: linux
has comment: http://stackoverflow.com/comment/87717473
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87715276
tagged with: python
score: -1
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/87714962
linked to: http://stackoverflow.com/q/50323877
has body: I'm trying to install the latest version of mply (3.5.0) on xubuntu (ubuntu 17.10): download the .tar.gz Unzipped it python setup.py build. Here I get the error displayed below. also tried directly python setup.py install. same error. tried installing gsl library by downloading the latest version, and following all the steps in https://coral.ise.lehigh.edu/jild13/2016/07/11/hello/. I have it installed in /home/gsl still the same error tried various other installations (sudo apt-get install libgsl0ldbl, sudo apt-get install libgs123, sudo apt-get install libgsl0-dev). Nothing works. tried copying the folder /home/gsl/include/gsl inside the mply-3.5.0/mply/gsl folder . this slightly changes something, because now I get fatal error: gsl/gsl_sf_result.h: No such file or directory (So it finds gsl_sf.h, but not gsl_sf_result.h (both these files are present inside the /gsl/include/gsl folder). tried with python setup.py build_ext --include-dirs=/home/gls/include/gls still nothing tried to copy the /home/gsl/include/gsl folder inside my /usr/local/include: cp -R /home/gsl/include/gsl /usr/local/include/gsl still nothing. Help! Error message: gcc -pthread -B /home/lorenzo/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/lorenzo/anaconda3/include/python3.6m -I/home/lorenzo/anaconda3/lib/python3.6/site-packages/numpy/core/include -I/home/lorenzo/anaconda3/include/python3.6m -c mlpy/gsl/gsl.c -o build/temp.linux-x86_64-3.6/mlpy/gsl/gsl.o mlpy/gsl/gsl.c:223:10: fatal error: gsl/gsl_sf.h: No such file or directory #include "gsl/gsl_sf.h"
has answer: http://stackoverflow.com/a/50351496
tagged with: c++
upvote count: 0
linked to: http://stackoverflow.com/q/11494179
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87714926
has comment: http://stackoverflow.com/comment/87712770
has comment: http://stackoverflow.com/comment/87713083
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87715080

http://stackoverflow.com/a/50317414
score: 1
answers question: http://stackoverflow.com/q/50317335
type: Answer
has body: So, it turns out that I had forgotten to change the wanted words parameter in the freeze.py file.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50327481
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50327174
type: Answer
score: 22
has comment: http://stackoverflow.com/comment/135582246
answers question: http://stackoverflow.com/q/50327174
upvote count: 22
has body: You can write a custom validator within a form by writing a validate_{field_name} method. If it raises a ValidationError, the form will not be valid and will display the error. For your specific case, here's a solution using regex. It finds the match for the string, and then uses a bit of splitting to get back the scores. After validating the form you can access the scores by form.score1, form.score2. import re from flask_wtf import FlaskForm from wtforms import ValidationError class MatchForm(FlaskForm): match1 = StringField("Russia-Saudi Arabia", validators=[DataRequired()]) def validate_match1(self, form, field): if not re.search(r"^[0-9]+:[0-9]+$", field.data): raise ValidationError("Invalid input syntax") s1, s2 = form.data.split(":") form.score1 = int(s1) form.score2 = int(s2)
has comment: http://stackoverflow.com/comment/110495670
type: AcceptedAnswer

http://stackoverflow.com/comment/87772752
has text: Don't use `np.append`. All it is a buggy front end to `concatenate`.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50377801

http://stackoverflow.com/q/50288130
has body: I am working on an assignment attempting to design two abstract data types in Python 3. My question is for the subclass "dnmMtx" I am looking for guidance on returning the number of columns along with the longest row in this subclasses "size" function and also trying to figure out how to delete a row. At first I thought i could pop a row or use a .delete option but neither worked out. Also, currently my size function returns the how many rows there are. Any help is greatly appreciated thank you! class DnmArr: def __init__(self): #create empty list self.arr=[] def __del__(self): print('Deconstructed') #return length def length(self): return len(self.arr) #append def append(self, x): #add x to arr if type(x) == int: self.arr.append(x) else: print('Not an integer.') #delete def delete(self,x): index = x #if element is present in array if index &lt;= len(self.arr): self.arr.pop(index) else: print('Element does not exist.') def value(self, x): if x &lt;= len(self.arr) and type(x) == int: print(self.arr[x-1]) else: print('Does not exist or list indices is not an integer') #initializing subclass using parent class DnmMtx(DnmArr): def __init__(self): DnmArr.__init__(self) self.arr=[[],[]] #creating 2d array def __del__(self): print('Deconstructed') def addrow(self): row = [] self.arr.append(row) def delrow(self, x): if type(x) == int: self.arr.delete(arr[x]) else: print('row does not exist/invalid row') def size(self): return len(self.arr) def append(self, x, y): if type(x) and type(y) == int: self.arr[x].append(y) else: print('Not an integer.') def delete(self, x, y): #if element is present if y &lt;= len(self.arr[x]) and x &lt;= len(self.arr): #check self.arr[x].pop(y) else: print('Element does not exist.') def value(self, x, y): if x and y &lt;= len(self.arr) and type(x) and type(y) == int: print(self.arr[x-1][y-1]) else: print('Does not exist or list indices is not an integer') #create object of type Dynamic Array a = DnmArr() b = DnmMtx()
tagged with: python
has comment: http://stackoverflow.com/comment/87592616
has answer: http://stackoverflow.com/a/50289740
type: Question
tagged with: python-3.x
has title: Returning the number of columns/longest row in 2D array and deleting a row
answer count: 1
accepted answer: http://stackoverflow.com/a/50289740
tagged with: abstract-data-type
tagged with: class
type: AnsweredQuestion
score: 0
tagged with: list

http://stackoverflow.com/a/50271538
has body: Here's a solution, though it does use a simple loop: import pandas as pd from datetime import datetime df = 'your dataframe' dfs = [] delta = df.date.max() - df.date.min() for i in range(0, delta.days+1, 20): mask = (df['date'] &gt;= df.date.min()+datetime.timedelta(days=i)) &amp; (df['date'] &lt;= df.date.min() + datetime.timedelta(days=i+20)) dfs.append(df.loc[mask])
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50271165

http://stackoverflow.com/a/50291671
has body: When you initlialize a list using seleksi = [] It is an empty list. The lenght of list is 0. Hence seleksi[0] gives an error. You need to append to the list for it to get values, something like seleksi.append(p.select()) If you still want to assign it based on index, initialize it as array of zeros or some dummy value seleksi = [0]* n See this: List of zeros in python
type: Answer
answers question: http://stackoverflow.com/q/50291583
score: 0

http://stackoverflow.com/q/50235025
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/87490432
downvote count: 1
has comment: http://stackoverflow.com/comment/87490271
score: 0
has comment: http://stackoverflow.com/comment/87490560
upvote count: 1
has title: Rendering from the wrong list in this pygame code; Hexgame
tagged with: python
tagged with: pygame
has body: I'm having a bug in a small pygame excercise where I'm trying to build a hex-field boardgame... I tried to minimize the code, but since I have absolutely no clue, where something goes wrong, it's still a bit in order to work: import pygame, random, math, time, sys # Important Game Vars - SCREEN and PLAYFIELD width = 1024 length = 680 hexW = 50 hexH = 60 playFieldSize = 1 midpoint = [int(width / 2), int(length / 2)] print('midpoint:', midpoint) playFields = [midpoint] holderList = [] for i in range(playFieldSize): for currentpoint in playFields: field = [currentpoint[0] + hexW, currentpoint[1]] if field not in playFields and field not in holderList: holderList.append(field) field = [currentpoint[0] - hexW, currentpoint[1]] if field not in playFields and field not in holderList: holderList.append(field) field = [currentpoint[0] - hexW / 2, currentpoint[1] + hexH * 0.75] if field not in playFields and field not in holderList: holderList.append(field) field = [currentpoint[0] + hexW / 2, currentpoint[1] + hexH * 0.75] if field not in playFields and field not in holderList: holderList.append(field) field = [currentpoint[0] - hexW / 2, currentpoint[1] - hexH * 0.75] if field not in playFields and field not in holderList: holderList.append(field) field = [currentpoint[0] + hexW / 2, currentpoint[1] - hexH * 0.75] if field not in playFields and field not in holderList: holderList.append(field) print('holder: ', holderList) for i in holderList: playFields.append(i) holderList = [] print('playfields:', playFields) print('len playfields:', len(playFields)) # Important Game Vars - POSITIONS AND COUNTS heroPos = [] activeHeroNo = 0 print('heroPos: ', heroPos) heroCount = 3 for i in (random.choices(playFields, k=heroCount)): heroPos.append(i) print('heroPos: ', heroPos) inputCooldown = 10 inputCooldownCounter = inputCooldown playSurface = pygame.display.set_mode((width, length)) pygame.display.set_caption('Herobrawl') # Colors red = pygame.Color(255, 0, 0) blue = pygame.Color(0, …
linked to: http://stackoverflow.com/q/19951816
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87487731
duplicate of: http://stackoverflow.com/q/19951816

http://stackoverflow.com/comment/87682227
comment on: http://stackoverflow.com/q/50332981
score: 0
has text: Possible duplicate of [Django admin: override delete method](https://stackoverflow.com/questions/15196313/django-admin-override-delete-method)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50272021
has comment: http://stackoverflow.com/comment/87601573
linked to: http://stackoverflow.com/q/2923579
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/87601180
tagged with: python-2.7
score: 0
has body: I have a thread class (TransmitThread) written in python which takes few parameters and then starts transmitting to a device(NI USRP). I have a rest flask based webservice,which on rest request by the user creates a new object of TransmitThread and calls the start(). Ideally it should start transmitting and wait for a flag which self.thdRunning which i can make false. I see 2 issues with my implementation 1. I do not see the prints from the Thread class 2. I store the threads in a dictionary as a reference. and when i get a subsequent rest request ,the older thread is in stopped state. Note: I am not so familiar with Python ,i am trying to learn so any additional inputs will also be helpfull Any input on how to keep the threads running and printing of the logs will help. class TransmitThread(threading.Thread,grc_wxgui.top_block_gui): // variables are initalised here thdRunning = True def __int__(self): pass def run(self): ################################################## # Variables ################################################## self.samp_rate = samp_rate = 32000 ....do some more thing.... print("Transmission started! Will wait to be killed") while self.thdRunning: time.sleep(2) print("Transmission thread stopped!") def endThreadExecution(self): self.thdRunning = False; Flask rest service implementation @app.route('/txdata/&lt;clienID&gt;/&lt;usrpIp&gt;/&lt;frequency&gt;/&lt;path:fname&gt;',methods=['GET']) def transmit(clienID,usrpIp,frequency,fname): global dict if(not isUsrptransmiting)|shallStartTxn: if fname.endswith('.iq12'): decIM = 12 else: decIM = 48 usrpIp = "addr="+str(usrpIp) print(usrpIp) fname = "/"+fname transmitThread = threading.Thread(target=TransmitThread,args=(fname, str(usrpIp), decIM, frequency)) transmitThread.daemon = True # Daemonize thread print("Service is Transmitting " + str(clienID) + "this is your username " + str(usrpIp) + " freq " + str(frequency) + " file " + str(fname) +" decIM "+str(decIM)) transmitThread.start() dict[str(usr…
has comment: http://stackoverflow.com/comment/87567134
has comment: http://stackoverflow.com/comment/87602309
type: Question
has title: Thread stopped during while loop execution
answer count: 0
has comment: http://stackoverflow.com/comment/87588719
has comment: http://stackoverflow.com/comment/87602793
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/87598429

http://stackoverflow.com/q/50307916
accepted answer: http://stackoverflow.com/a/50354502
tagged with: pointers
has body: I have a ctypes callback that takes a pointer to two doubles from the dll and returns a pointer to two doubles back to the .dll. The first part works correctly, but after a lot of testing and research, I still can't get the correct pointer to return to the .dll after the callback. Here's the ctypes callback code: from scipy.integrate import dblquad import ctypes LibraryCB = ctypes.WINFUNCTYPE(ctypes.py_object, ctypes.POINTER(ctypes.c_double)) def LibraryCall(ptr): n = ctypes.cast(ptr,ctypes.POINTER(ctypes.c_double)) x = n[0] #Value = 83.0 y = n[1] #Value = 30.0 area = dblquad(lambda x, y: x*y, 0, 0.5, lambda x: 0, lambda x: 1-2*x) return_val = area[0], area[1] return (return_val) lib_call = LibraryCB(LibraryCall) lib_call = ctypes.cast(lib_call,ctypes.POINTER(ctypes.c_longlong)) I used ctypes.py_object as the pointer type to return because all other pointer types return an error that it's not a valid pointer type for a callback. The pointer returns to the dll, but the values extracted do not match, which suggests that I don't have the correct pointer type. I also tried casting the return value to a pointer like this: rv = ctypes.cast(return_val,ctypes.POINTER(ctypes.c_double)), and returning that instead, but that didn't work. Here is the relevant ctypes code that calls the dll and the callback: CA_data1 = (ctypes.c_double * len(data1))(*data1) CA_data2 = (ctypes.c_double * len(data2))(*data2) hDLL = ctypes.WinDLL("C:/NASM_Test_Projects/SciPy_Test/SciPy_Test.dll") CallName = hDLL.Main_Entry_fn CallName.argtypes = [ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_double),ctypes.POINTER(ctypes.c_longlong)] CallName.restype = ctypes.c_double ret_ptr = CallName(CA_data1,CA_data2,length_array_out,lib_call) Thanks very much for any ideas on how to solve this.
has comment: http://stackoverflow.com/comment/87652306
has title: What is the correct pointer type to return from a ctypes callback?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87640596
answer count: 1
has answer: http://stackoverflow.com/a/50354502
type: Question
tagged with: ctypes
tagged with: function-pointers
tagged with: python

http://stackoverflow.com/q/50370410
tagged with: merge
has title: Merge 2 dataframes
type: Question
has comment: http://stackoverflow.com/comment/87763672
has comment: http://stackoverflow.com/comment/87756839
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50370450
upvote count: 1
accepted answer: http://stackoverflow.com/a/50370450
favorite count: 0
type: AnsweredQuestion
has body: I have 2 dataframe for ex: df1: seq_id1 seq_id2 seq1_A seq2_B seq2_A seq3_B seq4_A seq9_B seq9_A seq9_B etc and another dataframe such df2: sequences seq2_A seq9_A and keep only in the first dataframe, the row where the ID in the dataframe is present, here it would be: newdataframe merged: seq_id1 seq_id2 seq2_A seq3_B seq9_A seq9_B Thanks for your help :) here. are the dataframe= First one with only 60 rows : df1 second one with with all seq ID: df2 Here the columns ["#qseqid'"] in the first df has to match with the restricted df2 in the column ["seq2_id"]
tagged with: pandas
score: 1
tagged with: python

http://stackoverflow.com/a/50377363
downvote count: 0
upvote count: 1
has body: In [10]: p = ['a', 'b', 'c', 'a', 'c', 'a'] In [11]: q = [1, 2, 1, 3, 3, 1] In [12]: z = zip(p, q) In [13]: z Out[13]: [('a', 1), ('b', 2), ('c', 1), ('a', 3), ('c', 3), ('a', 1)] In [14]: counts = {} In [15]: for pair in z: ...: if pair in counts.keys(): ...: counts[pair] += 1 ...: else: ...: counts[pair] = 1 ...: In [16]: counts Out[16]: {('a', 1): 2, ('a', 3): 1, ('b', 2): 1, ('c', 1): 1, ('c', 3): 1} In [17]: sub_p = [] In [18]: sub_q = [] In [19]: for i, element in enumerate(p): ...: if element == 'a': ...: sub_p.append(element) ...: sub_q.append(q[i]) In [20]: sub_p Out[20]: ['a', 'a', 'a'] In [21]: sub_q Out[21]: [1, 3, 1] Explanation zip takes two lists and runs a figurative zipper between them. Resulting in a list of tuples I've used a simplistic approach, I'm just maintaining a map/dictionary that makes not of how many times it has seen a pair of char-int tuples Then I make 2 sub lists that you can modify to use the character in question and figure out what it maps to Alternative methods As abarnert suggested you could use A Counter from collections instead. Or you could just a count method on z . eg: z.count('a',1). Or you can use a defaultdict instead.
type: Answer
answers question: http://stackoverflow.com/q/50376528
score: 1

http://stackoverflow.com/a/73259052
score: 0
answers question: http://stackoverflow.com/q/50374610
has body: PyOpenSSL is being deprecated, so might want to consider using the cryptography module instead import cryptography der = open('/path/tp/file', 'rb').read() cert = cryptography.x509.load_der_x509_certificate(der) cert.serial_number
type: Answer

http://stackoverflow.com/comment/87741852
score: 0
type: QuestionComment
has text: Seed documentation of `csv.writer()` https://docs.python.org/2/library/csv.html
type: Comment
comment on: http://stackoverflow.com/q/50362707

http://stackoverflow.com/q/50296817
has title: Scoring in GridSearchCV for XGBoost
has body: I'm trying to analyze data for the first time using XGBoost. I want to find the best parameters using GridsearchCV. I want to minimize the root mean squared error and to do this, I used "rmse" as eval_metric. However, scoring in grid search does not have such a metric. I found on this site that the "neg_mean_squared_error" does the same, but I found that this gives me different results than the RMSE. When I calculate the root of the absolute value of the "neg_mean_squared_error", I get a value of around 8.9 while a different function gives me a RMSE of about 4.4. I don't know what goes wrong or how I get these two functions to agree/give the same values? Because of this problem, I get wrong values as best_params_ which give me a higher RMSE than some values I initially started with to tune. How to get score on the RMSE in the grid search and why my code gives different values? def modelfit(alg, trainx, trainy, useTrainCV=True, cv_folds=10, early_stopping_rounds=50): if useTrainCV: xgb_param = alg.get_xgb_params() xgtrain = xgb.DMatrix(trainx, label=trainy) cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds, metrics='rmse', early_stopping_rounds=early_stopping_rounds) alg.set_params(n_estimators=cvresult.shape[0]) # Fit the algorithm on the data alg.fit(trainx, trainy, eval_metric='rmse') # Predict training set: dtrain_predictions = alg.predict(trainx) # dtrain_predprob = alg.predict_proba(trainy)[:, 1] print(dtrain_predictions) print(np.sqrt(mean_squared_error(trainy, dtrain_predictions))) # Print model report: print("\nModel Report") print("RMSE : %.4g" % np.sqrt(metrics.mean_squared_error(trainy, dtrain_predictions))) param_test2 = { 'max_depth':[6,7,8], 'min_child_weight':[2,3,4] } grid2 = GridSearchCV(estimator = xgb.XGBRegressor( learning_rate =0.1, n_estimators=2000, max_depth=5, min_child_weight=2, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'reg:linear', nthread=4, scale_pos_weight=1, random_st…
tagged with: grid-search
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50297537
tagged with: parameters
score: 0
has answer: http://stackoverflow.com/a/71118107
answer count: 2
tagged with: machine-learning
tagged with: xgboost
type: Question

http://stackoverflow.com/comment/87572778
score: 2
comment on: http://stackoverflow.com/q/50278030
has text: Can you post your naive solution so we can see what you've tried?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50406572
has comment: http://stackoverflow.com/comment/95564024
has body: I managed to deal with this issue. Very simple but noted here for reference. Since LightGBM expects float32/64 for input, so 'categories' should be number, rather than str. And input data should be converted to float32/64 using .astype(). Changes1: added following 4 lines after X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) X_train_tfidf = X_train_tfidf.astype('float32') X_test_counts = X_test_counts.astype('float32') Y_train = Y_train.astype('float32') Y_test = Y_test.astype('float32') changes2: just convert 'category' column from [A, B, C, ...] to [0.0, 1.0, 2.0, ...] Maybe just assigning attirbute as TfidfVecotrizer(dtype=np.float32) works in this case. And putting vectorized data to LGBMClassifier will be much simpler. Update Using TfidfVectorizer is much simpler: tfidf_vec = TfidfVectorizer(dtype=np.float32, sublinear_tf=True, use_idf=True, smooth_idf=True) X_data_tfidf = tfidf_vec.fit_transform(df['contents']) X_train_tfidf = tfidf_vec.transform(X_train) X_test_tfidf = tfidf_vec.transform(X_test) clf_LGBM = lgbm.LGBMClassifier(objective='multiclass', verbose=-1, learning_rate=0.5, max_depth=20, num_leaves=50, n_estimators=120, max_bin=2000,) clf_LGBM.fit(X_train_tfidf, Y_train, verbose=-1) predicted_LGBM = clf_LGBM.predict(X_test_tfidf)
answers question: http://stackoverflow.com/q/50250432
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/95344465
has comment: http://stackoverflow.com/comment/95427444
downvote count: 0

http://stackoverflow.com/comment/87715480
type: QuestionComment
has text: I am not quite sure about the `,` before that first comma. Is it always there, or can it be missing? Also, see https://ideone.com/4ai0dI
comment on: http://stackoverflow.com/q/50349451
score: 0
type: Comment

http://stackoverflow.com/a/59951868
downvote count: 0
type: Answer
has body: Here's what worked for me: import pandas as pd import json df = pd.DataFrame([{"test":"w","param":1},{"test":"w2","param":2}]) print(df) test param 0 w 1 1 w2 2 So now we convert to a json string: d = df.to_json(orient='records') print(d) '[{"test":"w","param":1},{"test":"w2","param":2}]' And now we parse this string to a list of dicts: data = json.loads(d) print(data) [{'test': 'w', 'param': 1}, {'test': 'w2', 'param': 2}]
score: 5
answers question: http://stackoverflow.com/q/50384883
upvote count: 5

http://stackoverflow.com/q/50308886
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87633718
has comment: http://stackoverflow.com/comment/87633769
accepted answer: http://stackoverflow.com/a/50308907
upvote count: 0
has answer: http://stackoverflow.com/a/50308907
tagged with: python
has answer: http://stackoverflow.com/a/50308939
has title: Error in Factorial Program in Python
downvote count: 6
tagged with: recursion
tagged with: factorial
type: AnsweredQuestion
answer count: 2
has body: When I execute the below code in Python 3, it's gives me below error. Could some one explain me what is wrong in the below code. I know how to write a Factorial Program using simple function. But I would like to understand what is wrong in the below code. class Factorial: def __init__(self): self.n=1 def fact(self,n): if self.n &gt;= 1: return ((self.n) * (self.fact(n - 1))) else: return 1 a=Factorial() print("4! =", a.fact(4)) Error: RecursionError: maximum recursion depth exceeded in comparison
possible better answer: http://stackoverflow.com/a/50308939
score: -6
favorite count: 0

http://stackoverflow.com/comment/87680218
type: QuestionComment
comment on: http://stackoverflow.com/q/50331895
has text: point noted @chrisz
type: Comment
score: 0

http://stackoverflow.com/comment/119657202
type: Comment
has text: @alper compared to what?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/53918402

http://stackoverflow.com/comment/87647158
score: 0
type: Comment
type: QuestionComment
has text: How could I use enumerate() to complete this?
comment on: http://stackoverflow.com/q/50315675

http://stackoverflow.com/comment/87767914
score: 0
type: Comment
has text: Also, what are `asd` and `control`? You haven't defined them in your code.
type: QuestionComment
comment on: http://stackoverflow.com/q/50374882

http://stackoverflow.com/a/50347694
downvote count: 0
has comment: http://stackoverflow.com/comment/87747106
upvote count: 2
answers question: http://stackoverflow.com/q/50346235
type: Answer
has body: Taking some inspiration from this answer I came up with this regex+extract solution: In [77]: df.address.iloc[1] = 'Big Apple 19 21 7' In [78]: df.address.str.extract('(?P&lt;street&gt;^[^0-9]*) (?P&lt;building&gt;.+?) (?P&lt;door&gt;.+?) (?P&lt;apartment&gt;.+?$)') Out[78]: street building door apartment 0 Iso Omena 8 a 2 1 Big Apple 19 21 7 2 Iso Omena 8 a 2 3 Iso Omena 8 a 2 4 Iso Omena 8 a 2 5 Iso Omena 8 a 2 6 Iso Omena 8 a 2 7 Iso Omena 8 a 2 8 Iso Omena 8 a 2 9 Iso Omena 8 a 2
score: 2

http://stackoverflow.com/comment/87724737
score: 0
has text: Possible duplicate of [Selenium Python - selecting from a list on the web with no stored/embedded options](https://stackoverflow.com/questions/50311145/selenium-python-selecting-from-a-list-on-the-web-with-no-stored-embedded-optio)
type: QuestionComment
comment on: http://stackoverflow.com/q/50354157
type: Comment

http://stackoverflow.com/a/50250480
answers question: http://stackoverflow.com/q/50249514
has body: Which version of scrapy are you using? Upgrade it to the latest one (1.5.0). Create empty virtual environment and install scrapy: projects &gt; $ virtualenv --no-site-packages --python=python3.5 venv ... Installing setuptools, pkg_resources, pip, wheel...done. projects &gt; $ source venv/bin/activate [3.5.5](venv) projects &gt; $ pip freeze pkg-resources==0.0.0 [3.5.5](venv) projects &gt; $ pip install scrapy ... Successfully installed Automat-0.6.0 PyDispatcher-2.0.5 Twisted-18.4.0 asn1crypto-0.24.0 attrs-18.1.0 cffi-1.11.5 constantly-15.1.0 cryptography-2.2.2 cssselect-1.0.3 hyperlink-18.0.0 idna-2.6 incremental-17.5.0 lxml-4.2.1 parsel-1.4.0 pyOpenSSL-17.5.0 pyasn1-0.4.2 pyasn1-modules-0.2.1 pycparser-2.18 queuelib-1.5.0 scrapy-1.5.0 service-identity-17.0.0 six-1.11.0 w3lib-1.19.0 zope.interface-4.5.0 [3.5.5](venv) projects &gt; $ pip freeze asn1crypto==0.24.0 attrs==18.1.0 Automat==0.6.0 cffi==1.11.5 constantly==15.1.0 cryptography==2.2.2 cssselect==1.0.3 hyperlink==18.0.0 idna==2.6 incremental==17.5.0 lxml==4.2.1 parsel==1.4.0 pkg-resources==0.0.0 pyasn1==0.4.2 pyasn1-modules==0.2.1 pycparser==2.18 PyDispatcher==2.0.5 pyOpenSSL==17.5.0 queuelib==1.5.0 Scrapy==1.5.0 service-identity==17.0.0 six==1.11.0 Twisted==18.4.0 w3lib==1.19.0 zope.interface==4.5.0 Make scrapy project and write your spider: [3.5.5](venv) projects &gt; $ scrapy startproject reddit [3.5.5](venv) projects &gt; $ cd reddit/reddit/spiders/ [3.5.5](venv) spiders &gt; $ touch spider.py &amp;&amp; subl spider.py spider.py: import scrapy class RedditSpider(scrapy.Spider): name = 'reddit' allowed_domains = ['www.reddit.com'] start_urls = ['https://www.reddit.com/r/help/search?q=hydrochlorothiazide/'] def parse(self, response): #view(self.response) posts = response.xpath('//*[@class="contents"]/div') for post in posts: header = post.xpath('.//*[@class="search-result-header"]/a/text()').extract_first() text = '\n'.join(post.xpath('.//*[@class="md"]/p/text()').extract()) yield{'Header':header,'Text':tex…
has comment: http://stackoverflow.com/comment/87518399
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/50352104
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
tagged with: python
has body: I have the pandas data frame: df: id des 1 POS Transfer atis mcdon uber 2 MKLI QC Montreal abelutixy 3 PC - PAYMENT FROM - *****11*22 I want to add a new column "new" to the dataframe, where all the words in the df.des that has the substring tis, ber uti be removed That is df["new"]: POS Transfer mcdon MKLI QC Montreal PC - PAYMENT FROM - *****11*22 How do I do this
tagged with: regex
tagged with: substring
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50352298
tagged with: string
accepted answer: http://stackoverflow.com/a/50352298
has title: Remove substring from the words in pandas dataframe
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87574161
score: 0
type: QuestionComment
has text: There's also a `libtesseract-dev` package in the Ubuntu repos. Could that be what you are looking for?
type: Comment
comment on: http://stackoverflow.com/q/50277848

http://stackoverflow.com/a/50304014
has body: There's no simple answer to your problem. Scraping data requires you to carefully assess the data you are dealing with, work out where the parts you want to extract are located and figure out how to effectively store the data you extract. Try printing the data in your loops to visualise what is happening in your code (or try debugging). From there its easy to figure out it if you're iterating over what you expect. Look for patterns throughout the input data to help organise the data you extract. To help yourself, you should give your variables descriptive names, separate your code into logical chunks and add comments when it starts to get complicated. Here's some working code, but I encourage you to try what I told you above, then if you're still stuck look below for guidance. output = {} root = data['items'][0] for game_line in root['itemList']['items']: # Create a temporary dict to store the data for this gameline team_data = {} # Get competitors competitors = game_line['competitors'] for team in competitors: team_type = team['type'] # either HOME or AWAY # Create a new dict to store data for each team team_data[team_type] = {} team_data[team_type]['abbreviation'] = team['abbreviation'] team_data[team_type]['name'] = team['description'] # Get MoneyLine and Total Runs for item in game_line['displayGroups'][0]['itemList']: for outcome in item['outcomes']: team_type = outcome['type'] # either A or H team_type = 'HOME' if team_type == 'H' else 'AWAY' if item['mainMarketType'] == 'MONEYLINE': team_data[team_type]['moneyline'] = outcome['price']['american'] elif item['mainMarketType'] == 'SPREAD': team_data[team_type]['total runs'] = outcome['price']['handicap'] # Get the pitchers team_data['HOME']['pitcher'] = game_line['opponentAName'] team_data['AWAY']['pitcher'] = game_line['opponentBName'] # For each gameline, add the teamdata we gathered to the output dict output[game_line['description']] = team_data This produces like: { 'Atlanta Braves @ Miami Marlins': { 'AWAY'…
score: 1
has comment: http://stackoverflow.com/comment/87629312
has comment: http://stackoverflow.com/comment/87630901
type: Answer
accepted answer of: http://stackoverflow.com/q/50303405
downvote count: 0
answers question: http://stackoverflow.com/q/50303405
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87700267
comment on: http://stackoverflow.com/q/50342113
type: QuestionComment
has text: @ReblochonMasque Thanks for your reply. Edited the question, I meant non-digital string elements only.
score: 0
type: Comment

http://stackoverflow.com/comment/87482657
type: Comment
type: QuestionComment
score: 0
has text: Replace `$` with `\Z` as `$` matches a location before a final newline in the input string.
comment on: http://stackoverflow.com/q/50232385

http://stackoverflow.com/a/50512982
upvote count: 2
has body: The param # column indicates the number of parameters that the particular layer has. For example, your dense_9 layer has 64 units, and the input has 3136 elements. The number of params are given by the total number of elements in the weights matrix plus the elements in the biases matrix (because it's a dense layer). You have that 64 * 3136 + 64 = 200768, exactly the value in param #. If you check the value of param # for the next layer (activation_19) you will see that there aren't any parameters, because activations usually are not parametrized (they have a fixed formula for calculating them)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50356436
score: 2
type: Answer
answers question: http://stackoverflow.com/q/50356436

http://stackoverflow.com/a/50359583
has comment: http://stackoverflow.com/comment/87736269
accepted answer of: http://stackoverflow.com/q/50359558
type: Answer
has body: You can use map: import re def split_words(d): return [re.sub('^\W+|\W+$', '', i) for b in map(lambda x:re.split("(?&lt;='),(?=')", x), d) for i in b] mylist = [["'alpha','beta'",'delta','phi'], ["'alpha','beta'",'delta','phi, theta']] final_results = list(map(split_words, mylist)) Output: [['alpha', 'beta', 'delta', 'phi'], ['alpha', 'beta', 'delta', 'phi, theta']]
score: 0
has comment: http://stackoverflow.com/comment/87736327
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50359558

http://stackoverflow.com/comment/87765189
comment on: http://stackoverflow.com/a/50374398
type: Comment
score: 0
type: AnswerComment
has text: what does v:k do in here?

http://stackoverflow.com/q/50366401
linked to: http://stackoverflow.com/q/25470844
tagged with: parsing
favorite count: 0
has title: parser.add_argument support multiple types
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/50367387
answer count: 2
has answer: http://stackoverflow.com/a/50367387
possible better answer: http://stackoverflow.com/a/50367106
duplicate of: http://stackoverflow.com/q/25470844
has answer: http://stackoverflow.com/a/50367106
downvote count: 0
tagged with: python
score: 4
type: AnsweredQuestion
has body: I'm using my parser like so parser.add_argument('owner_type', type=int, required=False, location=location) I want to be able to send both int and str in that field owner_type. is there a way to do that? Didn't find anything in the docs.

http://stackoverflow.com/q/50338229
score: 1
has comment: http://stackoverflow.com/comment/87697253
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87696795
has comment: http://stackoverflow.com/comment/87714434
answer count: 0
has comment: http://stackoverflow.com/comment/87697368
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87697430
downvote count: 0
upvote count: 1
tagged with: python
has title: pip install packages in Python runing into errors
has comment: http://stackoverflow.com/comment/87697338
has body: I am trying to install a few packages in Python. For example trying to install quantmod but was told to upgrade my pip which I did through Anaconda prompt but when I go to try and install quantmod again I get the same error message. This happens with all packages I am trying to install... I am running pip install quantmod and to upgrade pip this python -m pip install --upgrade pip (base) C:\Users\USER\AppData\Local\Programs\Python\Python36-32&gt;pip install quantmod Collecting quantmod Could not find a version that satisfies the requirement quantmod (from versions: ) No matching distribution found for quantmod You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (base) C:\Users\USER\AppData\Local\Programs\Python\Python36-32&gt;python -m pip install --upgrade pip Requirement already up-to-date: pip in c:\users\USER\appdata\local\programs\python\python36-32\lib\site-packages (10.0.1) (base) C:\Users\USER\AppData\Local\Programs\Python\Python36-32&gt;pip install quantmod Collecting quantmod Could not find a version that satisfies the requirement quantmod (from versions: ) No matching distribution found for quantmod You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. EDIT 1 with pip install --upgrade pip: Exception: Traceback (most recent call last): File "C:\Users\USER\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\USER\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "C:\Users\USER\Anaconda3\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "C:\Users\USER\Anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Users\US…

pycharm
tags question: http://stackoverflow.com/q/50321217
tags question: http://stackoverflow.com/q/50322696
tags question: http://stackoverflow.com/q/50331601
tags question: http://stackoverflow.com/q/50317974
tags question: http://stackoverflow.com/q/50315780
tags question: http://stackoverflow.com/q/50375482
tags question: http://stackoverflow.com/q/50370581
tags question: http://stackoverflow.com/q/50243130
tags question: http://stackoverflow.com/q/50268871
tags question: http://stackoverflow.com/q/50306421
tag name: pycharm
tags question: http://stackoverflow.com/q/50291131
tags question: http://stackoverflow.com/q/50315407
tags question: http://stackoverflow.com/q/50316702
tags question: http://stackoverflow.com/q/50257509
tags question: http://stackoverflow.com/q/50377649
type: Tag
tags question: http://stackoverflow.com/q/50258621
tags question: http://stackoverflow.com/q/50327424
tags question: http://stackoverflow.com/q/50339691
tags question: http://stackoverflow.com/q/50309076
tags question: http://stackoverflow.com/q/50274927
tags question: http://stackoverflow.com/q/50373440
tags question: http://stackoverflow.com/q/50305004
tags question: http://stackoverflow.com/q/50296384
tags question: http://stackoverflow.com/q/50308750
tags question: http://stackoverflow.com/q/50339145
tags question: http://stackoverflow.com/q/50238432
tags question: http://stackoverflow.com/q/50264129
tags question: http://stackoverflow.com/q/50250010
tags question: http://stackoverflow.com/q/50318518
tags question: http://stackoverflow.com/q/50346498
tags question: http://stackoverflow.com/q/50325986
tags question: http://stackoverflow.com/q/50298283
tags question: http://stackoverflow.com/q/50327242
tags question: http://stackoverflow.com/q/50278029
tags question: http://stackoverflow.com/q/50252138
tags question: http://stackoverflow.com/q/50356367

http://stackoverflow.com/a/75501383
has body: If you more than 14 files in a workbook this error will appear. So, try to paste the content of excel into a new file and then try to load it. This resolved my issue. Hope it resolves yours as well.
score: 0
has comment: http://stackoverflow.com/comment/133291611
type: Answer
answers question: http://stackoverflow.com/q/50236928

http://stackoverflow.com/q/50239506
has title: How to hide and unhide a specific file or folder in Windows with Python
tagged with: python
has answer: http://stackoverflow.com/a/50239789
type: Question
type: UnansweredQuestion
score: 0
tagged with: hide
answer count: 1
tagged with: file
has body: I want to open a file/folder using Python (I know how to do this) but then hide the file/folder after. How can I hide and unhide specific files or folders in Python?

http://stackoverflow.com/q/50371627
possible better answer: http://stackoverflow.com/a/50371854
has title: Python JSON parser error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
has body: I need some help parsing JSON file. I've tried a couple of different ways to get the data I need. Below is a sample of the code and also a section of the JSON data but when I run the code I get the error listed above. There's 500K lines of text in the JSON and it first fails about about 1400 lines in and I can't see anything in that area section to indicate why. I've run it successfully by only checking blocks of JSON up to the first 1400 lines and I've used a different parser and got the same error. I'm debating if it's an error in the code, an error in the JSON or a result of the JSON being made of different kids of data as some (like the example below) is for a forklift and others for fixed machines but it is all structured just like below. All help sincerely appreciate. Code: import json file_list = ['filename.txt'] #insert filename(s) here for x in range(len(file_list)): with open(file_list[x], 'r') as f: distros_dict = json.load(f) #list the headlines to be parsed for distro in distros_dict: print(distro['name'], distro['positionTS'], distro['smoothedPosition'][0], distro['smoothedPosition'][1], distro['smoothedPosition'][2]) And here is a section of the JSON: { "id": "b4994c877c9c", "name": "Trukki_0001", "areaId": "Tracking001", "areaName": "Ajoneuvo", "color": "#FF0000", "coordinateSystemId": "CoordSys001", "coordinateSystemName": null, "covarianceMatrix": [ 0.47, 0.06, 0.06, 0.61 ], "position": [ 33.86, 33.07, 2.15 ], "positionAccuracy": 0.36, "positionTS": 1489363199493, "smoothedPosition": [ 33.96, 33.13, 2.15 ], "zones": [ { "id": "Zone001", "name": "Halli1" } ], "direction": [ 0, 0, 0 ], "collisionId": null, "restrictedArea": "", "tagType": "VEHICLE_MANNED", "drivenVehicleId": null, "drivenByEmployeeIds": null, "simpleXY": "33|33", "EventProcessedUtcTime": "2017-03-13T00:00:00.3175072Z", "PartitionId": 1, "EventEnqueuedUtcTime": "2017-03-13T00:00:00.0470000Z" }
has answer: http://stackoverflow.com/a/50371854
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/87759511
has answer: http://stackoverflow.com/a/50372000
has comment: http://stackoverflow.com/comment/87759373
tagged with: python
has comment: http://stackoverflow.com/comment/87759210
has comment: http://stackoverflow.com/comment/87759154
has comment: http://stackoverflow.com/comment/87759131
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87760628
accepted answer: http://stackoverflow.com/a/52289899
answer count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52289899

http://stackoverflow.com/comment/87731059
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50357222
has text: actually nothing is wrong with os.walk I believe, I just didn't realize it was a function. Thanks! Although, I guess I would still like to know what the error is in the code above to avoid repeating it more times, if anyone has solutions.
score: 0

http://stackoverflow.com/comment/87710866
comment on: http://stackoverflow.com/a/50346682
has text: If you have one sure, no problem if thats too much of a hastle
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50231528
score: 1
tagged with: signals
downvote count: 0
upvote count: 1
has body: My goal is to compute several data points in parallel and write them to an IO device asynchronously. The data points cannot be written just by themselves but need to be wrapped; more precisely, I am writing a JSON array and the [] symbols around the structs are required. My current approach is to use a multiprocessing.Pool and apply_async to compute the data points. Using a callback function, the data points are then send to a multiprocessing.Queue while a separate thread extracts elements from the queue synchronously and writes them to the IO device. It may happen that I need to cancel the process with a SIGINT. In that case, I want the computation to finish safely, i.e. stop the computation of all Pool processes but finish writing all remaining elements in the queue and the ] symbol. So far, I did not manage to find a working solution for my problem. At the current state, my two issues are: Sometimes, the process does not exit. The SIGINT_handler is called but the process doesn't terminate. I could not verify where this originates from but I assume it might be a deadlock in the queue? I wouldn't know how to prevent that though. As I understand it, pool.terminate() sends a SIGTERM to all its child processes. This apparently causes a KeyboardInterrupt exception in every one of them, cluttering the terminal with a dozen stack traces. My code can be found below. # Initialize the worker pool and necessary variables. pool = multiprocessing.Pool(os.cpu_count() - 1) data_queue = multiprocessing.Queue() counter_lock = threading.Lock() threads_todo = args.autnum # This function is executed after each successful experiment. def apply_finished(data): data_queue.put(data) with counter_lock: nonlocal threads_todo threads_todo -= 1 # Start the pool. for i in range(args.autnum): pool.apply_async(collect_data, (args,), callback=apply_finished) pool.close() # This function is called if SIGINT is send to this process. def SIGINT_handler(sig, frame): sys.stderr.write("SIGINT received…
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Cancel multiprocessing.Pool with SIGINT
tagged with: python-multiprocessing
answer count: 0

decode
tag name: decode
tags question: http://stackoverflow.com/q/50349305
tags question: http://stackoverflow.com/q/50279380
tags question: http://stackoverflow.com/q/50253753
tags question: http://stackoverflow.com/q/50259649
type: Tag
tags question: http://stackoverflow.com/q/50242948

http://stackoverflow.com/q/50243334
tagged with: python
tagged with: lstm
tagged with: c++
has title: Pass Vector of Floats to Tensor in Tensorflow C++
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/54689317
tagged with: tensorflow
type: Question
has body: I have an LSTM frozen graph that takes 10 sequences, and each input sequence has 10 vectors of length 2002. My code works in python, but I don't know how to do the same thing in C++. How can I convert my sequence of vectors into a sequence of LSTM-ready sequence of tensors? Code: /// concatenate vector 1 and vector 2 features std::vector&lt;float&gt; vecOne_vecTwo_concat; /// preallocate memory vecOne_vecTwo_concat.reserve(vecOne.size() + vecTwo.size()); /// concatenate (first half is vecOne; second half is vecTwo) /// add vecOne vecOne_vecTwo_concat.insert(vecOne_vecTwo_concat.end(), vecOne.begin(), vecOne.end()); /// add vecTwo vecOne_vecTwo_concat.insert(vecOne_vecTwo_concat.end(), vecTwo.begin(), vecTwo.end() ); /// append to vector of features sequence_vector_.push_back(vecOne_vecTwo_concat); /// check if we have enough sequences to make a classification /// here n_rnn_steps_ is 10 /// each vector in this sequence is of length 2002 /// so we have 10 vectors, each of length 2002 if (sequence_vector_.size() == n_rnn_steps_) { /* Here we feed the concatenated vector sequence into the session running the LSTM graph */ /// reset vector after we have feed it into the session sequence_vector_.clear(); }

http://stackoverflow.com/q/50289925
tagged with: loops
has comment: http://stackoverflow.com/comment/87596042
favorite count: 0
has comment: http://stackoverflow.com/comment/87595897
has comment: http://stackoverflow.com/comment/87596018
type: Question
upvote count: 4
has title: Python - How to stop the loop
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/50289963
score: 4
has comment: http://stackoverflow.com/comment/87595973
answer count: 4
has comment: http://stackoverflow.com/comment/87596119
has answer: http://stackoverflow.com/a/50289963
accepted answer: http://stackoverflow.com/a/50289964
type: AnsweredQuestion
tagged with: python-2.7
has body: I have this where it reads a file called source1.html, source2.html, source3.html, but when it cant find the next file (because it doesnt exist) it gives me a error. there can be an x amount of sourceX.html, so i need something to say if the next sourcex.html file can not be found, stop the loop. Traceback (most recent call last): File "main.py", line 14, in file = open(filename, "r") IOError: [Errno 2] No such file or directory: 'source4.html how can i stop the script looking for the next source file? from bs4 import BeautifulSoup import re import os.path n = 1 filename = "source" + str(n) + ".html" savefile = open('OUTPUT.csv', 'w') while os.path.isfile(filename): strjpgs = "Extracted Layers: \n \n" filename = "source" + str(n) + ".html" n = n + 1 file = open(filename, "r") soup = BeautifulSoup(file, "html.parser") thedata = soup.find("div", class_="cplayer") strdata = str(thedata) DoRegEx = re.compile('/([^/]+)\.jpg') jpgs = DoRegEx.findall(strdata) strjpgs = strjpgs + "\n".join(jpgs) + "\n \n" savefile.write(filename + '\n') savefile.write(strjpgs) print(filename) print(strjpgs) savefile.close() print "done"
has answer: http://stackoverflow.com/a/50289964
linked to: http://stackoverflow.com/q/82831
has comment: http://stackoverflow.com/comment/87596172
has answer: http://stackoverflow.com/a/50290533
has answer: http://stackoverflow.com/a/50290794

http://stackoverflow.com/comment/87521738
has text: Also in each iteration of the loop you're updating the same keys, so they would have the value only of the last iteration
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50252221
type: Comment

http://stackoverflow.com/a/50261968
has body: I would recommend generic encode and dec_to_base functions ALPHABET = \ "0123456789abcdefghijklmnopqrstuvwxyz" def encode (n): try: return ALPHABET [n] except IndexError: raise Exception ("cannot encode: %s" % n) def dec_to_base (dec = 0, base = 16): if dec &lt; base: return encode (dec) else: return dec_to_base (dec // base, base) + encode (dec % base) print (dec_to_base (9)) # 9 print (dec_to_base (10)) # a print (dec_to_base (255)) # ff print (dec_to_base (256)) # 100 Of course it works with other bases print (dec_to_base (255, base = 2)) # 11111111 print (dec_to_base (256, base = 2)) # 100000000 Reversing an encoding is done by providing the isomorphisms decode and base_to_dec def decode (s): try: return ALPHABET.index(s) except ValueError: raise Exception ("cannot decode: %s" % s) def base_to_dec (s, base = 16, pow = 0): if s is "": return 0 else: return decode (s[-1]) * (base ** pow) + base_to_dec (s[0:-1], base, pow + 1) print (base_to_dec ('ff')) # 255 print (base_to_dec ('100')) # 256 And using a different base print (dec_to_base ('11111111', base = 2)) # 255 print (dec_to_base ('100000000', base = 2)) # 256
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/50261666
type: Answer
has comment: http://stackoverflow.com/comment/87542710
downvote count: 0

http://stackoverflow.com/q/50270515
has title: How to change Canvas background color on click using button using tkinter in python
type: AnsweredQuestion
has body: I wanted to create a simple program to change the background colour of canvas in python using tkinter. The should work like this: suppose the current background colour of my canvas is red, the user clicks on a button on the canvas, then colour changes to blue, the user again clicks the button on the canvas, this time the colour changes to yellow. I need a simple program without classes if possible.
upvote count: 1
accepted answer: http://stackoverflow.com/a/50270715
answer count: 1
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
downvote count: 5
score: -4
has answer: http://stackoverflow.com/a/50270715

http://stackoverflow.com/q/50288361
score: 1
answer count: 1
tagged with: synchronization
tagged with: azure-storage
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50673815
accepted answer: http://stackoverflow.com/a/50673815
has comment: http://stackoverflow.com/comment/87593534
tagged with: azure
tagged with: io
has body: In AWS, a similar functionality exists using awscli as explained here. Does there exist a similar functionality in Azure using Python SDK or CLI? Thanks.
tagged with: python
has title: How to keep a folder synchronised with an Azure storage account in Python?
type: AnsweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87606925
type: AnswerComment
has text: if I want to do it in a loop and show it for each variable?
type: Comment
comment on: http://stackoverflow.com/a/50295118
score: 0

http://stackoverflow.com/q/50230233
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has body: I have a dataframe like this. I am trying to remove the string which presents in substring column. Main substring Sri playnig well cricket cricket sri went out NaN Ram is in NaN Ram went to UK,US UK,US My expected outupt is, Main substring Sri playnig well cricket sri went out NaN Ram is in NaN Ram went to UK,US I tried df["Main"].str.reduce(df["substring"]) but not working, pls help.
accepted answer: http://stackoverflow.com/a/50230388
tagged with: string
favorite count: 0
type: Question
has title: How to reduce part of a dataframe colunm value based on another column
answer count: 2
tagged with: data-analysis
possible better answer: http://stackoverflow.com/a/50230680
has answer: http://stackoverflow.com/a/50230388
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50230680
type: AnsweredQuestion

http://stackoverflow.com/q/50309815
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/50310048
downvote count: 0
has title: Changing color of bar plot if value is less than zero and fill white space
tagged with: python
has answer: http://stackoverflow.com/a/50310048
type: AnsweredQuestion
score: 2
has body: I have created a DataFrame: df.tail(20) Speed 130 -0.000272 131 -0.000219 132 -0.000178 133 -0.000234 134 -0.000261 135 -0.000281 136 -0.000244 137 -0.000255 138 -0.000290 139 -0.000210 140 -0.000216 141 -0.000209 142 -0.000139 143 -0.000060 144 0.000007 145 0.000043 146 0.000068 147 0.000093 148 -0.000025 149 -0.000005 I am using a barchart to draw barplot: ind = np.arange(len(df)) ax.bar(ind, df['Speed'], width=0.5, color="r") What I am trying to do is changing bar colors to red if values are less than zero and green if they are higher than zero. And show smooth graph instead of bars with white spaces. Thanks
tagged with: matplotlib
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/87549450
has text: @tdelaney when I run the command from your first message I get `/u/bcs2363/.local/lib/python3.5/site-packages/bs4/__init__.py` so does this mean its a local install? I'm running this on a university linux machine so I'm hoping this isn't an issue with them not letting install it without it only being local
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50265145
score: 0

http://stackoverflow.com/comment/87669773
has text: Oh yah true, although odd
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50326863
type: Comment

http://stackoverflow.com/q/50235724
answer count: 1
has answer: http://stackoverflow.com/a/50235880
tagged with: python-typing
type: Question
has body: I want to use function to check whether an argument passed to a function is a function or not. I was doing something like: from types import FunctionType def f(ff: FunctionType): # do something It seems wrong, as I can literaly pass anything to f. How do I check argument passed in is a function or not with annotation?
tagged with: function
type: UnansweredQuestion
tagged with: python
has title: With python3 function annotation, how do I check type of function as input?
has comment: http://stackoverflow.com/comment/87488807
score: 0

http://stackoverflow.com/comment/87771920
comment on: http://stackoverflow.com/q/50365835
score: 0
has text: @hpaulj You don't see the use, but I do. For example most of my numeric inputs ends up in `np.array`s. (yes, "whole" vectors of 2 or 3 elements :-). I find having to do these manual conversions after arg parsing a burden -- and ugly, if that even matters.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53390332
upvote count: 1
answers question: http://stackoverflow.com/q/50243086
accepted answer of: http://stackoverflow.com/q/50243086
type: Answer
has body: if you use the ModelCheckpoint function in the callbacks, you should add the para 'save_weights_only=True' in the ModelCheckpoint function: from keras.callbacks import ModelCheckpoint callbacks_list = [ModelCheckpoint(top_weights_path, monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True)] hope useful
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87515648
type: QuestionComment
comment on: http://stackoverflow.com/q/50248548
type: Comment
score: 0
has text: @jpp The result is to categorize things related to A. D and E quoted C, but C is in the A category, so finding a way to group them together into the A category.

http://stackoverflow.com/a/50382323
has body: You can open the file in binary mode. Obviously then you no longer have printable string data, but binary data. So you will need to convert it. text = open("oxeb.txt","rb").read() text = text.decode('iso-8859-1')
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50382020
has comment: http://stackoverflow.com/comment/87780778
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50382020
has comment: http://stackoverflow.com/comment/87819888
downvote count: 0
type: Answer

http://stackoverflow.com/a/50287783
score: 0
has body: Here is the pandas approach I mentioned in the comment. import pandas as pd After importing the data into a pandas dataframe via sth like df = pd.read_csv('/wherever/file/may/roam/filename', _some_kwargs_depending_on_your_csv_layout_) you have your data structured like this: In: df Out: open high low close 2018-05-05 2.75 2.05 2.67 2.92 2018-05-08 2.93 2.97 2.79 2.84 2018-05-09 2.46 2.74 2.45 2.69 2018-05-10 2.69 2.69 2.21 2.33 And then, you can resample your time index which aggregates your data per month. To get a value per month, you only have to tell how you want the numbers being condensed - in your case you wanted min- and max-values: In: df.resample('M').min() Out: open high low close 2018-05-31 2.46 2.05 2.21 2.33 In: df.resample('M').max() Out: open high low close 2018-05-31 2.93 2.97 2.79 2.92 However, you can also apply other statistical functions of interest, like sum(), mean() or std(): In: df.resample('M').sum() Out: open high low close 2018-05-31 10.83 10.45 10.12 10.78 In: df.resample('M').mean() Out: open high low close 2018-05-31 2.7075 2.6125 2.53 2.695 In: df.resample('M').std() Out: open high low close 2018-05-31 0.193972 0.394324 0.255604 0.261343 And if you want the max-value per month over all columns, you can apply another max()-function, with respect to the other axis: In: df.resample('M').max().apply(max, 1) Out: 2018-05-31 2.97 analog with min: In: df.resample('M').min().apply(min, 1) Out: 2018-05-31 2.05
has comment: http://stackoverflow.com/comment/88281582
accepted answer of: http://stackoverflow.com/q/50287141
answers question: http://stackoverflow.com/q/50287141
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/50326058
type: Question
possible better answer: http://stackoverflow.com/a/50328487
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50389407
tagged with: python
accepted answer: http://stackoverflow.com/a/50389407
has body: I am working on Integration spark-streaming with twitter using python API. Mostly examples or code-snippets and blogs I have seen is that they are taking few columns from Twitter JSON file for their final manipulation. But according to my use-case I required all fields of twitter JSON and convert it to a dataframe. This is where I am facing the problem as I sqlContext.read.json() is dumping whole JSON DStream into _corrupt_record +--------------------+ | _corrupt_record| +--------------------+ |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| |{u'quote_count': ...| Also, It seems that this problem can be solved using structured streaming using spark 2+ version. But I have to stick to spark 1.6. Following is my code snippet. def process(time, rdd): print("========= %s =========" % str(time)) try: sqlContext = getSqlContextInstance(rdd.context) jsonRDD = sqlContext.read.json(rdd) jsonRDD.registerTempTable("tweets") jsonRDD.printSchema() except: pass rawKafkaStream = KafkaUtils.createStream(ssc, zkQuorum, "kafka-consumer", {kafkaTopic: 4}) parsed_stream = rawKafkaStream.map(lambda rawTweet: json.loads(rawTweet[1])) parsed_stream.foreachRDD(process)
has answer: http://stackoverflow.com/a/50328487
type: AnsweredQuestion
answer count: 2
tagged with: apache-spark
score: 1
upvote count: 1
downvote count: 0
has title: pyspark streaming twitter json to DF
favorite count: 0

http://stackoverflow.com/comment/87711596
score: 0
type: AnswerComment
has text: Yeah I'm using python3
type: Comment
comment on: http://stackoverflow.com/a/50347345

http://stackoverflow.com/comment/87690405
has text: Try with 19200 and then 9600, confirm if the Arduino blinks or not. This will tell you if the Arduino gets the command in the first place or not.
comment on: http://stackoverflow.com/a/50330709
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87555599
has text: sorry that was a writing typo, I do use 127.0.0.1:5000
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50268887

http://stackoverflow.com/comment/87560166
has text: Maybe you want to concatenate? search "numpy.concatenate"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50271519

http://stackoverflow.com/q/50242552
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87504208
tagged with: ttk
tagged with: python
has title: Update window and values in Tkinter
tagged with: frames
tagged with: tkinter
answer count: 0
score: 2
has body: I have been working on creating an app to help some of our office workers.I have somewhat of a skeleton working but my problem is I can't get my windows to update their values after the initialization of them. I have global variables along with some get and set functions: building = "SomeBuilding" def setBuilding(bldg): global building building = bldg print("building:", building) def getBuilding(): print("Building from get:",building) return building And I have a class which is used to create the app and the frames: class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne,PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.update() frame.tkraise() The problem comes in when I take some values from a frame and store them in the global variable. The global variable gets updated but when moving to the next frame I have a label which displays the value of the global variable. This happens to be the value the global variable was initially. class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) #buidling bldg_label = ttk.Label(self, text="Building Name (ie. Bldg1):", font=LARGE_FONT) bldg_label.grid(row=0, column=0, padx=2, pady = 10) self.bldg_var = tk.StringVar() bldg_entry =ttk.Entry(self,width = 6, textvariable = self.bldg_var) bldg_entry.grid(row=0, column=1, padx=2, pady=10) Within this class I have a button that sets the values of the building entry button2 = ttk.Button(self, text="Apply",command=lambda: setBuilding(self.bldg_var.get())) button2.grid(row=row_num, column = 1) and a button to go to the next frame: button3 = ttk.Button(self, text="…
has comment: http://stackoverflow.com/comment/87503644
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7546050
has comment: http://stackoverflow.com/comment/87504119

http://stackoverflow.com/comment/87581450
type: QuestionComment
score: 0
has text: This appear to be the same as this (unanswered) question, but with greater detail: https://stackoverflow.com/questions/46131620/vscode-did-not-recognize-my-installed-python-packages
comment on: http://stackoverflow.com/q/50282464
type: Comment

http://stackoverflow.com/q/50366591
has answer: http://stackoverflow.com/a/50367223
tagged with: python
score: -1
has body: I was trying to sort list2 = ['four','six','two','three','one','five'] according to list1 = [4,6,2,3,1,5] so that my code updates list2 to ['one', 'two', 'three', 'four', 'five', 'six']. I tried the following code: list2.sort(key = lambda x: list1[list2.index(x)]) But it gives the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; ValueError: 'four' is not in list However, doing the same thing with sorted() function and updating list2 to sorted list gives the required result. Why?
has answer: http://stackoverflow.com/a/50366730
has comment: http://stackoverflow.com/comment/87749402
has title: Why list.sort() doesn't work but sorted() works fine for the given list in this scenario
tagged with: list
answer count: 2
downvote count: 3
linked to: http://stackoverflow.com/q/22678141
favorite count: 0
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/22678141
type: UnansweredQuestion

http://stackoverflow.com/comment/87765285
has text: Try: https://regex101.com/r/OzUEO9/1
comment on: http://stackoverflow.com/q/50374496
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87558681
has text: But in your code you're trying to click `span`...
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50270199
type: QuestionComment

http://stackoverflow.com/comment/87553328
has text: I appreciate your help. I still can't manage to show anything everything I execute it :\
comment on: http://stackoverflow.com/a/50267240
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50278923
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/50279319
has comment: http://stackoverflow.com/comment/87574839
has comment: http://stackoverflow.com/comment/87574526
answer count: 1
upvote count: 1
tagged with: percentage
downvote count: 1
has body: I wrote a script, and I assigned part of it to select random sample of 10% of the files in a dir and copy them to a new dir. This is my method below, but it gives less than 10% (~9.6%) each time, and never the same amount. for x in range(int(len(files) *.1)): to_copy = choice(files) shutil.copy(os.path.join(subdir, to_copy), os.path.join(output_folder)) this gave #files source run 1 run 2 29841 2852 2845 1595 152 156 11324 1084 1082
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50279319
has comment: http://stackoverflow.com/comment/87574763
tagged with: python
has title: Getting a percentage of files in a folder
tagged with: copy

http://stackoverflow.com/q/50323471
score: 0
answer count: 1
tagged with: django
has title: Django execute a custom function from Admin
has answer: http://stackoverflow.com/a/50355066
has body: I am new to Django and have gone through the first Django App tutorial.I understand the separate bits but am not able to form a complete solution. My requirement is to add a custom button to a Model's Change List Page in Admin, redirect it to a confirmation page, execute a function on confirmation and then redirect to the change list page with execution status. I have added the custom button but am lost after that. Currently this is what I am doing: Changed the admin class list template class ReconciliationAdmin(admin.ModelAdmin): change_list_template = 'SalesReconciliation/change_list.html' This is my change list template: {% extends "admin/change_list.html" %} {% load i18n admin_static %} {% block object-tools-items %} {{ block.super }} Run Reconciliation {% endblock %} Changed the urls.py in the main app as follows: urlpatterns = [ url(r"^reconcileConfirm/", include("SalesReconciliation.urls")), ] Changed the urls.py in the child app as follows: urlpatterns = [ url(r'^reconcileConfirm/', views.ReconcileConfirm, name='ReconcileConfirm') ] In the views.py of the child app added the follows: def ReconcileConfirm(request): return HttpResponse("..something") I am hoping that this would work like: Click on Run Reconciliation link -> Main urls.py routes to child urls.py -> child urls.py routes to views.py -> function in views py performs some operations But I am getting the following errors: NoReverseMatch at /SalesReconciliation/reconciliation/ Reverse for 'reconcileConfirm' not found. 'reconcileConfirm' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/SalesReconciliation/reconciliation/ Django Version: 2.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'reconcileConfirm' not found. 'reconcileConfirm' is not a valid view function or pattern name. Also I would like to know whether it is the correct approach.
type: Question
tagged with: django-admin
type: UnansweredQuestion
tagged with: django-models
tagged with: python

http://stackoverflow.com/comment/87600895
type: Comment
has text: usrconfig.extend(usrconfig) was causing the issue. Deleting this line solved the problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/50292257
score: 0

http://stackoverflow.com/q/50307071
type: Question
tagged with: python-3.x
upvote count: 3
has title: Create a pie with matplotlib
has body: Hello I have this code with Python : import matplotlib.pyplot as plt total_a = 0.004095232 total_b = 0.05075945 total_c = 0.005425 total_d = 0.022948572 total_e = 0.015012 slices = [total_a,total_b,total_c,total_d,total_e] activities = ['a', 'b', 'c', 'd','e'] cols = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'orangered'] plt.pie(slices,labels=activities,autopct='%1.1f%%',colors=cols,startangle=140,shadow=True) plt.show() But I get this when I execute this code : I don't understand why I don't get a full pie ? Thank you for your help !
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/50307190
tagged with: python
has answer: http://stackoverflow.com/a/50315480
possible better answer: http://stackoverflow.com/a/50315480
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 2
tagged with: pie-chart
downvote count: 1
has answer: http://stackoverflow.com/a/50307190
favorite count: 0

http://stackoverflow.com/comment/87762686
type: Comment
has text: Is that a typo in `PhotoImage(.....boi/"5C kopiera.gif")`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50373235

http://stackoverflow.com/a/50290771
has comment: http://stackoverflow.com/comment/87604037
score: 0
has body: I assume, what you really need is to have a list of dataframes (which non necessary have any specific names) and then union them all together. dataframes = [df1, df2, df3, etc... ] res_df, tail_dfs = dataframes[0], dataframes[1:] for df in tail_dfs: res_df = res_df.unionAll(df) upd. even better option to union described in comment.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50284760
answers question: http://stackoverflow.com/q/50284760
type: Answer

http://stackoverflow.com/comment/87724198
score: 0
type: AnswerComment
has text: okay brilliant - that seemed to work! However, my program is not actually scraping any of the text names I want it to.. 2018-05-15 16:27:54 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.f6s.com/programs?type[]=accelerator&sort=open> {'program': []} It's just leaving it blank, I take it there is something wrong with my spider css?
type: Comment
comment on: http://stackoverflow.com/a/50353656

http://stackoverflow.com/q/50274850
has body: The below code outputs a spiral matrix of size(n*n) def generateMatrix(self, a): #generates a list with specified elemnts from 1 to n^2 x = [list(range(i, i+a)) for i in range(1, a**2, a)] numrows = len(x) numcols = len(x[0]) top = 0 bottom = numrows-1 left = 0 right = numcols-1 direction = 0 b = [] while (top &lt;= bottom and left &lt;= right): if direction is 0: for i in range(left, right+1): b.append(x[top][i]) top += 1 elif direction is 1: for i in range(top, bottom+1): b.append(x[i][right]) right -= 1 elif direction is 2: for i in range(right, left-1, -1): b.append(x[bottom][i]) bottom -= 1 elif direction is 3: for i in range(bottom, top-1, -1): b.append(x[i][left]) left += 1 direction = (direction+1) % 4 return b While running this code in online IDE I am getting TypeError: 'int' object is not iterable. I have checked if I am iterating wrongly in the code. But could not find any problems as such. I know this question has been asked before and I have checked the solutions. But nothing is working. Can anyone inspect what is wrong with my code?
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87566429
tagged with: python
has title: TypeError: 'int' object is not iterable while running in online IDE
has comment: http://stackoverflow.com/comment/87566421
has comment: http://stackoverflow.com/comment/87587998
score: 0
tagged with: list
tagged with: typeerror
has comment: http://stackoverflow.com/comment/87587987
downvote count: 1
has comment: http://stackoverflow.com/comment/87568467
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/87566455

http://stackoverflow.com/a/50362714
has body: You can use broadcasted NumPy comparison— &gt;&gt;&gt; A[np.arange(n)[:, None] &lt; m] = 0 &gt;&gt;&gt; array([[0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 0.], [1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1.]]) Here, calling [:, None] augments the shape of np.arange(n) such that the comparison &lt; is broadcasted across every element of m, for each item in the range. This generates a boolean mask of the same shape as A which is then used to set values to 0. Note—If A is guaranteed to be an array of ones, I would recommend Divakar's solution, which is very similar to this.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50362679
accepted answer of: http://stackoverflow.com/q/50362679
downvote count: 0
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/87629556
score: 0
comment on: http://stackoverflow.com/q/50305075
has text: thanks for the feedback on my question, next time I post here I will make sure to put everything you guys have said into consideration. Fortunetly Rajat Surana was abke to answer my q.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50343315
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50343137
score: 1
has body: The way you suggest is certainly pythonic. The only issue I can see is that you need just the two biggest elements, but still have to sort all tuples in the dict: this could be done more efficiently with heapq.nlargest values = dict(heapq.nlargest(2, mydict.items(), lambda i: i[1]))
downvote count: 0
has comment: http://stackoverflow.com/comment/87705001
accepted answer of: http://stackoverflow.com/q/50343137
type: AcceptedAnswer

http://stackoverflow.com/comment/87878143
has text: What does your boss mean by "procedural style programming"? If he's opposed to OOP, I doubt he'd be very happy with a Java-style Singleton Design Pattern, which is the exact kind of thing most anti-OOP people hate. Or, if he means "not functional like Scheme" (or Haskell), using the class instead of a closure is just going to look like pointless obfuscation to him.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50370744
score: 2

http://stackoverflow.com/a/50298475
answers question: http://stackoverflow.com/q/50298412
has comment: http://stackoverflow.com/comment/87614344
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/87614384
has comment: http://stackoverflow.com/comment/87614124
has comment: http://stackoverflow.com/comment/87613886
has comment: http://stackoverflow.com/comment/87614036
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87614378
has comment: http://stackoverflow.com/comment/87614163
accepted answer of: http://stackoverflow.com/q/50298412
has body: With read_table, the default separator is assumed to be whitespace (sep='\t'). Change read_table to read_csv, which infers your separator. Alternatively, specify sep=',' for the same effect. You're trying to add a new column year, but you're not doing that correctly. You can use assign to add it in Concatenate vertically (axis=0, the default), not horizontally. df_list = [] for file in files: year = ... df_list.append(pd.read_csv(file, header=None).assign(year=year)) big_df = pd.concat(df_list, ignore_index=True) big_df.to_csv("Combined.csv", header=False, index=False)

http://stackoverflow.com/a/50381010
answers question: http://stackoverflow.com/q/50380468
has body: Internally lldb keeps a stack of "I/O Handlers" and so for instance expr just pushes the "Expr I/O Handler" onto the stack, collects the input till it is done and then pops itself off the stack and runs the command. There's what looks like a first sketch of an SB class (SBInputReader) to do this in the C++ SB API's but I don't think it's complete and it isn't currently exposed to Python. So I don't think there's enough wired up for you do to this from Python yet.
has comment: http://stackoverflow.com/comment/87814309
has comment: http://stackoverflow.com/comment/87792561
has comment: http://stackoverflow.com/comment/87778154
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50380468
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87545986
type: QuestionComment
has text: I prefer #1, but that is a preference.
score: 0
comment on: http://stackoverflow.com/q/50263986
type: Comment

http://stackoverflow.com/q/50242091
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I am working with a large array of positive numbers, say num_arrays. For example the shape of my numpy array is num_arrays.shape = (10, 10, 3000, 100, 50). Now I have a function defined as def func(x): return np.exp(-x**2)*np.sqrt(x) When I call func(num_arrays) it returns me MemoryError. I understand that this is because my array size is too large, but is there any ideas as to how I can avoid this error and still achieve my results?
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/87501796
tagged with: python
favorite count: 0
has title: Memory error for numpy operations: How do I bypass this?
has comment: http://stackoverflow.com/comment/87501909
score: 2
has comment: http://stackoverflow.com/comment/87505370
has comment: http://stackoverflow.com/comment/87504554
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87501910

http://stackoverflow.com/q/50265439
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/87549267
has comment: http://stackoverflow.com/comment/87549278
has comment: http://stackoverflow.com/comment/87548997
has comment: http://stackoverflow.com/comment/87548906
favorite count: 0
has comment: http://stackoverflow.com/comment/87549009
type: Question
has comment: http://stackoverflow.com/comment/87549047
has comment: http://stackoverflow.com/comment/87548904
has comment: http://stackoverflow.com/comment/87549284
has comment: http://stackoverflow.com/comment/87549146
tagged with: automation
tagged with: command-prompt
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/50266102
accepted answer: http://stackoverflow.com/a/50266102
has comment: http://stackoverflow.com/comment/87549226
has comment: http://stackoverflow.com/comment/87548925
has comment: http://stackoverflow.com/comment/87549312
has comment: http://stackoverflow.com/comment/87549184
has title: python dynamically answer yes/no to terminal prompt
type: AnsweredQuestion
tagged with: bash
has comment: http://stackoverflow.com/comment/87549220
has comment: http://stackoverflow.com/comment/87548942
upvote count: 1
has body: prompt question generator class SynthesisPromptGenerator: def wait_key(self): ''' Wait for a key press on the console and return it. ''' result = None for singlePrompt in ["questionCat", "questionDog"]: try: result = raw_input(singlePrompt) print 'input is: ', result except IOError: pass return result I have a PromptGenerator that will generate multiple terminal prompt questions, and after answering first question, then second will pop up, as questionCat (and wait for keyboard input) questionDog (and wait for keyboard input) my goal is to automatically and dynamically answer to the questions class PromptResponder: def respond(self): generator = SynthesisPromptGenerator() child = pexpect.spawn(generator.wait_key()) child.expect("\*Cat\*") child.sendline("yes") child.expect("\*Dog\*") child.sendline("no") child.expect(pexpect.EOF) if __name__ == "__main__": responder = PromptResponder() responder.respond() if the prompt question contains Cat then answer yes if the prompt question contains Dog then answer no So it comes to: how to get the prompt string from terminal and filter based on it? how to answer multiple prompt questions in python? I did some search but found most questions are for shell script echo yes | ./script, not much doing it in python thank you very much
answer count: 1

http://stackoverflow.com/q/50337452
has comment: http://stackoverflow.com/comment/87691996
tagged with: windows
has title: Python task scheduler file input and output 0x2
tagged with: python
tagged with: scheduled-tasks
has body: I've got a process I'm trying to automate through the Windows task scheduler. The file is located right next to the script on a subfolder in my desktop. A mockup that shows the problem I'm running into is: import os if __name__ == "__main__": lines = [] with open(r'C:\Users\user\Desktop\folder\config.txt') as file: for line in file: lines.append(line) with open(r'C:\Users\user\Desktop\folder\output.txt', 'w') as file: for line in lines: file.write(line) When I run this through the command line, the code works fine. The config file is read in properly and the output works properly. However, in task scheduler, the program fails to execute with an 0x2 error code. In task scheduler, I have the tried with the following task scheduler options selected: Run only when user is logged on/Run with highest priveledges Run only when user is logged on/Highest priveledges not checked Run whether user is logged on or not/Run with highest priveledges Run whether user is logged on or not/Highest priveledges not checked I am using absolute paths - as you can see in the above example. I'm also using the "start in" option inside of task scheduler. This is seriously annoying me. Edit: I am using absolute paths inside of task scheduler to both the Python executable and the script.
type: Question
has comment: http://stackoverflow.com/comment/87692742
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87693818
has comment: http://stackoverflow.com/comment/87693465
has comment: http://stackoverflow.com/comment/87696620
has comment: http://stackoverflow.com/comment/87694886
score: 0

http://stackoverflow.com/comment/87809060
comment on: http://stackoverflow.com/a/50383529
score: 0
type: Comment
type: AnswerComment
has text: @AnthonyLethuillier Definitely agree with that, Numba is the cleanest, best bet for your problem. I think I will still try to add some more info to this answer so it is more complete for future readers anyways

http://stackoverflow.com/comment/87595956
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50289938
has text: Also why read the entire df, and then make a new df just of the tweet column? You can just read the tweet column: `df = pd.read_csv("C:\\Users\\Ankit\\Downloads\\file.csv",usecols=['text'], index_col=0)`
score: 1

http://stackoverflow.com/q/50353740
has answer: http://stackoverflow.com/a/56376124
tagged with: python
has answer: http://stackoverflow.com/a/50354588
possible better answer: http://stackoverflow.com/a/50354588
tagged with: excel
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/87723836
upvote count: 7
accepted answer: http://stackoverflow.com/a/56376124
score: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/87723771
has body: Is there way to ignore duplicate column names after using to_excel() function of pandas? Say, I have old_wb.xlsx: &gt;&gt; df1 = pd.read_excel('wb1.xlsx') ---------------------merged header-------------------- col1 col2 col3 col1 col4 col1 col2 col5 test test test test test test test test and say I did some processing to my Excel file, for example, remove the merged header and save it to another Excel file: &gt;&gt; df1.to_excel('new_wb.xlsx', 'Sheet1', merged_cells=False, header=None, index=False) The column names of new_wb.xlsx looks like this: col1 col2 col3 col1.1 col4 col1.2 col2.1 col5 test test test test test test test test It added .1 to the duplicate column names and it also increments as the duplicate column name goes. I tried renaming the column name before using to_excel() but it didn't work. It seems the renaming of duplicates happens in to_excel(). &gt;&gt; df1.rename(columns=lambda x: x.replace('.1','')) Upon searching, I found an argument for to_excel() which is mangle_dupe_cols=False, unfortunately it returned: ValueError: Setting mangle_dupe_cols=False is not supported yet Any help on how to ignore duplicate column names in saving `to_excel()'
type: Question
answer count: 2
has title: pandas to_excel() ignore/allow duplicate column names

http://stackoverflow.com/q/50240423
has title: TypeError: __init__() got multiple values for argument 'fieldnames'
has comment: http://stackoverflow.com/comment/87498317
answer count: 2
has comment: http://stackoverflow.com/comment/87498292
has comment: http://stackoverflow.com/comment/87498405
downvote count: 0
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/50240512
has comment: http://stackoverflow.com/comment/87498356
type: AnsweredQuestion
has body: I have done a web scrape on a website for practice and I am trying to put the data into a pandas dataframe that can be exported to a csv and when I come to a point a TypeError: __init__() got multiple values for argument 'fieldnames' shows up. I want to write the file using the csv module. Can someone explain how the error has come to happen and how to solve it? My code is as follows: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import csv my_url = 'https://www.allagents.co.uk/find-agent/london/' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') containers = page_soup.findAll('div', {'class':'itemlabel3'}) filename = "webscrape.csv" records = [] for container in containers: comp_name = container.find('div', {'class':'labelleft2 col-md-10'}).div.h4.a.text address=container.find('div', {'class':'labelleft2 col-md-10'}).div.p.text.replace('\n','') tel = container.find('div', {'class':'labelleft2 col-md-10'}).div.find('p', {'style':'clear: both; margin-bottom: 15px;'}).strong.text records.append({'company': comp_name, 'address': address, 'telephone': tel}) writer = csv.DictWriter(filename, "w", fieldnames=['company', 'address', 'telephone']) writer.writeheader() for r in records: writer.writerow(r) Error comes on line : writer = csv.DictWriter(filename, "w", fieldnames=['company', 'address', 'telephone']) Thanks in advance, any help is appreciated.
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/50240506
score: 1
has comment: http://stackoverflow.com/comment/87498349
accepted answer: http://stackoverflow.com/a/50240512
upvote count: 1
has answer: http://stackoverflow.com/a/50240506
has comment: http://stackoverflow.com/comment/87498383
favorite count: 0
type: Question

http://stackoverflow.com/comment/124615222
type: Comment
type: QuestionComment
has text: Using annotate with these fields will be both efficient and readable IMO
comment on: http://stackoverflow.com/q/50292851
score: 0

http://stackoverflow.com/q/50252114
accepted answer: http://stackoverflow.com/a/50252911
answer count: 2
has body: I have a function foo(par1) with an internal function call, (db_fetch) which is a database call using SQLAlchemy to get a stored value as below: def foo(par1): db_value = db_fetch(par1) if db_value &gt; 10: return db_value * 5 else: return 1 I am currently creating a db pytest fixture and loading test data every time I run the test suite in order to provide data for the db_fetch function call. How can i convert the test to use dummy data for the db_fetch function call to speed up the test run?
tagged with: pytest
possible better answer: http://stackoverflow.com/a/50252807
has answer: http://stackoverflow.com/a/50252911
score: 0
has answer: http://stackoverflow.com/a/50252807
has title: How to unit test function that has an external function call using pytest
upvote count: 1
downvote count: 1
tagged with: sqlalchemy
favorite count: 0
tagged with: unit-testing
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87522806
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87522848

http://stackoverflow.com/q/50382685
has body: import chardet a='haha' print(chardet.detect(a)) TypeError: Expected object of type bytes or bytearray, got: &lt; class 'str'> I just type code from tutorial. I really can not figure out what wrong happended.
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/62906637
possible better answer: http://stackoverflow.com/a/62906637
accepted answer: http://stackoverflow.com/a/50383525
downvote count: 0
tagged with: chardet
favorite count: 0
has title: I use chardet to test encode , but i got error
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87781177
has answer: http://stackoverflow.com/a/50383525
score: 6
upvote count: 6
tagged with: python

http://stackoverflow.com/q/50370929
has answer: http://stackoverflow.com/a/50385360
answer count: 2
score: 1
downvote count: 0
upvote count: 1
tagged with: exchangelib
has body: Hello I'm currently working with exchangelib. Right now I want to create a subfolder of a subfolder of the inbox and I don't know if it's possible, yet. So I just want to ask if anyone knows more about my problem? My code for creating a subfolder of the inbox is simply: from exchangelib import Credentials, Account, Folder credentials = Credentials('test.example@mail.com', 'password') account = Account('test.example@mail.com', credentials=credentials, autodiscover=True) folder = Folder(parent=account.inbox, name="subfolder_name") folder.save() item.move(folder)
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Exchangelib: Create subfolder of subfolder of inbox
possible better answer: http://stackoverflow.com/a/50407053
accepted answer: http://stackoverflow.com/a/50385360
has answer: http://stackoverflow.com/a/50407053
tagged with: python

http://stackoverflow.com/q/50319942
tagged with: loops
upvote count: 1
has title: Loop through variables in Dask using Machine Learning
downvote count: 1
favorite count: 0
type: Question
tagged with: dask
has answer: http://stackoverflow.com/a/50321019
type: UnansweredQuestion
tagged with: python
has body: Good afternoon. I am encountering a slight hiccup in Dask. I'm fairly new to Dask (in Python) and I'd like to run parallelized ML models using pure Dask (as opposed to dask-ml) based on the variable named 'class'. I wish to know what the predicted outcome of the model will be as I vary feature1 (as, in my data, I know this is the most significant one). I run my computing on a 4-node cluster and save all the predicted for all classes in predicted_all. Here's an example of my pandas data df: +-------+--------+-------------+-------------+---+-------------+ | class | target | feature1 | feature2 | … | feature10 | +-------+--------+-------------+-------------+---+-------------+ | A | 5 | 97.19859896 | 816.6842211 | … | 0.54895439 | | A | 6 | 46.09606585 | 784.3270075 | … | 8.251889349 | | A | 43 | 17.65188263 | 549.5501609 | … | 13.50763389 | | A | 2 | 98.85817622 | 708.1968399 | … | 7.621150619 | | A | 56 | 88.01917025 | 613.0401243 | … | 6.000443628 | | B | 4 | 70.80513786 | 906.0185026 | … | 19.41657943 | | B | 78 | 93.80801173 | 891.289798 | … | 8.501099853 | | B | 7 | 46.63101139 | 483.0638367 | … | 3.875892614 | | B | 1 | 67.5788966 | 743.5923161 | … | 8.671806546 | | B | 0 | 90.90392867 | 109.8205978 | … | 17.70970394 | | … | | … | … | … | … | | Z | 89 | 58.424834 | 794.9165579 | … | 17.51302389 | | Z | 854 | 58.21094669 | 714.8873807 | … | 3.334251242 | | Z | 25 | 75.5155099 | 61.59911771 | … | 8.507249536 | | Z | 90 | 47.13722692 | 861.3884932 | … | 11.95500215 | | Z | 52 | 9.824626526 | 528.1958297 | … | 10.10468804 | +-------+--------+-------------+-------------+---+-------------+ df is a pandas dataframe onto which I'd like to run a loop so that dask parallelizes the work on each node whilst using pandas dataframe. As per the Dask tutorials, I do as follows: import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression classes = ['ABC...Z'] predicted_all = pd.DataFrame() def linearmodel(class): #application of linear regression on d…
tagged with: pandas
score: 0
answer count: 1

http://stackoverflow.com/comment/87644376
has text: @CtheSky thankyou for your answer. the extra information was unnecessary, but thanks. :)
type: AnswerComment
comment on: http://stackoverflow.com/a/50305408
score: 0
type: Comment

http://stackoverflow.com/q/50237093
has comment: http://stackoverflow.com/comment/87498435
has title: Start process from another process with Multiprocessing library in Python 3
has body: I'm developing an application with 3 main processes (GUI, process1, process2). The GUI creates process1, and process1 creates process2 (process2 is supposed to start a new QT gui in another window). While process1 is created and working without any trouble, process2 is created but not working, no new QTWidget is created as I want. No error or exception is thrown. Since the project is very large and I cannot write all the code in this question, here is an scheme of the application: class GuiMain(QMainWindow): ... proc1 = Process1(...) proc1.start() ... class Process1(mp.Process) def __init__(self, ...): mp.Process.__init__(self) def run(self): ... proc2 = Process2(...) proc2.start() ... class Process2(mp.Process) def __init__(self, ...): mp.Process.__init__(self) def run(self): # Creating a new QTApplication with MyQTWidget app = QtGui.QGuiApplication(sys.argv) ex = rcp_gui.MyQWidget() sys.exit(app.exec_()) class MyQWidget(QWidget): def __init__(self): QWidget.__init__() ... if __name__ == '__main__': app = QApplication(sys.argv) application = GuiMain() sys.exit(app.exec_()) Am I missing something? Is not possible to start a new QT window from another process than the main one? How can I achieve that?. Thank you in advance.
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/87492034
score: 0
has comment: http://stackoverflow.com/comment/87492362
tagged with: python
tagged with: python-3.x
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87491618
tagged with: pyqt5

http://stackoverflow.com/comment/87774550
has text: Great! `Happy Coding`.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50379148

http://stackoverflow.com/comment/87561010
has text: @kishore You can do that using the `dateparser` package. The details are in the readme. https://github.com/scrapinghub/dateparser#usage
type: Comment
comment on: http://stackoverflow.com/a/50271516
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87580502
type: Comment
comment on: http://stackoverflow.com/q/50281187
score: 0
has text: Due to the loss of information that occurs because of the way you're converting the wav data to image data, it'll be impossible to convert it back into its original form.
type: QuestionComment

http://stackoverflow.com/comment/87564097
type: Comment
has text: Oh, you mean finding which of the three lists: list1, list2, list3 has the optimal weights?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50267718

http://stackoverflow.com/q/50238030
tagged with: python
has comment: http://stackoverflow.com/comment/87494118
type: Question
has title: Worse results when using tf.estimator.DNNRegressor vs tf.contrib.learn.DNNRegressor
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
has body: I am having issues when using the canned tf.estimator.DNNRegressor available for Tensorflow. I am getting much worse results at around 3.05 loss with tf.estimator.DNNRegressor vs 0.018 loss with the tf.contrib.learn.DNNRegressor. It's important to note that they are running the same code (same features, same epochs, steps, activation_fn=tf.nn.relu, hidden_units, optimizer, etc.) I would like to know if there are some significant differences between the two regressors. Why am I getting worse results if they are using the same parameters? and How to solve this in order to have similar results? I saw that the tf.contrib.learn.DNNRegressor is being deprecated, so the new estimator implementation should at least have similar results, right? Thanks in advance for any help or clarification.
has comment: http://stackoverflow.com/comment/87493405
has comment: http://stackoverflow.com/comment/87494225

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/50256825

http://stackoverflow.com/q/50320718
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/50320970
has title: Docker app cannot find module named 'graphene_django'
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has body: I used the Django Rest Framework cookiecutter available here to scaffold a project. I've made no changes aside from setting up a virtualenv, installing requirements, and running pip install graphene_django. However, when I add graphene_django to the INSTALLED_APPS I receive the following error when attempting to run the server: ModuleNotFoundError: No module named graphene_django Any ideas why? Traceback: Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked Pip freeze: ... graphene-django==2.0.0 ... Command to run app: docker-compose up
type: Question
tagged with: docker
tagged with: docker-compose
score: 1
tagged with: graphene-django

http://stackoverflow.com/comment/87623406
type: QuestionComment
has text: If not, just loop. Break it down step by step, and all the parts are easy. `results = d['results']`, then `for result in results:`, then `components = result['address_components']`, then `for component in components:`, then you can do things like `if 'postal_code' in component['types']:`.
comment on: http://stackoverflow.com/q/50303439
score: 0
type: Comment

http://stackoverflow.com/comment/87717850
has text: this is not what OP wants to do though.. It just looks like that because he is using a bad example. *"the keys are those element from second list that are found in the first and values are lists of elements found between "keys""*
comment on: http://stackoverflow.com/a/50350826
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/87703891
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50336535
has text: I like it. How does it scale up when nrows is huge, and time resolution is high
type: AnswerComment

http://stackoverflow.com/comment/87768059
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50375660
has text: @roganjosh The script I'm calling is `openbmp-mrt` from `src/bin`. The `openbmp` is a directory within `src/site-packages` which contains the `mrt` directory which in turn contains the module I'm trying to import

http://stackoverflow.com/q/50277602
has title: Pandas DataFrame pivot reset
has answer: http://stackoverflow.com/a/50277797
answer count: 1
accepted answer: http://stackoverflow.com/a/50277797
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I have a data frame and applying a pivot on that but the output is not as expected. import pandas as pd import numpy as np raw_data = { 'PRODUCT': ['Display', 'InStream', 'Mobile'], 'BLAZE_TAG_NAME_DESC': ['enewsletter', 'get_the_guide', 'logo'], 'CLICKTHRU': [19,30,40], 'INTERACTION':[30,40,50]} df_a = pd.DataFrame(raw_data, columns = ['PRODUCT', 'BLAZE_TAG_NAME_DESC', 'CLICKTHRU','INTERACTION']) df_b = pd.pivot_table(df_a,index="PRODUCT",columns="BLAZE_TAG_NAME_DESC",values=['CLICKTHRU','INTERACTION'],aggfunc=np.sum,fill_value = 0) Output: I want the output is like I tried the trick reset index. but that's not working df.reset_index() please help.
type: Question

http://stackoverflow.com/comment/87693229
comment on: http://stackoverflow.com/q/50338469
type: Comment
type: QuestionComment
score: 0
has text: why does `def func(z,x): z.append(x)` not work for you? I do not see the appeal of your `func()` btw.

http://stackoverflow.com/comment/87491154
type: AnswerComment
comment on: http://stackoverflow.com/a/50236534
score: 1
type: Comment
has text: I think Python 2.6 is halfway *ancient*. People only use 2.7 and 3.x nowadays.

http://stackoverflow.com/comment/87613709
has text: There are various problems with that code. But apart from the issues already mentioned, and your unnecessary use of globals, are you sure that `message['data']` and `message1['data']` contain integers and not strings?
type: Comment
comment on: http://stackoverflow.com/q/50298283
score: 1
type: QuestionComment

http://stackoverflow.com/a/50242802
answers question: http://stackoverflow.com/q/50242754
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: The command would look like plt.plot(*D["str1"]) i.e. you select the "str1" entry from the dictionary and unpack it to the x and y arguments of plot.
accepted answer of: http://stackoverflow.com/q/50242754
type: Answer

http://stackoverflow.com/a/50821759
has comment: http://stackoverflow.com/comment/88702090
accepted answer of: http://stackoverflow.com/q/50256838
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/88739494
has body: The Cell Types Database contains two groups of data sets -- large sets of transcriptomics-only cells (see http://celltypes.brain-map.org/download), and one large set of cells with electrophysiology, some of which also have morphology (http://celltypes.brain-map.org/data). Detailed information on the experimental overview and methods used in these studies is available as whitepapers in the Documentation section (http://help.brain-map.org/display/celltypes/Documentation). The example cell in your question has electrophysiology and morphology, but no transcriptomics, so it does not inherently belong to a transcriptomic cluster. The AllenSDK currently supports downloading metadata for electrophysiology-morphology cells, but not the transcriptomics-only cells. You can download metadata these cells as CSV files. If you would like to be able to access transcriptomics metadata from the AllenSDK instead of flat CSV files, please create an issue on the AllenSDK issue tracker (https://github.com/alleninstitute/allensdk/issues). Good news -- in a couple days we will be releasing cluster assignments on much of the data you see here (http://celltypes.brain-map.org/data), including the mouse visual cortex data set. This will include many more cells for some data sets. You will be able to download this data, including cluster assignments and metadata, as CSV files. Note that mouse visual cortex data available within the Cell Types Database is a different set of cells (and profiling methodology) from the data in the Cellular Taxonomy science case study.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50256838

http://stackoverflow.com/q/50306223
upvote count: 2
has comment: http://stackoverflow.com/comment/87628615
has answer: http://stackoverflow.com/a/50306485
possible better answer: http://stackoverflow.com/a/50306485
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50306427
has answer: http://stackoverflow.com/a/56942100
has body: I only want to run a piece of code if the time is between specific minutes in an hour but I can't figure out how to get the hour number in Python. The equivalent code in PHP is: if (intval(date('i', time())) &gt; 15 &amp;&amp; intval(date('i', time())) &lt; 32) { // any time from hour:16 to hour:33, inclusive } else { // any time until hour:15 or from hour:32 } In Python it would be something like this: import time from datetime import date if date.fromtimestamp(time.time()): run_my_code() else: print('Not running my code') I'd typically use cron but this is running inside a Lambda and I want to make absolutely sure this code does NOT get run all the time.
has title: Python Only If Time is 5 past the hour
tagged with: python
tagged with: date
score: 2
linked to: http://stackoverflow.com/q/30071886
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50306427
answer count: 3

http://stackoverflow.com/comment/117542955
comment on: http://stackoverflow.com/a/54318948
type: Comment
type: AnswerComment
has text: I had a similar problem which gave me this error: `'min value is {0}'` for loading an Excel file through `pd.read_excel` which uses _openpyxl_ engine. I got through this by **clearing all formatting** as you suggested here and worked with no problem! Thanks!!
score: 0

http://stackoverflow.com/comment/87654516
score: 0
type: Comment
type: QuestionComment
has text: Shouldn't this be `identifier`, instead of `itentifier`?
comment on: http://stackoverflow.com/q/50319394

http://stackoverflow.com/q/50346117
type: Question
answer count: 2
has body: I got a binary file written in java.I want to read the file with python,and convert every 4 bytes to a float. the first 4 bytes is bce9 1165,but I read it is b'\xbc\xe9\x11e' by the code with open(filename, "rb+") as f: f.read(4) it's different！ Then I convert it by struct.unpack('f',data1).but I got the wrong float. the wrong float is 4.30659236383095e+22. but it's truly -0.028450677 so how to decode it？
has answer: http://stackoverflow.com/a/50346252
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/29393785
has title: how to transform bytes to float with python?
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/50346363
has answer: http://stackoverflow.com/a/50346363
possible better answer: http://stackoverflow.com/a/50346252
favorite count: 0

http://stackoverflow.com/comment/87503009
has text: So how would you suggest implementing this with a return statement in the parse function. I've heard it's better practice to have functions like this return rather than print.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50242610
type: AnswerComment

http://stackoverflow.com/q/50306696
upvote count: 1
has answer: http://stackoverflow.com/a/50307267
has body: I actually have a dataframe such: seq1_id seq2_id dN length1 length2 GC1 GC2 g13600.t1_0042_0042 g66097.t1_0035_0035 0.10 45 67 0.78 0.67 g1464.t1_0035_0042 g45594.t1_0042_0035 0.67 56 34 0.65 0.87 g34744.t1_0042_0035 g50055.t1_0035_0035 0.08 34 76 0.75 0.45 g12096.t1_0035_0042 g34020.t1_0042_0035 0.43 31 54 0.89 0.76 and I would like to change the order of my columns, in fact get on the first column only the gene name with the first _number being _0035 and in the other the first _number being 0042, here it would give: seq1_id seq2_id dN length1 length2 GC1 GC2 g66097.t1_0035_0035 g13600.t1_0042_0042 0.10 45 67 0.78 0.67 g1464.t1_0035_0042 g45594.t1_0042_0035 0.67 34 56 0.87 0.65 g50055.t1_0035_0035 g34744.t1_0042_0035 0.08 34 76 0.75 0.45 g12096.t1_0035_0042 g34020.t1_0042_0035 0.43 54 31 0.76 0.89 as you can se, on the first column, I got only gene name begening with _0035 and when there is a swip, the column length1 and 2 and GC1 and 2 move too. thanks for your help
tagged with: parsing
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
tagged with: pandas
score: 1
has title: Switch two column depending to a pattern with pandas
accepted answer: http://stackoverflow.com/a/50307267
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/87645070
type: QuestionComment
has text: See [this demo](http://rextester.com/WPFT25099), are the results expected ones?
score: 0
comment on: http://stackoverflow.com/q/50312991
type: Comment

http://stackoverflow.com/comment/87683755
type: Comment
comment on: http://stackoverflow.com/q/50327792
has text: I don't know anything about thrift, but 0x5353482D is the four characters "SSH-", which happens to be the first data sent by an ssh server when something connects to it. My guess is that you're trying to start up thrift on a raw TCP socket connected to the ssh server.
score: 1
type: QuestionComment

http://stackoverflow.com/a/50264468
upvote count: 5
type: Answer
has body: You can using replace df.replace(dict(zip(np.unique(df.values),list(range(len(np.unique(df.values))))))) Origin Destination 0 0 3 1 0 2 2 3 0 3 3 2 4 3 1 5 1 0 Succinct and nice answer from Pir df.replace((lambda u: dict(zip(u, range(u.size))))(np.unique(df))) And df.replace(dict(zip(np.unique(df), itertools.count())))
score: 5
has comment: http://stackoverflow.com/comment/87547242
downvote count: 0
has comment: http://stackoverflow.com/comment/87547096
answers question: http://stackoverflow.com/q/50264334

http://stackoverflow.com/comment/87745618
type: Comment
has text: @abarnert `\\\\jocker\\linux\\notes\\details.txt ` and `\\jocker\linux\notes\details.txt ` both file paths are opening in browser. Please help in figuring out what may be possible errors. Thanks for your help.
score: 0
comment on: http://stackoverflow.com/q/50358321
type: QuestionComment

http://stackoverflow.com/comment/87502984
has text: This is a py2 vs py3 error. Use `raw_input`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50242641
type: QuestionComment

http://stackoverflow.com/comment/87578225
score: 1
has text: add a name to each url in your url patterns
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50280824

http://stackoverflow.com/q/50294989
tagged with: bokeh
has comment: http://stackoverflow.com/comment/87608578
has title: Can I use some client-side cache for 'Big Datas' dynamic visualisation on a Dashboard?
favorite count: 0
type: Question
tagged with: dashboard
type: UnansweredQuestion
has body: Good afternoon people ! Programming language : Python. Web Framework : Django. Graphic framework : Bokeh. Currently trying to set up a Dashboard-like application for my company where each factory would be able to upload their own csv-like data and have dynamic results presentation after data cleaning and processing, and some predictions from machine-learning if enough data is provided. The dynamic part is mostly using widgets to let them choose how to visualize, what to visualize, different parts of the data analysis process etc... with either JS Callbacks of the Bokeh server functionality. Until now I decided not to use DataBase Storage but server-side storage in different big CSV, it seems like I have faster access to those on server-side than filtering each time my tables for a given factory upload. Also thought about creating temporary tables/models but didn't feel it right. Before getting into any hard time programming that, I'd like to know if there is any easy answer to my questions, didn't find suitable solution online regarding this, considering the fact that they might upload a bunch of CSV at once. Is there anyway to save all the data (after cleaned on the server) in client-side cache so I have to send it only one time and then just sending the adapted graph structures, which would take the data from client-side cache to display them ? Is there any smarter way to do so between JS callbacks and Bokeh Server ? The documentation didn't help me much to decide between them. I am taking any tips, and thanks for your time. Have a nice week-end !
tagged with: bigdata
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87665786
answer count: 0
score: 1

http://stackoverflow.com/comment/87652231
score: 1
type: Comment
type: AnswerComment
has text: I did not downvote, but this would have been my first option had I answered the question. +1
comment on: http://stackoverflow.com/a/50318029

apiclient
tags question: http://stackoverflow.com/q/50240315
tag name: apiclient
type: Tag

http://stackoverflow.com/comment/87590565
score: 0
has text: Uhh, I thought the condition is testing if a variable exists, even if the variable is False.
type: QuestionComment
comment on: http://stackoverflow.com/q/50287280
type: Comment

http://stackoverflow.com/comment/87614378
comment on: http://stackoverflow.com/a/50298475
type: Comment
type: AnswerComment
score: 1
has text: @BruceWayne AHA! Because your text files have no header. The reason that happened is because concat tries to auto align the concatted DataFrames, resulting in a huge memory blowout with NaNs. Thanks for that, I'll fix my answer to reflect that.

http://stackoverflow.com/q/50371740
has body: when I click the key in the left down corner with a Windows logo and click IDLE (Python 3.6 32-bit) it loads (I can see the blue cicle) but IDLE doesn't open. I tried about ten times. Yesterday it worked fine. Same happens when I press the Windows key. I have Windows 10 and my computer is HP Compaq CQ2000. I don't think I did any changes to Python files on my computer since yesterday. How can I fix it?
has title: Every time I want to start Python IDLE, it just loads
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87764060
has comment: http://stackoverflow.com/comment/87764812
tagged with: python
tagged with: python-idle
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87759472
has comment: http://stackoverflow.com/comment/87765483

http://stackoverflow.com/comment/87762547
comment on: http://stackoverflow.com/q/50373062
score: 0
has text: To get started: https://stackoverflow.com/questions/4709652/python-regex-match-date
type: Comment
type: QuestionComment

python-3.6
tags question: http://stackoverflow.com/q/50248017
tags question: http://stackoverflow.com/q/50268298
tags question: http://stackoverflow.com/q/50269701
tags question: http://stackoverflow.com/q/50247068
tags question: http://stackoverflow.com/q/50330952
tags question: http://stackoverflow.com/q/50261986
tags question: http://stackoverflow.com/q/50348581
tags question: http://stackoverflow.com/q/50277848
tags question: http://stackoverflow.com/q/50243910
tags question: http://stackoverflow.com/q/50276363
tags question: http://stackoverflow.com/q/50235844
tags question: http://stackoverflow.com/q/50353277
tags question: http://stackoverflow.com/q/50382119
tags question: http://stackoverflow.com/q/50315407
tags question: http://stackoverflow.com/q/50312426
type: Tag
tags question: http://stackoverflow.com/q/50359002
tags question: http://stackoverflow.com/q/50244910
tag name: python-3.6
tags question: http://stackoverflow.com/q/50331601
tags question: http://stackoverflow.com/q/50317358
tags question: http://stackoverflow.com/q/50375793
tags question: http://stackoverflow.com/q/50238832
tags question: http://stackoverflow.com/q/50271664
tags question: http://stackoverflow.com/q/50271671
tags question: http://stackoverflow.com/q/50273544
tags question: http://stackoverflow.com/q/50257798
tags question: http://stackoverflow.com/q/50384549
tags question: http://stackoverflow.com/q/50260772
tags question: http://stackoverflow.com/q/50309685
tags question: http://stackoverflow.com/q/50316521
tags question: http://stackoverflow.com/q/50255229

http://stackoverflow.com/a/50383536
has comment: http://stackoverflow.com/comment/87785157
has comment: http://stackoverflow.com/comment/87785572
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87821510
upvote count: 1
has comment: http://stackoverflow.com/comment/87821240
has comment: http://stackoverflow.com/comment/87821339
has comment: http://stackoverflow.com/comment/87821403
answers question: http://stackoverflow.com/q/50383432
has body: Since you named variable post in for loop, you should use post inside cycle. It should be {{ post.likes.count }} Agree Instead of {{ obj.likes.count }} Agree
score: 1
accepted answer of: http://stackoverflow.com/q/50383432
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87821263

http://stackoverflow.com/a/50299307
score: 2
has comment: http://stackoverflow.com/comment/87618380
has comment: http://stackoverflow.com/comment/87617969
answers question: http://stackoverflow.com/q/50298305
upvote count: 2
downvote count: 0
type: Answer
has body: I think one easiest way is to use aspect='auto' with ax[1].imshow(z). But this will distort the image in a way that may be not the same as what you've shown in the question. And it may not work for cases where there is no single n. I'm not sure if I got you 100%, but let me try this method. The key idea here are: Change the aspect ratio of your fig. The exact ratio comes from both your image data and your subplot layout. Use tight layout to eliminate unnecessary between axes which may offset your graph a little bit. Here is my example code and figure: import matplotlib.pyplot as plt from matplotlib.figure import figaspect import numpy as np n = 10 x = np.random.rand(n,1) y = np.random.rand(1,n) z = np.random.rand(n,n) width_max = max(s.shape[0] for s in [x, y, z]) height_max = max(s.shape[1] for s in [x, y, z]) row = 1 col = 3 fig, ax = plt.subplots(row, col) w, h = figaspect(row*width_max/(col*height_max)) fig.set_size_inches(w, h) ax[0].imshow(x) ax[1].imshow(z) ax[2].imshow(y) plt.tight_layout() plt.show() I hope this solves your real problem. I think this also works for a case like: x = np.random.rand(3,1) y = np.random.rand(1,10) z = np.random.rand(7,6)

http://stackoverflow.com/comment/87621321
comment on: http://stackoverflow.com/q/50296126
type: Comment
type: QuestionComment
has text: My assumption is that the .sql file is a script which takes your JSON and inserts it into a table? If that is so, that file is most likely meant to be run from SSMS manually.
score: 0

http://stackoverflow.com/comment/87633898
score: 0
has text: @Lemon Separate pickle files based on which server a message comes from, or store the information in a database of some kind (and store originating-server-location information along with the quote itself).
comment on: http://stackoverflow.com/a/50307648
type: Comment
type: AnswerComment

rx-py
tag name: rx-py
tags question: http://stackoverflow.com/q/50324645
type: Tag

http://stackoverflow.com/q/50308028
downvote count: 0
has title: python bs4 get element in popup without selenium
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/87632598
tagged with: python
accepted answer: http://stackoverflow.com/a/50308399
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50308399
has body: I would like to gather data behind a popup in this page. https://www.commonsense.org/education/game/garrys-mod I am trying to gather data in the popup Subjects &amp; skills. I know I could use selenium, but I would rather not if it is not useful. The data I am trying to gather is in there: subjectSkills = gameSoup.find('div',class_='popper popper-popover subjects-skills') However, it returns None, since it is behind a popup that looks like this: &lt;a href="#" id="subjects-skills" class="body-color" data-toggle="popover" data-content=".subjects-skills" data-arrow="false" target="_self"&gt;Subjects &amp;amp; skills&lt;/a&gt; When the arrow button has been clicked, the value of data-arrow changes to true and this might be a solution, but I am unsure how/if it is possible to change this value. Thanks
score: 3
upvote count: 3
answer count: 1

http://stackoverflow.com/comment/87647677
score: 0
comment on: http://stackoverflow.com/q/50314243
type: Comment
type: QuestionComment
has text: Well, multiplying `F` by `dy*dx/2/np.pi` certainly does change something: Now all values of `F` lie between zero and one.

http://stackoverflow.com/comment/87565128
comment on: http://stackoverflow.com/q/50274084
has text: Did you also restart the command window in which you ran `pip3 install pynacl`?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87602239
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50292648
has text: Yes, this did work and it's also quite fast on the dataset. Thank you for your help!
type: Comment

http://stackoverflow.com/comment/87620618
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50282531
has text: The anwer was close enough to perfect to be useful.and still is.
type: Comment

http://stackoverflow.com/comment/87659391
score: 0
has text: @IgnacioVazquez-Abrams This is so confusing, what's `allow_unicode` used for?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50321644

http://stackoverflow.com/comment/87532222
type: QuestionComment
comment on: http://stackoverflow.com/q/50257152
score: 1
type: Comment
has text: Your training set is just 1 image ?

http://stackoverflow.com/a/50285659
answers question: http://stackoverflow.com/q/50278649
score: 3
type: Answer
has body: It works fine on my side. According to your description, it seems that you may directly request on browser to the address http://localhost:9000 via Get method, which could raise this issue. You can use Bot Framework Emulator to test and debug the bot application on local.
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50278649
has comment: http://stackoverflow.com/comment/87612119

http://stackoverflow.com/q/50332249
tagged with: math
tagged with: python
accepted answer: http://stackoverflow.com/a/50333734
has body: I have interpolation function: from scipy import interpolate def f(x): x_points = [38508,38510,38512] y_points = [0.249267578125,0.181396484375,0.1912841796875] tck = interpolate.splrep(x_points, y_points,k=2,xb=38508,xe=38512) return interpolate.splev(x, tck) when i evaluate f(38503) output is 0.75 which is nothing like y_points. Any suggestion on how to decrease this error using this or other interpolation methods?
has answer: http://stackoverflow.com/a/50333734
tagged with: interpolation
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/2745329
has comment: http://stackoverflow.com/comment/87681615
has comment: http://stackoverflow.com/comment/87707815
answer count: 1
type: Question
has title: How to set upper and lower bound on B-Spline result to get a reasonable interpolation

http://stackoverflow.com/q/50365283
tagged with: apply
has comment: http://stackoverflow.com/comment/87746862
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50365330
type: UnansweredQuestion
has title: How can I pass arguments dynamically to a DataFrame.apply() lambda function?
upvote count: 1
tagged with: python
has body: I'm trying to run the Pandas apply() method for a Dataframe to create a new column, as follows: df['new_column'] = df.groupby(groupby).apply(lambda x: some_function(x, df['existing_column'])) So, basically, I'm trying to pass the second argument of some_function dynamically, relative to what df['existing_column'] stores as a value for each row (values differ). The error I get is the common TypeError: 'Series' objects are mutable, thus they cannot be hashed. Is there a proper way to to this? I tried doing a for-loop for each row, but that kills my CPU.
tagged with: pandas
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/116628969
comment on: http://stackoverflow.com/a/65933710
score: 0
has text: My problem is that I can't seem to get to the directory where the notebook I want to import is. I have the notebook I want to import (Notebook A) and Notebook I want to import into (Notebook B) in the same Google Drive directory. But when I open Notebook B in colab, the system says (using !pwd) that it is in `/content` and that it can't see Notebook A. All it can see is `sample_data`. How do I put myself in the right directory?
type: Comment
type: AnswerComment

combobox
tags question: http://stackoverflow.com/q/50280170
type: Tag
tag name: combobox

http://stackoverflow.com/comment/87566302
type: Comment
has text: You forgot to include logic keeping the row with the smallest distance between weights.
comment on: http://stackoverflow.com/a/50263912
type: AnswerComment
score: 0

http://stackoverflow.com/q/50298114
possible better answer: http://stackoverflow.com/a/53433216
has answer: http://stackoverflow.com/a/50298513
upvote count: 23
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50330016
accepted answer: http://stackoverflow.com/a/50330016
score: 21
has body: This question specifically aims for a Django 2.0 answer as the registration module isn't available (yet) for it. More, this might seem to broad, but I often found myself in situations where I can't use any 3rd party module because ... oh well..policies. I'm sure many did. And I know that looking and putting together information taken from here or django docs was a headache. Workflow: Let's suppose we need the following flow: The user goes to the sign-up page and fills in the following fields: first_name, last_name and email (the email will be used as the username). The user submits the form and receives a confirmation email with an URL containing a unique token. When the user clicks on the received link, he's redirected to a page where he'll set his password. When done, he's logged in to the dashboard page. Extra-info: The user will later log in by using his email (which is actually his username) and password. Specific question: How will the models/views (using CBVs)/forms/urls look like?
has comment: http://stackoverflow.com/comment/87613434
has comment: http://stackoverflow.com/comment/87613416
tagged with: python
linked to: http://stackoverflow.com/q/15012235
answer count: 4
has comment: http://stackoverflow.com/comment/87613361
has title: Django 2 - How to register a user using email confirmation and CBVs?
has answer: http://stackoverflow.com/a/74376383
downvote count: 2
tagged with: authentication
has answer: http://stackoverflow.com/a/53433216
tagged with: django

http://stackoverflow.com/comment/87629151
type: Comment
type: QuestionComment
has text: Yes, thank you very much, i just had to write {img_str.size*8} because new list of bits is 8 times longer
score: 0
comment on: http://stackoverflow.com/q/50306145

rounding-error
tag name: rounding-error
tags question: http://stackoverflow.com/q/50374779
type: Tag

http://stackoverflow.com/comment/117648135
type: AnswerComment
comment on: http://stackoverflow.com/a/50231262
score: 0
type: Comment
has text: @duhaime One question: ```runtime.txt``` you mean ```requirements.txt``` or is that a separate file?

http://stackoverflow.com/q/50275174
type: UnansweredQuestion
tagged with: matplotlib
has body: I am playing with Non-Negative Matrix Factorisation (NMF) algorithm on MNIST database and I want to visualise how the first 15 components change when I reduce total number of components. First I download the MNIST Database and transform it to numPy arrays import numpy as np from mnist import MNIST mndata = MNIST('./data') images_train, labels_train = mndata.load_training() images_test, labels_test = mndata.load_testing() labels_train = labels_train.tolist() labels_test = labels_test.tolist() X_train = np.array(images_train).astype('float64') y_train = np.array(labels_train) X_test = np.array(images_test).astype('float64') y_test = np.array(labels_test) Then I build the NMF model with 100 components from sklearn.decomposition import NMF nmf = NMF(n_components=100, random_state=0) nmf.fit(X_train) and I display first 15 components import matplotlib.pyplot as plt fig, axes = plt.subplots(3, 5, figsize=(12, 7), subplot_kw={'xticks': (), 'yticks': ()}) for i, (component, ax) in enumerate(zip(nmf.components_, axes.ravel())): ax.imshow(component.reshape(28,28), cmap=plt.cm.binary) ax.set_title("{}. component".format(i + 1)) Output: Then I repeat the same process for 50 components Output: and lastly for 15 components Output: I wonder if the first 15 components of these NMF models changes smoothly when I reduce the number of total components. I would like to plot whole bunch of the pictures like the ones above and display them in an animation. More precisely I would like to animate them when number of total components goes from 100 to 15 with the step equal to 5. How can I do this?
tagged with: animation
tagged with: python
has comment: http://stackoverflow.com/comment/87578663
score: 0
has comment: http://stackoverflow.com/comment/87593073
tagged with: visualization
answer count: 0
has title: How to make an animation from a bunch of plots containing subplots
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87590088
type: Question

http://stackoverflow.com/q/50275281
tagged with: salt-project
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-2.6
type: UnansweredQuestion
tagged with: python
has title: salt-ssh : Error appear when trying to cpmile a sls command
has body: this message error appear when i trying to run test.ping command : _error: Failed to return clean data retcode: 10 stderr: ERROR: Unable to locate appropriate python command stdout: ERROR: salt requires python 2.6 or newer on target hosts, must have same major version as origin host knowing that the version of python installed in both hosts (master and minion ) is the same
answer count: 0
score: 1

http://stackoverflow.com/comment/87777155
type: QuestionComment
score: 0
has text: can you provide an example 4-scale list?
comment on: http://stackoverflow.com/q/50380479
type: Comment

medium-editor
tags question: http://stackoverflow.com/q/50288156
type: Tag
tag name: medium-editor

http://stackoverflow.com/a/50379681
answers question: http://stackoverflow.com/q/50378554
score: 0
has body: Another (maybe less pythonic solution) can be this: city_state_df = pd.DataFrame({'citystate' :['ALABAMA', np.NaN, 'Birmingham', 'Huntsville', np.NaN,'CALIFORNIA',np.NaN, 'Los Angeles','San Diego',np.NaN]}) citystate 0 ALABAMA 1 NaN 2 Birmingham 3 Huntsville 4 NaN 5 CALIFORNIA 6 NaN 7 Los Angeles 8 San Diego 9 NaN Copy the column and delete the rows that are not upper case in the first column and the one that are uppercase in the second one. Use bfill in the first and delete the rows that are null.In the end rename the columns city_state_df['city'] = city_state_df['citystate'] city_state_df = city_state_df.replace(np.nan, '', regex=True) city_state_df['citystate'] = city_state_df['citystate'].apply(lambda x: x if x.isupper() else np.NaN).ffill() city_state_df['city'] = city_state_df['city'].apply(lambda x: np.NaN if x.isupper() else x) city_state_df = city_state_df.replace('', np.NaN, regex=True).dropna(subset=['city']) city_state_df.columns = ['state', 'city'] Output: state city 2 ALABAMA Birmingham 3 ALABAMA Huntsville 7 CALIFORNIA Los Angeles 8 CALIFORNIA San Diego
has comment: http://stackoverflow.com/comment/87806015
type: Answer

http://stackoverflow.com/comment/87547761
has text: But your just import at `\api\factory.py`, do not at the same directory with your `settings.py`
comment on: http://stackoverflow.com/q/50264831
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/102498992
comment on: http://stackoverflow.com/a/57520238
type: Comment
score: 4
has text: I can't find the default files in `site-packages/sphinx/templates/apidoc` on my computer, but you can find them [here](https://github.com/sphinx-doc/sphinx/tree/master/sphinx/templates/apidoc)
type: AnswerComment

http://stackoverflow.com/q/50317735
downvote count: 0
has body: I'm writing an ORM wrapper that allows one to write model definitions with type annotations. I would now like to add generic types Unique[T], Index[T] and Primary[T] to annotate types that have a corresponding constraint. However, I would like those types to be transparent proxies for T for IDEs and other static type checkers. So if one has a type like: something: Unique[str] Type checkers and IDEs would act like it said: something: str The current implementation is: T = TypeVar('T') class Unique(Generic[T]): def __new__(cls, *args, **kwargs): raise TypeError(f'cannot instantiate {cls}') Would there be a way to make it into a sort of proxy type?
tagged with: python
answer count: 1
favorite count: 0
type: Question
score: 3
upvote count: 3
tagged with: python-typing
accepted answer: http://stackoverflow.com/a/50321031
has answer: http://stackoverflow.com/a/50321031
has comment: http://stackoverflow.com/comment/90126276
has title: How to make generic proxy types work with static type checkers
type: AnsweredQuestion

http://stackoverflow.com/comment/87554379
has text: Not like that. I am getting empty dataframe after applying melt function. data is like: 6 digits in player match and 4 digits in player_average. Any suggestion to handle this situation?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50248505
type: Comment

http://stackoverflow.com/q/50350915
has comment: http://stackoverflow.com/comment/87717836
has title: Python - Extract Number From String Without Square Bracket
has body: So i am currently developing an AI, but i need help with getting the age. So if someone inputs "I am 14 years old" i want it to take the 14 and set it has a variable. I have done this but, square brackets go around the output, which i don't want, so i am looking for a way to,get the number from the string without square brackets. This is my code #Gets users age elif "i am" in inp and "years old" in inp: age=[int(s) for s in inp.split() if s.isdigit()] age=str(age) print(age) Any help is appreciated
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50351009
tagged with: python
has comment: http://stackoverflow.com/comment/87717840
has answer: http://stackoverflow.com/a/50351021
has answer: http://stackoverflow.com/a/50351209
answer count: 3
score: 0
type: Question

http://stackoverflow.com/q/50384261
has title: How to submit multiple forms to same flask page?
favorite count: 0
has comment: http://stackoverflow.com/comment/87784228
has comment: http://stackoverflow.com/comment/87784290
type: Question
has comment: http://stackoverflow.com/comment/91573085
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87784251
has comment: http://stackoverflow.com/comment/87784200
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/87784718
tagged with: python
tagged with: flask
tagged with: post
score: 3
has body: I have multiple forms in a page.On submit it all should goto same page for processing. But how will I address that? Currently I have this: if request.method == 'POST': project = request.form['project_name'] But this doesn't specify from which form I am submitting data from. Is there anyway to specify form to be processed?
answer count: 0
upvote count: 3
downvote count: 0
tagged with: forms

http://stackoverflow.com/a/50333124
has comment: http://stackoverflow.com/comment/87692410
has body: I would suggest you using the win32gui library for this task as shown below: import win32gui hwnd = win32gui.FindWindow(None, 'Notepad') win32gui.SetForegroundWindow(hwnd) win32gui.ShowWindow(hwnd, 9) The number 9 represents SW_RESTORE as shown here
answers question: http://stackoverflow.com/q/50332830
has comment: http://stackoverflow.com/comment/87694116
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87682697
downvote count: 0
has comment: http://stackoverflow.com/comment/87682766
type: Answer

http://stackoverflow.com/q/50263299
has comment: http://stackoverflow.com/comment/87544838
tagged with: python
has comment: http://stackoverflow.com/comment/87544810
has comment: http://stackoverflow.com/comment/87544671
type: AnsweredQuestion
score: 0
has title: Python Calculator Kinematics
has comment: http://stackoverflow.com/comment/87544741
accepted answer: http://stackoverflow.com/a/50263522
has comment: http://stackoverflow.com/comment/87544890
has answer: http://stackoverflow.com/a/50263522
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87544644
downvote count: 1
favorite count: 0
has body: Hey guys what I'm trying to do here is make a very basic kinematics variable solver, so I've got the basic equation vf = vi + at. Now what I'm trying to do is make it so if you don't know the variable, you input / which is the variable you solve for. But the problem is, when I try to enter the variable as / it gives me an error because I'm using integers. But if I remove the int() from each variable it wont let the equations work! I'm stuck, if anyone can give me some input it'd be greatly appreciated. It seems my image isn't uploading so heres a gyazo link for it https://gyazo.com/3325b42c51f839dc901cdefc1fe9b7fd vf = input("What is the final velocity?") if vf == "/": dontuse = "vf" else: pass vi = int(input("What is the intial velocity?")) if vi == "/": dontuse = "vi" else: pass a = int(input("What is the acceleration?")) if a == "/": dontuse = "a" else: pass t = int(input("What is the time?")) if t == "/": dontuse = "t" else: pass def eq1(): vf = vi + a*t def eq2(): vi = vf/(a*t) def eq3(): t = (vf - vi)/a if dontuse == "vf": eq1()
type: Question

blackmagic-fusion
type: Tag
tag name: blackmagic-fusion
tags question: http://stackoverflow.com/q/50306853

http://stackoverflow.com/a/50335878
answers question: http://stackoverflow.com/q/50332525
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87728472
type: Answer
has body: cpXXm and cpXXmu specify whether the target python implementation has wide unicode support or not (python was compiled with --enable-unicode=ucs4 or not). You can check that with $ python -c "import sys; print('ucs2' if sys.maxunicode == 65535 else 'ucs4')" If it prints ucs2, then wheels built with the python installation will produce cp27m wheels, otherwise to produce cp27mu wheels it should print ucs4. The system python on MacOS does not have wide unicode support, so you will need another installation of python that has one. Either install the brewed python2: $ brew install python or download and install the latest official pkg-installer of python 2.7.15 from Python.org or compile one yourself from source: $ wget https://www.python.org/ftp/python/2.7.15/Python-2.7.15.tgz $ tar xvf Python-2.7.15.tgz $ cd Python-2.7.15 $ ./configure --enable-unicode=ucs4 $ make $ make install Note the --enable-unicode=ucs4 or python will be compiled without wide unicode support. When building the wheel now, be sure to use the correct executable (not the system's /usr/bin/python). You can read more about wide unicode in PEP 261.
accepted answer of: http://stackoverflow.com/q/50332525

http://stackoverflow.com/a/50309464
answers question: http://stackoverflow.com/q/50309409
downvote count: 3
score: -2
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87635347
has comment: http://stackoverflow.com/comment/87635397
has body: You can do something like: min, max = (f(1),(f2)) if f(1)&lt;f(2) else (f(2),f(1)) If this is what you were looking for.
has comment: http://stackoverflow.com/comment/87635494
has comment: http://stackoverflow.com/comment/87634925

http://stackoverflow.com/q/50257656
tagged with: biopython
score: 0
duplicate of: http://stackoverflow.com/q/20082730
duplicate of: http://stackoverflow.com/q/36250353
has title: Import error ("cannot import name Seq") in biopython for both Python 2.7 and 3.6
answer count: 1
has answer: http://stackoverflow.com/a/50259930
has body: This is my code: from Bio.Seq import Seq from Bio.Alphabet import IUPAC my_seq = Seq("GATCG", IUPAC.unambiguous_dna) for index, letter in enumerate(my_seq): print("%i %s" %(index, letter)) print (len(my_seq)) I get an error "Unable to import Seq from Bio.Seq". Error on terminal is given below: Traceback (most recent call last): File "sequence-length.py", line 1, in &lt;module&gt; from Bio.Seq import Seq File "/home/tanuj/.local/lib/python2.7/site-packages/Bio/Seq.py", line 21, in &lt;module&gt; import string # for maketrans only File "/home/tanuj/Desktop/biopython/scripts-test/string.py", line 1, in &lt;module&gt; from Bio.Seq import Seq ImportError: cannot import name Seq I am not sure what the problem is, because the code was working fine, but after some time, the interpreter was unable to import Seq and started showing the error. How can I fix this?
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87533272
linked to: http://stackoverflow.com/q/36250353
tagged with: python
has comment: http://stackoverflow.com/comment/87538898

http://stackoverflow.com/comment/87730142
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50355944
has text: @user4815162342 I am flexible and willing to learn the best way to go about this if you don't mind offering an answer with the right solution? I cobbled this together using limited knowledge scraped from disparate examples from the web so I'd appreciate any help that I can get. Hopefully, it is clear what I am trying to achieve?
score: 0

http://stackoverflow.com/comment/87698776
score: 1
type: Comment
type: QuestionComment
has text: There are so many ways you could visualize this well. One easy option would be a box plot, which statisticians like to use. You could also do a bar chart with a line graph going through it. It depends on what you really want to do.
comment on: http://stackoverflow.com/q/50341291

http://stackoverflow.com/comment/87681240
score: 0
comment on: http://stackoverflow.com/a/50332512
type: AnswerComment
has text: Thank you! What about the creation of a mean "ABS" column based on the same wavelength values, should one use groupby?
type: Comment

http://stackoverflow.com/q/50238190
has answer: http://stackoverflow.com/a/50238284
tagged with: python
tagged with: flask
has body: So I have a wiki site made with python using flask. In the site you have to register to submit a post. When I made my account I looked at the db file. Under users it has my username but my password looks something like this pbkdf2:sha256:50000$trQqtDeG$fb666b434b1920c814101fd3afedf75c9e21e2eebbfe7e6aa9fe4aec3d69b1e3 I made my password poop ( dont ask why lol ) but thats what it comes up as. Lets say if I were to oneday forget my password, how can I check to see what it is? Edit: Thanks for the explanation ! :)
has comment: http://stackoverflow.com/comment/87493674
tagged with: sqlite
answer count: 1
has title: Possible to see passwords on db browser for sqlite?
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2

http://stackoverflow.com/q/50246166
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50247064
has answer: http://stackoverflow.com/a/50246757
favorite count: 0
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87510608
has comment: http://stackoverflow.com/comment/87509830
type: Question
answer count: 2
has title: Multiple Csv to json with no repetitive childrens
tagged with: d3.js
has body: I have a csv columns as follows, now I am trying to convert it to name/Children/Size format as required in D3 in JSON. There are repetetive Childrens Occuring For example In name ="type" there is children ="young", size = 400000 L1 L2 L3 L4 L5 L6 Size Type cars young young young young 40000 Type cars student US US US 10000 Type cars student UK UK UK 20000 Type cars Graduates Young India Delhi 20000 Type cars Graduates Old UK London 30000 Type Bike Undergrads CB CB UNC 6000 prime prime prime prime prime prime 600 My output I am getting is : { "name": "Segments", "children": [ { "name": "Type", "children": [ { "name": "cars", "children": [ { "name": "young", "children": [ { "name": "young", "children": [ { "name": "young", "children": [ { "name": "young", "size": "40000" } ] } ] } ] }, { "name": "student", "children": [ { "name": "US", "children": [ { "name": "US", "children": [ { "name": "US", "size": "10000" } ] } ] }, { "name": "UK", "children": [ { "name": "UK", "children": [ { "name": "UK", "size": "20000" } ] } ] } ] } ] } ] }, { "name": "prime", "children": [ { "name": "prime", "children": [ { "name": "prime", "children": [ { "name": "prime", "children": [ { "name": "prime", "children": [ { "name": "prime", "size": "600" } ] } ] } ] } ] } ] } ] } expecting output is: { "name": "Segments", "children": [ { "name": "Type", "children": [ { "name": "cars", "children": [ { "name": "young", "size": "40000" } ] }, { "name": "student", "children": [ { "name": "US", "size": "10000" } { "name": "UK", "size": "20000" } ] } ] }, { "name": "prime", "size": "600" } ] } I am using Following code: import json import csv class Node(object): def __init__(self, name, size=None): self.name = name self.children = [] self.size = size def child(self, cname, size=None): child_found = [c for c in self.children if c.name == cname] if not child_found: _child = Node(cname, size) self.children.append(_child) else: _child = child_found[0] return _child def as_dict(self): res = {'name': self.…
possible better answer: http://stackoverflow.com/a/50247064
accepted answer: http://stackoverflow.com/a/50246757

http://stackoverflow.com/comment/87561832
score: 0
comment on: http://stackoverflow.com/q/50272484
type: Comment
type: QuestionComment
has text: it is the length of A minus 1

http://stackoverflow.com/q/50341267
has comment: http://stackoverflow.com/comment/87698718
has answer: http://stackoverflow.com/a/50341715
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87699011
has comment: http://stackoverflow.com/comment/87698720
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50341478
has body: I'm struggling to deserialize an input data file in python 2.7 and didn't really know where to start. I saved the input file as JSON: { "Group": { "Test": { "test1": { "x1": 100, "y1": 150 }, "test2": { "x1": 23, "y1": 56, "x2": 200, "y2": 234 }, "test3": { "x1": 123, "y1": 456, "x2": 345, "y2": 986, "x3": 234, "y3": 654 }, "test4": { "x1": 789, "y1": 987, "x2": 345, "y2": 555, "x3": 111, "y3": 222, "x4": 333, "y4": 444 } } } } I'm trying to strip out the data so if case "test1" is needed I can take the value of x1 and y1 and populate a field. If 3 pairs of x and y values are needed I would need to grab the values from "test3". I'm trying to populate fields in the following variable in code. It's saved as a dictionary as the end product is a JSON file. I need to populate the width and height fields with the values from the data file listed above. Here is the variable printed out using json.dumps for readability: { "subs": { "1": { "video_info": { "width": x1, "height": y1 } }, "2": { "video_info": { "width": x2, "height": y2 } }, "3": { "video_info": { "width": x3, "height": y3 } } } } The above variable was pieced together by pulling data from different objects (each dictionary under "subs") so I can't write the whole thing as a dictionary from scratch. Each item in "subs" already has a width and height value that needs to be overwritten. Examples of deserialization I've seen all had set keys. Any help would be appreciated.
downvote count: 5
has comment: http://stackoverflow.com/comment/87698854
tagged with: python
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87698699
answer count: 2
has comment: http://stackoverflow.com/comment/87729349
has comment: http://stackoverflow.com/comment/87698772
upvote count: 0
type: UnansweredQuestion
score: -5
has title: Deserializing a JSON data file

http://stackoverflow.com/comment/88087177
score: 0
has text: I work what they say in the following link https://stackoverflow.com/questions/29483119/django-1-8-syncdb-not-working-throwing-a-foreign-key-constraint-error
comment on: http://stackoverflow.com/q/50338395
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87568510
type: AnswerComment
has text: @avocet, yes, asterisk (`*`) - is a special RegEx symbol, so you might want to escape it by a backslash character...
comment on: http://stackoverflow.com/a/50262648
type: Comment
score: 0

http://stackoverflow.com/comment/87729415
has text: look at picture, there is a same paths in the shell and in the python interpreter
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50356498
score: 0

http://stackoverflow.com/q/50334421
score: 0
accepted answer: http://stackoverflow.com/a/50334539
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/50334539
has comment: http://stackoverflow.com/comment/87685515
downvote count: 1
tagged with: matrix-indexing
favorite count: 0
has comment: http://stackoverflow.com/comment/87685851
has answer: http://stackoverflow.com/a/50334709
type: Question
tagged with: python
has body: My matrix is : [['f', 'e', 'e', 'd'], ['t', 'h', 'e', 'd'], ['o', 'g']] Code : for i in range(cols): result = "" for j in range(rows): result += matrix[j][i] temp.append(result) return(" ".join(temp)) When I am running the loop, which needs to capture elements row-wise, it throws an error as soon as the element (row = 3, col = 3) in the last row is reached which is not present. Is there any way I can skip the element that is not present by giving any condition like skip if an index does not exist and move on with the next first row again?
has answer: http://stackoverflow.com/a/50334571
possible better answer: http://stackoverflow.com/a/50334709
tagged with: python-3.x
tagged with: python-2.7
has title: How to skip the index when the indexing goes out of range [Python]
type: AnsweredQuestion

http://stackoverflow.com/comment/87755445
type: QuestionComment
comment on: http://stackoverflow.com/q/50360205
has text: i added the code
score: 0
type: Comment

http://stackoverflow.com/q/50236291
type: UnansweredQuestion
upvote count: 1
has title: Not receiving the Full output from esxtop command
has comment: http://stackoverflow.com/comment/87516147
duplicate of: http://stackoverflow.com/q/33291631
tagged with: esxi
score: 1
has comment: http://stackoverflow.com/comment/87515581
tagged with: ssh
tagged with: python
tagged with: shell
tagged with: paramiko
linked to: http://stackoverflow.com/q/33291631
favorite count: 0
type: Question
answer count: 0
downvote count: 0
has body: I'm using paramiko for performing esxtop command on my VMware ESXI. To receive the output i try to write the file in a text file . the problem is that i'm not getting the proper output from the script. Steps performed: 1. Login through ssh_client. 2.`stdin,stdout,stderr = ssh_client.exec_command("TERM=xterm esxtop" , get_pty=True)` #TERM=xterm is to set Environment variable to set the proper listing out esxtop command 3.with open("output.txt", "w") as infile: for line in iter(stdout.readline, ""): infile.write(line) # Writing the output to the output.txt file. The problem is that i'm not getting Complete output and it looks like this error: 125236 125236 esxtop.96492 1 81.97 76.35 0.00 10.56 ^[[K^M it is not showing output after ^[[K^M. Can anyone suggest me a solution for this. Thanks in advance. Arshpreet

http://stackoverflow.com/comment/87503922
comment on: http://stackoverflow.com/a/50238741
type: AnswerComment
has text: Your code deals only with control characters from categories __C0__ and __C1__. You're missing __Cf__ (format control character), __Cs__ (surrogate code point), __Co__ (private-use character) and __Cn__ (reserved unassigned code point or a noncharacter).
score: 0
type: Comment

http://stackoverflow.com/comment/87631872
comment on: http://stackoverflow.com/a/50307890
score: 2
type: AnswerComment
has text: Consider also [`os.path.join`](https://docs.python.org/2/library/os.path.html#os.path.join)
type: Comment

http://stackoverflow.com/comment/87656982
comment on: http://stackoverflow.com/q/50320293
has text: Yeah, I guess I completely disregarded (or at least overlooked) the last sentence of the question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87777913
comment on: http://stackoverflow.com/a/50342292
type: Comment
has text: I cannot use tight_layout because I have some complicated figures (with 60 subplots or so) and tight_layout messes everything up. That is why I use plt.subplots_adjust (which actually works well for the displayed figures).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87493035
comment on: http://stackoverflow.com/q/50237237
type: Comment
type: QuestionComment
score: 0
has text: I'm not familiar with which toolset puts stuff in `/Library/Frameworks`. What change did you make to fix the pandas problem?

http://stackoverflow.com/comment/87819652
type: AnswerComment
has text: @AlvaroAguilar yep, that is correct. To make sure that third-party service responses in such a way you expect it to, you should use the capabilities of monitoring system of your project. More info at this cool article: https://circleci.com/blog/testing-3rd-party-apis-and-microservices
comment on: http://stackoverflow.com/a/50361022
type: Comment
score: 0

http://stackoverflow.com/q/50310374
tagged with: http://stackoverflow.com/tag/json
has title: Shopify API JSON Feed / Limit 250 and Pages / GET pulls exactly the same records every time not next page
type: Question
accepted answer: http://stackoverflow.com/a/50310425
answer count: 2
possible better answer: http://stackoverflow.com/a/50310840
tagged with: api
tagged with: shopify
tagged with: django
tagged with: python
has body: I am trying to get a list of all collects and when I do the API call to count them: https://[store-username].myshopify.com/admin/collects/count.json HTTP/1.1 200 OK { "count": 307 } I know the limit is 250 and page default is 1 https://[store-username].myshopify.com/admin/collects.json?limit=250&amp;page=1 Will get 250 records. When I do page 2 - I'll get exactly the same records that in page 1 https://[store-username].myshopify.com/admin/collects.json?limit=250&amp;page=2 So for curiosity, I tried page 10 - which is out of range - that would be 2500 > 307 and it returned the same 250 as in page 1 2nd thing: When I put it in the code / python - and I do script to run https://[store-username].myshopify.com/admin/collects.json?limit=250&amp;page=1 It gets 250 records and then I do Page 2 https://[store-username].myshopify.com/admin/collects.json?limit=250&amp;page=2 and return is NONE I am pulling my hair off and can't get those all 307 to update my database only 250 - so I have no idea why the Page 2 in the browser is loading exactly the same records as PAGE 1 and 250 for PAGE 2 it should be 307-250 = 57 records and in the script it is pulling NONE. Can you help? def handle(self, *args, **options): security = urllib2.HTTPPasswordMgrWithDefaultRealm() security.add_password(None, "https://[store-username].myshopify.com/admin/collects/count.json", “[credentials]”, "[credentials]") auth_handler = urllib2.HTTPBasicAuthHandler(security) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) url = 'https://[store-username].myshopify.com/admin/collects/count.json' collect_feed = urllib2.urlopen(url) data = collect_feed.read() js = json.loads(str(data)) count = int(js['count']) page_size = 250 pages = int(math.ceil(count / page_size)) list_of_collects = Collect.objects.all() if list_of_collects: list_of_collects.delete() current_page = 1 while (current_page &lt;= pages): opening_url = "https://[store-username].myshopify.com/admin/collects.json?limit=" + st…
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50310425
has answer: http://stackoverflow.com/a/50310840

http://stackoverflow.com/a/50277999
type: Answer
accepted answer of: http://stackoverflow.com/q/50277108
has body: You are missing inner quotation marks. In Python, quotation marks (single or double) may denote a string, so you need to use double outer quotes with single inner quotes. Try this instead: test.loc[0, "'First'"] I strongly advise you clean up the column names by removing punctuation and leading / trailing whitespace: test.columns = test.columns.str.replace('[^\w\s]','').str.strip()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50277108
has comment: http://stackoverflow.com/comment/87572836
score: 1

http://stackoverflow.com/comment/87608720
score: 0
has text: While it's not included in your question, I think your problem will probably be a lack of optimisation of your queries, most likely an N+1 select problem. When you want to access, per-row, data from a related table make sure to add a `.prefetch_related(...)` to the queryset in the DRF view. Given what you're describing, it sounds like a problem I've seen before, where rendering each row using a DRF serializer requires at least one additional round-trip to the database.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50292851

http://stackoverflow.com/comment/87757807
comment on: http://stackoverflow.com/a/50233670
type: Comment
has text: How Can I column "col" Initialize that 0??
type: AnswerComment
score: 0

http://stackoverflow.com/q/50291923
score: 5
answer count: 5
has answer: http://stackoverflow.com/a/79072373
accepted answer: http://stackoverflow.com/a/50293641
has body: I'm trying do display some JSON results in a Jinja2 HTML Template, but it returns either an empty page, or every character of the JSON on a new row, or every character with spacing. The object that I'm sending to Jinja2 Template looks like this: [ { "name": "John", "lastname": "Smith", "age": 22, "likes": [ {"fruits": ["bananas", "oranges"] }, {"sweets": ["chocolate"] } ] } ] To send the JSON object to the Jinja2 template I use: render_template("report.html", items=items) On the Jinja2 Template HTML if I use {{ items }} it displays the full object as text. If I'm trying to get the {{ items['name'] }} it will not display anything on the page, the page will be completely empty. I have also tried {% for x in items %} {{ x }} {% endfor %} and it only displays the same "text" but with spacing: [ { " n a m e " : "J o h n " [...] In the HTML file, I'm trying to do something like: &lt;div id="name"&gt;{{ items['name'] }}&lt;/div&gt; How can I display the objects within the JSON object I'm passing to Jinja2?
downvote count: 0
has answer: http://stackoverflow.com/a/50293641
tagged with: flask
tagged with: jinja2
has answer: http://stackoverflow.com/a/50291984
favorite count: 0
has comment: http://stackoverflow.com/comment/87600022
has title: Flask Jinja2 - Parse JSON
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87600430
upvote count: 5
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/61515263
tagged with: python
possible better answer: http://stackoverflow.com/a/61148430
type: Question
has answer: http://stackoverflow.com/a/61148430

http://stackoverflow.com/q/50372641
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50373689
tagged with: grid
favorite count: 0
type: Question
tagged with: tkinter
has title: tkinter.scrolledtext.ScrolledText columnspan issue
upvote count: 2
tagged with: python
has body: Below is a section of code to help show what I want. The ScrolledText widget takes over 3/4 of the width but I have it setup to take up 1/2, trying to determine how to split two controls down the middle. When I comment out the ScrolledText widget and add a 2nd test listbox in it's place with same grid information it splits down the middle. Is there something different to setting up a ScrolledText widget? page.rowconfigure(1, weight=1) page.columnconfigure(0, weight=1) page.columnconfigure(6, weight=1) lb_reports = Listbox(page, selectmode=SINGLE) lb_reports.grid(row=1, column=0, columnspan=5, sticky=W + N + S + E, pady=5, padx=5) # Following list box is here as a test, it does split down the middle of screen as expected. # self.lb_reports1 = Listbox(page, selectmode=SINGLE) # self.lb_reports1.grid(row=1, column=5, columnspan=5, sticky=W + N + S + E, pady=5, padx=5) # this widget takes right 3/4 of screen instead of 1/2 st_test = tkinter.scrolledtext.ScrolledText(page) st_test.grid(row=1, column=6, columnspan=5, sticky=W + N + S + E, pady=5, padx=5)
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/50373689

http://stackoverflow.com/q/50376650
tagged with: amazon-s3
has body: I tried to check the existing s3 buckets have tags or not, if bucket not have tags, will add the tags, i tried below code for region in region_list: s3 = boto3.resource('s3', region) s3_client = boto3.client('s3', region) for bucket in s3.buckets.all(): s3_bucket = bucket s3_bucket_name = s3_bucket.name response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name) tagset = response['TagSet'] if len(response['TagSet'])==0: print "s3 bucket not have tags, adding tags" else: pass but getting below error Traceback (most recent call last): File "C:\Python27\ec2info.py", line 235, in &lt;module&gt; response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name) File "C:\Python27\lib\site-packages\botocore\client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Python27\lib\site-packages\botocore\client.py", line 612, in _make_api_call raise error_class(parsed_response, operation_name) ClientError: An error occurred (NoSuchTagSet) when calling the GetBucketTagging operation: The TagSet does not exist where i am doing wrong here, what is the correct way of checking s3 bucket have tags or not Thanks in advance for your help
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50377918
tagged with: boto3
tagged with: amazon-web-services
answer count: 4
score: 8
has answer: http://stackoverflow.com/a/73814696
downvote count: 0
has title: How to check S3 bucket have tags or not
has answer: http://stackoverflow.com/a/50391359
has answer: http://stackoverflow.com/a/62845366
upvote count: 8
favorite count: 0
type: Question

http://stackoverflow.com/q/50296170
type: AnsweredQuestion
has title: Running periodic task at time stored in database
upvote count: 5
tagged with: django-celery
tagged with: python
accepted answer: http://stackoverflow.com/a/50296465
answer count: 4
has answer: http://stackoverflow.com/a/50296465
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50296523
score: 5
tagged with: celerybeat
linked to: http://stackoverflow.com/q/11523918
downvote count: 0
tagged with: django
has body: Currently, I have periodic tasks set up with a Job Scheduler on my Azure instance. These are triggering API (Django) endpoints at fixed times. I want to make these times dynamic (which will not work with this solution). The plan is to fire these tasks directly from Django. The schedule times will be stored in my database (MySQL) and be retrieved to create the scheduled job. When these values are changed the scheduler should also change accordingly. After looking at Celery it seems that using periodic tasks crontab schedules could work. Using this, is it possible to set my scheduled time based on values from my database? It looks like I will also need a Redis instance as well. Since I would only be using Celery for periodic tasks is it still the right approach?
has answer: http://stackoverflow.com/a/50297203
tagged with: celery
possible better answer: http://stackoverflow.com/a/50296523
has answer: http://stackoverflow.com/a/74110520

http://stackoverflow.com/a/50271931
score: 0
has body: Use this code : WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[class='applyBtn']&gt;a"))) driver.find_element_by_css_selector('div[class='applyBtn']&gt;a').click()
answers question: http://stackoverflow.com/q/50271772
type: Answer

http://stackoverflow.com/q/50274289
upvote count: 11
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm pretty sure there is a duplicate lying around, but couldn't find it. When declaring a urlpatterns in urls.py on dev, I use the following successfully: urlpatterns = [ # some routes ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Which understandably, works. But if I try the following: urlpatterns = [ # some routes, static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ] django server dies complaining: ?: (urls.E004) Your URL pattern [&lt;URLPattern '^static\/(?P&lt;path&gt;.*)$'&gt;] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. Why aren't the two definitions equivalent? The return of static() should be the same: return [ re_path(r'^%s(?P&lt;path&gt;.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs), ] And thus valid, but only works if I concatenate the element to the list instead of defining it in the list directly. Why one method works but not the other?
downvote count: 0
tagged with: django
has title: adding static() to urlpatterns only work by appending to the list
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/50274371
accepted answer: http://stackoverflow.com/a/50274371
type: AnsweredQuestion
answer count: 1
tagged with: django-urls

http://stackoverflow.com/comment/87601298
has text: thanks for your elaborated answer. I tried as you showed. But after formatting, writing the data is having the problem most probably.
type: AnswerComment
comment on: http://stackoverflow.com/a/50283465
type: Comment
score: 0

http://stackoverflow.com/comment/87727100
score: 0
comment on: http://stackoverflow.com/q/50355334
has text: What errors are you seeing? What have you tried already?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87644414
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50313767
has text: no error "Process finished with exit code 0"
score: 0

http://stackoverflow.com/q/50241145
has comment: http://stackoverflow.com/comment/94278931
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87499906
tagged with: python
tagged with: ebay-api
score: 2
tagged with: python-2.7
answer count: 0
upvote count: 2
downvote count: 0
has body: I am building an app using eBay API and when I try to add a new listing on my account I get a very strange response from eBay server as in the following: # -*- coding: utf-8 -*- ''' © 2012-2013 eBay Software Foundation Authored by: Tim Keefer Licensed under CDDL 1.0 ''' import os import sys import datetime from optparse import OptionParser sys.path.insert(0, '%s/../' % os.path.dirname(__file__)) from samples.common import dump import ebaysdk from ebaysdk.utils import getNodeText from ebaysdk.exception import ConnectionError from ebaysdk.trading import Connection as Trading def init_options(): usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Enabled debugging [default: %default]") parser.add_option("-y", "--yaml", dest="yaml", default='ebay.yaml', help="Specifies the name of the YAML defaults file. [default: %default]") parser.add_option("-a", "--appid", dest="appid", default=None, help="Specifies the eBay application id to use.") parser.add_option("-p", "--devid", dest="devid", default=None, help="Specifies the eBay developer id to use.") parser.add_option("-c", "--certid", dest="certid", default=None, help="Specifies the eBay cert id to use.") (opts, args) = parser.parse_args() return opts, args def AddItem(opts): """http://www.utilities-online.info/xmltojson/#.UXli2it4avc """ try: api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid, certid=opts.certid, devid=opts.devid, warnings=False) myitem = { "Item": { "Title": "Testiranje", "Description": "Opis za testiranje", "PrimaryCategory": {"CategoryID": "377"}, "StartPrice": "1.0", "BuyItNowPrice": "1.0", "CategoryMappingAllowed": "true", "Country": "US", "ConditionID": "3000", "Currency": "USD", "DispatchTimeMax": "3", "ListingDuration": "Days_7", "ListingType": "FixedPriceItem", "PaymentMethods": "PayPal", "PayPalEmailAddress": "veryrarethings@gmail.com", "PictureDetails": {"PictureURL": "…
favorite count: 0
type: Question
has title: Application name invalid as a response from eBay server - eBay API

http://stackoverflow.com/q/50287283
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
tagged with: web-scraping
tagged with: python-requests
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/50289111
has title: error in scraping inner tags of html element using python
has body: Recently i am working on exercise and in which i had extracted whole webpage source data . I am very much interested in area tag . In area tag i am very much interested in onclick attribute . Now how can we extract onclick attribute from particular element . Now our extracted data is looking like these , &lt;area class="borderimage" coords="21.32,14.4,933.96,180.56" href="javascript:void(0);" onclick="return show_pop('78545','51022929357','1')" onmouseover="borderit(this,'black','&lt;b&gt;इंदौर, गुरुवार, 10 मई , 2018 &lt;b&gt;&lt;br&gt;&lt;bआप पढ़ रहे हैं देश का सबसे व...')" onmouseout="borderit(this,'white')" alt="&lt;b&gt;इंदौर, गुरुवार, 10 मई , 2018 &lt;b&gt;&lt;br&gt;&lt;bआप पढ़ रहे हैं देश का सबसे व..." shape="rect"&gt; I am very much interested in onclick attribute and my code is like these which i had already done but nothing has worked , paper_url = 'http://epaper.bhaskar.com/indore/129/10052018/mpcg/1/' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} # Total number of pages available in these product page = requests.get(paper_url,headers = headers) page_response = page.text parser = html.fromstring(page_response) XPATH_Total_Pages = '//div[contains(@class,"fs12 fta w100 co_wh pdt5")]//text()' raw_total_pages = parser.xpath(XPATH_Total_Pages) lastpage=raw_total_pages[-1] print(int(lastpage)) finallastpage=int(lastpage) reviews_list = [] XPATH_PRODUCT_NAME = '//map[contains(@name,"Mapl")]' #XPATH_PRODUCT_PRICE = '//span[@id="priceblock_ourprice"]/text()' #raw_product_price = parser.xpath(XPATH_PRODUCT_PRICE) #product_price = raw_product_price raw_product_name = parser.xpath(XPATH_PRODUCT_NAME) XPATH_REVIEW_SECTION_2 = '//area[@class="borderimage"]' reviews = parser.xpath(XPATH_REVIEW_SECTION_2) product_name =raw_product_name #result = product_name.find(',') #finalproductname = slice[0:product_name] print(product_name) print(reviews) for review in reviews: #soup = BeautifulSoup(…
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50289111
tagged with: data-science

webdriver
tags question: http://stackoverflow.com/q/50299868
tags question: http://stackoverflow.com/q/50303797
tags question: http://stackoverflow.com/q/50298553
tags question: http://stackoverflow.com/q/50324563
tags question: http://stackoverflow.com/q/50340985
tags question: http://stackoverflow.com/q/50266500
type: Tag
tags question: http://stackoverflow.com/q/50353906
tags question: http://stackoverflow.com/q/50248876
tag name: webdriver
tags question: http://stackoverflow.com/q/50287106
tags question: http://stackoverflow.com/q/50273156
tags question: http://stackoverflow.com/q/50243867
tags question: http://stackoverflow.com/q/50360120

http://stackoverflow.com/comment/87902080
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the help, it works like a charm. very subtle.
comment on: http://stackoverflow.com/a/50429549

http://stackoverflow.com/q/50353563
has comment: http://stackoverflow.com/comment/87729966
has title: How to get Country from value of the key Location?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: geopy
answer count: 0
tagged with: nltk
type: UnansweredQuestion
tagged with: stackexchange-api
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/87806676
downvote count: 3
has body: I am trying to add a new key called Country. My main problem is to convert the location into Country. The Users from Stackoverflow can write everything and it has no format. I have tried geopy but it doesn't detect some countries for Russia or Tokyo as a state. The second problem is that geopy doesn't allow many requests. I have around 8 million Users. That Code is just an edit version: def geopytesting(testing, user): from geopy import Nominatim try: geolocator = Nominatim() location2 = geolocator.geocode(testing) print(location2.address) except BaseException: print("Error") geopytesting("Russia",None) geopytesting("Hamburg",None) geopytesting("Madrid",None) geopytesting("Omaha",None) geopytesting("Berlin",None) geopytesting("Schleswig-Holzstein",None) geopytesting("Asyż",None) geopytesting("",None) geopytesting("Tilted Tower",None) I hope you can Help me. I really try many things and I haven't seen a post which handle this specific problem. Either it detect some countries or I get kicked out because I made too many requests.
score: 1

http://stackoverflow.com/comment/87611242
comment on: http://stackoverflow.com/q/50296997
has text: show how you send the data
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50321850
has body: They have this in HTML source: &lt;li class='link-visible'&gt; &lt;a href='/pages/detail2_cat_est_ordinateurs_puis_rubrique_est_wh_tabmul_puis_ref_est_in10092521.html'&gt; apple ipad mini 4 7.9'' retina 128 go wi-fi gris sideral (2015) &amp;nbsp;&lt;strong&gt;(MK9N2NF/A&lt;/strong&gt;) &lt;/a&gt; &lt;/li&gt; &lt;li class='link-visible'&gt; &lt;a href='/pages/detail2_cat_est_ordinateurs_puis_rubrique_est_wh_tabmul_puis_ref_est_in10103554.html'&gt; Apple iPad 32 Go Wi-Fi Or (2017) &amp;nbsp;&lt;strong&gt;(MPGT2NF/A&lt;/strong&gt;) &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href='/pages/detail2_cat_est_ordinateurs_puis_rubrique_est_wh_tabmul_puis_ref_est_in10103538.html'&gt; apple ipad 32 go wi-fi gris sideral (2017) &amp;nbsp;&lt;strong&gt;(MP2F2NF/A&lt;/strong&gt;) &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href='/pages/detail2_cat_est_ordinateurs_puis_rubrique_est_wh_tabmul_puis_ref_est_in10103545.html'&gt; Apple iPad 32 Go Wi-Fi Silver (2017) &amp;nbsp;&lt;strong&gt;(MP2G2NF/A&lt;/strong&gt;) &lt;/a&gt; &lt;/li&gt; So as you can see it's //li[@class="link-visible"]/a (you have this) and //li/a (you need to add this to catch "load more results")
score: 0
accepted answer of: http://stackoverflow.com/q/50321111
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50321111
has comment: http://stackoverflow.com/comment/87669603
type: Answer

http://stackoverflow.com/q/50232728
has answer: http://stackoverflow.com/a/50234121
tagged with: django
tagged with: python
score: 0
has title: Change the python2.7 package to my required python3.5 package when use virtualenv
has comment: http://stackoverflow.com/comment/87482840
answer count: 1
tagged with: virtualenv
type: Question
has comment: http://stackoverflow.com/comment/87483999
linked to: http://stackoverflow.com/q/23842713
has body: When I create the virtualenv, if I do not add the --no-site-packages as param: virtualenv venv I can get the packages, in the venv/lib/ there are a python2.7 package: python2.7 under the python2.7 there are site-packages. But, I have a requirement, I want copy the python3.5 to the venv/lib/ how can I do this? EDIT-1 I use the post method create the venv, in the venv/lib/: there is the python3.5 directory, but in the venv/lib/python3.5/site-packages there are few packages: But in my Mac's sitepages: there are so many packages, my requirement is add those packages in the venv when create the venv: my origin site-packages path is:/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages EIDT-2 Before, I do not use virtualenv, I have installed many site-packages in my Mac, (/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages), and I want to use venv now, so I am looking for a method to create the venv and the site-packages I have installed should include in it.
type: UnansweredQuestion

http://stackoverflow.com/comment/87584731
comment on: http://stackoverflow.com/q/50284233
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [python print one line same space](https://stackoverflow.com/questions/14789930/python-print-one-line-same-space)

http://stackoverflow.com/q/50301757
score: 3
answer count: 0
upvote count: 3
downvote count: 0
has body: I am trying to use pybluez to get battery details of one of the connected bluetooth device. I could not understand how to extract them. Is it atleast possible to extract battery details using pybluez? if not which module of which programming language i can use to get the details?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: windows
tagged with: python
has title: Extracting Battery charge level in a connected bluetooth device using python in windows
tagged with: bluetooth

http://stackoverflow.com/comment/87531573
type: QuestionComment
has text: Thanks a whole bunch..so should I remove this question from here and move it to code review?
comment on: http://stackoverflow.com/q/50252083
score: 0
type: Comment

http://stackoverflow.com/q/50346006
has comment: http://stackoverflow.com/comment/87708663
tagged with: python
has comment: http://stackoverflow.com/comment/87708666
has comment: http://stackoverflow.com/comment/87708852
has comment: http://stackoverflow.com/comment/87708479
tagged with: numpy
has comment: http://stackoverflow.com/comment/87709086
has comment: http://stackoverflow.com/comment/87708918
has comment: http://stackoverflow.com/comment/87708554
score: 0
tagged with: fftpack
type: UnansweredQuestion
has body: When computing a FFT of an array of size ~ 1.5 million items: import numpy as np from scipy.fftpack import fft x0 = np.ones(1492828, dtype=np.int32) fft(x0) print 'hello' the FFT computation never finishes, and the program is freezing. If I change 1492828 to 1492827, it seems to work. But if I change 1492828 to 1492826, it still freezes, which is kind of strange. Is this a known bug? Note: The CPU stays at 25% (normal, I have a 4-core CPU), and the RAM usage of the Python process stays at ~75 MB I'm using Python 2.7.15 64-bit on Windows 7 64-bit: print scipy.__version__ # 1.1.0 print sys.version # 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
has comment: http://stackoverflow.com/comment/87708208
answer count: 1
has answer: http://stackoverflow.com/a/50346730
has comment: http://stackoverflow.com/comment/87708545
tagged with: scipy
tagged with: fft
type: Question
has comment: http://stackoverflow.com/comment/87708319
has comment: http://stackoverflow.com/comment/87708257
has comment: http://stackoverflow.com/comment/87708999
linked to: http://stackoverflow.com/q/46357589
linked to: http://stackoverflow.com/q/21161033
has title: scipy.fftpack's FFT freezing

http://stackoverflow.com/q/50311585
accepted answer: http://stackoverflow.com/a/50311636
upvote count: 2
has answer: http://stackoverflow.com/a/50312357
has answer: http://stackoverflow.com/a/50311636
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
tagged with: django
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/70780848
answer count: 4
has answer: http://stackoverflow.com/a/50311620
has title: How to call Python variable in JavaScript?
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/70780848
favorite count: 0
type: Question
has body: I have a Python function that returns some value. Also I connected to my project Google Charts. So I need to pass that value to a js function in html file of Google Charts. The project is on Django btw. What is the most correct way to do this? {% extends "gappi_tmp/wrapper.html" %} {% block content %} {% endblock %}

http://stackoverflow.com/q/50326532
has comment: http://stackoverflow.com/comment/87670162
has comment: http://stackoverflow.com/comment/87668869
downvote count: 4
accepted answer: http://stackoverflow.com/a/50337380
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87678843
upvote count: 1
linked to: http://stackoverflow.com/q/33642951
answer count: 1
tagged with: data-mining
tagged with: ubuntu-12.04
favorite count: 0
has answer: http://stackoverflow.com/a/50337380
type: Question
has title: Data mining with csv (python)
tagged with: python-3.x
has body: Im trying to learn the basics in data science, so I'm attempting to mine the following dataset (csv) using python. https://www.kaggle.com/jessevent/all-crypto-currencies 70mg file My setup 6 Core bulldoser AMD 120 GB SSD 2GB data drive Ubuntu 12.04 with libvirt KVM/QEMU Python 3 Python 2.7 It has transpired that my setup can't crunch the numbers as I need to save in execl format .xlsx and i cant save the file as the system hangs. I'm wondering if its possible to use the native csv file and run numpy, matplotlib and pandas etc, and not call the data using .excel. I need to be able to use the the dataset, for doing basic data exploration, data cleaning and model construction, validation etc
score: -3
tagged with: python

http://stackoverflow.com/comment/87777247
has text: No, this code is supposed to be in `foo/foo.py` and Python set `__file__` to the full path of the file. Well, it could be full path to `foo.pyc` but after `dirname()` it is irrelevant.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50379338
type: Comment

http://stackoverflow.com/a/57059486
upvote count: 4
downvote count: 0
has body: It appears that moz:geckodriverVersion has been added to the capabilities sometime late 2018. driverversion = driver.capabilities['moz:geckodriverVersion'] browserversion = driver.capabilities['browserVersion']
type: Answer
answers question: http://stackoverflow.com/q/50359334
score: 4

http://stackoverflow.com/q/50250580
tagged with: firefox
downvote count: 0
has title: Error: GDK_BACKEND does not match available displays; Running Selenium using Crontab
tagged with: python
accepted answer: http://stackoverflow.com/a/51162392
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51162392
tagged with: cron
answer count: 1
favorite count: 0
type: Question
upvote count: 2
has body: I am trying to run selenium using cron. import os from selenium import webdriver from selenium.webdriver.firefox.options import Options from pyvirtualdisplay import Display from selenium.webdriver.common.desired_capabilities import DesiredCapabilities firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = True firefox_capabilities['handleAlerts'] = True firefox_capabilities['acceptSslCerts'] = True firefox_capabilities['acceptInsecureCerts'] = True binary = webdriver.firefox.firefox_binary.FirefoxBinary("/usr/bin/firefox") now = datetime.datetime.now() print "* Time of RUN : ",now display = Display(visible=0, size=(1024, 768)) # display.start() browser = webdriver.Firefox(firefox_binary=binary,executable_path=os.getcwd()+'/geckodriver') browser.get('http://www.google.com') print browser.title browser.quit() # display.stop() Following is the error displayed in geckodriver.log 1525859641163 geckodriver INFO geckodriver 0.20.1 1525859641167 geckodriver INFO Listening on 127.0.0.1:34837 1525859642167 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.1xUlJhxoO4Ar" Error: GDK_BACKEND does not match available displays things I tried: tried running selenium without display (pyvirtualdisplay) i.e headless selenium tried binary parameter while invoking webdriver.firefox() tried geckodriver excutable(linux) in webdriver.firefox() used export Dispaly=:0; in the cron cmd

http://stackoverflow.com/a/50241246
has comment: http://stackoverflow.com/comment/87500426
type: Answer
score: 0
has body: You are comparing a string with a float, try this instead: def cel_to_fahr(c): if c &lt; -273.15: return "physical matter can reach only till -273.15" else: f = c * 9/5 + 32 return f temp = open("tempr.txt") tempr = temp.read() tempr = tempr.splitlines() for t in tempr: print(cel_to_fahr(float(t))) Assuming there that you have only float in your file. The data read from a file, are read as a string until you cast them. If you are unsure about the format of data, you can use a try/catch logic. But for your simple question where all the data are know in your file, this would be overkill.
answers question: http://stackoverflow.com/q/50241214
has comment: http://stackoverflow.com/comment/87500085
has comment: http://stackoverflow.com/comment/87500388
has comment: http://stackoverflow.com/comment/87500412
has comment: http://stackoverflow.com/comment/87500108

http://stackoverflow.com/q/50249924
has answer: http://stackoverflow.com/a/50250289
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/50250317
has answer: http://stackoverflow.com/a/50250317
tagged with: pandas
has title: export some columns to new csv file from existing dataframe
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/46546388
possible better answer: http://stackoverflow.com/a/50250289
favorite count: 0
has body: I have a dataframe called 'data' with 55 columns and I want to create a new csv file with the first 52 columns. The last three column names I do not want to include are 'Class', 'part_id' and 'image_file'. I have been searching and the solution is something like this: import pandas as pd useful_columns = [col1,col2,...] #list the columns I need data[useful_columns].to_csv('new.csv', index=False) #prevent creating extra column #reference: https://stackoverflow.com/questions/46546388/how-to-skip-columns-of-csv-file I get an error that says 'col1, col2 not defined' but I do have 52 columns that I want to export to a new csv file, it is so long to write each column name (Particle ID, Area(ABD), Aspect Ratio...etc). Is there a fast way to say "just take the first 52 columns from the existing dataframe and put them into a new csv file? Thanks so much in advance!

http://stackoverflow.com/q/50300010
favorite count: 0
type: Question
has body: I wanted share a problem I encountered and the solution I found that worked on my system. For reference, this is my environment: Ubuntu 16.04 64-bit, nVidia GPU, conda 4.5.2 I created a conda virtual environment and installed tensorflow-gpu (which resulted in 1.7.0 being installed which is not the latest, but is fine for my purposes). I then did $ conda install keras keras was installed correctly, BUT it also installed tensorflow non-gpu version, which I cannot use. This seems like a dependency bug in which keras package does not recognize tensorflow-gpu package as installed. I was forced to remove tensorflow (non-gpu package) and to use $ python3.6 -m pip install keras This worked, but I would rather have consistent conda managed packages. I hope that Anaconda fixes this, but in the meantime, you can try my solution. BTW, don't even get me started on why I couldn't just use pip or pip3 instead of "python3.6 -m pip". Python 3.6 and 3.5 on Ubuntu at least are at war with each other causing all kinds of "module not found" problems. But that's for another post.
tagged with: anaconda
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50300337
tagged with: python
has title: conda bug with keras package installs tensorflow even if tensorflow-gpu is already installed
tagged with: conda
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/a/50263999
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50263776
has body: The regex could be much simpler: re.split("([A-Z \.]+\.)",text) And then your code could just be: data = list(filter(None, [s.strip() for s in re.split("([A-Z \.]+\.)",text)])) Then you can do: names = data[0:][::2] speech = data[1:][::2] See it in action here
type: Answer
answers question: http://stackoverflow.com/q/50263776

http://stackoverflow.com/comment/87672152
comment on: http://stackoverflow.com/a/50296229
score: 0
type: Comment
has text: I have found the solution using the xpath, as you said and it looks like `'text': quote.xpath('/html/body/div[1]/div/div[3]/div/div/div/div/div/div[1]/div/div[1]/article[1]/div[4]/div/div/div/div[1]/p/text()').extract(),`. Otherwise it doesn't show the text in a nice format. While the title is `'titleInArticle': quote.xpath('//header/h1/text()').extract(),` and displays correctly.
type: AnswerComment

scipy
tags question: http://stackoverflow.com/q/50284132
tags question: http://stackoverflow.com/q/50314243
tags question: http://stackoverflow.com/q/50330474
tags question: http://stackoverflow.com/q/50288513
tags question: http://stackoverflow.com/q/50382699
tags question: http://stackoverflow.com/q/50241797
tags question: http://stackoverflow.com/q/50238052
tags question: http://stackoverflow.com/q/50319788
tags question: http://stackoverflow.com/q/50368824
tags question: http://stackoverflow.com/q/50292546
tags question: http://stackoverflow.com/q/50282805
tags question: http://stackoverflow.com/q/50254625
tags question: http://stackoverflow.com/q/50353421
tags question: http://stackoverflow.com/q/50273650
tags question: http://stackoverflow.com/q/50371889
tags question: http://stackoverflow.com/q/50289220
tags question: http://stackoverflow.com/q/50380357
tags question: http://stackoverflow.com/q/50288685
tags question: http://stackoverflow.com/q/50361464
tags question: http://stackoverflow.com/q/50261232
tags question: http://stackoverflow.com/q/50338194
tags question: http://stackoverflow.com/q/50336699
type: Tag
tags question: http://stackoverflow.com/q/50262350
tags question: http://stackoverflow.com/q/50305938
tag name: scipy
tags question: http://stackoverflow.com/q/50326425
tags question: http://stackoverflow.com/q/50249736
tags question: http://stackoverflow.com/q/50294715
tags question: http://stackoverflow.com/q/50234234
tags question: http://stackoverflow.com/q/50356688
tags question: http://stackoverflow.com/q/50378113
tags question: http://stackoverflow.com/q/50358434
tags question: http://stackoverflow.com/q/50374255
tags question: http://stackoverflow.com/q/50340056
tags question: http://stackoverflow.com/q/50311256
tags question: http://stackoverflow.com/q/50355583
tags question: http://stackoverflow.com/q/50371428
tags question: http://stackoverflow.com/q/50240187
tags question: http://stackoverflow.com/q/50267780
tags question: http://stackoverflow.com/q/50264616
tags question: http://stackoverflow.com/q/50239641
tags question: http://stackoverflow.com/q/50274753
tags question: http://stackoverflow.com/q/50298506
tags question: http://stackoverflow.com/q/50234733
tags question: http://stackoverflow.com/q/50244224
tags question: http://stackoverflow.com/q/50270521
tags question: http://stackoverflow.com/q/50265501
tags question: http://stackoverflow.com/q/50376948
tags question: http://stackoverflow.com/q/50340791
tags question: http://stackoverflow.com/q/50298570
tags question: http://stackoverflow.com/q/50294355
tags question: http://stackoverflow.com/q/50374882
tags question: http://stackoverflow.com/q/50360053
tags question: http://stackoverflow.com/q/50384045
tags question: http://stackoverflow.com/q/50280640
tags question: http://stackoverflow.com/q/50346006
tags question: http://stackoverflow.com/q/50371298
tags question: http://stackoverflow.com/q/50244910

http://stackoverflow.com/comment/87632216
type: AnswerComment
has text: Yes actually I think this is what OP wants. Upvoted.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50308167

http://stackoverflow.com/q/50284132
tagged with: cython
tagged with: scipy
favorite count: 0
type: Question
tagged with: lapack
accepted answer: http://stackoverflow.com/a/50285530
has body: I define the function that calculates the determinant of a matrix here. But sometimes I get the wrong sign. I modeled my function from this answer. from scipy.linalg.cython_lapack cimport dgetrf cpdef double det_c(double[:, ::1] A, double[:, ::1] work, double[::1] ipiv): '''obtain determinant of float type square matrix A Notes ----- As is, this function is not yet computing the sign of the determinant correctly, help! Parameters ---------- A : memoryview (numpy array) n x n array to compute determinant of work : memoryview (numpy array) n x n array to use within function ipiv : memoryview (numpy array) length n vector use within function Returns ------- detval : float determinant of matrix A ''' cdef int n = A.shape[0], info work[...] = A dgetrf(&amp;n, &amp;n, &amp;work[0,0], &amp;n, &amp;ipiv[0], &amp;info) cdef double detval = 1. cdef int j for j in range(n): if j != ipiv[j]: detval = -detval*work[j, j] else: detval = detval*work[j, j] return detval When I test this function and compare it to np.linalg.det, sometimes I got the wrong sign. &gt;&gt;&gt; a = np.array([[1,2],[3,5.]]) &gt;&gt;&gt; np.linalg.det(a) &gt;&gt;&gt; -1.0000000000000004 &gt;&gt;&gt; det_c(a, np.zeros((2, 2)), np.zeros(2, dtype=np.int32)) &gt;&gt;&gt; 1 Other times, the right sign. &gt;&gt;&gt; b = np.array([[1,2,3],[1,2,1],[5,6,1.]]) &gt;&gt;&gt; np.linalg.det(b) &gt;&gt;&gt; -7.999999999999998 &gt;&gt;&gt; det_c(a, np.zeros((3, 3)), np.zeros(3, dtype=np.int32)) &gt;&gt;&gt; -8.0
type: AnsweredQuestion
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/50285530
tagged with: numpy
has title: Estimating determinant using LAPACK wrapper for LU decomposition in Cython
downvote count: 0
linked to: http://stackoverflow.com/q/47315471
answer count: 1

http://stackoverflow.com/q/50271024
favorite count: 0
type: Question
has title: multiplying a column by another if it is the same year
possible better answer: http://stackoverflow.com/a/50271123
tagged with: python
has body: I have 2 dataframes, one is sampled monthly, the other is sampled yearly with datetime index. I want to multiply the values from a column in the monthly dataframe by the value from a column in the yearly dataframe if it is the same year. How can I do that? Thank you very much for your help, df = pd.DataFrame({'column1' : [1, 1, 1, 2, 2]}, index=['2018-01-01', '2018-01-02', '2018-01-03', '2019-01-03', '2019-01-02']) df.index= pd.to_datetime(df.index) df column1 2018-01-01 1 2018-01-02 1 2018-01-03 1 2019-01-03 2 2019-01-02 2 df2 = pd.DataFrame({'columnX' : [2, 3]}, index=['2018', '2019']) df2.index= pd.to_datetime(df2.index) df2 columnX 2018-01-01 2 2019-01-01 3 Expected result: df Column1 Results 2018-01-01 1 2 2018-01-02 1 2 2018-01-03 1 2 2019-01-03 2 6 2019-01-02 2 6
has answer: http://stackoverflow.com/a/50271123
accepted answer: http://stackoverflow.com/a/50271539
has answer: http://stackoverflow.com/a/50271381
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50271539

http://stackoverflow.com/comment/87603409
type: AnswerComment
has text: It will remove the characters from both ends, right?
score: 2
comment on: http://stackoverflow.com/a/50293460
type: Comment

http://stackoverflow.com/comment/87499166
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50240354
has text: Actually i have a dataset of 11K datapoints. This is just for development phase. After changing it to 10, i am facing another weird error of inconsistent number of samples. After reshaping it to 3 dimension. The length of data is now 1 but code requires it in 3 dimension so what step should be taken here?

http://stackoverflow.com/a/50291749
score: 0
answers question: http://stackoverflow.com/q/50291410
type: Answer
has body: Just use a functor (a variable that is holding a function): if any_all_flag = 'all': my_functor = all else: my_functor = any if my_functor(bet_res[i] for i in res_number_list): good_row_list.append(row_dict) else: bad_row_list.append(row_dict)

http://stackoverflow.com/a/50333714
has body: To answer your question, you need to understand the call stack. Any time a function is called, the program needs to remember where it was so that -- when the callee returns -- it can jump back to the same point in the caller. Therefore, it pushes its current state onto a stack. Using functions is a big part of best practice (for so many reasons: abstraction, encapsulation, code reuse, etc.), so modern languages (including Python) make pushing a frame onto the stack a very lightweight operation. However, it is not free. If you use a function that calls itself as a loop, you will eventually overflow the call stack. The best thing to do if you need a program to loop indefinitely (or even a large number of times) is to use the construct made for that purpose: a loop. Note: See chepner's comment about tail-call optimization, which is a part of the compilation/execution process in many languages (especially functional languages).
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/87684174
has comment: http://stackoverflow.com/comment/87683685
type: Answer
answers question: http://stackoverflow.com/q/50333263
upvote count: 4
has comment: http://stackoverflow.com/comment/87683761
accepted answer of: http://stackoverflow.com/q/50333263
downvote count: 0

http://stackoverflow.com/q/50363321
tagged with: scrapy
answer count: 1
type: Question
has body: I am new to Scrapy and reading Learing Scrapy to study, and I have a question about the scrape order. The book provide a piece of code: rules = ( Rule(LinkExtractor(restrict_xpaths='//*[contains(@class,"next")]')), Rule(LinkExtractor(restrict_xpaths='//*[@itemprop="url"]'), callback='parse_item') ) And it said that Scrapy using a LIFO strategy to crawl. So I suppose that the first item should be the item on the last page, but it turns out the first item is on the first page. Why? According to the code, I think Scrapy will keep following the first rule until it find the last page, and then it will start to parse items on the last page. I am confused. And if a website has millions of pages, Scrapy won't parse any items until it reaches the last page?
tagged with: python
accepted answer: http://stackoverflow.com/a/50368920
has answer: http://stackoverflow.com/a/50368920
type: AnsweredQuestion
score: 0
tagged with: web-scraping
has title: What order is followed when Scrapy CrawlSpider scraping pages?

http://stackoverflow.com/q/50270618
has body: I am trying to connect to a MySQL db on my ubuntu VPS with python and I am using this code import pymysql conn= pymysql.connect(host='remotehost',port='3306', user='user',password='password',db='db') a = conn.cursor() sql = 'SELECT * from `users`;' a.execute(sql) countrow = a.execute(sql) print("Number of rows :",countrow) data = a.fetchone() print(data) When I run the code I get the following error pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'remotehost' ([WinError 10061] No connection could be made because the target machine actively refused it)") I have checked my MySQL db and the 'user' that I am connecting to the server with has the "Any host" hostname set. I can't seem to fix this issue.
has title: Can't connect to MySQL server, No connection could be made because the tared machine actively refused it
downvote count: 0
answer count: 1
tagged with: pymysql
tagged with: mysql
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87559256
type: Question
has answer: http://stackoverflow.com/a/50271251
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50271251
has comment: http://stackoverflow.com/comment/87558854

http://stackoverflow.com/q/50260825
type: Question
has title: Python Web Server with PHP code?
tagged with: server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87539962
tagged with: python
tagged with: php
score: 0
has comment: http://stackoverflow.com/comment/87539801
linked to: http://stackoverflow.com/q/8984287
answer count: 0
upvote count: 1
has body: Can I load PHP to a Python Web Server or it is impossible? I want to use Python for Web Server and PHP, but PHP is loading to notes in HTML.
duplicate of: http://stackoverflow.com/q/8984287
tagged with: web
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/50368172
type: Answer
accepted answer of: http://stackoverflow.com/q/50364171
has body: This is failing while running migrations. Digging through the stack trace, my best guess is that: this is a migration that adds a StreamField to an existing page model, as a required (null=False) field there is an existing instance of that page model (most likely, it's HomePage, as the standard Wagtail project template creates one of those as part of the initial migrations), and so it needs to be populated with a default value the default value that you specified when creating the migration is a non-empty string, which isn't a valid value for a StreamField If so, the fix is to edit the offending migration and change the default value on the StreamField to an empty string.
has comment: http://stackoverflow.com/comment/87763699
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50364171
score: 1

http://stackoverflow.com/a/50338468
has comment: http://stackoverflow.com/comment/87693437
has comment: http://stackoverflow.com/comment/87693611
answers question: http://stackoverflow.com/q/50338391
score: 2
downvote count: 0
has body: The trick to this question is understanding your object types. Let's try finding the type of dict1['c'], as this is the one we're trying to add to: print(type(dict1['c'])) &lt;class 'list'&gt; While we're at it let's see what's inside this list: print(type(dict1['c'][0])) &lt;class 'dict'&gt; So we have a list, and the first element of the list is a dictionary. It looks like we want to add another dictionary to this list. But, wait, is the fact we're adding a dictionary at all relevant? Probably not, we know list can contain any number of objects. So let's see how we can add to a list. A quick google gives us Difference between append vs. extend list methods in Python. So we need list.append. Let's try that: dict1['c'].append(newvalue) print(dict1) {'a': 1, 'b': 2, 'c': [{'aa': 11, 'bb': 22}, {'aa': 111, 'bb': 222}]} Hey, presto! That's exactly what we were looking for.
type: Answer
upvote count: 2

django-templates
tags question: http://stackoverflow.com/q/50300869
tags question: http://stackoverflow.com/q/50319136
tags question: http://stackoverflow.com/q/50252509
tags question: http://stackoverflow.com/q/50242278
tags question: http://stackoverflow.com/q/50275355
tags question: http://stackoverflow.com/q/50328620
tags question: http://stackoverflow.com/q/50315768
tags question: http://stackoverflow.com/q/50242164
tags question: http://stackoverflow.com/q/50261760
tags question: http://stackoverflow.com/q/50267803
tags question: http://stackoverflow.com/q/50240389
tags question: http://stackoverflow.com/q/50262951
tags question: http://stackoverflow.com/q/50266369
tags question: http://stackoverflow.com/q/50288476
tags question: http://stackoverflow.com/q/50254906
tags question: http://stackoverflow.com/q/50367686
tags question: http://stackoverflow.com/q/50310878
tag name: django-templates
tags question: http://stackoverflow.com/q/50307049
tags question: http://stackoverflow.com/q/50312181
tags question: http://stackoverflow.com/q/50281488
tags question: http://stackoverflow.com/q/50335467
tags question: http://stackoverflow.com/q/50380630
tags question: http://stackoverflow.com/q/50264798
type: Tag
tags question: http://stackoverflow.com/q/50360205

http://stackoverflow.com/a/50332832
score: 1
type: Answer
has body: The input and kernel sizes to the nn.conv1d is not right. From the API doc, Input tensor should be of shape: [batch, in_width, num_input_channels] Kernel/weights should be of shape: [filter_width, num_input_channels, out_channels] The inputs are of shape [586,1,1040,1] and should be [586, 1040, 1], and the kernel has the num_input_channels defined wrongly when calling the new_conv_layer. It should be 1 in the first call and 6 in the next call.
accepted answer of: http://stackoverflow.com/q/50330549
answers question: http://stackoverflow.com/q/50330549
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/50328215
has comment: http://stackoverflow.com/comment/87673535
upvote count: 30
has comment: http://stackoverflow.com/comment/102360331
has body: When you import matplotlib, it will probably be trying to use the tk backend as the default. If you didn't install tk, or you do not want to use it anywhere else in your project, then a possible solution would be to simply use a different backend: import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt
type: Answer
score: 29
accepted answer of: http://stackoverflow.com/q/50327906
answers question: http://stackoverflow.com/q/50327906
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/50381203
accepted answer: http://stackoverflow.com/a/50381259
has comment: http://stackoverflow.com/comment/87778541
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50381259
tagged with: http://stackoverflow.com/tag/csv
has title: Writing Nested Dictionary to csv
possible better answer: http://stackoverflow.com/a/50381508
favorite count: 0
type: Question
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/87778576
has body: I have a dictionary: dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}} I would like to tabulate this dictionary into a csv with the uppermost key being the leftmost column and the sub keys being headers on the uppermost row with each subsequent row being filled with the sub key values as such: Location a b c Location1 1 2 3 Location2 4 5 6 Which I have successfully accomplished using the following script: import csv dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}} fields = ["Location","a","b","c"] with open(r"C:\Users\tyler.cowan\Desktop\tabulated.csv", "w", newline='') as f: w = csv.DictWriter(f, extrasaction='ignore', fieldnames = fields) w.writeheader() for k in dic: w.writerow({field: dic[k].get(field) or k for field in fields}) What is peculiar is that I write this test case into a real case, and end up with the equivalent of my location keys being distributed into other columns. Now my first thought was well I must have messed up building the dictionary but upon inspection I get the exact same format of dictionary with the exception of more key values. Yet with output like Location a b c d e f g h Location1 1 2 3 Location1 7 8 9 10 Location2 4 5 6 Location2 2 3 4 5 Below is my full script # -*- coding: utf-8 -*- import os import csv def pretty(d, indent=0): #prettify dict for visual Inspection for key, value in d.items(): print('\t' * indent + str(key)) if isinstance(value, dict): pretty(value, indent+1) else: if value == "": print("fubar") print('\t' * (indent+1) + str(value)) inFolder = "Folder" dirList = os.listdir(inFolder) #print(dirList) fields = [ 'Lat-Long'] allData = {} for file in dirList: fname, ext = os.path.splitext(file) if fname not in fields: fields.append(fname) #handle .dat in this block if ext.lower() == ".dat": #print("found dat ext: " + str(ext)) with open(os.path.join(inFolder,file), "r") as f: for row in f: try: row1 = row.split(" ") if str(row1[0])+"-"+str(row1[1]) not in allData: allData[str…
upvote count: 5
downvote count: 0
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50381508

http://stackoverflow.com/comment/87677103
comment on: http://stackoverflow.com/a/50330519
type: Comment
type: AnswerComment
score: 1
has text: This method also returns a copy of the array.

http://stackoverflow.com/comment/87770252
type: Comment
has text: So I added alot of my code in the OP, `x[i]` is not a single value, it should be (at least to my current understanding) an entire set of data. The first for loop in my code shows how I'm populating `x` with data. When I remove the `try: except:` it still has the same problem.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50376413

http://stackoverflow.com/comment/87735749
type: Comment
comment on: http://stackoverflow.com/q/50359271
score: 0
has text: Thanks @thebjorn - not sure what that means. Convert the ORM call to JSON?
type: QuestionComment

http://stackoverflow.com/comment/87498130
has text: @Kevin, Thanks for the link. Will read up.
score: 0
comment on: http://stackoverflow.com/q/50240317
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87629616
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50305112
has text: Did you try upgrading your pip to the latest version available?

http://stackoverflow.com/a/50282248
answers question: http://stackoverflow.com/q/50281730
has body: Sometimes it's handy to list exactly what code is being ran: nextt = int(input("\nWelcome! ...")) # "nextt" is being set in the local scope if nextt == 1: # "nextt" is being compared to 1 amount = int(input("\nHow ...")) # "amount" is being set in the local scope if amount &gt; balance: # "amount" is being compared to "balance" # Uh oh! We haven't defined "balance" yet! print("Sorry, ...") ... To fix this, you can use the global keyword, which looks for the variable in the global scope. Lets look at an example of how this works before getting to the solution: def f1(): a = 2 print("Value of a: {}; ID of a: {}".format(a, id(a))) def f2(): global a print("[Before] Value of a: {}; ID of a: {}".format(a, id(a))) a = 3 print("[After] Value of a: {}; ID of a: {}".format(a, id(a))) &gt;&gt;&gt; a = 1 # we define "a" in the global scope &gt;&gt;&gt; a, id(a) # id(variable) gets a unique value for this variable (1, 1635934432) &gt;&gt;&gt; f1() Value of a: 2; ID of a: 1635934464 # So you see that the ID is different, because this is f1's version of "a", not the global one &gt;&gt;&gt; a, id(a) (1, 1635934432) # the value and ID of the global variable remain unchanged &gt;&gt;&gt; f2() [Before] Value of a: 1; ID of a: 1635934432 # see the value and ID of the local "a" are now the same as the global variable [After] Value of a: 3; ID of a: 1635934496 # we replaced the value and ID here &gt;&gt;&gt; a, id(a) (3, 1635934496) # which has affected the global version now as well Finally, the full solution: global balance # "balance" is set to the global value nextt = int(input("\nWelcome! ...")) # "nextt" is being set if nextt == 1: # "nextt" is being compared to 1 amount = int(input("\nHow much ...: ")) # "amount" is being set if amount &gt; balance: # "amount" is being compared to "balance" print("Sorry, ...") ...
type: Answer
score: 0

http://stackoverflow.com/a/50324576
answers question: http://stackoverflow.com/q/50324489
type: Answer
score: 0
has body: Using apply and endswith Ex: import pandas as pd df = pd.read_csv(filename, names=["Email"]) print(df["Email"].apply(lambda x: x if x.endswith("@myclinic.com.au") else x+"@myclinic.com.au")) Output: 0 douglas@myclinic.com.au 1 mildura@myclinic.com.au 2 broadford@myclinic.com.au 3 officer@myclinic.com.au 4 nowa nowa@myclinic.com.au 5 langsborough@myclinic.com.au 6 brisbane@myclinic.com.au 7 robertson@myclinic.com.au 8 logan village@myclinic.com.au 9 ipswich@myclinic.com.au Name: Email, dtype: object

http://stackoverflow.com/a/50360601
type: Answer
answers question: http://stackoverflow.com/q/50360539
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87738629
has body: You can use __dict__ to create attributes from data of varying length, and then use classmethod to sum the attributes passed: import string class Foo: def __init__(self, data): self.__dict__ = dict(zip(string.ascii_lowercase, data)) @classmethod def bar(cls, instance, vals = []): return sum(instance.__dict__.values()) if not vals else sum(getattr(instance, i) for i in vals) f = Foo(range(20)) print(Foo.bar(f)) print(Foo.bar(f, ['a', 'c', 'e', 'k', 'm'])) Output: 190 28
score: 1

http://stackoverflow.com/q/50361456
has answer: http://stackoverflow.com/a/50361562
has comment: http://stackoverflow.com/comment/87739582
has comment: http://stackoverflow.com/comment/87739555
tagged with: python
score: -1
favorite count: 0
has body: I want to store a dict and read it with other script fastly. the data stored in a dict like {1:a,2:b,3:c,...}.I stored the dict on disk using code： with open(filename+,'w') as f: f.write(str(dict1)) then I want to get the value with the key like [3,7,9...] in the other python script. Does it must read the whole file？it wastes a lot of time. I find mmap,but I don't know how to use it.
type: Question
has comment: http://stackoverflow.com/comment/87739434
has title: How to get the value fastly from a file on python?
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/87570085
type: Comment
type: QuestionComment
has text: Thanks for your help Bryan. I've updated my tk (to v8.6.7) but still no luck.
comment on: http://stackoverflow.com/q/50276202
score: 0

http://stackoverflow.com/comment/87624051
type: QuestionComment
comment on: http://stackoverflow.com/q/50296720
has text: You were right. I saw that in the other answer, but as an instance of spyder was starting, I tought it was installed also in the other environment. Thanks
score: 0
type: Comment

http://stackoverflow.com/comment/87627486
type: Comment
comment on: http://stackoverflow.com/q/50290922
type: QuestionComment
score: 0
has text: What permissions does the directory and the files have?

http://stackoverflow.com/comment/87536028
type: QuestionComment
score: 0
has text: the `if` statement will never be evaluated inside the `while` statement since `coffee` is 0
comment on: http://stackoverflow.com/q/50259042
type: Comment

http://stackoverflow.com/comment/87724514
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50353078
has text: @DanielMöller Apologies, in the model definition I take both the output from that and another architecture to train against - I've added that to the code now to clarify. You're right that the error is regarding the `y_train`, I just completely misunderstood it. If you post that as an answer I'll accept it.
score: 0

http://stackoverflow.com/comment/87562309
comment on: http://stackoverflow.com/a/50271669
type: AnswerComment
score: 1
has text: @Nir There is no difference between `numpy`'s `median` and `statistics`' `median` - they should return the same results in all situations except they behave slightly differently when input is an empty list. I would just use `numpy` version.
type: Comment

http://stackoverflow.com/a/50308660
accepted answer of: http://stackoverflow.com/q/50308466
has body: The simplest solution is to ask tkinter what class the widget is -- not the python class but rather the internal tk class. For the root window it will be Tk, and for a toplevel it will be Toplevel (unless you've explicitly changed it, which would be highly unusual). import tkinter as tk class MyTop(tk.Toplevel): pass root = tk.Tk() top = tk.Toplevel(root) mytop = MyTop(root) assert(root.winfo_class() == "Tk") assert(top.winfo_class() == "Toplevel") assert(mytop.winfo_class() == "Toplevel")
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50308466
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/50264675
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50265050
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87548099
type: Question
tagged with: python-3.x
has body: I want to use os module specifically to handle read/write binary files. I have an issue when reading values of data type that takes more than 1 byte such as int64, float32, ... etc. To illustrate my issue, let's see the following example I wrote. I generate random values of type np.float64 which is 8 byte each: # Write n = 10 dim = 2 fd = os.open('test.dat', os.O_CREAT | os.O_WRONLY) data_w = np.random.uniform(low=0.5, high=13.3, size=(n,dim)).astype(np.float64) print("Written Data are:\n%s\n" % data_w) os.write(fd, data_w.tobytes()) os.close(fd) print("------------------ \n") # Read start_read = 0 # 0 for now. Later I can read from any row! total_num_to_read = n*dim fd = os.open('test.dat', os.O_RDONLY) os.lseek(fd, start_read, 0) # start_read from the beginning 0 raw_data = os.read(fd, total_num_to_read) # How many values to be read data_r = np.fromiter(raw_data, dtype=np.float64).reshape(-1, dim) print("Data Read are:\n%s\n" % data_r) os.close(fd) The reading is not correct. Look how it is returned: Written Data are: [[ 2.75763292 9.87883101] [ 1.73752327 9.9633879 ] [ 1.01616811 1.81174597] [ 9.93904659 10.6757686 ] [ 7.02452029 2.68652109] [ 5.29766028 11.15384409] [ 4.12499766 10.37214532] [11.75811252 3.30378401] [ 1.72738203 2.11228277] [ 7.7321937 11.64298051]] ------------------ Data Read are: [[250. 87.] [227. 216.] [161. 15.] [ 6. 64.] [162. 178.] [ 59. 35.] [246. 193.] [ 35. 64.] [218. 97.] [ 81. 50.]] I cannot retrieve it correctly! I thought np.fromiter(raw_data, dtype=np.float64).reshape(-1, dim) is supposed to take care of it but I don't know where the issue is. How can I read binary data in this case given that I know it is of particular data type (i.e., np.float64)?
accepted answer: http://stackoverflow.com/a/50265050
answer count: 1
downvote count: 0
has title: Having issue when reading binary data of float
upvote count: 1

http://stackoverflow.com/q/50265289
score: 2
tagged with: python-3.x
has body: LCSS LCSS My code def Distance(P1,P2,R=6378137):# lon1=P1[1];lon2=P2[1] lat1=P1[0];lat2=P2[0] dist = R*math.acos(1-(math.pow((math.sin((90-lat1)*math.pi/180)*math.cos(lon1*math.pi/180)-math.sin((90-lat2)*math.pi/180)*math.cos(lon2*math.pi/180)),2)\ +math.pow((math.sin((90-lat1)*math.pi/180)*math.sin(lon1*math.pi/180)-math.sin((90-lat2)*math.pi/180)*math.sin(lon2*math.pi/180)),2)\ +math.pow((math.cos((90-lat1)*math.pi/180)-math.cos((90-lat2)*math.pi/180)),2))/2) return round(dist,2) def LCSS(A,B,e=500,f=5): if len(A)*len(B)==0: return 0 elif Disance(A[-1],B[-1)&lt;e and abs(len(A)-len(B))&lt;f: return LCSS()+1 else: return max(LCSS(A[:-1],B),LCSS(A,B[:-1])) The question(s) I have no idea the function of LCSS because the function is running all the time in my code, rather than to return a N(int) &lt; max(len(A),len(B)). Thanks!
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: how to use recursion for LCSS in python
favorite count: 0
tagged with: recursion
tagged with: python
type: Question
upvote count: 2

http://stackoverflow.com/comment/87747954
has text: That is super helpful thank you! The stream folder is under my username, so that's the first thing that was off. Second, it seems that it is a different issue keeping this from running at start-up: `May 16 08:25:27 netherlands startup-script: INFO startup-script: No screen session found. May 16 08:25:27 netherlands startup-script: INFO startup-script: No screen session found. May 16 08:25:27 netherlands startup-script: INFO startup-script: Return code 1. May 16 08:25:27 netherlands startup-script: INFO Finished running startup scripts.`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50338897
score: 0

http://stackoverflow.com/a/50350460
has body: It's the difference between list.count and dict.__getitem__ (rc[word]). list.count is O(n) whereas dict.__getitem__ is O(1) due to, as you mention, hashing. Source: https://wiki.python.org/moin/TimeComplexity
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50350280
accepted answer of: http://stackoverflow.com/q/50350280
score: 1

http://stackoverflow.com/a/50305894
has comment: http://stackoverflow.com/comment/87636826
has comment: http://stackoverflow.com/comment/87705061
has comment: http://stackoverflow.com/comment/87643443
has comment: http://stackoverflow.com/comment/87643452
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50305218
has body: import random from random import randint num1 = random.randint(1,20) num2 = random.randint(1,20) question = ["Bigger" , "Smaller"] questiondecide = random.choice(question) biggest = max(num1, num2) smallest = min(num1, num2) if questiondecide == "Bigger": userAnswer = input("Please find the Higher value between " + str(num1) + " and " + str(num2) + ":" + "\n") print(biggest) if userAnswer == biggest: print("This is the biggest number") print("and you have chosen the bigger number!") elif userAnswer == smallest: print("This is the smallest number") print("but you have not chosen the bigger number!") elif questiondecide == "Smaller": userAnswer = input("Please find the Lower value between " + str(num1) + " and " + str(num2) + ":" + "\n") if userAnswer == biggest: print("This is the biggest number") print("but you have not chosen the smaller number!") elif userAnswer == smallest: print("This is the smallest number") print("and you have chosen the smaller number!") Hope this helps! Have any questions ask away!

http://stackoverflow.com/a/50293917
has comment: http://stackoverflow.com/comment/87604157
has comment: http://stackoverflow.com/comment/87604982
downvote count: 0
has comment: http://stackoverflow.com/comment/87604193
has comment: http://stackoverflow.com/comment/87604325
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50293656
has comment: http://stackoverflow.com/comment/87609939
upvote count: 17
score: 17
has body: Don't blame Numpy, blame PIL / Pillow. ;) You're generating floats, but PIL expects integers, and its float to int conversion is not doing what we want. Further research is required to determine exactly what PIL is doing... In the mean time, you can get rid of those lines by explicitly converting your values to unsigned 8 bit integers: img_arrays = (np.random.random((100, 256, 256, 3)) * 255).astype(np.uint8) As FHTMitchell notes in the comments, a more efficient form is img_arrays = np.random.randint(0, 256, (100, 256, 256, 3), dtype=np.uint8) Here's typical output from that modified code: The PIL Image.fromarray function has a known bug, as described here. The behaviour you're seeing is probably related to that bug, but I guess it could be an independent one. ;) FWIW, here are some tests and workarounds I did on the bug mentioned on the linked question.
answers question: http://stackoverflow.com/q/50293656
has comment: http://stackoverflow.com/comment/87604947
type: Answer

http://stackoverflow.com/a/50375346
has body: As I wrote in a comment, you have a directed graph (X/Y is an edge, X and Y are vertices) and you're trying to find all cycles, without any specific difficulty. Here's an example of how you can create a graph (represented by an adjacency list) from your list and then rebuild the edges out of the detected cycles. def get_cycles(edges): # create the graph from the edges graph = {} for e in edges: v1, v2 = e.split('/') graph.setdefault(v1, []).append(v2) for cycle in graph_cycles(graph): # rebuld the edges from the cycle if len(cycle) == 1: yield (cycle[0]+"/"+cycle[0], ) else: # zip a,b,...,y,z with b,c,...,z,a to get the edges a/b, b/c, ..., y/z, z/a yield tuple([a+"/"+b for a,b in zip(cycle[-1:]+cycle[:-1], cycle)]) print (list(get_cycles(['A/A', 'A/B','B/A','B/C','C/D','C/A','D/E','E/C']))) # output: [('A/B', 'B/C', 'C/A'), ('A/B', 'B/A'), ('A/A',), ('B/C', 'C/A', 'A/B'), ('B/A', 'A/B'), ('C/A', 'A/B', 'B/C'), ('C/D', 'D/E', 'E/C'), ('D/E', 'E/C', 'C/D'), ('E/C', 'C/D', 'D/E')] If the graph is small enough, a simple Depth First Seach will do the trick. You can take a look at this answer for instance: def graph_cycles(graph): return (cycle for node in graph for cycle in dfs(graph, node, node)) # dfs defined in https://stackoverflow.com/a/40834276 This is far from the optimal solution, but you can replace graph_cycles by a better implementation (Tarjan's or Kosaraju's algorithm, see en.wikipedia.org/wiki/Strongly_connected_component.) In both cases, you'll have to take special care of nodes pointing directly to themselves (X/X edges).
score: 0
answers question: http://stackoverflow.com/q/50353330
type: Answer

http://stackoverflow.com/comment/87902238
score: 0
type: AnswerComment
has text: @BPL, the `Difference3` may be because in QScintilla you need to select till the next line for the region to get selected
comment on: http://stackoverflow.com/a/50431088
type: Comment

http://stackoverflow.com/a/50321727
answers question: http://stackoverflow.com/q/50301500
has comment: http://stackoverflow.com/comment/105958149
type: Answer
upvote count: 2
score: 2
has body: You can try to run flake8 twice — once with a global config excluding tests/ and the second run just in tests/: commands = flake8 --exclude=tests cd tests &amp;&amp; flake8
downvote count: 0

http://stackoverflow.com/comment/87662615
type: Comment
type: QuestionComment
has text: Are you trying to use the same parameters across different read functions in pandas?
comment on: http://stackoverflow.com/q/50323460
score: 0

http://stackoverflow.com/q/50382613
tagged with: keras
has title: Incorrect number of dimensions in Keras input
has body: I'm attempting to follow along on what I'm thinking is the 5th or 6th simple introductory tutorial for keras that almost but never quite works. Stripping everything out, I appear to come down to a problem with the format of my input. I read in an array of images, and extract two types, images of sign language ones and images of sign language zeros. I then set up an array of ones and zeros to correspond to what the images actually are, then make sure of sizes and types. import numpy as np from subprocess import check_output print(check_output(["ls", "../data/keras/"]).decode("utf8")) ## load dataset of images of sign language numbers x = np.load('../data/keras/npy_dataset/X.npy') # Get the zeros and ones, construct a list of known values (Y) X = np.concatenate((x[204:409], x[822:1027] ), axis=0) # from 0 to 204 is zero sign and from 205 to 410 is one sign Y = np.concatenate((np.zeros(205), np.ones(205)), axis=0).reshape(X.shape[0],1) # test shape and type print("X shape: " , X.shape) print("X class: " , type(X)) print("Y shape: " , Y.shape) print("Y type: " , type(Y)) This gives me: X shape: (410, 64, 64) X class: &lt;class 'numpy.ndarray'&gt; Y shape: (410, 1) Y type: &lt;class 'numpy.ndarray'&gt; which is all good. I then load the relevant bits from Keras, using Tensorflow as the backend and try to construct a classifier. # get the relevant keras bits. from keras.models import Sequential from keras.layers import Convolution2D # construct a classifier classifier = Sequential() # initialize neural network classifier.add(Convolution2D(32, (3, 3), input_shape=(410, 64, 64), activation="relu", data_format="channels_last")) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) classifier.fit(X, Y, batch_size=32, epochs=10, verbose=1) This results in: ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (410, 64, 64) This SO question, I think, suggests that my input shape …
linked to: http://stackoverflow.com/q/41563720
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50383715
tagged with: python

http://stackoverflow.com/comment/87722123
type: AnswerComment
score: 0
has text: Oh I understand, maybe readlines() function causes the problem. Have you tried reading [lines one by one](https://stackoverflow.com/a/3277512/4681316). Then you could do the operations on the line and write it down to another file. Or you should use regex to find the correct pattern.
type: Comment
comment on: http://stackoverflow.com/a/50352743

http://stackoverflow.com/comment/87763893
has text: Is your XML file exactly like what you have in your question? If it's blank I don't think the xpaths are matching. Maybe add some print statements to debug. Like `print(etree.tostring(tree, pretty_print=True))` to see what the tree looks like. Maybe also a `print("hit!")` in the `for` to see if you get 3 messages for each MODocument selected.
comment on: http://stackoverflow.com/a/50359862
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50378386
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50370571
has comment: http://stackoverflow.com/comment/87905202
downvote count: 0
type: Answer
has body: If you want to compare the values month per month I would run an automated (scheduled) task every month. Then, I would create a new record with the new value for the field b in the task method. So you would have a history of values in this way, one a month. Therefore, my recommendation is that you should create a normal field without the compute attribute: b = fields.Float()
answers question: http://stackoverflow.com/q/50370571
has comment: http://stackoverflow.com/comment/87907389
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/87575544
has text: You mean like in [this question](https://stackoverflow.com/q/16748577/8881141)?
comment on: http://stackoverflow.com/q/50279217
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/50297923
has comment: http://stackoverflow.com/comment/87612743
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50298139
tagged with: python
has body: I have my JSON Structure like this, I wish to create new list by checking driverKey of each dictionary inside list { "RDBMS": [ { "userName": "a", "entityName": "entity1", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "PostgreSQL Unicode" }, { "userName": "b", "entityName": "entity2", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "PostgreSQL Unicode" }, { "userName": "a", "entityName": "entity3", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "SQL Server" } ] } Expected Output: { "PostgreSQL": [ { "userName": "a", "entityName": "entity1", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "PostgreSQL Unicode" }, { "userName": "b", "entityName": "entity2", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "PostgreSQL Unicode" } ], "SQL SERVER": [ { "userName": "a", "entityName": "entity1", "connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;", "databaseName": "database1", "driverKey": "PostgreSQL Unicode" }] } I have tried different approach but "connectionString" inside my dictionary gives me different output. loop over list and getting item does not solve my problem. Any Suggestions
tagged with: dictionary
has answer: http://stackoverflow.com/a/50297996
has title: Convert list of dictionaries to separate list based on dictionary values
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/50298139
accepted answer: http://stackoverflow.com/a/50297996
has comment: http://stackoverflow.com/comment/87612671

http://stackoverflow.com/q/50374779
has answer: http://stackoverflow.com/a/78609291
tagged with: python
tagged with: rounding-error
upvote count: 11
answer count: 4
has answer: http://stackoverflow.com/a/50376089
score: 9
tagged with: numpy
downvote count: 2
type: UnansweredQuestion
has body: I'm working with floating point numbers. If I do: import numpy as np np.round(100.045, 2) I get: Out[15]: 100.04 Obviously, this should be 100.05. I know about the existence of IEEE 754 and that the way that floating point numbers are stored is the cause of this rounding error. My question is: how can I avoid this error?
has comment: http://stackoverflow.com/comment/87766673
tagged with: floating-point
has answer: http://stackoverflow.com/a/50375035
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/56497911
has title: How to avoid incorrect rounding with numpy.round?
has comment: http://stackoverflow.com/comment/87787471
tagged with: rounding
has comment: http://stackoverflow.com/comment/87801771
has comment: http://stackoverflow.com/comment/87767360
has comment: http://stackoverflow.com/comment/87787653

http://stackoverflow.com/a/67880268
upvote count: 0
answers question: http://stackoverflow.com/q/50280265
downvote count: 1
has body: I would like to pass an array {% include '/blocks/block-products-carousel.html' with groups= [ {title: 'All', active: true}, {title: 'Power Tools', active: false}, {title: 'Hand Tools', active: false}, {title: 'Plumbing', active: false}, ],
type: Answer
has comment: http://stackoverflow.com/comment/136102706
score: -1

http://stackoverflow.com/q/50352091
has answer: http://stackoverflow.com/a/50365363
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50365363
score: 0
answer count: 1
has body: I am trying to sign a huge video upload, because I want to upload it directly to S3. It works on localhost, but on my live site it fails to sign the request because of: Mixed Content: The page at 'https://www.example.com/profile' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://www.example.com/sign_s3/?file_name=17mbvid.mp4&amp;file_type=video/mp4'. This request has been blocked; the content must be served over HTTPS. I am hosting everything on heroku, every page is already using HTTPS and its not possible to open it in HTTP, because I redirect all traffic to HTTPS. I am using the letsencrypt SSL certificate. So far I have no idea where to look, the only information I found, is that I need a valid SSL certificate, which I have. Here is the JS function: function getSignedRequest(file) { var xhr = new XMLHttpRequest(); xhr.open("GET", "/sign_s3?file_name=" + file.name + "&amp;file_type=" + file.type); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('got signed request'); var response = JSON.parse(xhr.responseText); console.log(response); console.log('uploadFile', response.url) uploadFile(file, response.data, response.url); } else { console.log("Could not get signed URL."); } } }; //console.log('send'); xhr.send(); } Right after the error in the console I see this console log: Could not get signed URL. which means it fails here: if (xhr.status === 200) On the server: @app.route('/sign_s3/', methods=["GET", "POST"]) @login_required @check_confirmed def sign_s3(): if "localhost" in request.url_root: file_name = str(current_user.id) + "local-profil-video." + request.args.get('file_name').split(".")[-1] else: file_name = str(current_user.id) + "-profil-video." + request.args.get('file_name').split(".")[-1] file_type = request.args.get('file_type') session = boto3.Session( aws_access_key_id=app.config['MY_AWS_ID'], aws_secret_access_key=app.config['MY_AWS_SECRET'], region_name='eu-centra…
type: Question
tagged with: ssl
tagged with: javascript
tagged with: python
tagged with: xmlhttprequest
has title: XMLHttpRequest endpoint blocked while signing S3 request because no HTTPS, eventhough everything is on HTTPS

http://stackoverflow.com/comment/88317194
comment on: http://stackoverflow.com/a/50420596
has text: @morienor i am downloading the dataset and will try to run it using your implementation.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/87771669
type: AnswerComment
has text: When I try this, I am getting the first table header followed by every single link in each of the tables. What I want is only the links located in that first table so the first location in the dictionary has the first header, followed by the links in that first table
comment on: http://stackoverflow.com/a/50377615
type: Comment
score: 0

http://stackoverflow.com/comment/87781594
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50382120
has text: I did have a feeling it could be capacity issue. Unfortunately my budget is not huge, I've attached a list of instances in my price range. Would you recommend any of these / are they a relatively big upgrade on the t2.medium? I will take some time and digest the vpc-flow-logs, thanks Douglas.

http://stackoverflow.com/comment/87735640
score: 0
comment on: http://stackoverflow.com/a/50359367
type: AnswerComment
has text: So I tried your code and for some reason, I end up with any empty list for final_results and as a result, an index out of bounds error. When I use get_text() the document prints all the text though but once I start using find or find_all, the lists are returned empty.
type: Comment

http://stackoverflow.com/q/50232891
has comment: http://stackoverflow.com/comment/87538249
has comment: http://stackoverflow.com/comment/87537933
answer count: 2
has comment: http://stackoverflow.com/comment/87485077
score: 0
has title: Connect to Couchdb using Django rest framework 3.6.2 and python 3
tagged with: django-rest-framework
tagged with: couchdb
type: Question
has answer: http://stackoverflow.com/a/50521563
has comment: http://stackoverflow.com/comment/87509735
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87485146
linked to: http://stackoverflow.com/q/2169737
tagged with: django
has answer: http://stackoverflow.com/a/51698065
tagged with: python
has body: I am working on Django Rest framework. I have created a few APIs and am storing data in sql lite. Now, I want to save data to CouchDB from the rest API calls basically crud application. I am not getting how to connect to couch db via Django rest framework. I'm stuck here not getting how to do crud in couch db using Django rest api. Below is one of the api written in django for adding accconts. I want to save this data in CouchDB. models.py class BankAccount(models.Model): SAVINGS = 'saving' CURRENT = 'current' TYPE = ( (SAVINGS,'Saving'), (CURRENT,'Current') ) type = models.CharField(max_length=20, choices=TYPE, default=SAVINGS) bank_name = models.CharField(max_length=200) account_number = models.IntegerField() balance = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): """returns the model as string.""" return self.bank_name def __str__(self): """returns the model as string.""" return self.type serializers.py class BankAccountSerializer(serializers.ModelSerializer): class Meta: model = BankAccount fields = '__all__' views.py class BankAccountView(APIView): def get_object(self, pk): try: return BankAccount.objects.get(pk=pk) except BankAccount.DoesNotExist: raise Http404 def get(self, request, format=None): accounts = BankAccount.objects.all() serializer = BankAccountSerializer(accounts, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = BankAccountSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, format=None): data = json.loads(request.body) pk = data['id'] action = data['action'] if action == 'delete': return self.deleteItem(pk) account = self.get_object(pk) serializer = BankAccountSerializer(account, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializ…

http://stackoverflow.com/comment/135483570
has text: This is kind of "how do I get my JSON parser to stop parsing my JSON".
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50252251
type: Comment

http://stackoverflow.com/comment/87600636
comment on: http://stackoverflow.com/q/50288783
type: QuestionComment
has text: It doesn't terminate the script; it is running a *new* shell whose input and output are logged. When you terminate *that* shell, your Python script will resume.
type: Comment
score: 0

http://stackoverflow.com/q/50295907
tagged with: python
score: 4
tagged with: conda
tagged with: miniconda
tagged with: environment
has answer: http://stackoverflow.com/a/61863196
type: AnsweredQuestion
tagged with: anaconda
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/57013837
favorite count: 0
accepted answer: http://stackoverflow.com/a/50296291
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/57013837
has answer: http://stackoverflow.com/a/50296291
has body: I have installed miniconda3 on a system using the bash installation script, then performed a conda install of some packages into this installation. This installation is available to other users in a read-only fashion. They can source a setup script that adds the conda installation to their LD_LIBRARY_PATH, PATH, and PYTHONPATH. I would like the user to be able to add their own custom modules on top of this environment. Ideally the user would run some form of conda create environment that results in the user being able to install packages in their local environment, but takes the previously installed packages from my area. Is there a good way to do this? The important point for this is that my conda installation has some architecture specific libraries which are needed to get proper performance on the computer system we have. If a user does a standard conda create ... everything is installed from scratch and the user does not get the proper libraries.
has title: Create Conda environment on top of existing installation

http://stackoverflow.com/q/50293496
accepted answer: http://stackoverflow.com/a/50293599
has body: I am currently running into a problem and hoping that someone could assist. Currently have 2 dataframes of items which are hundreds of thousands of lines long. (one has over 200k and one over 180k). the larger of the 2 dataframes is going to contain unique values of users, while the smaller one does not so for example: df1: user1 user2 user3 user4 user5 df2: user1 user1 user5 user4 user5 user5 What i need to do is take each user from df1 and efficiently see if it is in df2 and how many times it occurs. Thanks!
has answer: http://stackoverflow.com/a/50293672
has answer: http://stackoverflow.com/a/50293599
score: 8
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50293568
upvote count: 8
downvote count: 0
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has title: Count occurrences of item in one dataframe in another
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50293672

http://stackoverflow.com/comment/101498176
comment on: http://stackoverflow.com/a/56250747
score: 12
type: AnswerComment
type: Comment
has text: Especially good examples: they show an aspect under which _C_ sometimes managed to be clearer and more elegant than Python, I thought they were never going to fix this

http://stackoverflow.com/comment/87764985
comment on: http://stackoverflow.com/a/50369111
type: Comment
has text: Should `$NAME` stay as it is and use `NAME=yourdemon`, if this works like this, or do I have to change something more than `yourdemon` and the path to my .py file?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87582423
type: AnswerComment
has text: o, but yes, totally forgot to write '''anzal = int(lot.get.get())''' below the function
comment on: http://stackoverflow.com/a/50282094
score: 0
type: Comment

http://stackoverflow.com/comment/87618358
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50300635
has text: Your data ranges from the 19th of august to the 27th of august. This range is shown in the plot as well. So it is not obvious why you think that some x-axis values are missing.
type: Comment

http://stackoverflow.com/q/50305934
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/87628507
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87628218
has title: Can you call an attribute with an f string through a loop?
has body: import pandas as pd def get_stat(symbol, stat): df = pd.read_csv(f"{symbol}.csv") return df['close'].f"{stat}"() def test_run(): for symbol in ['nugt', 'soxs']: for stat in ['max','min', 'mean']: print(f"{stat} Close") print(symbol, get_stat(symbol)) if __name__ == "__main__": test_run() The "stat" variable doesn't link between the "test_run" function and "get_stat" function which in turn won't let me call it in the .f"stat"() part. I am aiming for the results to look like this: max Close nugt #### min Close nugt #### mean Close nugt #### max Close soxs #### min Close soxs #### mean Close soxs ####
has comment: http://stackoverflow.com/comment/87628093
favorite count: 0
type: Question

http://stackoverflow.com/a/61642519
has body: You can redraw the plot dynamically from scratch. from IPython import display def dynamic_plot(X,Y, figsize=[10,5], max_x=None, min_y=None, max_y=None): '''plots dependency between X and Y dynamically: after each call current graph is redrawn''' gcf().set_size_inches(figsize) cla() plot(X,Y) if max_x: plt.gca().set_xlim(right=max_x) if min_y: plt.gca().set_ylim(bottom=min_y) if max_y: plt.gca().set_ylim(top=max_y) display.display(gcf()) display.clear_output(wait=True) And the demo use for jupyter notebook: import time X=[] Y=[] for i in range(10): X.append(i) Y.append(i**.5) dynamic_plot(X,Y,[14,10], max_x=10, max_y=4) time.sleep(0.3)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50301229

http://stackoverflow.com/comment/87480463
comment on: http://stackoverflow.com/q/50231400
has text: @cinico, trying to make reverse stairs, so i wanted the list to start like [5,4,3....], [4,3,2] etc
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87644477
score: 0
type: AnswerComment
has text: @EMZ It seems that it's returning a bound method. You should call the result(s).
type: Comment
comment on: http://stackoverflow.com/a/50313915

http://stackoverflow.com/comment/87564782
type: AnswerComment
comment on: http://stackoverflow.com/a/50271380
has text: I get that reducing sequences of variable lengths to a fixed tensor is mostly needed, and that this can be done by using the last cell output or an aggregate over whole output sequence. But is the difference, intuitively speaking? Are there cases where one approaches is preferable compared to the other?
score: 0
type: Comment

http://stackoverflow.com/comment/87638374
has text: Regex are fast and well known. They are a legit choice but I really don't like them. Too cryptic.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50311032
type: QuestionComment

http://stackoverflow.com/q/50274851
has comment: http://stackoverflow.com/comment/87602207
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
has body: I have installed the mysqlclient in pip3, but I still get this error when I run uwsgi --ini uwsgi: *** Operational MODE: threaded *** django.setup() Traceback (most recent call last): File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 26, in &lt;module&gt; import MySQLdb as Database File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/MySQLdb/__init__.py", line 19, in &lt;module&gt; import _mysql ImportError: No module named '_mysql' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "myProject/wsgi.py", line 19, in &lt;module&gt; django.setup() File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Python3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ldl/repo/myProject/venv/lib/python3.5/site-packages/django/co…
score: 0
has comment: http://stackoverflow.com/comment/87567743
has comment: http://stackoverflow.com/comment/87584697
has title: I have installed the `mysqlclient`, why there still get Did you install mysqlclient or MySQL-python? issue
type: Question
linked to: http://stackoverflow.com/q/46902357

http://stackoverflow.com/q/50242754
accepted answer: http://stackoverflow.com/a/50242802
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50242802
score: 1
upvote count: 1
has body: I want to make a simple XY-plot based on the data in a dictionary. My data looks like thit: D = {'str1': [[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]],'str2': [[8, 9, 10, 11, 12], [8, 9, 10, 11, 12]]} Is there a way to just plot, for example, the first dictionary form D. The command should be something like plt.plot("str1")
favorite count: 0
tagged with: plot
type: Question
tagged with: pandas
tagged with: matplotlib
tagged with: python
has title: Plot a two dimensional array using a dictionary with pandas/python
has comment: http://stackoverflow.com/comment/87503247
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/87510965
type: Comment
comment on: http://stackoverflow.com/q/50243583
has text: What is the type of `poster_path_image2`?
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87603220
comment on: http://stackoverflow.com/a/50293135
score: 0
type: Comment
type: AnswerComment
has text: Because that's what "inherit from a class instance" means: take some given object x and use it as a template for stamping out more xs dynamically, and indeed the OPs response to Matias Cicero's answer confirms it.

http://stackoverflow.com/comment/87743700
type: Comment
has text: Easier still if you use `ws.values`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50357172

http://stackoverflow.com/a/50376933
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has body: Below is my suggestion import re def swapfunc(text, b, c): if re.search(r"\b"+b+r"\b|\b"+c+r"\b", text, re.I): if not re.search(r"\b"+b+r"\b", text, re.I): return b+" not found"; elif not re.search(r"\b"+c+r"\b", text, re.I): return c+" not found"; else: text = re.sub(r"\b"+b+r"\b", '__c__', text, flags=re.IGNORECASE) text = re.sub(r"\b"+c+r"\b", '__b__', text, flags=re.IGNORECASE) text = text.replace('__c__', c.upper()) text = text.replace('__b__', b.upper()) return text else: return "Values "+b+" and "+c+" not found"; print(swapfunc("dylan and Bob work together.", "Dylan", "bob")) print(swapfunc("Dylan and Bob work together.", "BOB", "DylAn")) print(swapfunc("and Bob work together.", "dylan", "bob")) print(swapfunc("Dylan and work together.", "DYLAN", "BoB"))
accepted answer of: http://stackoverflow.com/q/50375941
score: 1
answers question: http://stackoverflow.com/q/50375941

http://stackoverflow.com/comment/87540214
type: QuestionComment
comment on: http://stackoverflow.com/q/50260946
score: 0
type: Comment
has text: Same thing, unfortunately

http://stackoverflow.com/comment/90126276
type: Comment
type: QuestionComment
has text: I'd love some mechanism to say that allows generic proxies. The proposed solution isn't enough, unfortunately.
comment on: http://stackoverflow.com/q/50317735
score: 1

http://stackoverflow.com/q/50367007
downvote count: 0
upvote count: 7
has body: Consider the following function import typing def make_list(el : typing.Any): return [el, el] How do I hint that it returns typing.List[type(el)]
tagged with: python-typing
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50367128
accepted answer: http://stackoverflow.com/a/50367128
tagged with: python
has title: Python type hinting, output type depends on input type
type: AnsweredQuestion
score: 7
answer count: 1

http://stackoverflow.com/q/50359053
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87734840
tagged with: python
tagged with: midi
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87735171
has body: I am trying to extract information out of a JSON file that I dumped. I used Mido module to get the information I need, and the only way I've found to get these features is by dumping it as a JSON. But, after some search, I've tried and not managed to extract and store the info in a python array (numpy array)* Below, you see the sample code. I am pretty sure that double [[ at the beginning of the file is making all this trouble. if __name__ == '__main__': filename = 'G:\\ΣΧΟΛΗ p12127\\Πτυχιακη\\MAPS Dataset\\MAPS_AkPnBcht_1\\AkPnBcht\\ISOL\\CH\\MAPS_ISOL_CH0.1_F_AkPnBcht.mid' midi_file = mdfile(filename) for i, track in enumerate(midi_file.tracks): print('Track: ', i,'\nNumber of messages: ', track) for message in track: print(message) def midifile_to_dict(mid): tracks = [] for track in mid.tracks: tracks.append([vars(msg).copy() for msg in track]) return { 'ticks_per_beat': mid.ticks_per_beat, 'tracks': tracks, } mid = mido.MidiFile('G:\\ΣΧΟΛΗ p12127\\Πτυχιακη\\MAPSDataset\\MAPS_AkPnBcht_1\\AkPnBcht\\ISOL\\CH\\MAPS_ISOL_CH0.1_F_AkPnBcht.mid') dataj = json.dumps(midifile_to_dict(mid), indent=2) data = json.loads(dataj) Output : { "ticks_per_beat": 32767, "tracks": [[ { "type": "set_tempo", "tempo": 439440, "time": 0 }, { "type": "end_of_track", "time": 0 } ]] } So, to close this up, how could I extract this info? Is JSON even a good approach? And if so, how could I actually extract this info? Or a way to go inside the [[ ]]. [Windows 7, Python 3.6+]
has title: Extract info from json file, Python
tagged with: mido
has comment: http://stackoverflow.com/comment/87735042
linked to: http://stackoverflow.com/q/2835559
score: 0
tagged with: feature-extraction

http://stackoverflow.com/comment/87825684
type: Comment
has text: ah i see what you mean. this makes a lot of sense thank you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50364157

http://stackoverflow.com/q/50382040
accepted answer: http://stackoverflow.com/a/50382096
has answer: http://stackoverflow.com/a/57067313
has answer: http://stackoverflow.com/a/50382096
score: 16
upvote count: 16
favorite count: 0
linked to: http://stackoverflow.com/q/529424
has answer: http://stackoverflow.com/a/50382101
has body: letters = ['a', 'b', 'c'] Assume this is my list. Where for i, letter in enumerate(letters) would be: 0, a 1, b 2, c How can I instead make it enumerate backwards, as: 2, a 1, b 0, c
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/50384359
possible better answer: http://stackoverflow.com/a/57067313
linked to: http://stackoverflow.com/q/38738548
tagged with: python
has answer: http://stackoverflow.com/a/50382108
has answer: http://stackoverflow.com/a/50382188
has answer: http://stackoverflow.com/a/50382102
has comment: http://stackoverflow.com/comment/87780126
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50382155
has title: How can I use enumerate to count backwards?
has comment: http://stackoverflow.com/comment/87782110
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87780124
has comment: http://stackoverflow.com/comment/87780115
downvote count: 0

http://stackoverflow.com/a/50321073
downvote count: 0
has body: One way to perhaps do this would be to create a COM object using .NET and execute Python code using IronPython. Here is an idea of how it could work: using System; using System.Runtime.InteropServices; using System.IO; using System.Text; using IronPython.Hosting; namespace PythonComObject { [Guid("F34B2821-14FB-1345-356D-DD1456789BBF")] public interface PythonComInterface { [DispId(1)] bool RunSomePython(); [DispId(2)] bool RunPythonScript(); } // Events interface [Guid("414d59b28-c6b6-4e65-b213-b3e6982e698f"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface PythonComEvents { } [Guid("25a337e0-161c-437d-a441-8af096add44f"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(PythonComEvents))] public class PythonCom : PythonComInterface { private ScriptEngine _engine; public PythonCom() { // Initialize IronPython engine _engine = Python.CreateEngine(); } public bool RunSomePython() { string someScript = @"def return_message(some_parameter): return True"; ScriptSource source = _engine.CreateScriptSourceFromString(someScript, SourceCodeKind.Statements); ScriptScope scope = _engine.CreateScope(); source.Execute(scope); Func&lt;int, bool&gt; ReturnMessage = scope.GetVariable&lt;Func&lt;int, bool&gt;&gt;("return_Message"); return ReturnMessage(0); } public bool RunPythonScript() { ScriptSource source = _engine.CreateScriptSourceFromFile("SomeScript.py"); ScriptScope scope = _engine.CreateScope(); source.Execute(scope); Func&lt;int, bool&gt; some_method = scope.GetVariable&lt;Func&lt;int, bool&gt;&gt;("some_method"); return some_method(1); } } } I haven't tried this, it is just an idea, I hope it works or at least get you in the right direction. Some helpful references: https://blogs.msdn.microsoft.com/seshadripv/2008/06/30/how-to-invoke-a-ironpython-function-from-c-using-the-dlr-hosting-api/ http://ironpython.net https://www.nuget.org/packages/IronPython/
has comment: http://stackoverflow.com/comment/87676802
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/50320824

python-decorators
tags question: http://stackoverflow.com/q/50381697
tags question: http://stackoverflow.com/q/50358261
type: Tag
tags question: http://stackoverflow.com/q/50354039
tags question: http://stackoverflow.com/q/50350379
tags question: http://stackoverflow.com/q/50364173
tag name: python-decorators
tags question: http://stackoverflow.com/q/50264021
tags question: http://stackoverflow.com/q/50356207

http://stackoverflow.com/q/50297704
tagged with: python-3.8
answer count: 7
has answer: http://stackoverflow.com/a/76882877
has comment: http://stackoverflow.com/comment/97818693
has answer: http://stackoverflow.com/a/79477118
upvote count: 122
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-assignment-expression
has answer: http://stackoverflow.com/a/58396771
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92269486
has comment: http://stackoverflow.com/comment/87612345
has answer: http://stackoverflow.com/a/56250747
has title: What are assignment expressions (using the "walrus" or ":=" operator)? Why was this syntax added?
tagged with: python
has body: Since Python 3.8, code can use the so-called "walrus" operator (:=), documented in PEP 572, for assignment expressions. This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambdas. What exactly are the syntax, semantics, and grammar specifications of assignment expressions? Why was this new (and seemingly quite radical) concept introduced, even though PEP 379 (which proposes the similar idea of "Adding an assignment expression") was withdrawn?
has answer: http://stackoverflow.com/a/50297705
has answer: http://stackoverflow.com/a/76595753
has answer: http://stackoverflow.com/a/71656529
has comment: http://stackoverflow.com/comment/133794873
downvote count: 6
score: 116
has comment: http://stackoverflow.com/comment/103166927

http://stackoverflow.com/comment/135497743
has text: @Andj I see, thanks a lot. To be honest, I was not aware what kind of hornet's nest I was stirring up here
comment on: http://stackoverflow.com/a/76857639
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87779890
comment on: http://stackoverflow.com/a/50341029
type: Comment
score: 0
type: AnswerComment
has text: sqashmigrations is used when you want set many migrations files to one,it;s not something must be done.

http://stackoverflow.com/a/50364627
type: Answer
has comment: http://stackoverflow.com/comment/87745957
has comment: http://stackoverflow.com/comment/87745983
has comment: http://stackoverflow.com/comment/87746363
accepted answer of: http://stackoverflow.com/q/50364584
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87745631
has comment: http://stackoverflow.com/comment/87746567
upvote count: 2
has body: I think need read_csv for DataFrames with map and insert for new column after ServiceID: df1 = pd.read_csv('services.csv') df2 = pd.read_csv('test.csv') #get position of ServiceID column pos = df2.columns.get_loc('ServiceID') + 1 df2.insert(pos, 'Service', df2['ServiceID'].map(df1.set_index('ServiceID')['Service'])) print (df2) ClinicServiceID ClinicID ServiceID Service \ 0 1 1 1 General Practitioner 1 2 1 2 Pathology 2 3 2 1 General Practitioner 3 4 2 2 Pathology 4 5 2 3 Radiology Name Suburb State Postcode \ 0 Hurstville Clinic Hurstville NSW 1493 1 Hurstville Clinic Hurstville NSW 1493 2 Sydney Centre Clinic Sydney NSW 2000 3 Sydney Centre Clinic Sydney NSW 2000 4 Sydney Centre Clinic Sydney NSW 2000 Email Lat Lon 0 hurstville@myclinic.com.au -33.975869 151.088939 1 hurstville@myclinic.com.au -33.975869 151.088939 2 sydney@myclinic.com.au -33.867139 151.207114 3 sydney@myclinic.com.au -33.867139 151.207114 4 sydney@myclinic.com.au -33.867139 151.207114
answers question: http://stackoverflow.com/q/50364584

http://stackoverflow.com/q/50246361
has body: I am working on a python project. All was working well when I just had one level of inheritance but once I added SavingAccount and CheckingAccount which should be a child of BankAccount which is a child of Customer I started to get the following error: 'CheckingAccount' object has no attribute 'balance' I assumed I would do the second layer of inheritance the same as the first but maybe I must be missing. Thanks in advance for any help! class Customer: def __init__(self,firstName, lastName, social): self.firstName = firstName self.lastName = lastName self.social = social def setfirstName(self,firstName): self.firstName = firstName def setlastName(self,lastName): self.lastName = lastName def __str__(self): self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social) return self.name class BankAccount(Customer): from random import randint n = 10 range_start = 10**(n-1) range_end = (10**n)-1 accountNumber = randint(range_start, range_end) def __init__(self,customer,balance = 0): self.customer = customer self.balance = balance def setCustomer(self,customer,accountNumber): self.customer = customer self.accountNumber = accountNumber def getCustomer(self,customer,accountNumber): return self.customer, self.accountNumber def deposit(self, amount): self.balance = self.balance + amount return self.balance def withdrawal(self, amount): self.balance = self.balance - amount return self.balance def __str__(self): customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance) return customer class CheckingAccount(BankAccount): def __init__(self, bankAccount): self.bankAccount = bankAccount def applyAnnualInterest(self): excess = self.balance - 10000 if excess &gt; 0: interest = (excess * .02) self.balance = self.balance + interest return self.balance else: return self.balance class SavingAccount(BankAccount): def __init__(self, bankAccount): self.bankAccount = bankAccount def applyAnnualInterest(self): interest = (self.balan…
has answer: http://stackoverflow.com/a/50246413
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has title: Multi level inheritance python - 'CheckingAccount' object has no attribute 'balance'

http://stackoverflow.com/comment/87590521
type: Comment
comment on: http://stackoverflow.com/a/50287262
type: AnswerComment
score: 0
has text: @CatherineZhang - I add some sample data, give em a sec.

http://stackoverflow.com/q/50272502
has body: I have the following DF and f(a,b) function: A B 0 5 3 1 4 2 2 7 1 f(a,b): return (a+b,a-b) I want to a apply f(a,b) on columns A,B... and return two values into two new columns df[sum,sub] A B C D 0 5 3 8 2 1 4 2 6 2 2 7 1 8 6
tagged with: function
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50272595
possible better answer: http://stackoverflow.com/a/50272595
has answer: http://stackoverflow.com/a/50272540
has title: Applying a function on to columns in dataframe and returning to values of two new columns Python
tagged with: dataframe
tagged with: python
tagged with: apply
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/50272540
answer count: 2
has comment: http://stackoverflow.com/comment/87602334
tagged with: pandas

http://stackoverflow.com/comment/87575213
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50279292
has text: Sounds like a job for `pandas` IMHO

http://stackoverflow.com/a/50290953
type: Answer
has comment: http://stackoverflow.com/comment/127533146
answers question: http://stackoverflow.com/q/50290536
has comment: http://stackoverflow.com/comment/87616139
has comment: http://stackoverflow.com/comment/87598532
has body: open_file = open("/user/clsadmin/terrs.pkl", "rb") data = pickle.load(open_file) open_file.close()
score: 0
has comment: http://stackoverflow.com/comment/87598360

http://stackoverflow.com/a/50316630
answers question: http://stackoverflow.com/q/50316521
type: Answer
has comment: http://stackoverflow.com/comment/87649124
has comment: http://stackoverflow.com/comment/87649706
has comment: http://stackoverflow.com/comment/87649679
has body: I think you'll find that the ip address has to be a string. For instance '127.0.0.1' not an int, the port is an int though.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87649813
accepted answer of: http://stackoverflow.com/q/50316521
has comment: http://stackoverflow.com/comment/87650012

http://stackoverflow.com/a/50335563
has comment: http://stackoverflow.com/comment/87687713
answers question: http://stackoverflow.com/q/50335389
has comment: http://stackoverflow.com/comment/87687616
type: Answer
has comment: http://stackoverflow.com/comment/87687525
has body: If the file content is same as you specified, this could solve your query: lst = [] with open('path/to/file', 'r') as f: for line in f: if line.startswith('&gt;seq') and line[4] not in lst: lst.append(line[4]) print(lst) # ['A', 'B', 'C', 'D'] print(len(lst)) # 4
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87688398
upvote count: 1

http://stackoverflow.com/comment/87605261
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50292748
has text: Do you want me to add the code too?
type: Comment

http://stackoverflow.com/a/50354506
type: Answer
answers question: http://stackoverflow.com/q/50349916
has comment: http://stackoverflow.com/comment/87746943
has body: This post: Creating a simple XML file using python has examples for how to write an XML file using Python ElementTree. It's always best to use a library for creating XML rather than trying to write it as plain text. Escaping special characters is one reason; another is to ensure you get the start and end tags and namespaces right. We see a lot of people struggling to parse broken XML on StackOverflow, and it's usually because someone wrongly thought it would be easy to hand-generate it rather than using a library for the job.
downvote count: 0
has comment: http://stackoverflow.com/comment/87745606
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87745944
has comment: http://stackoverflow.com/comment/111292439

http://stackoverflow.com/a/50353242
has comment: http://stackoverflow.com/comment/87812952
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50353149
type: Answer
score: 0
has body: You can't simply return from a thread like that. The thread.start method just starts the thread and returns None. Multiple solutions can be found here: how to get the return value from a thread in python?.

http://stackoverflow.com/comment/87666394
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50319788
has text: @sun0727 I think @sascha's comment above gives more insight than I can. One derivative-free method I have used is particle swarm optimization, but I don't think of that as using a small number of evaluations of the minimized function. One thing I would say (which you may already know) is that you could think of this as choosing a, b, c and d to minimize g(a, b, c, d), where g(a, b, c, d) is equal to `sum(f(a, b, c, d, m) - A(m) if f >= A else C * (A - f) for m in M)`, where C is a large penalty term. This would be an unconstrained optimization problem, which various tools seek to solve.
type: Comment

http://stackoverflow.com/comment/91859875
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50325723
has text: We finally used a cache on memory to store the state of the state machine, which allows to have different workers.

http://stackoverflow.com/comment/87547486
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50264681
score: 0
has text: It's depend on the content of `banned_words`. If it contains all form of one banned word, we needn't transform the word to lowercase.

http://stackoverflow.com/q/50319596
has comment: http://stackoverflow.com/comment/87671830
tagged with: cuda
has body: Hi I'm trying to understand each step of cuda kernel. It will by nice to get all grid indexes that are occupy by data. My code is to add 2 vectors and is written in python numba. n = 10 x = np.arange(n).astype(np.float32) y = x + 1 setup number of threads and blocks in grid threads_per_block = 8 blocks_per_grid = 2 Kernel def kernel_manual_add(x, y, out): threads_number = cuda.blockDim.x block_number = cuda.gridDim.x thread_index = cuda.threadIdx.x block_index = cuda.blockIdx.x grid_index = thread_index + block_index * threads_number threads_range = threads_number * block_number for i in range(grid_index, x.shape[0], threads_range): out[i] = x[i] + y[i] Initialize kernel: kernel_manual_add[blocks_per_grid, threads_per_block](x, y, out) When i try to print out grid_index i get all input indexes 2*8. How to get grid indexes (10 of them) that are used to compute data?
has answer: http://stackoverflow.com/a/50320110
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87655522
linked to: http://stackoverflow.com/q/9985912
answer count: 1
linked to: http://stackoverflow.com/q/5643178
accepted answer: http://stackoverflow.com/a/50320110
has comment: http://stackoverflow.com/comment/87656271
has title: How to get current working grid index in cuda python
type: Question
has comment: http://stackoverflow.com/comment/87656488
tagged with: numba
has comment: http://stackoverflow.com/comment/87656996
tagged with: python

http://stackoverflow.com/comment/87682697
has text: Works with `hwnd = win32gui.FindWindow(None, 'Untitled - Notepad')`. Can win32gui handle anything that pywinauto does?
score: 0
comment on: http://stackoverflow.com/a/50333124
type: Comment
type: AnswerComment

class
tags question: http://stackoverflow.com/q/50335016
tags question: http://stackoverflow.com/q/50259303
type: Tag
tags question: http://stackoverflow.com/q/50312494
tags question: http://stackoverflow.com/q/50312503
tags question: http://stackoverflow.com/q/50239003
tags question: http://stackoverflow.com/q/50300510
tags question: http://stackoverflow.com/q/50332735
tags question: http://stackoverflow.com/q/50246236
tags question: http://stackoverflow.com/q/50322454
tags question: http://stackoverflow.com/q/50288130
tags question: http://stackoverflow.com/q/50246005
tags question: http://stackoverflow.com/q/50338023
tags question: http://stackoverflow.com/q/50311057
tag name: class
tags question: http://stackoverflow.com/q/50249633
tags question: http://stackoverflow.com/q/50274005
tags question: http://stackoverflow.com/q/50289322
tags question: http://stackoverflow.com/q/50384592
tags question: http://stackoverflow.com/q/50301380
tags question: http://stackoverflow.com/q/50319394
tags question: http://stackoverflow.com/q/50362969
tags question: http://stackoverflow.com/q/50277390
tags question: http://stackoverflow.com/q/50297337
tags question: http://stackoverflow.com/q/50280742
tags question: http://stackoverflow.com/q/50254976
tags question: http://stackoverflow.com/q/50381697
tags question: http://stackoverflow.com/q/50310223
tags question: http://stackoverflow.com/q/50285139
tags question: http://stackoverflow.com/q/50321768
tags question: http://stackoverflow.com/q/50308562
tags question: http://stackoverflow.com/q/50273608
tags question: http://stackoverflow.com/q/50372342
tags question: http://stackoverflow.com/q/50333012
tags question: http://stackoverflow.com/q/50268472
tags question: http://stackoverflow.com/q/50354185
tags question: http://stackoverflow.com/q/50276731
tags question: http://stackoverflow.com/q/50359968
tags question: http://stackoverflow.com/q/50345763
tags question: http://stackoverflow.com/q/50273517
tags question: http://stackoverflow.com/q/50318278

http://stackoverflow.com/comment/87583480
type: AnswerComment
comment on: http://stackoverflow.com/a/50267886
has text: I installed flask and kivy without activate the venv, thus they are globally installed. I tested the whole scenario again and it's what you said. Both answers are correct, however, I pick this one as the answer because it answers specifically the two questions asked.
score: 0
type: Comment

http://stackoverflow.com/q/50378870
has title: Params for functions in jupyter lab w/ Python
type: Question
has answer: http://stackoverflow.com/a/50379626
tagged with: jupyter
upvote count: 6
has body: I'm starting to use Jupyter lab which is nice. One thing that I have a question about is how to get the param arguments for a function that I created? If I do my_function() and then press the tab key, I get a long list of a variety of things that are present in my environment. Such as other functions, classes, or instances (variables I defined), modules, and PARAM, which is what I care about. It is nice that each of these are color coded, but is there an easy way to get to each of my params for my function without having to scroll through a million things? For example in R, I can do myfunction(&lt;tab key&gt;) to get a list of all params for that function.
tagged with: jupyter-lab
downvote count: 0
tagged with: python
type: UnansweredQuestion
answer count: 1
score: 6
favorite count: 0

http://stackoverflow.com/a/53310545
has comment: http://stackoverflow.com/comment/120937550
has comment: http://stackoverflow.com/comment/133979594
has comment: http://stackoverflow.com/comment/114205225
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/113974849
has comment: http://stackoverflow.com/comment/94950231
has comment: http://stackoverflow.com/comment/134391822
has comment: http://stackoverflow.com/comment/109228499
upvote count: 1051
has comment: http://stackoverflow.com/comment/109356012
has comment: http://stackoverflow.com/comment/131735907
has comment: http://stackoverflow.com/comment/95417126
has comment: http://stackoverflow.com/comment/121950375
has comment: http://stackoverflow.com/comment/116342678
has comment: http://stackoverflow.com/comment/113648604
has comment: http://stackoverflow.com/comment/131282272
accepted answer of: http://stackoverflow.com/q/50236117
has comment: http://stackoverflow.com/comment/136121366
type: Answer
has comment: http://stackoverflow.com/comment/96796627
answers question: http://stackoverflow.com/q/50236117
has body: Once upon a time I stumbled with this issue. If you're using macOS go to Macintosh HD > Applications > Python3.6 folder (or whatever version of python you're using) > double click on "Install Certificates.command" file. :D
score: 1049
has comment: http://stackoverflow.com/comment/108569616
has comment: http://stackoverflow.com/comment/106357540
downvote count: 2

http://stackoverflow.com/comment/87735863
comment on: http://stackoverflow.com/q/50359558
type: Comment
type: QuestionComment
has text: Doing it at this point is likely to be very fragile. What happens if there are literal quotes or commas that need to be retained in the list elements? You'll need to deal with escaping them, and then parsing that when flattening.
score: 0

http://stackoverflow.com/a/50375922
answers question: http://stackoverflow.com/q/50372901
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: outtmpl expects a string, but you have: file_name = ['/Users/yashar/Documents/GitHub/video_utils/download_video_youTube_python/' + str(row['movieId']) + '.mp4'] which creates a list with the filename as the first element. So I think instead you want: file_name = '/Users/yashar/Documents/GitHub/video_utils/download_video_youTube_python/' + str(row['movieId']) + '.mp4'
type: Answer
has comment: http://stackoverflow.com/comment/87791222
accepted answer of: http://stackoverflow.com/q/50372901

http://stackoverflow.com/q/50290723
has answer: http://stackoverflow.com/a/50290772
possible better answer: http://stackoverflow.com/a/50290772
favorite count: 0
has body: I am trying to re-write some Python code to Javascript. I can't figure out how to rewrite this part : zone_indices = [[idx for idx, val in enumerate(classified) if zone + 1 == val] for zone in range(maxz)] idx for idx, val : what does it mean to put idx at the beginning ?
type: Question
has answer: http://stackoverflow.com/a/50290826
tagged with: javascript
tagged with: python
accepted answer: http://stackoverflow.com/a/50291266
type: AnsweredQuestion
score: 0
answer count: 3
has title: Python loop : idx for idx (rewrite to javascript)
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50291266

http://stackoverflow.com/q/50293272
has answer: http://stackoverflow.com/a/50294860
type: Question
has title: How can I set a constraint to allow selecting 2 fields as maximum?
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: odoo-10
tagged with: odoo
score: 1
tagged with: odoo-8
accepted answer: http://stackoverflow.com/a/50294860
has body: I have 4 fields but only 2 can be selected as maximum. If 3 fields were selected, I would need to raise a ValidationError. How can I do this? By the way, they can be selected in random order. field1 = fields.Boolean(string='Field 1') field2 = fields.Boolean(string='Field 2') field3 = fields.Boolean(string='Field 3') field4 = fields.Boolean(string='Field 4') @api.constrains('field1', 'field2', 'field3', 'field4') def fields_constr(self): if fields ...

http://stackoverflow.com/a/50233563
answers question: http://stackoverflow.com/q/50232666
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: If I understand correctly... First we must be able to sort runs_tier, so lets make it numerical, removing the s and setting Othersto nan &gt;&gt;&gt; df broadcast_month_id player_id runs_tier 0 201803 67 100s 1 201803 67 400s 2 201802 67 50s 3 201802 67 100s 4 201801 67 50s .. ... ... ... 10 201707 67 50s 11 201706 67 50s 12 201705 67 50s 13 201704 67 50s 14 201704 67 Others [15 rows x 3 columns] &gt;&gt;&gt; df['numeric_tier'] = pd.to_numeric(df['runs_tier'].apply(lambda x: x[:-1]), errors='coerce') &gt;&gt;&gt; df broadcast_month_id player_id runs_tier numeric_tiers 0 201803 67 100s 100.000 1 201803 67 400s 400.000 2 201802 67 50s 50.000 3 201802 67 100s 100.000 4 201801 67 50s 50.000 .. ... ... ... ... 10 201707 67 50s 50.000 11 201706 67 50s 50.000 12 201705 67 50s 50.000 13 201704 67 50s 50.000 14 201704 67 Others nan [15 rows x 4 columns] Now we can sort the dataframe, so that the first appearance of every player is the lastest topmost tier df = df.sort_values(['player_id', 'broadcast_month_id', 'numeric_tiers'], ascending=[True, False, True]) and select only that first appearance: &gt;&gt;&gt; df = df[~df.duplicated('player_id')] &gt;&gt;&gt; df broadcast_month_id player_id runs_tier numeric_tiers 0 201803 67 100s 100.000 and then we can join it &gt;&gt;&gt; run_tier['lastest'] = df.set_index('player_id')['runs_tier'] &gt;&gt;&gt; run_tier runs_tier 100s 400s 50s Others lastest player_id 67 2 1 11 1 100s

http://stackoverflow.com/comment/87657928
score: 1
has text: That will depend on what you are trying to achieve with that block of logic, either define defaults for those variables or change the logic such that you don't use them before assigning a value.
type: Comment
comment on: http://stackoverflow.com/a/50320942
type: AnswerComment

visual-studio-code
tags question: http://stackoverflow.com/q/50381820
tags question: http://stackoverflow.com/q/50294025
tags question: http://stackoverflow.com/q/50282464
tags question: http://stackoverflow.com/q/50300785
tags question: http://stackoverflow.com/q/50367947
tag name: visual-studio-code
tags question: http://stackoverflow.com/q/50283442
tags question: http://stackoverflow.com/q/50382256
type: Tag
tags question: http://stackoverflow.com/q/50298745
tags question: http://stackoverflow.com/q/50278558
tags question: http://stackoverflow.com/q/50340064
tags question: http://stackoverflow.com/q/50311901
tags question: http://stackoverflow.com/q/50305232

http://stackoverflow.com/comment/87716811
type: QuestionComment
score: 0
has text: The question is a little ambiguous. Do you just want to target the enemies automatically or do you want some kind of homing missile?
comment on: http://stackoverflow.com/q/50348125
type: Comment

http://stackoverflow.com/q/50236117
has body: I'm practicing the code from 'Web Scraping with Python', and I keep having this certificate problem: from urllib.request import urlopen from bs4 import BeautifulSoup import re pages = set() def getLinks(pageUrl): global pages html = urlopen("http://en.wikipedia.org"+pageUrl) bsObj = BeautifulSoup(html) for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")): if 'href' in link.attrs: if link.attrs['href'] not in pages: #We have encountered a new page newPage = link.attrs['href'] print(newPage) pages.add(newPage) getLinks(newPage) getLinks("") The error is: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1319, in do_open raise URLError(err) urllib.error.URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1049)&gt; Btw,I was also practicing scrapy, but kept getting the problem: command not found: scrapy (I tried all sorts of solutions online but none works... really frustrating)
has answer: http://stackoverflow.com/a/57968930
linked to: http://stackoverflow.com/q/42098126
tagged with: web-scraping
linked to: http://stackoverflow.com/q/27835619
has title: Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org
tagged with: scrapy
linked to: http://stackoverflow.com/q/51774807
favorite count: 0
has answer: http://stackoverflow.com/a/70695810
has answer: http://stackoverflow.com/a/50254746
has answer: http://stackoverflow.com/a/62888599
has answer: http://stackoverflow.com/a/57941428
linked to: http://stackoverflow.com/q/34503206
tagged with: beautifulsoup
type: Question
duplicate of: http://stackoverflow.com/q/42098126
has answer: http://stackoverflow.com/a/77637314
has answer: http://stackoverflow.com/a/75614375
has answer: http://stackoverflow.com/a/57902885
has comment: http://stackoverflow.com/comment/87506763
has answer: http://stackoverflow.com/a/76435228
duplicate of: http://stackoverflow.com/q/27835619
has answer: http://stackoverflow.com/a/73226430
accepted answer: http://stackoverflow.com/a/53310545
linked to: http://stackoverflow.com/q/44649449
has answer: http://stackoverflow.com/a/60671292
possible better answer: http://stackoverflow.com/a/60671292
tagged with: python
upvote count: 317
has answer: http://stackoverflow.com/a/77234222
has answer: http://stackoverflow.com/a/57228672
score: 315
tagged with: ssl-certificate
has answer: http://stackoverflow.com/a/67513277
answer count: 27
has answer: http://stackoverflow.com/a/51778655
linked to: http://stackoverflow.com/q/52805115
has comment: http://stackoverflow.com/comment/87489550
linked to: http://stackoverflow.com/q/25863101
has answer: http://stackoverflow.com/a/68579512
has answer: http://stackoverflow.com/a/60803098
has answer: http://stackoverflow.com/a/60105385
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87505183
has comment: http://stackoverflow.com/comment/87505246
has comment: http://stackoverflow.com/comment/87489728
downvote count: 2
has answer: http://stackoverflow.com/a/64152045
has answer: http://stackoverflow.com/a/57904021
has answer: http://stackoverflow.com/a/66094151
has comment: http://stackoverflow.com/comment/122846071
has answer: http://stackoverflow.com/a/59083112
has answer: http://stackoverflow.com/a/76693973
has answer: http://stackoverflow.com/a/70635190
has answer: http://stackoverflow.com/a/53310545
has comment: http://stackoverflow.com/comment/87505261
has answer: http://stackoverflow.com/a/65037908
has answer: http://stackoverflow.com/a/53317544

http://stackoverflow.com/comment/87681245
comment on: http://stackoverflow.com/a/50331846
type: Comment
has text: Interesting. When I save the file with BOM, the system (macOS) completely ignores the shebang. It runs it as a `bash` script instead of the Python specified.
type: AnswerComment
score: 0

http://stackoverflow.com/q/50261146
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87540784
downvote count: 0
favorite count: 0
type: Question
tagged with: debugging
has body: I'm running a python script in a screen session. That is: I open the screen session, start the script and intend to let it run in the background, shutting down the terminal. When I re-open the screen session, it tells me a 'Fatal IO error: client killed' occurred. I don't think it's because of my specific code, since it runs fine as long as I stay active in the window (I don't detach the screen session). What could be the cause of this and/or how could I troubleshoot?
has comment: http://stackoverflow.com/comment/87540488
tagged with: gnu-screen
tagged with: python
has title: Fatal IO error when using Python in screen session
has comment: http://stackoverflow.com/comment/87540930
answer count: 0
score: 2
upvote count: 2

http://stackoverflow.com/comment/87582182
has text: Please add the result for the data.
type: Comment
comment on: http://stackoverflow.com/q/50282616
score: 0
type: QuestionComment

http://stackoverflow.com/q/50382499
upvote count: 3
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/50382569
favorite count: 0
type: Question
has body: Having a hard time wrapping my head around this (overtired): I have a dict like so: {'FOO': [7, 11], 'BAR': [42, 0]} I need to convert it to be: {'name': 'FOO', 'count1': 7, 'count2': 11}, {'name': 'BAR', 'count1': 42, 'count2': 0} Any help is appreciated.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87780782
tagged with: python
has comment: http://stackoverflow.com/comment/87780845
tagged with: dictionary
has title: Python: convert dict of key: list to dict: key/value pairs
score: 0
tagged with: list

http://stackoverflow.com/a/50341984
has body: Use the lookup function: i = data1.idxmax(axis=1) data2.lookup(i.index, i.values) This will give you an array with the values. To get the result as a Series, simply create it: pd.Series(data2.lookup(i.index, i.values))
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50341927
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50341927
score: 2

http://stackoverflow.com/comment/87523785
has text: I have updated the error and also posted the full stack trace. There was a type in the error which i corrected
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50252992

http://stackoverflow.com/a/50276961
score: 0
type: Answer
has body: Using the information you gave, I did the following with my version of your code(Just the parts that you need to have fixed) Max_data = '2018-05-04T13:08:20.000+0000' #How ever max data is assigned, this is not needed print Max_data[:10] # This will only print the 2018-05-04 while removing everything else The output: 2018-05-04 Using Max_data[:10] is what it seems you are in need of(At least one method. It isn't the same as the original code so you may not like this fix, though it is shorter then the original code. Remove the datetime.strptime(max_data,'%Y-%m-%d') and replace it withMax_data[:10] I know you don't need it exactly the way I placed it but its just to show how to get rid of the information you don't need
answers question: http://stackoverflow.com/q/50276835

http://stackoverflow.com/comment/87872326
type: AnswerComment
comment on: http://stackoverflow.com/a/50362324
type: Comment
has text: oh sorry it works, I forgot this thing `)` Thank you so much @Rakesh
score: 0

http://stackoverflow.com/comment/87512264
comment on: http://stackoverflow.com/a/50247064
score: 0
has text: @CyleySimon Careful, you should write `el for el in p[row]`, not `el for el in p`. Let me know if this solves your problem.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87584291
has text: Seems to me this error shows up in `python2` with some modules . Try using `python3` instead
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50283979

http://stackoverflow.com/comment/87653102
type: Comment
type: AnswerComment
score: 0
has text: @eXistanCe I added in my timing results.
comment on: http://stackoverflow.com/a/50318458

http://stackoverflow.com/comment/87700781
score: 0
comment on: http://stackoverflow.com/q/50342166
type: QuestionComment
has text: OK check the last part of my answer if you want a tldr. Gives you an easy way to do it without having to worry about multiple for loops and stuff. Also as was said in another answer, you are increasing both your column and row indices, so you're acessing elements in a diagonal. Also, your while condition is `while not 13 in worldmap` which is always false, because first off `worldmap` doesn't change, and second off, it contains a list of lists of 13s, not the number 13 itself.
type: Comment

http://stackoverflow.com/comment/87755109
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50355483
has text: @VivekKumar can one run with a single job, check the memory usage and use that as an estimate per thread? Then one could estimate `n_jobs` as `available_memory/memory_per_thread`

http://stackoverflow.com/a/50254514
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87526386
answers question: http://stackoverflow.com/q/50254450
has body: Here is one simple way: res = [list(range(i, i+4)) for i in range(1, 14, 4)] print(res) [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] You can also wrap in a generic function: def square(n): return [list(range(i, i+n)) for i in range(1, n**2, n)] res = square(4) Explanation The syntax for range construction is range(start, end, [step]). step is optional; if it is not specified, it is assumed to be 1. The first part range(i, i+n) creates a range object from i to i+n-1, inclusive. The second part range(1, n**2, n) iterates in steps of n to n*n, not including the final term. Since end is non-inclusive, squaring n provides the desired cap.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50254450

http://stackoverflow.com/comment/87699794
score: 0
has text: i am getting these error `File "chatbot.py", line 8, in <module> import sqlite3 File "/home/pythondemo/.local/lib/python3.6/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/home/pythondemo/.local/lib/python3.6/sqlite3/dbapi2.py", line 50, in <module> version_info = tuple([int(x) for x in version.split(".")]) NameError: name 'version' is not defined` Thats the reason i am installing.
comment on: http://stackoverflow.com/q/50324400
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50384901
answers question: http://stackoverflow.com/q/50337586
type: Answer
score: 0
has body: With regard to our comment discussion and in really simple terms: Calling program: from subprocess import call print("executing external code") return_code = call('python3 a1.py', shell=True) if return_code == 5: print("Code executed correctly result: ",return_code) elif return_code == 42: print("Code excuted correctly result: ", return_code) else: print("Code failed") return_code = call('python3 a1.py "parameter"', shell=True) if return_code == 5: print("Code executed correctly result: ",return_code) elif return_code == 42: print("Code excuted correctly result: ", return_code) else: print("Code failed") Called program (named a1.py): import sys x=sys.argv print("doing some work") if len(x) &gt; 1: sys.exit(42) else: sys.exit(5) Result: executing external code doing some work Code executed correctly result: 5 doing some work Code excuted correctly result: 42

http://stackoverflow.com/a/50341228
score: 0
has comment: http://stackoverflow.com/comment/87698618
answers question: http://stackoverflow.com/q/50341158
has body: please pay attention to the return sentence def capitalize_all(t): res = [] for s in t: res.append(s.capitalize()) #you should return res after for loop ends return res
type: Answer

http://stackoverflow.com/q/50301920
type: Question
answer count: 2
has title: selenium.common.exceptions.WebDriverException: Message: connection refused while trying to open Firefox browser through GeckoDriver in Raspberry-pi3
accepted answer: http://stackoverflow.com/a/50303964
tagged with: firefox
tagged with: geckodriver
has answer: http://stackoverflow.com/a/50303964
possible better answer: http://stackoverflow.com/a/50301964
tagged with: raspberry-pi3
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50301964
type: AnsweredQuestion
downvote count: 0
tagged with: selenium
score: 1
has body: Hi I have a raspberry pi 3 and decided to try get selenium running with python 3. I installed it using "pip3 install selenium" and there were no errors. After I made a small test script with this code: from selenium import webdriver from selenium.webdriver.common.keys import Keys # create a new Firefox session driver = webdriver.Firefox() driver.implicitly_wait(30) driver.maximize_window() # Navigate to the application home page driver.get("http://www.google.com") # get the search textbox search_field = driver.find_element_by_id("lst-ib") search_field.clear() # enter search keyword and submit search_field.send_keys("Selenium WebDriver Interview questions") search_field.submit() # get the list of elements which are displayed after the search # currently on result page using find_elements_by_class_name method lists= driver.find_elements_by_class_name("_Rm") # get the number of elements found print ("Found " + str(len(lists)) + " searches:") # iterate through each element and print the text that is # name of the search i=0 for listitem in lists: print (listitem.get_attribute("innerHTML")) i=i+1 if(i&gt;10): break # close the browser window driver.quit() but it gives me an error: Traceback (most recent call last): File "/home/pi/SeleniumTest.py", line 5, in &lt;module&gt; driver = webdriver.Firefox() File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 170, in __init__ keep_alive=True) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/pi/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(response) File "/home/pi/.local/lib/python3.5/site-packages/seleniu…
favorite count: 0

http://stackoverflow.com/comment/87682818
type: AnswerComment
has text: I figured that would not necessarily be the best solution, since I wondered that myself and didn't find an answer online for it (figures...). Now, if anybody has the same brain failure as me, that maybe will save them some searching for themselves.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50333264

http://stackoverflow.com/comment/87557098
type: QuestionComment
comment on: http://stackoverflow.com/q/50269598
has text: Where are you defining `click_entry`? Is it a global in the same module as `fidgetSpinner`? That's the only place it can be if the code you've shown is going to work. Though your class is very weird, since it does all its work statically in the class namespace, not in `__init__` or some other method that gets called for each separate instance.
score: 0
type: Comment

http://stackoverflow.com/a/50321554
has comment: http://stackoverflow.com/comment/87658993
score: 2
answers question: http://stackoverflow.com/q/50321512
has body: It seems like you want to use groupby with head: In [8]: df.groupby([df.user_id, df.session_id]).head(3) Out[8]: user_id session_id item_id rating length time 0 123 36 28 3.5 6243.0 2015-03-07 22:44:40 1 123 36 29 2.5 4884.0 2015-03-07 22:44:14 2 123 36 30 3.5 6846.0 2015-03-07 22:44:28 10 223 63 30 8.0 5412.0 2015-03-22 01:42:10 12 223 63 32 8.5 4872.0 2015-03-22 01:42:03 14 225 63 35 7.5 6491.0 2015-03-22 01:42:19 18 225 63 41 5.0 15026.0 2015-03-22 01:42:37 19 225 63 45 6.5 8532.0 2015-03-07 22:42:25
type: Answer
has comment: http://stackoverflow.com/comment/87658991
has comment: http://stackoverflow.com/comment/87659043
accepted answer of: http://stackoverflow.com/q/50321512
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87659045
downvote count: 0
has comment: http://stackoverflow.com/comment/87659056

http://stackoverflow.com/comment/87634563
type: AnswerComment
comment on: http://stackoverflow.com/a/50307026
has text: but actually I am also using a monitor mode interface and get Ethernet-frames :/
type: Comment
score: 0

http://stackoverflow.com/comment/87536365
type: QuestionComment
comment on: http://stackoverflow.com/q/50259204
type: Comment
has text: @nawarkhede yes how can i get all the three values in the tuple to different variables.
score: 0

http://stackoverflow.com/q/50341847
tagged with: cookies
tagged with: python
type: Question
has title: Getting a New ASP.NET Session ID after Expiration in Scrapy
upvote count: 2
accepted answer: http://stackoverflow.com/a/50362715
score: 2
answer count: 1
has answer: http://stackoverflow.com/a/50362715
downvote count: 0
tagged with: scrapy
tagged with: asp.net
favorite count: 0
type: AnsweredQuestion
has body: I have written a scraper in Scrapy 1.5 that successfully navigates to a webpage (running ASP.NET running on IIS version 8.5), submits a form, and then gets to scraping. After a few hours, all of the pages start returning blank data. I believe that my ASP.NET session id is expiring when this happens. I can never make it through the entire table (several thousand pages) while crawling at a respectful rate, but the table doesn't change from session to session. My approach was to scrape until the pages were returned blank, then go back to the form submission page and resubmit the form. I am keeping track of the page number so that I can pick up where I left off. The problem is that when I resubmit the form, the pages are still returned blank. If I stop the scraper, and set the count variable manually to the last page scraped, it works fine when I restart the scraper. Using fiddler I can see that the only thing that is different is that I have a new ASP.NET session id. So my question is, how can I clear out my ASP.NET session id so that I am given a new one and I can continue scraping? Here is a redacted version of the spider: class assessorSpider(scrapy.Spider): name = 'redacted' allowed_domains = ['redacted.redacted'] start_urls = ['http://redacted.redacted/search.aspx'] base_url = start_urls[0] rows_selector = '#T1 &gt; tbody:nth-child(3) &gt; tr' numberOfPages = -1 count = 1 def parse(self, response): #ASP.NET Session Id gets stored in the headers after initial search frmdata = {'id':'frmSearch', 'SearchField':'%','cmdGo':'Go'} yield scrapy.FormRequest(url = self.base_url, formdata = frmdata, callback = self.parse_index) self.log('Search submitted') def parse_index(self, response): self.log('proceeding to next page') rows = response.css(self.rows_selector) if (len(rows) &lt; 50 and self.count != self.numberOfPages): self.log('Deficient rows. Resubmitting') yield scrapy.Request(callback=self.parse, url = self.base_url, headers='') self.log('Ready to yield value') for …

http://stackoverflow.com/comment/87734648
type: Comment
type: QuestionComment
score: 0
has text: Thanks seuling, I was able to make it work thanks to your advice and Daniel's :)
comment on: http://stackoverflow.com/q/50326090

http://stackoverflow.com/q/50273640
has title: Django Twilio Texting - django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
has body: I’m new to Python and Django, but have decided to make my own wedding website based on https://www.placecard.me/blog/django-wedding-website/. The only major difference I want to make is to change the the email communication to SMS. I came across this https://github.com/CleverProgrammer/CP-Twilio-Python-Text-App texting app. I incorporated the texting app into a Django project to test and attempt to send a text message to all guests in the database. I’m running Python 3.6.5 and Django 2.0.5 I have the following directory structure for my Django project. I have the following code: settings.py import os enter code here`# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'twilio', 'sms_send', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'WebsiteSMS.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_pr…
has answer: http://stackoverflow.com/a/50273963
accepted answer: http://stackoverflow.com/a/50273963
answer count: 1
tagged with: django
type: AnsweredQuestion
score: 0
tagged with: django-2.0
tagged with: python
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87724066
has text: Ty, post as answer and ill mark it correct :)
score: 0
comment on: http://stackoverflow.com/q/50351830
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50381696
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/50381895
has title: Selecting info by breaking url using pandas
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50381924
has answer: http://stackoverflow.com/a/50381895
has body: I have a pandas df with a following column: url www.abc.com/ www.abc.com/ttt/page1 www.abc.com/vvv/page4/info www.abc.com/zzz/page4 I would like to transform it in 4 columns like: main prod page more_info www.abc.com NaN NaN NaN www.abc.com ttt page1 NaN www.abc.com vvv page4 info www.abc.com zzz page4 I tried pandas.Series.str.split and urlparse.urlsplit but did not succeed.
tagged with: python
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50381924
tagged with: pandas
score: 1

http://stackoverflow.com/a/50377764
has comment: http://stackoverflow.com/comment/115423927
answers question: http://stackoverflow.com/q/50376066
score: 10
upvote count: 10
has body: Fairly straightforward with FuncAnimation in matplotlib: import numpy as np import matplotlib.pyplot as plt; plt.close('all') import networkx as nx from matplotlib.animation import FuncAnimation def animate_nodes(G, node_colors, pos=None, *args, **kwargs): # define graph layout if None given if pos is None: pos = nx.spring_layout(G) # draw graph nodes = nx.draw_networkx_nodes(G, pos, *args, **kwargs) edges = nx.draw_networkx_edges(G, pos, *args, **kwargs) plt.axis('off') def update(ii): # nodes are just markers returned by plt.scatter; # node color can hence be changed in the same way like marker colors nodes.set_array(node_colors[ii]) return nodes, fig = plt.gcf() animation = FuncAnimation(fig, update, interval=50, frames=len(node_colors), blit=True) return animation total_nodes = 10 graph = nx.complete_graph(total_nodes) time_steps = 20 node_colors = np.random.randint(0, 100, size=(time_steps, total_nodes)) animation = animate_nodes(graph, node_colors) animation.save('test.gif', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=0.5)
type: Answer
has comment: http://stackoverflow.com/comment/115381284
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50376066
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/115425123

http://stackoverflow.com/a/50259343
type: Answer
has comment: http://stackoverflow.com/comment/87536632
answers question: http://stackoverflow.com/q/50259303
has body: You need this instead of main if you're executing the script standalone if __name__ == 'main': newPlayer = Player(10000,3000) print(newPlayer)
score: 0

http://stackoverflow.com/comment/87715226
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50348064
type: QuestionComment
has text: Have you compile `cv` with `ffmpeg`?

http://stackoverflow.com/a/50277993
type: Answer
has comment: http://stackoverflow.com/comment/87574621
score: 0
has body: Just create a transaction during the registration. I'm assuming the bank is also a (currency dependant?) user, say with id=1. Then something like, from django.db import transaction #signup form def signup(request): if request.method =='POST': form = SignUpForm(request.POST) if form.is_valid(): #atomic makes sure that the changes are only commited if the entire block of code is succesfully completed with transaction.atomic(): new_user = form.save() transaction_signup = Transaction( user_debit = new_user, user_credit = get_user_model().objects.get(id=1), exchange_amount = 1, currency_id = Curreny.objects.get(id=3) ) transaction_signup.save() #We want to log in the user after his sign up username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/') else: form = SignUpForm() return render(request, 'sign-up.html', {'SignUpForm': form}) would work. You don't however HAVE to do this in your view. You can for example use post save signals.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87580520
accepted answer of: http://stackoverflow.com/q/50275890
answers question: http://stackoverflow.com/q/50275890

mixed-models
tag name: mixed-models
type: Tag
tags question: http://stackoverflow.com/q/50300224

http://stackoverflow.com/comment/87615069
comment on: http://stackoverflow.com/q/50299143
has text: Note that `import foo.bar as bar` only works if `foo.bar` is itself a module, while `from foo import bar` works for *any* module-level name in `foo`.
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/a/50301964
has comment: http://stackoverflow.com/comment/87621574
score: 0
has comment: http://stackoverflow.com/comment/87621109
has comment: http://stackoverflow.com/comment/87621579
has body: you need to install the geckodriver, it's a requirement, I don't know if is available by apt, but if not you can download the armv7hf version from its official release page on GitHub https://github.com/mozilla/geckodriver/releases If you need to install it manually, extract the executable geckodriver to a directory in path, usually /usr/local/bin or '$HOME/bin` EDIT: Another possible cause is running selenium over SSH, in this scenario your RPi won't have a display to attach the firefox window to and it will crash, to solve this you need to run Firefox in headless mode like this: # create a new Firefox session opt = webdriver.FirefoxOptions() opt.set_headless() driver = webdriver.Firefox(options=opt) # here instead of maximize you have to set a custom size driver.set_window_size(1920, 1080)
has comment: http://stackoverflow.com/comment/87621087
type: Answer
answers question: http://stackoverflow.com/q/50301920

http://stackoverflow.com/comment/87558569
has text: I have the static directory, because I pushed it from local repo.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50270560

http://stackoverflow.com/comment/87655056
type: QuestionComment
comment on: http://stackoverflow.com/q/50319337
score: 0
has text: Working! Thank you very much. I spend more than three hours on this... It was a stupid mistake, but it may happen to others and finding the (rest of the) steps to do this wasn't easy. Do you want to write an answer or do you prefer I do so?
type: Comment

http://stackoverflow.com/a/50342263
answers question: http://stackoverflow.com/q/50342165
type: Answer
has body: looks like you mixed Bir_dict and NoBir_dict. Can you try the code below? def caught_speeding(speed, is_birthday): Bir_dict = {0:speed&lt;=65,1:66&lt;=speed&lt;=85,2:speed&gt;=86} NoBir_dict = {0:speed&lt;=60,1:61&lt;=speed&lt;=80,2:speed&gt;=81} def getKey(dict,value): return [key for key in dict.keys() if (dict[key] == value)] if is_birthday: out1=getKey(Bir_dict,True) return out1[0] else: out2=getKey(NoBir_dict,True) return out2[0] Despite it works, I can suggest an alternative way with dictionaries: Ticket definitions do not interfere with each other, in other words, there can only be one True statement within a dictionary. So, you can modify your code as: def caught_speeding(speed, is_birthday): Bir_dict = {0:speed&lt;=65,1:66&lt;=speed&lt;=85,2:speed&gt;=86} NoBir_dict = {0:speed&lt;=60,1:61&lt;=speed&lt;=80,2:speed&gt;=81} def getKey(dict): return [key for key in dict.keys() if (dict[key] == True)] if is_birthday: out1=getKey(Bir_dict) return out1[0] else: out2=getKey(NoBir_dict) return out2[0]
has comment: http://stackoverflow.com/comment/87700440
has comment: http://stackoverflow.com/comment/87700496
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/50342165
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/50321978
has comment: http://stackoverflow.com/comment/87659732
duplicate of: http://stackoverflow.com/q/50323754
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87659748
has comment: http://stackoverflow.com/comment/87659719
score: 1
has comment: http://stackoverflow.com/comment/87659737
has comment: http://stackoverflow.com/comment/87659753
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87659795
has body: I have isolated the following part of a bigger code: import numpy as np population= np.random.normal(0,1,5) individuals=population print(population) for i in range(len(individuals)): individuals[i]=0 print(population) response: [-0.1791731 -0.0756427 0.44463943 -0.51173395 0.9121922 ] [0. 0. 0. 0. 0.] I can't understand why the results are not identical.
has comment: http://stackoverflow.com/comment/87659816
has comment: http://stackoverflow.com/comment/87659987
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/50322014
has title: Code actualising automatically variables when not desired
has comment: http://stackoverflow.com/comment/87659984
has comment: http://stackoverflow.com/comment/87659782
linked to: http://stackoverflow.com/q/50323754
has answer: http://stackoverflow.com/a/50322014
linked to: http://stackoverflow.com/q/2612802
downvote count: 0
has comment: http://stackoverflow.com/comment/87659771
upvote count: 1
has comment: http://stackoverflow.com/comment/87659818

http://stackoverflow.com/q/50361770
has answer: http://stackoverflow.com/a/66520740
score: 4
tagged with: hidapi
has title: Interpreting HIDAPI python output
linked to: http://stackoverflow.com/q/35020368
linked to: http://stackoverflow.com/q/41070706
has body: I would like to read a string from a USB HID scanner with Python on OS X. The example below is my starting point and I have been able to tailor the code to my scanner: I have been able to execute the command: h.open() successfully and printout the manufacturer and product strings. The scan codes were verified with EVDEV with the scanner. The challenge is interpreting the data returned and mapping it back to an ascii string. This post provides python HIDAPI example code: from __future__ import print_function import hid import time print("Opening the device") h = hid.device() h.open(1118, 2048) # A Microsoft wireless combo keyboard &amp; mouse print("Manufacturer: %s" % h.get_manufacturer_string()) print("Product: %s" % h.get_product_string()) print("Serial No: %s" % h.get_serial_number_string()) try: while True: d = h.read(64) if d: print('read: "{}"'.format(d)) finally: print("Closing the device") h.close() $ sudo python try.pyoutput: Opening the device Manufacturer: Microsoft Product: Microsoft® Nano Transceiver v2.0 Serial No: None read: "[0, 0, 0, 0, 0, 0, 0, 0]" read: "[0, 0, 0, 0, 0, 0, 0, 0]" read: "[0, 0, 0, 0, 0, 0, 0, 0]" --8&lt;-- snip lots of repeated lines --8&lt;-- read: "[0, 0, 0, 0, 0, 0, 0, 0]" read: "[0, 0, 0, 0, 0, 0, 0, 0]" read: "[0, 0, 21, 0, 0, 0, 0, 0]" read: "[0, 0, 21, 0, 0, 0, 0, 0]" read: "[0, 0, 21, 0, 0, 0, 0, 0]" read: "[0, 0, 21, 0, 0, 0, 0, 0]" read: "[0, 0, 0, 0, 0, 0, 0, 0]" read: "[0, 0, 4, 0, 0, 0, 0, 0]" read: "[0, 0, 4, 22, 0, 0, 0, 0]" read: "[0, 0, 4, 22, 0, 0, 0, 0]" read: "[0, 0, 4, 22, 0, 0, 0, 0]" read: "[0, 0, 4, 22, 0, 0, 0, 0]" read: "[0, 0, 4, 22, 0, 0, 0, 0]" read: "[0, 0, 4, 0, 0, 0, 0, 0]" read: "[0, 0, 4, 0, 0, 0, 0, 0]" read: "[0, 0, 4, 9, 0, 0, 0, 0]" read: "[0, 0, 4, 9, 0, 0, 0, 0]" read: "[0, 0, 4, 9, 0, 0, 0, 0]" read: "[0, 0, 4, 9, 0, 0, 0, 0]" read: "[0, 0, 4, 9, 7, 0, 0, 0]" read: "[0, 0, 4, 9, 7, 0, 0, 0]" read: "[0, 0, 7, 0, 0, 0, 0, 0]" ^Closing the device Traceback (most recent call last): File "try.py"…
favorite count: 0
type: Question
upvote count: 4
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52891898
tagged with: python

http://stackoverflow.com/q/50248547
answer count: 1
has comment: http://stackoverflow.com/comment/87514859
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50252474
tagged with: python
tagged with: http://stackoverflow.com/tag/r
has body: I hope to know a general approach when do data engineering. I have a data set with some variables with too many categories, and including these variables into a predictive model definitely would increase the complexity of the model, thus leads to overfit. While normally I would group those categories into fewer groups by drawing plots to see if the response variable is significantly different among these groups. Is there a more efficient way dealing with this issue, like automatically carry out some statistical test? ADDED: In a nutshell, I hope to group or bin values in a variable so that the response variable in each group has very different distribution.
has comment: http://stackoverflow.com/comment/87514448
score: 0
has comment: http://stackoverflow.com/comment/87515155
has title: Data with too many categories

http://stackoverflow.com/comment/87707575
comment on: http://stackoverflow.com/q/50345780
has text: So sorry, duplicate answer was changed to [this](https://stackoverflow.com/questions/45114945/how-do-i-create-dynamic-variable-names-inside-a-loop-in-pandas), second solution with `globals`. But still better is dictionary approach
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87771117
comment on: http://stackoverflow.com/q/50377335
has text: and you might just be missing a backslash (or forward slash) in your input search pattern
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87515059
score: 0
has text: I have the code to retrieve the data from S3 but I don't know how to connect it to be displayed in the admin view
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50248626

http://stackoverflow.com/comment/87549385
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50265694
has text: Thanks for correcting me Ben. I must have mistype it!

http://stackoverflow.com/q/50336547
has title: Deleting data in pandas given a string condition
has comment: http://stackoverflow.com/comment/87689244
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50336568
has body: I am having trouble understanding the mechanics here given the following. I have a dataframe reading from a .csv : a1 b1 c1 1 aa bb cc 2 ab ba ca df.drop(df['a1'].str.contains('aa',case = False)) I want to drop all the rows in column a1 that contain 'aa' I believe to have attempted everything on here but still get the : ValueError: labels [False False False ... False False False] not contained in axis Yes, I have also tried skipinitialspace=True axis=1 Any help would be appreciated, thank you.
linked to: http://stackoverflow.com/q/28679930
tagged with: dataframe
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/50336568
upvote count: 2

http://stackoverflow.com/comment/87766128
score: 2
has text: Its unclear whether you are executing a C++ program (perhaps `subprocess.call` or `os.system`) or whether you are calling a C extension library in python. These have very different solutions.
comment on: http://stackoverflow.com/q/50374806
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87490531
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50233819
has text: Possible duplicate of [zip-like function that pads to longest length?](https://stackoverflow.com/questions/1277278/zip-like-function-that-pads-to-longest-length)
score: 0

http://stackoverflow.com/comment/87522994
type: Comment
has text: https://docs.opencv.org/3.4.1/dc/da3/tutorial_copyMakeBorder.html
type: QuestionComment
comment on: http://stackoverflow.com/q/50252468
score: 1

http://stackoverflow.com/q/50365163
score: 1
accepted answer: http://stackoverflow.com/a/50365972
tagged with: recursion
type: AnsweredQuestion
has body: When I execute the following code on Python console using the below statement, for L in permute([12, 32, 3]): print(L) for the code below, def permute(L): if len(L) &lt;= 1: yield L else: for i in range(0, len(L)): L[0], L[i] = L[i], L[0] for L1 in permute(L[1:]): yield [L[0]] + L1 each result appears just once. But, if I remove else and remove the associated indentation of the code below it, I receive each result twice. Why does it happen?
has answer: http://stackoverflow.com/a/50365972
tagged with: if-statement
has title: Why removing else causes recursive function to repeat the result?
has answer: http://stackoverflow.com/a/50365376
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/50365376
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/87617662
type: QuestionComment
comment on: http://stackoverflow.com/q/50300208
score: 1
type: Comment
has text: All those examples can be expressed as `*` multiplication with broadcasting. They don't involve any `dot` like summation of products, just some form of `outer` product. e.g. `a[:,None]*b`, `a*b[:,None]`, `a[...,None]*b`.

http://stackoverflow.com/q/50302553
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/50302595
has title: Data structure with O(1) random removal and adds for shuffling generator order
tagged with: python
tagged with: data-structures
has answer: http://stackoverflow.com/a/50302601
possible better answer: http://stackoverflow.com/a/50302601
type: AnsweredQuestion
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/21017188
has body: I need a data structure that lets you add elements and remove them randomly in O(1) time. The reason for this that I need to shuffle data from a generator, but I can't load everything into memory at the same time due to size. This is an example of usage, which automatically shuffles the order of the results generated by a generator expression without loading everything into memory: def generator_shuffler(generator) a = magical_data_structure_described_above for i in generator: a.add(i) if len(a) &gt; 10: yield a.poprandom() Initially I tried a python set(), however from here: Set.pop() isn&#39;t random?, it seems that set() doesn't actually remove the items in an arbitrary order. How would I implement the data structure with the above usage?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50302595

http://stackoverflow.com/comment/87581317
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50263301
has text: @ Arthur Dent I have init in every folder including /
score: 0

http://stackoverflow.com/comment/87780244
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50382111
score: 2
has text: @C8H10N4O2 depends on if the file is large or not, you may not want the entire file in memory.

http://stackoverflow.com/a/65050907
has body: Providing solution in TF 2.3, where eager execution enabled by default. To fix above issue, you should convert d from tensor to numpy. Complete working code as shown below %tensorflow_version 2.x print(tf.__version__) import tensorflow as tf import numpy as np data=np.random.randint(0,10,[2,4,300]) tensor_va=tf.constant(data) d=tensor_va.numpy().shape [1] W_omega = tf.compat.v1.get_variable(name='a_omega', shape=[d,d], dtype=tf.float32, initializer=tf.random_uniform_initializer(-0.01, 0.01)) print(W_omega) Output: 2.3.0 &lt;tf.Variable 'a_omega:0' shape=(4, 4) dtype=float32, numpy= array([[ 0.00958031, -0.00010247, 0.00161975, -0.00098458], [ 0.00287828, -0.00026206, -0.00369554, 0.00339144], [-0.00205746, -0.00392851, 0.00062867, 0.00173409], [-0.00409856, 0.0012137 , -0.00762768, -0.00545195]], dtype=float32)&gt;
answers question: http://stackoverflow.com/q/50358345
type: Answer
score: 0

http://stackoverflow.com/comment/87692407
score: 0
comment on: http://stackoverflow.com/q/50337901
type: QuestionComment
has text: I'm not aware of this. How do you do it?
type: Comment

http://stackoverflow.com/a/50394788
type: Answer
has comment: http://stackoverflow.com/comment/97694292
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/97695199
has comment: http://stackoverflow.com/comment/97694279
has comment: http://stackoverflow.com/comment/97695278
has comment: http://stackoverflow.com/comment/97694366
has comment: http://stackoverflow.com/comment/97695519
answers question: http://stackoverflow.com/q/50337569
has comment: http://stackoverflow.com/comment/97695393
has comment: http://stackoverflow.com/comment/97690319
downvote count: 0
has comment: http://stackoverflow.com/comment/97695563
has body: Pickle is used by the multiprocessing module to communicate between the different parts, and in the programming guidelines it explains that you must ensure that all your data that you pass between processes must be compatible with pickling: Picklability: Ensure that the arguments to the methods of proxies are picklable. You are using data that is not picklable. Specifically, what is going wrong is that the cv2.Boost class doesn't quite tell the truth on how you can create more copies of the class. pickle stores references to classes and functions, not their definition, because that's way more efficient. This means that instances only need to store the data for that instance, not also all of the class hierarchy and method definitions. In order to do this, pickle takes the module a class or function is defined in, and the name of the object, and together that's the reference to the class or function. It then double-checks that it can use that name to load the same class or function back again. That sanity check failed for the cv2.Boost class. You have instances of a class is named Boost and that claims to have come from the cv2 module, but when pickle then goes to the cv2 module and looks up the Boost attribute of that module it found a different object. This means your data could not be unpickled. There are ways to correct this; you need to teach the pickle module to use a different function to load the same data again, using the copyreg.pickle() function; if such a registration exists for the cv2.Boost class then pickle will not make the above check: import copyreg import cv2 def _pickle_boost(boost): return cv2.Boost, ( boost.trainData, boost.tflag, boost.responses, boost.varIdx, boost.sampleIdx, boost.varType, boost.missingDataMask, boost.paramsd, ) copyreg.pickle(cv2.Boost().__class__, _pickle_boost) WARNING: I didn't actually test if the above will work, because I don't have a 2.4.x version of cv2 installed locally; I merely referred to the cv2.Boost() documenta…

http://stackoverflow.com/a/50364148
upvote count: 5
type: Answer
has body: As Anton vBR has pointed out, this should solve your problem filtered = df.loc[df['Column A'] == column_A_value]['Column B'] And if you like to get just one value you can do: list(df.loc[df['Column A'] == column_A_value]['Column B'])[0]
accepted answer of: http://stackoverflow.com/q/50364049
score: 5
answers question: http://stackoverflow.com/q/50364049
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87554815
type: QuestionComment
has text: @Juanvulcano it depends on your specific dataset, you could preprocess it all with something like `scikit-image` or even `ImageMagick` or rescale/randomly crop it on the fly for data augmentation. See also keras' own `ImageDataGenerator` which might be helpful (e.g. you can define a `target_size` and let it do the rescaling)
score: 0
comment on: http://stackoverflow.com/q/50266996
type: Comment

http://stackoverflow.com/comment/87667304
comment on: http://stackoverflow.com/q/50325746
score: 0
type: Comment
type: QuestionComment
has text: I want different admin sites for diffrent admins. for A and B level and diffrent authentication. please remeber company is associated with B level.

http://stackoverflow.com/a/50233020
type: Answer
answers question: http://stackoverflow.com/q/50232893
score: 0
has body: You can try using just *args as argument. Ex: def test(*args): print(args) test({"a": 1, "b":2, "c":3, "d":[1,2,3,45]}) Output: ({'a': 1, 'c': 3, 'b': 2, 'd': [1, 2, 3, 45]},)
has comment: http://stackoverflow.com/comment/87484628

http://stackoverflow.com/comment/135683377
has text: Since the answer is now (partially) outdated and I lost over an hour troubleshooting this, I suggest future people with this issue to read carefully the updated tutorial: **TensorFlow 2.10 was the last TensorFlow release that supported GPU on native-Windows**; so either you `pip install "tensorflow<2.11"` or you use WSL
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50359157

http://stackoverflow.com/comment/87514183
comment on: http://stackoverflow.com/q/50248319
has text: Used to generate a string of any length with 26 letters
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50236742
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 2
has body: I am writing some code that I want to be able to run on previous versions of Python before type-hinting was added without needing a separate code base. Is there a simple way to accomplish this? Similar to how from __future__ import print_function would allow you to use print() in Python 2 code, is there a from __future__ import type_hints? The accepted answer to the duplicate question does provide one way to make it work in 2.7, but it doesn't say if that should also work fine in Python 3. I'm going to ask in the comments of the answer, but my question is looking for something compatible with both Python 2 and earlier versions of Python 3.
tagged with: backwards-compatibility
accepted answer: http://stackoverflow.com/a/50262940
downvote count: 0
has comment: http://stackoverflow.com/comment/87491046
has answer: http://stackoverflow.com/a/50237577
tagged with: type-hinting
has title: Is there a way to use type hinting on back-compatible code in Python?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/35230635
possible better answer: http://stackoverflow.com/a/50237577
has answer: http://stackoverflow.com/a/50262940
tagged with: python
has comment: http://stackoverflow.com/comment/87490979

http://stackoverflow.com/comment/87673577
type: QuestionComment
score: 0
has text: Do you get any output in the logs/terminal from the django app when you hit that URL?
comment on: http://stackoverflow.com/q/50328840
type: Comment

http://stackoverflow.com/comment/87565865
has text: Well, I should then define many other large string variables in my file2, cause it also has many refers to them. And it adds too many lines to a file2 + i want to have some more files in future
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50274456
score: 0

http://stackoverflow.com/comment/87620070
type: QuestionComment
has text: So one thing that I have experienced when doing genetic algorithms (very minimal), is that it really comes down to how your data is formatted. What do your "genes" represent? Is it a set of motions for example? Or is it more geared toward a policy? If your agents aren't learning, but are mutating correctly, then the problem is most likely in your fitness function or with what the genes are representing.
comment on: http://stackoverflow.com/q/50301734
type: Comment
score: 0

http://stackoverflow.com/comment/87491974
has text: At first you have to wait for an response. If you try to read the socket immediately it will yield no data since there is nothing yet.
type: QuestionComment
comment on: http://stackoverflow.com/q/50237213
type: Comment
score: 1

search
tags question: http://stackoverflow.com/q/50262222
tags question: http://stackoverflow.com/q/50237102
tags question: http://stackoverflow.com/q/50267894
tags question: http://stackoverflow.com/q/50259546
type: Tag
tags question: http://stackoverflow.com/q/50281268
tag name: search
tags question: http://stackoverflow.com/q/50299811

http://stackoverflow.com/comment/87596750
score: 0
comment on: http://stackoverflow.com/q/50290349
has text: Why not split last 4 digits?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87638149
type: Comment
type: QuestionComment
has text: The fact that the scanner doesn't produce errors isn't enough; you need to know that it produces the right output (which appears to be a list of token objects that have `value` attributes that are strings).
comment on: http://stackoverflow.com/q/50310920
score: 0

http://stackoverflow.com/comment/87727813
type: QuestionComment
score: 0
has text: @Bakuriu I added a real example.
type: Comment
comment on: http://stackoverflow.com/q/50355330

http://stackoverflow.com/comment/87655962
type: QuestionComment
has text: besides, that _should_ work, unless `os.path.abspath("Game.py")` contains spaces.
score: 0
comment on: http://stackoverflow.com/q/50319970
type: Comment

timer
tag name: timer
tags question: http://stackoverflow.com/q/50241279
type: Tag

http://stackoverflow.com/q/50276835
type: AnsweredQuestion
has title: Python converting a string salesforce timestamp to date
has comment: http://stackoverflow.com/comment/87570312
score: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50277259
has comment: http://stackoverflow.com/comment/87570415
answer count: 4
has answer: http://stackoverflow.com/a/50277259
possible better answer: http://stackoverflow.com/a/50277174
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/50277174
tagged with: datetime
has answer: http://stackoverflow.com/a/50276961
tagged with: python
has body: This is the datetime string I am getting 2018-05-04T13:08:20.000+0000. I want to convert it to a date 2018-05-04. Below is the for loop i want use but just can't seem to strip out all the hour secs and etc. Max_data is the string with 2018-05-04T13:08:20.000+0000 from datetime import timedelta, date def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)): yield start_date + timedelta(n) start_date = datetime.strptime(max_data,'%Y-%m-%d') end_date = date.today() for single_date in daterange(start_date, end_date): print single_date.strftime("%Y-%m-%d")
has answer: http://stackoverflow.com/a/50277258
tagged with: python-2.7

http://stackoverflow.com/comment/87673384
type: Comment
comment on: http://stackoverflow.com/q/50328401
type: QuestionComment
has text: :( sorry, I'm very new to Python.
score: 0

http://stackoverflow.com/a/50282949
has comment: http://stackoverflow.com/comment/87606754
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50278105
has body: Actually, fixed it by killing heavy running processes. There was one process that was using a lot of memory. This was nothing related to Matplotlib. Let me know if I have to delete this question. It was a little silly on my part!
score: 1
downvote count: 0

http://stackoverflow.com/q/50247517
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/63038706
tagged with: audio
score: 3
upvote count: 3
answer count: 2
tagged with: filter
downvote count: 0
has answer: http://stackoverflow.com/a/50248062
has body: #complie by python3 only_test.py import pyaudio import numpy as np import wave import time import math #from pydub import AudioSegment #from pydub.playback import play #from scipy.signal import iirfilter from scipy import signal RATE = 48000 CHUNK = 4096 WIDTH = 2 volume = 0.0 duration = 1.0 #SHORT_NORMALIZE = (1.0/32768.0) #INPUT_BLOCK_TIME = 1 #INPUT_BLOCK_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME) while True: #use a blackman window window = np.blackman(CHUNK) #load audio stream p = pyaudio.PyAudio() player = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, output=True, frames_per_buffer=CHUNK) stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) #errorcount = 0 for i in range(int(20*RATE/CHUNK)): sound = stream.read(CHUNK) #imp_ff = signal.filtfilt(b,a,sound) #playback microphone sound #player.write(np.fromstring(sound,dtype=np.int16),CHUNK) #generate samples with return frequency to array #samples= (np.sin(2*np.pi*np.arange(RATE*duration)*freq/RATE)).astype(np.int16) #inverse frequency samples #inverse_samples = -samples #return frequency sound stream #player.write(np.fromstring((volume*inverse_samples)\ ,dtype=np.int16),CHUNK) #unpack the data and times by hamming window indata = np.array(wave.struct.unpack("%dh"%(len(sound)/WIDTH),\ sound))*window #take the fft and square each value fftData = abs(np.fft.rfft(indata))*2 #ifftData = abs(np.fft.irfft(indata))*2 #find the maxium which = fftData[1:].argmax() + 1 #use quadratic interpolation around the max if which != len(fftData)-1: y0,y1,y2 = np.log(fftData[which-1:which+2:]) x1 = (y2-y0)*.5 / (2*y1-y2-y0) #find the frequency and output it freq = (which+x1)*RATE/CHUNK print("the freq is %d hz." % (freq)) else: freq = which*RATE/CHUNK print("the freq is %d hz." % (freq)) #playback the mic sound player.write(np.fromstring(sound,dtype=np.int16),CHUNK) if freq &lt; 65: freq = 0 #generate samples, note conversion to array #samples = (np.sin(2*np.pi*np.arange(RATE*duration…
favorite count: 0
tagged with: signal-processing
type: Question
has title: python specific frequency remove(notch filter)?

http://stackoverflow.com/comment/87479061
comment on: http://stackoverflow.com/a/50230908
has text: @WiktorStribiżew yep.. added note..
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92677395
comment on: http://stackoverflow.com/q/50272416
score: 0
has text: I had the exact same question. It seems to me that the pipeline creation step is almost like an initialization of a pipeline, and then in the search_space array, the `classifier` key each time overwrites the `RandomForestClassifier()` of the `pipe = ...` line. I have been searching for an answer for this over the past few days, and I even messaged Chris Albon, but no luck yet. I am not sure if I am right.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50274979
score: 1
accepted answer of: http://stackoverflow.com/q/50274461
type: AcceptedAnswer
downvote count: 0
has body: Set, List Comprehension &amp; Ternary Condition plus Pandas If you want Pythonic as well as pretty, here is one way. import pandas as pd breakfast = [['Apple,Banana'],['Apple,Yogurt'],['Banana,Oatmeal']] breakfast = [i[0].split(',') for i in breakfast] columns=list(set([j for i in breakfast for j in i])) columns.sort() values = [[1 if j in i else 0 for j in columns]for i in breakfast] df = pd.DataFrame(values, columns=columns) print(df) Apple Banana Oatmeal Yogurt 0 1 1 0 0 1 1 0 0 1 2 0 1 1 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87567235
has comment: http://stackoverflow.com/comment/87567589
has comment: http://stackoverflow.com/comment/87566661
type: Answer
has comment: http://stackoverflow.com/comment/87566571
answers question: http://stackoverflow.com/q/50274461

http://stackoverflow.com/a/50360932
downvote count: 0
answers question: http://stackoverflow.com/q/50358354
upvote count: 10
has body: I've found what I was looking for: I had to add the IndexName in my code like this. dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Testing-Table') def lambda_handler(event, context): response = table.query ( IndexName='status-index', KeyConditionExpression=Key('status').eq('active') ) for i in response['Items']: print(i['user_id'],&quot;:&quot;,i['status']) Here is an image of the result:
score: 10
type: Answer

http://stackoverflow.com/comment/87734565
type: AnswerComment
has text: Does it even need to be the minimum or can you just subtract off some arbitrary date and just add that back later?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50358798

http://stackoverflow.com/comment/87611071
has text: Hi, it's not really clear exactly what you are asking, so I tried to just run the code. But the formatting is off, and there is a missing CSV file that you have have not provided. Additionally, there is alot of extraneous code here related to formatting, visuals, etc. It's always much more helpful if you can pare the code down to the bare minimum needed to discuss a particular.
type: QuestionComment
comment on: http://stackoverflow.com/q/50280177
score: 0
type: Comment

http://stackoverflow.com/comment/87724953
type: QuestionComment
comment on: http://stackoverflow.com/q/50280177
score: 0
has text: Sorry, I'm still not able to understand what your question is really asking. Perhaps someone else will have a better time than me .
type: Comment

http://stackoverflow.com/comment/87777845
has text: you should get something for doing his homework.. ha! :-p
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50380841

http://stackoverflow.com/q/50339991
has answer: http://stackoverflow.com/a/50340179
has comment: http://stackoverflow.com/comment/87696845
score: 0
has answer: http://stackoverflow.com/a/50340202
answer count: 3
has title: Python np.dstack : too many values to unpack
tagged with: python
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50340768
has comment: http://stackoverflow.com/comment/87696367
has body: Was experimenting with np.dstack and got the error: ValueError: too many values to unpack (expected 2) Here's the code: a = np.array((1,2,3)) b = np.array((2,3,4)) for x, y in np.dstack((a,b)): print(x,",",y) solutions?
type: UnansweredQuestion

http://stackoverflow.com/comment/87594206
comment on: http://stackoverflow.com/q/50288258
has text: @MatiasValdenegro I am getting following error "AttributeError: 'NoneType' object has no attribute 'op'"
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50311285
answers question: http://stackoverflow.com/q/50311201
score: 8
has comment: http://stackoverflow.com/comment/87639088
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87639269
has comment: http://stackoverflow.com/comment/87638887
has comment: http://stackoverflow.com/comment/87639312
upvote count: 8
has comment: http://stackoverflow.com/comment/87639125
accepted answer of: http://stackoverflow.com/q/50311201
has body: I think you want .shift + .cumsum() The +1 is because your first row will always be NaT for the difference, which evaluates to False for the comparison, which will always start the SessionID from 0 otherwise. import pandas as pd df['SessionID'] = (df.timestamp-df.timestamp.shift(1) &gt; pd.Timedelta(5, 'm')).cumsum()+1 timestamp App SessionID 6784 2018-04-08 14:31:29.209 Google 1 6785 2018-04-08 14:58:42.875 Google 2 6786 2018-04-08 18:18:04.757 Chrome 3 6787 2018-04-08 21:08:41.368 Google 4 6788 2018-04-11 10:53:10.744 Google 5 6789 2018-04-14 19:54:37.441 Google 6 6790 2018-04-14 19:54:59.833 Google 6 6791 2018-04-14 19:55:10.844 YouTube 6 6792 2018-04-14 19:55:34.486 Google 6 6793 2018-04-14 20:23:00.315 Google 7 6794 2018-04-15 08:23:44.873 Google 8 6795 2018-04-15 08:24:07.257 Google 8 6796 2018-04-16 16:42:35.538 Google 9 6797 2018-04-16 16:42:48.351 Google 9 6798 2018-04-17 08:10:54.734 Google 10 6799 2018-04-17 08:13:28.855 Google 10 6800 2018-04-17 08:16:49.408 Google 10 6801 2018-04-17 08:18:55.049 Google 10 6802 2018-04-17 08:21:04.201 Google 10 6803 2018-04-17 08:26:14.254 Google 11 If you also have UserID you can then implement logic where you increment the ID when either the time is greater than 5 minutes, OR the userID changes. That is accomplished by: import pandas as pd data = '''\ 1,2018-04-08T09:48:17.573,YouTube 1,2018-04-08T09:47:57.849,Chrome 1,2018-04-08T09:48:28.538,Instagram 1,2018-04-08T09:48:37.381,Maps 2,2018-04-08T09:48:46.680,Netflix 2,2018-04-08T09:48:56.672,Google Play Store 1,2018-04-08T09:56:58.880,Google 1,2018-04-08T09:57:25.461,DB Navigator 1,2018-04-08T11:28:38.762,Google 1,2018-04-08T12:58:31.455,Google 1,2018-04-08T14:31:18.131,Google 1,2018-04-08T14:31:29.209,Google 1,2018-04-08T14:58:42.875,Google 1,2018-04-08T18:18:04.757,Chrome 1,2018-04-08T21:08:41.368,Google 1,2018-04-11T10:53:10.744,Google 1,2018-04-14T19:54:37.441,Google 1,2018-04-14T19:54:59.833,Google 1,2018-04-14T19:55:10.844,YouTube 1,2018-04-14T19:55:34.486,Google…
has comment: http://stackoverflow.com/comment/87639047
type: Answer
has comment: http://stackoverflow.com/comment/87639302
has comment: http://stackoverflow.com/comment/87639250
has comment: http://stackoverflow.com/comment/87639114

http://stackoverflow.com/comment/87639939
type: QuestionComment
comment on: http://stackoverflow.com/q/50311096
has text: @NaN I get this response ----> 1 numpy.version.version AttributeError: module 'numpy' has no attribute 'version'
score: 0
type: Comment

http://stackoverflow.com/comment/123377670
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53815323
has text: I try to transform a 1-channel .tif to RGB with `cv2.COLOR_GRAY2RGB` , but I get this error: `frame = np.array(frame, dtype=np.uint8) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'` why?
type: Comment

http://stackoverflow.com/a/50278388
upvote count: 37
has body: Use str.strip and str.split: df['LABELS'] = df['LABELS'].str.strip('()').str.split(',') But if no NaNs here, list comprehension working nice too: df['LABELS'] = [x.strip('()').split(',') for x in df['LABELS']]
type: Answer
has comment: http://stackoverflow.com/comment/131297465
has comment: http://stackoverflow.com/comment/131297493
has comment: http://stackoverflow.com/comment/131654385
score: 37
answers question: http://stackoverflow.com/q/50278300
downvote count: 0
has comment: http://stackoverflow.com/comment/87573467

http://stackoverflow.com/comment/87928352
comment on: http://stackoverflow.com/a/50277863
score: 0
has text: @Francesco If the answer has helped you feel free hit accept and both you and me will get points and others might find it helpful. I think change for python 2 is nota big deal and people will figure it out.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/112441589
has text: I just want to thank you for this comment/solution. I never would've guessed it, since I have my slugfield's set for allowing UTF-8 & therefore "knew" it required me to use <slug:> in the path. I was going bananas trying to figure out how to regex the path until you said that <str:> works for this. Thanks!
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51581700

http://stackoverflow.com/comment/87495568
type: QuestionComment
has text: When you run the code as it currently appears in your question, what error message do you get? Please copy-paste the entire error message text into your question, including any traceback.
score: 0
comment on: http://stackoverflow.com/q/50238917
type: Comment

http://stackoverflow.com/comment/87520682
type: Comment
has text: That did the trick, thanks! Does casting to a dict automatically eliminate duplicate keys? Edit: Just saw the explanation form @mkrieger1, thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/50251705
score: 0

http://stackoverflow.com/comment/87629526
type: QuestionComment
comment on: http://stackoverflow.com/q/50306527
score: 0
has text: See the example of this link: https://docs.python.org/3/library/multiprocessing.html
type: Comment

http://stackoverflow.com/a/50347345
has body: This worked for me: from bs4 import BeautifulSoup import urllib r = urllib.urlopen("https://www.oportaldaconstrucao.com/empresa/1964/aj-navalho/").read() soup = BeautifulSoup(r, 'lxml') letter = soup.find_all("i", class_="fa fa-envelope")[0].next_sibling print letter Output: ajnavalho@ajnavalho.pt
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50346414
answers question: http://stackoverflow.com/q/50346414
has comment: http://stackoverflow.com/comment/87711673
has comment: http://stackoverflow.com/comment/87711596
has comment: http://stackoverflow.com/comment/87711417
type: AcceptedAnswer

http://stackoverflow.com/a/50282427
answers question: http://stackoverflow.com/q/50282379
type: Answer
score: 0
has body: store it as a variable outside of function. for example string playerName = playername() and add return playername to the end of the function "playername" def playername(): print("What is your name?") playername = input() return playername def main(): playerName = playername() print(playerName) main()

http://stackoverflow.com/q/50371163
has title: Creating custom loss for continous conditional random field
upvote count: 2
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: I am currently trying to implement the network presented in 1 using Keras. The model can be divided into two parts: the first one, called the super pixels depth network, regresses depth values for an image segmented in super pixels while the second one is a continuous conditional random field layer whose goal is to ensure spatial and temporal consistency in the depth maps predicted for each frame of a video. Each part has its set of parameters, W for the super pixel network and alpha_s &amp; alpha_t for the CRF. Both are trained jointly using stochastic gradient descent. I had no problem implementing the super pixels depth network, it’s just the first 31 layers of VGG-16 followed by a super pixels pooling layer. The tricky part for me is the CRF layer and the following loss function: In this equation: I is a frame from a video. d is a Nx1 vector of ground truth super pixels depth where N is the number of super pixels in the video. L is a NxN matrix depending on alpha_s, alpha_t and the spatio-temporal relations between super pixels given by the segmentation algorithm. Z is a Nx1 vector of estimated super pixels depth depending on W. If I am not mistaken, this loss function does not have the conventional form “loss(y_true, y_pred)" and uses y_true (d in the expression) and the network weights (in z and L). My idea is to use the functional API and write a custom loss function that computes -log P( d | I ) but I am wondering how the gradients will be computed? I read here that Keras is taking care of gradients computation as long as we are only using existing operations but matrix inversion is not in the tensorflow backend. Will it work if I call tf.matrix_inverse? Best regards, Ambroise 1 Zhao, Xu-Ran, Xun Wang, and Qi-Chao Chen. "Temporally Consistent Depth Map Prediction Using Deep Convolutional Neural Network and Spatial-Temporal Conditional Random Field." Journal of Computer Science and Technology 32.3 (2017): 443-456. link
tagged with: keras
favorite count: 0
type: Question
tagged with: crf
tagged with: python

http://stackoverflow.com/comment/87516338
comment on: http://stackoverflow.com/q/50249478
type: Comment
type: QuestionComment
has text: Can you edit the question and post the TraceBack error as well?
score: 2

http://stackoverflow.com/comment/87628432
type: QuestionComment
has text: I've edited your question to include that information. Please review whether it still asks what you want to ask. Nevertheless, please [edit] it further to turn the contained code into a [mcve], so that others can reproduce the problem without having to invent code of their own.
comment on: http://stackoverflow.com/q/50305964
score: 0
type: Comment

http://stackoverflow.com/comment/87665993
type: Comment
comment on: http://stackoverflow.com/a/50323538
has text: @cricket_007 you do see the `python-3.x` tag on the question? for 2.x you should switch to `raw_input()` instead, but nothing in the questions suggests 2.x to me.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50346252
score: 0
has body: f.read(4) is your issue here file.read reads at most size bytes and returns.Python Docs You'll have to create a wrapper function to read exact bytes. You can get inspiration from here :Check link
type: Answer
answers question: http://stackoverflow.com/q/50346117

http://stackoverflow.com/q/50367195
has answer: http://stackoverflow.com/a/50367326
has answer: http://stackoverflow.com/a/50367399
score: 0
has body: I have a file containing numerical values: 1 4 6 10 12 and I'm trying to append these values into its respective position in an array where i would obtain: [None,1,None,None,4,None,6,None,None,None,10,None,None,12] Since 1 from the file would be at index 1 in the list, 4 from the file would be at index 4 in the list and so on. I begin by first reading in the file: filename = open("numbers.txt", "r", encoding = "utf-8") numfile = filename lst = [None] * 12 for line in numfile: line = line.strip() #strip new line line = int(line) #making the values in integer form vlist.append(line) #was thinking of line[val] where value is the number itself. print(vlist) but I'm getting the output: [None,None,None,None,None,None,None,None,None,1,4,6,10,12] Where the numbers are appended to the far right of the array. Would appreciate some help on this.
has title: Appending numbers from a file into a list by it's value
has comment: http://stackoverflow.com/comment/87751068
has comment: http://stackoverflow.com/comment/87750788
accepted answer: http://stackoverflow.com/a/50367326
type: Question
linked to: http://stackoverflow.com/q/1540049
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50367488
possible better answer: http://stackoverflow.com/a/50367370
has answer: http://stackoverflow.com/a/50367370
tagged with: python
answer count: 4

http://stackoverflow.com/comment/87659201
has text: I saw it in the traceback when trying to find the root of the error: line 2963, in softmax return tf.nn.softmax(x, axis=axis) TypeError: softmax() got an unexpected keyword argument 'axis'
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50321437

http://stackoverflow.com/q/50326052
favorite count: 0
accepted answer: http://stackoverflow.com/a/50326543
type: Question
has answer: http://stackoverflow.com/a/50326543
upvote count: 8
tagged with: python
has title: SQLAlchemy Join to retrieve data from multiple tables
has body: I'm trying to retrieve data from multiple tables with SQLAlchemy using the .join() method. When I run the query I was expecting to get a single object back which had all the data from the different tables joined so that I could use a.area_name and so on where area_name is on one of the joined tables. Below is the query I am running and the table layout, if anyone could offer insight into how to achieve the behavior I'm aiming for I would greatly appreciate it! I've been able to use the .join() method with this same syntax to match results and return them, I figured it would return the extra data from the rows as well since it joins the tables (perhaps I'm misunderstanding how the method works or how to retrieve the information via the query object?). If it helps with the troubleshooting I'm using MySQL as the database query: a = User.query.filter(User.user_id==1).join(UserGroup, User.usergroup==UserGroup.group_id).join(Areas, User.area==Areas.area_id).first() and the tables: class User(db.Model): user_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), unique=True) usergroup = db.Column(db.Integer, db.ForeignKey('user_group.group_id'), nullable=False) area = db.Column(db.Integer, db.ForeignKey('areas.area_id'), nullable=False) class UserGroups(db.Model): id = db.Column(db.Integer, primary_key=True) group_id = db.Column(db.Integer, nullable=False, unique=True) group_name = db.Column(db.String(64), nullable=False, unique=True) class Areas(db.Model): id = db.Column(db.Integer, primary_key=True) area_id = db.Column(db.Integer, nullable=False, unique=True) area_name = db.Column(db.String(64), nullable=False, unique=True)
score: 8
possible better answer: http://stackoverflow.com/a/50326265
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50326265
downvote count: 0
tagged with: mysql
tagged with: sqlalchemy

http://stackoverflow.com/comment/87483637
comment on: http://stackoverflow.com/q/50232239
type: Comment
score: 1
type: QuestionComment
has text: http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.autoincrement See the section starting with "The setting only has an effect for columns which are: ..." The way I read that, it's behaving as expected, since your new column doesn't meet the stated criteria.

http://stackoverflow.com/q/50361475
has body: I have a simple task at hand...handling exception so the code does not throw IncompleteRead when using urllib/urllib2 between python2.x/3.x for python2 try: page = urllib2.urlopen(urls).read() except httplib.IncompleteRead, e: page = e.partial for python3 try: page = request.urlopen(urls).read() except (http.client.IncompleteRead) as e: page = e.partial now since the module itself are different, how to do a try-except when i have no idea which python version will my users be running? I cannot check for python version within my try-except as well...or can I? is there a way to catch its super class so it becomes same for both python version? if yes, how?
has title: Exception handling in version agnostic code
tagged with: python
has comment: http://stackoverflow.com/comment/87739462
has comment: http://stackoverflow.com/comment/87739583
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50361604
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50361518
has comment: http://stackoverflow.com/comment/87739479
has answer: http://stackoverflow.com/a/50361645
tagged with: python-2.7
score: 0
answer count: 3
tagged with: exception

http://stackoverflow.com/comment/87663552
type: Comment
score: 0
type: AnswerComment
has text: @jferard Clever trick! Thank you so much! It is indeed what I want +1
comment on: http://stackoverflow.com/a/50322606

http://stackoverflow.com/comment/87751759
type: Comment
has text: kindly note this will print only letters of key names
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50367351

http://stackoverflow.com/comment/127757715
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/72316062
has text: learn more about decorators: [realpython](https://realpython.com/primer-on-python-decorators/)
score: 0

http://stackoverflow.com/q/50353630
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50353706
has answer: http://stackoverflow.com/a/50353706
type: Question
has title: How can i implement Vector addition for the form [1,2,3,4] + v where v is vector and [1,2,3,4] is a list in python?
tagged with: python
has body: Here is the code for the program: I tried to implement a vector class as i learned about operator overloading in python. I was able to make a vector class which can be used much like a list with operations like len(vector) , vector1 + vector2 (addition operator overloading) and subtraction . But i found a problem. Here is the code of the program and i have stated the problem below : class vector: """Initialize Vector""" def __init__(self,d): self.coords = [0]*d def __len__(self): return len(self.coords) def __getitem__(self, item): #Getting an item from a vector return self.coords[item] def __setitem__(self, key, value): self.coords[key] = value def __add__(self, other): if(len(self)!= len(other)): print("Don't add these too ! they are not same types :P") else: result = vector(len(self)) for i in range(0,len(result)): result[i] = self[i] + other[i] return result def __sub__(self, other): if(len(self) != len(other)): print("Dont subtract these two!") else: result = vector(len(self)) for i in range(0,len(result)): result[i] = self[i] - other[i] return result def __eq__(self, other): return self.coords == other.coords def __ne__(self, other): return self.coords != other.coords def __str__(self): return '&lt;'+ str(self.coords)[1:-1] +'&gt;' print("Input for vector 1") x = vector(2) for i in range(0,len(x)): x[i] = int(input('Enter a number\n')) print("Input for vector 2") y = vector(2) for i in range(0,len(y)): y[i] = int(input('Enter a number\n')) z = x-y print(str(x)) print(" + ") print(str(y)) print(" = ") print(str(z)) It works if i add a vector + list but list + vector gives an error. How can i implement the other .
type: AnsweredQuestion

http://stackoverflow.com/comment/87757426
type: Comment
type: QuestionComment
score: 0
has text: Give us a stripped-down example of two dozen lines or so that we know exactly what you are trying to achieve.
comment on: http://stackoverflow.com/q/50370744

qsqldatabase
type: Tag
tags question: http://stackoverflow.com/q/50372753
tag name: qsqldatabase

http://stackoverflow.com/a/50277514
answers question: http://stackoverflow.com/q/50264616
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50264616
has body: Your Python and MATLAB files are not ordered in the same way, which gives you the error. Even though the shapes of the arrays are the same, the values are ordered row-wise in Python, and column-wise in MATLAB. You can fix this by reshaping your input array and transposing. This will give you the same ordering of the values as in MATLAB: input = input.reshape((input.shape[1], input.shape[0])).T
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/50361887
answers question: http://stackoverflow.com/q/50361356
accepted answer of: http://stackoverflow.com/q/50361356
type: Answer
score: 4
upvote count: 4
has body: NaN will always interrupt the line plot: Because the NaN still exist in the data the line will be interrupted. Pandas doesn't know how to carry the line through an NaN so only sequential numeric values can be plotted. You must remove the NaN to have the line continue all the way through the valid data. If you plot points you will see everything. Here is a LINK to a similar but different question about plotting NaN where the answer mentions the problem with plotting a line through NaN. Reproducible example: import random import pandas as pd import numpy as np c = [np.nan] * 10 c.extend(random.sample(range(100), 10)) random.shuffle(c) d = {"a":random.sample(range(100), 20), "b":random.sample(range(100), 20), "c":c} df = pd.DataFrame(d) df.plot(style="-o") # both points and line to show all values df.dropna().plot()
type: AcceptedAnswer
downvote count: 0

pdf-parsing
type: Tag
tag name: pdf-parsing
tags question: http://stackoverflow.com/q/50337660

http://stackoverflow.com/q/50299676
linked to: http://stackoverflow.com/q/419163
has title: How to import the main function from a Python file not defining "def main" in it?
linked to: http://stackoverflow.com/q/3781851
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50299786
answer count: 1
has comment: http://stackoverflow.com/comment/87616277
type: Question
has body: I am writing a Python (3.5) module in which I'd like to make use of an existing Python module from an open source project. The module I want to import contains: several functions a if __name__ == '__main__': instruction but does not contain a def main(args) function. Because there is no actual main function, I cannot import it by means of import module and use it as module.main(). Although I did find options to separately execute it as script via the commands os.system() and subprocess.Popen(), I am actually looking for a way to make this call an integral part of my code. I understand I can add the def main() part myself in the original code, but because it comes from an open source project, I am looking for ways to leave it untouched, so that I don't need to maintain it myself if it gets updated. I have gone through other very similar questions, such as this and this that could not solve my issue. This answer gives me the feeling what I am trying to do is not trivial. Is there any way to do this?
tagged with: python-import
has comment: http://stackoverflow.com/comment/87619143
tagged with: program-entry-point
has comment: http://stackoverflow.com/comment/87616795
linked to: http://stackoverflow.com/q/2349991
accepted answer: http://stackoverflow.com/a/50299786
tagged with: python

rss
type: Tag
tags question: http://stackoverflow.com/q/50374186
tag name: rss
tags question: http://stackoverflow.com/q/50318656
tags question: http://stackoverflow.com/q/50313292

http://stackoverflow.com/comment/87652937
has text: @eXistanCe This is a good question. I think, cycles wise, this is likely shorter, but from a couple of quick tests it seems chrisz' answer is slightly faster. I would recommend doing a timing comparison on your data, it really depends.
type: Comment
comment on: http://stackoverflow.com/a/50318378
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87586711
score: 0
type: AnswerComment
has text: @AChampion This is the first time I have posted on this site, so I posted an issue in my question.
comment on: http://stackoverflow.com/a/50283621
type: Comment

http://stackoverflow.com/comment/87544837
type: QuestionComment
comment on: http://stackoverflow.com/q/50262913
has text: Are you trying to use both tensorflow keras and the keras together? I just [solved one same error in another question](https://stackoverflow.com/questions/50259158/keras-custom-layer-node-object-has-no-attribute-output-masks#comment87540259_50259158). Can you upload all your imports or a [MCVE](https://stackoverflow.com/help/mcve) if possible?
score: 0
type: Comment

http://stackoverflow.com/q/50283741
tagged with: pip
has comment: http://stackoverflow.com/comment/87598305
tagged with: tensorflow
has title: Errors after installing tensorflow in python 3.5 gpu through pip
type: Question
has comment: http://stackoverflow.com/comment/87591462
score: 0
has body: I have installed tensorflow through native pip, then these errors show up. I don't know if this is a problem with python distribution. I have recently encountered a problem when working with ros; anaconda and ros needed different versions,so I have solved somehow by removing the path in anaconda or something: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/usr/lib/python3.5/imp.py", line 242, in load_module return load_dynamic(name, filename, file) File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic return _load(spec) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory 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 "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import…
tagged with: python
has comment: http://stackoverflow.com/comment/87594141
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/87662531
score: 0
comment on: http://stackoverflow.com/q/50323357
type: Comment
has text: Maybe filter out the strings using a simple LL parser rather than a regex? But at this point we should probably just give up and use some library to construct an AST for us. ¯\\\_(ツ)\_/¯
type: QuestionComment

http://stackoverflow.com/a/50256393
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50255995
has body: You missed assigning the new number to the current number (since the newest will become the old and you will re read a new number). Some side notes, you don't need to cast your input since python will do that for you, you can use input("message") #instead of print("message") new = input() Small last remarks, you don't need to initialize ints ( f_n =0) and it's better to name the param to what you are going to need it for, f_n nn and stuff like that are not as clear when you want to re read your code (or if someone else trying to read it) oldnb = input("Enter the first number") finished = false while not finished: newnb = input("Enter the next number, 0 to finish: ") if(newnb == 0) finished=true else if newnb == oldnb print("Same") elif newnb&gt;oldnb print("Up") else print("Down")
has comment: http://stackoverflow.com/comment/87530871

http://stackoverflow.com/q/50236928
linked to: http://stackoverflow.com/q/66499849
has answer: http://stackoverflow.com/a/51512594
has title: Openpyxl: 'ValueError: Max value is 14' when using load_workbook
has answer: http://stackoverflow.com/a/71602213
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50846096
tagged with: openpyxl
downvote count: 0
has answer: http://stackoverflow.com/a/65571339
has answer: http://stackoverflow.com/a/70537454
has answer: http://stackoverflow.com/a/71526058
favorite count: 0
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/69789654
has answer: http://stackoverflow.com/a/54318948
has answer: http://stackoverflow.com/a/65014135
score: 5
upvote count: 5
has body: I have attempted to open an excel file in which I need to insert dataframes to certain sheets, while leaving other sheets alone. The script works fine when I tested it on other excel files. When I use it on the one I actually need, I get an error message. Here is the script: from openpyxl import load_workbook book = load_workbook(self.directory) Self.directory refers to my file location. As you can see in the traceback, it fails already at this line when trying to execute load_workbook(), and gives the following error message: ValueError: Max value is 14 Here is the relevant traceback (I left the directory locations starting with the virtual environment folder 'virtual'): """ book = load_workbook(self.directory) virtual\lib\site-packages\openpyxl\reader\excel.py", line 217, in load_workbook shared_strings = read_string_table(archive.read(strings_path)) virtual\lib\site-packages\openpyxl\reader\strings.py", line 22, in read_string_table text = Text.from_tree(node).content virtual\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree obj = desc.expected_type.from_tree(el) virtual\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree obj = desc.expected_type.from_tree(el) virtual\lib\site-packages\openpyxl\styles\fonts.py", line 110, in from_tree return super(Font, cls).from_tree(node) virtual\lib\site-packages\openpyxl\descriptors\serialisable.py", line 100, in from_tree return cls(**attrib) virtual\lib\site-packages\openpyxl\cell\text.py", line 114, in __init__ self.family = family virtual\lib\site-packages\openpyxl\descriptors\nested.py", line 36, in __set__ 6, in __set__ super(Nested, self).__set__(instance, value) virtual\lib\site-packages\openpyxl\descriptors\base.py", line 110, in __set__ , in __set__ super(Min, self).__set__(instance, value) virtual\lib\site-packages\openpyxl\descriptors\base.py", line 89, in __set__ in __set__ raise ValueError('Max value is {0}'.format(self.max)) ValueError: Max value is 14 """…
has answer: http://stackoverflow.com/a/75501383
tagged with: python
has answer: http://stackoverflow.com/a/69820296
answer count: 11
tagged with: valueerror

http://stackoverflow.com/comment/87684628
type: QuestionComment
score: 0
has text: Have you tried inspecting the dataframe before calling `first()`? Replace the `.first()` with `.show()`. What is the output?
comment on: http://stackoverflow.com/q/50329878
type: Comment

http://stackoverflow.com/q/50370411
has answer: http://stackoverflow.com/a/50371064
answer count: 5
possible better answer: http://stackoverflow.com/a/50370471
tagged with: python
tagged with: regex
has body: I need a regex for python that finds words with five consecutive consonants. These words would work - tnortvcvni (rtvcvn) kahjdflka (hjdflk) But these words wouldn't (no five letters in row without vowels) - peanut butter jelly
has answer: http://stackoverflow.com/a/50370471
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50370736
has title: Regex to find five consecutive consonants
has comment: http://stackoverflow.com/comment/87757093
has answer: http://stackoverflow.com/a/50370736
score: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/87757839
has answer: http://stackoverflow.com/a/50370478
has answer: http://stackoverflow.com/a/50370600
favorite count: 0
type: Question

http://stackoverflow.com/a/50324697
has comment: http://stackoverflow.com/comment/87665927
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87666112
accepted answer of: http://stackoverflow.com/q/50324563
type: Answer
answers question: http://stackoverflow.com/q/50324563
has body: The solution is very much new to me. The function name should not start with "test_" (Otherwise it will be consider as a separate Test Case) I renamed the function name and it is working fine!
score: 1

http://stackoverflow.com/q/50308812
upvote count: 26
has answer: http://stackoverflow.com/a/50328882
has comment: http://stackoverflow.com/comment/87633607
has answer: http://stackoverflow.com/a/60004447
has answer: http://stackoverflow.com/a/50309198
has comment: http://stackoverflow.com/comment/87633581
has comment: http://stackoverflow.com/comment/87633630
has title: Is it possible to limit the number of coroutines running corcurrently in asyncio?
type: UnansweredQuestion
downvote count: 0
has body: I already wrote my script using asyncio but found that the number of coroutines running simultaneously is too large and it often ends up hanging around. So I would like to limit the number of coroutines concurrently, and once it reaches the limit, I want to wait for any coroutine to be finished before another is executed. My current code is something like the following: loop = asyncio.get_event_loop() p = map(my_func, players) result = loop.run_until_complete(asyncio.gather(*p)) async def my_func(player): # something done with `await` The players is of type list and contains many elements (say, 12000). It needs so much computational resource to run all of them simultaneously in asyncio.gather(*p) so I would rather like the number of players run simultaneously to be 200. Once it reaches 199, then I wish another coroutine starts to be executed. Is this possible in asyncio?
has comment: http://stackoverflow.com/comment/109513660
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48483348
answer count: 3
tagged with: python-asyncio
score: 26
tagged with: python

http://stackoverflow.com/comment/87763715
comment on: http://stackoverflow.com/q/50373737
score: 2
type: Comment
type: QuestionComment
has text: Your output example is not valid csv.

http://stackoverflow.com/a/50260668
score: 10
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87540168
has body: No, by default there is no graph nor sessions in eager executing, which is one of the reasons why it is so appealing. You will need to write code that is compatible with both graph and eager execution to write your net's graph in graph mode if you need to. Note that even though you can use Tensorboard in eager mode to visualize summaries, good ol' tf.summary.FileWriter is incompatible with eager execution: you need to use tf.contrib.summary.create_file_writer instead (works in graph mode too, so you won't have to change your code).
has comment: http://stackoverflow.com/comment/87540542
answers question: http://stackoverflow.com/q/50257614
upvote count: 10
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50257614

http://stackoverflow.com/q/50283520
tagged with: ajax
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/87606055
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/87583494
has title: How do i choose architecture for my scraping web app?
answer count: 0
type: UnansweredQuestion
has body: I have written a bunch of simple Python scripts that parse and scrape information on the web and store it in JSON files, so that I can access that data and work with it. Now I want to build a web application on top of my project. Basic use case would be: User inputs his search request in html form. User gets response without reloading the page. Seems fairly simple, however a couple of questions arises when it comes to choosing a technology, or technology stack: 1. SQL vs JSON. I store my data in a JSON files now which seems to work quite nice: I have an array with 700-800 objects of about 5-6 key-value pairs of unicode strings and urls: {"title": "some title", "img": "some-img-cdn.com/serve/img11484846435.png", "article": "item_article", "url": "some_url.com/group/item_article.html"} My old laptop search that data blazingly fast, but what about the web? What will happen, when multiple users will try to access the same file at the same time? What about Python's GIL and the way linux serves files? The question is, how much slower is reading and searching in JSON file as opposed to SQL database? 2. Python in PHP way. I use Python as a general-purpose language, I write backend in PHP. This time not only do I want to write parsing/crawling part of this app in Python, but I want to create and serve web pages using Python. I get used to write PHP in a simple way, something like the following: $search = $_POST['search_request']; $conn = new mysqli($servername, $username, $password, $dbname); $sql = "SELECT * FROM data WHERE title='" . mysqli_real_escape_string($search) . "'"; $result = mysqli_query($conn, $sql); echo $page; mysqli_close($conn); However, it finds out that Python gets quite complex when it comes to developing a web app. You have to use a full-fledged web framework such as Django which seems as quite an overkill to me, especially in my case when I do not need to worry about storing user's data, no sign up or sign in is required, no email checking. So, second q…
has comment: http://stackoverflow.com/comment/87603711
tagged with: python
tagged with: php

http://stackoverflow.com/comment/87633168
type: Comment
has text: which library are you importing requests from?
comment on: http://stackoverflow.com/a/50308511
score: 0
type: AnswerComment

http://stackoverflow.com/a/67601851
answers question: http://stackoverflow.com/q/50295010
has body: Public dashboards This is not meant for production. It’s for experiments or while doing a proof of concept. #superset_config.py PUBLIC_ROLE_LIKE_GAMMA = True or PUBLIC_ROLE_LIKE: Optional[str] = "Gamma" After this, we need to re-run the init user (if already run) docker-compose exec superset superset-init Dashboards & charts can be embedded without superset header (Nav bar etc) by adding standalone=true parameter to the url, like this : http://localhost:9000/superset/dashboard/world_health/?standalone=true We need to grant database source permissions to public role for the data to be visible. please see: https://sairamkrish.medium.com/apache-superset-custom-authentication-and-integrate-with-other-micro-services-8217956273c1
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/50325985
upvote count: 1
has comment: http://stackoverflow.com/comment/87673668
favorite count: 0
has comment: http://stackoverflow.com/comment/87691151
has comment: http://stackoverflow.com/comment/87692117
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87672267
accepted answer: http://stackoverflow.com/a/50339687
score: 1
has answer: http://stackoverflow.com/a/50339687
has comment: http://stackoverflow.com/comment/87671548
tagged with: python
tagged with: loops
has title: tkinter mutliplying the price from table
has comment: http://stackoverflow.com/comment/87674782
has body: I am making a simple program for cafe management system that reads food names as a buttons from a table also I want to read the the food price from the table and multiply it by the number of button clicks and then save them into a Text how I can do this please this is the image that show where are the two main isues are from tkinter import * from tkinter import ttk import sqlite3 import time import datetime import random variable = 1 bttn_clicks=0 button_dict = {} button_dic = {} conn = sqlite3.connect('hoteldb.db') c = conn.cursor() def showqurec(): global button,data2 data2 = readqurec() for index, dat in enumerate(data2): button= ttk.Button(master, text=dat[0],command=lambda dat=dat:update_count(dat)) button.grid(row=index+1, column=0,padx=0, pady=0) button_dict[dat] = button def showqado(): global button,data2 data2 = readqado() for index, dat in enumerate(data2): button = ttk.Button(master, text=dat[0],command=lambda dat=dat: update_count(dat)) button.grid(row=index+1, column=1,pady=0,padx=0) button_dict[dat] = button def showcasho(): global button,data2 data2 = readcasho() for index, dat in enumerate(data2): button=ttk.Button(master, text=dat[0],command=lambda dat=dat:update_count(dat)) button.grid(row=index+1, column=2,padx=0, pady=0) button_dict[dat] = button def readfromdatabase(): cur.execute("SELECT qureec.name,qado.name,casho.name FROM qureec,qado,casho") return cur.fetchall() def readqurec(): cur.execute("SELECT name FROM qureec ") return cur.fetchall() def readqado(): cur.execute("SELECT name FROM qado ") return cur.fetchall() def readcasho(): cur.execute("SELECT name FROM casho ") return cur.fetchall() def update_count(x): global bttn_clicks,my_text,price my_text=StringVar() for name in data2: my_text = button_dict[x].cget('text') bttn_clicks += 1 def Receipt(): txtReceipt.delete("1.0", "4.0") x = random.randint(10908, 500876) randomRef = str(x) Receipt_Ref.set("BILL" + randomRef) txtReceipt.insert("1.0", 'Receipt Ref: \t\t\t'+Receipt_Ref.get()+"\t\t"…
type: Question
has comment: http://stackoverflow.com/comment/87692589
has comment: http://stackoverflow.com/comment/87673269
tagged with: tkinter
has comment: http://stackoverflow.com/comment/87671335
downvote count: 0
answer count: 1

http://stackoverflow.com/q/50333866
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87684303
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/49882785
has comment: http://stackoverflow.com/comment/87684945
has comment: http://stackoverflow.com/comment/87684204
upvote count: 7
has answer: http://stackoverflow.com/a/50334197
favorite count: 0
has comment: http://stackoverflow.com/comment/87684378
type: Question
has comment: http://stackoverflow.com/comment/87684552
has comment: http://stackoverflow.com/comment/87684376
has comment: http://stackoverflow.com/comment/87684503
has comment: http://stackoverflow.com/comment/87684291
has comment: http://stackoverflow.com/comment/87684661
tagged with: pandas
possible better answer: http://stackoverflow.com/a/50335890
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/50335890
has title: Why does isinstance return the wrong value only inside a series map?
accepted answer: http://stackoverflow.com/a/50334197
has body: A call to isinstance returns True outside but False inside a map over a series (and an applymap over a dataframe)... import pandas as pd import pytz s = pd.Series([pd.Timestamp(2018,5,11,6,0,0,0, pytz.timezone('UTC'))]) s 0 2018-05-11 06:00:00+00:00 dtype: datetime64[ns, UTC] A call to isinstance for the single value in this series yields True. isinstance(s.iloc[0], pd.Timestamp) True Inside a map over the series it gives True. s.map(lambda x: isinstance(x, pd.Timestamp)).iloc[0] True But if we try something contingent on that value, say convert to a string... s.map(lambda x: x.isoformat() if isinstance(x, pd.Timestamp) else x).iloc[0] Timestamp('2018-05-11 06:00:00+0000', tz='UTC') ...it appears to have returned False and the method isoformat is not called (The actual method call is irrelevant because its not called).

http://stackoverflow.com/comment/88111124
type: Comment
type: QuestionComment
has text: This sounds like a simple problem but please add a clearer description of the structure of your data, or better yet add some sample data so we can propose relevant solutions
comment on: http://stackoverflow.com/q/50358870
score: 0

http://stackoverflow.com/a/76857639
has comment: http://stackoverflow.com/comment/135494235
answers question: http://stackoverflow.com/q/50252251
upvote count: 2
has comment: http://stackoverflow.com/comment/135497617
has comment: http://stackoverflow.com/comment/135497743
downvote count: 0
has comment: http://stackoverflow.com/comment/135497709
has comment: http://stackoverflow.com/comment/135497132
has comment: http://stackoverflow.com/comment/135496683
has comment: http://stackoverflow.com/comment/135494327
has comment: http://stackoverflow.com/comment/135495701
score: 2
has comment: http://stackoverflow.com/comment/135497786
has comment: http://stackoverflow.com/comment/135497401
type: Answer
has body: Not sure if this is a good idea (see the comments under your question), but here is what you could try to do to achieve what you want to: Provide a custom decoder that mangles your escaped sequences before decoding and a custom encoder that reverts the mangling after encoding. Here is a version that mangles the escape sequences by escaping them once more. It works for your specific example but will break for many others (see the comments under this answer, as well) – which brings me back to the first sentence (Not sure if this is a good idea …). import json import re class EscapeDecoder(json.JSONDecoder): def decode(self, s): s = re.sub(r"\\u([0-9a-f]{4})", r"\\\\u\1", s, flags=re.IGNORECASE) return super().decode(s) class EscapeEncoder(json.JSONEncoder): def encode(self, o): s = super().encode(o) return re.sub(r"\\\\u([0-9a-f]{4})", r"\\u\1", s, flags=re.IGNORECASE) example=r""" { "command": "python -m spacy download en \u0026\u0026 python -m spacy download de \u0026\u0026 python main.py" } """ json_example=json.loads(example, cls=EscapeDecoder) dumped = json.dumps(json_example, cls=EscapeEncoder, indent=4) assert(example[1:-1] == dumped) # strip leading and trailing line break for assertion to work And here is version that is a bit more robust, as it tries to avoid escape characters in the Python representation of the loaded dictionary altogether. It comes with the caveat that the mangled sequences must not be present in the original string: import json class ReplaceDecoder(json.JSONDecoder): def decode(self, s): assert "[s]" not in s and "[u]" not in s return super().decode(s.replace(r"\\", "[s]").replace(r"\u", "[u]")) class ReplaceEncoder(json.JSONEncoder): def encode(self, o): return super().encode(o).replace("[u]", r"\u").replace("[s]", r"\\") example=r""" { "command": "python -m spacy download \\u en \u0026\u0026 python -m spacy download de \u0026\u0026 python main.py" } """ json_example=json.loads(example, cls=ReplaceDecoder) dumped = json.dumps(json_exampl…
has comment: http://stackoverflow.com/comment/135543421
has comment: http://stackoverflow.com/comment/135497396

http://stackoverflow.com/a/50255717
answers question: http://stackoverflow.com/q/50255668
score: 2
upvote count: 2
downvote count: 0
has body: x = np.linspace(0,1,11) x[x&lt;0.5]*=2 x[x&gt;=0.5]+=1
type: Answer

http://stackoverflow.com/comment/87679232
type: QuestionComment
has text: It's like a football match. First half (1 - 45th minute), second half (46th - 90th minute)
type: Comment
comment on: http://stackoverflow.com/q/50331541
score: 1

http://stackoverflow.com/comment/88240778
score: 0
type: AnswerComment
has text: Thanks for the answer!! Actually, my problem was initializing the weights too small.
type: Comment
comment on: http://stackoverflow.com/a/50283225

http://stackoverflow.com/a/50362715
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87744118
answers question: http://stackoverflow.com/q/50341847
has comment: http://stackoverflow.com/comment/87744157
has comment: http://stackoverflow.com/comment/87777963
type: Answer
accepted answer of: http://stackoverflow.com/q/50341847
has body: There are two things that come to mind: 1) Your "start a fresh session" request might be getting rejected by the downloader: By default, it filters URLs that it's already seen, such as your base url. Try yield scrapy.Request(callback=self.parse, url = self.base_url, dont_filter=True, headers='') in your "reset the session request" 2) If that doesn't work (or perhaps in addition to): I'm pretty new to Scrapy and Python, so there might be a more direct method to "reset your cookies" but specifying a fresh cookiejar should work. https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#multiple-cookie-sessions-per-spider The cookiejar is essentially a dict-like object that is tracking your current session's cookies. You can specify the cookiejar key by using meta. # Set up a new session if bad news: if (len(rows) &lt; 50 and self.count != self.numberOfPages): self.log('Deficient rows. Resubmitting') yield scrapy.Request( callback=self.parse, url=self.base_url, dont_filter=True, meta={ # Since you are already tracking a counter, # this might make for a reasonable "next cookiejar id" 'cookiejar': self.count } ) Now that you are specifying a new cookiejar, you are in a new session. You must take account for this in your other requests, checking whether a cookiejar is set, and continuing to pass this value. Otherwise you end up back in the default cookiejar. It might be easiest to manage this expectation from the very beginning by defining start_requests: def start_requests(self): return [ scrapy.Request( url, dont_filter=True, meta={'cookiejar': self.count} ) for url in self.start_urls ] Now your other request objects just need to implement the following pattern to "stay in the same session", such as in your parse method: yield scrapy.FormRequest( url = self.base_url, formdata = frmdata, callback = self.parse_index, meta={ 'cookiejar': response.meta.get('cookiejar') } )
has comment: http://stackoverflow.com/comment/87780088
upvote count: 2
score: 2

http://stackoverflow.com/q/50330601
favorite count: 0
has title: 'cv2.FlannBasedMatcher' object has no attribute 'knnMatches'
type: Question
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
tagged with: opencv
score: 0
has body: The code is for the implementation of a SIFT-based algorithm with FLANN matcher on a captured image from the webcam. The error for some reason is in the knnMatch where we deal with the captured image. The attached image link shows the error causing line. It would be great if someone could provide some solution to this issue, please comment below for specific details. import cv2 import numpy as np MIN_MATCH_COUNT = 30 detector = cv2.xfeatures2d.SIFT_create() FLANN_INDEX_KDITREE = 0 flannParam = dict(algorithm=FLANN_INDEX_KDITREE,tree=5) searchParam = dict(check = 50) flann=cv2.FlannBasedMatcher(flannParam,searchParam) trainImg=cv2.imread("E:\\EXCHANGE_Courses\\training_img1.jpg") trainImg1 = cv2.cvtColor(trainImg,cv2.COLOR_BGR2GRAY) trainKP,trainDecs = detector.detectAndCompute(trainImg1,None) cam = cv2.VideoCapture(1) print(cam.isOpened()) for i in range(1): return_value, image = cam.read() cv2.imwrite('capture'+str(i)+'.jpg', image) del(cam) while True: QImage = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) queryKP,queryDesc = detector.detectAndCompute(QImage,None) # Now match the key descriptions from the training image and the query image # np.asarray(des1,np.float32),np.asarray(des2,np.float32),k=2 # queryDesc,trainDecs, k=2 matches=flann.knnMatches(queryDesc,trainDecs, k=2) print("upper part clear") # Filter the pool of keypoints as we need to collect the key points of interest only with the object in mind goodMatch=[] for m,n in matches: if(m.distance<0.75*n.distance): goodMatch.append(m) print("all ok here") if(len(goodMatch)>MIN_MATCH_COUNT): tp=[] qp=[] for m in goodMatch: tp.append(trainKP[m.trainIdx].pt) qp.append(queryKP[m.queryIdx].pt) tp,qp = np.float32((tp,qp)) H,status = cv2.findHomography(tp,qp,cv2.RANSAC,3.0) h,w=trainImg.shape trainBorder = np.float32([[[0,0],[0,h-1],[w-1,h-1],[0,w-1]]]) queryBorder = cv2.perspectiveTransform(trainBorder,H) # changed QImageBGR to image cv2.polylines(QImage,[np.uint8(queryBorder)],True,(0,255,0),3) else: print("Not enough…
has answer: http://stackoverflow.com/a/51344449
tagged with: spyder
tagged with: image-processing
tagged with: image
downvote count: 1

http://stackoverflow.com/comment/87501310
type: QuestionComment
comment on: http://stackoverflow.com/q/50241395
score: 0
has text: Can you help me the loop, couldn't get it.
type: Comment

http://stackoverflow.com/a/56892555
score: 4
has body: I tried numpy.vectorize but it gave 'Memory Error' for huge dataframe. The below code worked perfectly for me. It will give you a list of maximum lengths for each column in an excel spreadsheet (read into a dataframe using pandas) import pandas as pd xl = pd.ExcelFile('sample.xlsx') df = xl.parse('Sheet1') maxColumnLenghts = [] for col in range(len(df.columns)): maxColumnLenghts.append(max(df.iloc[:,col].astype(str).apply(len))) print('Max Column Lengths ', maxColumnLenghts)
answers question: http://stackoverflow.com/q/50339065
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/50274643
has comment: http://stackoverflow.com/comment/87566400
has comment: http://stackoverflow.com/comment/87645647
score: 0
has body: I am a beginner in python having trouble when scraping a table. My desired goal is not to have any empty space in the output. My code: import requests from bs4 import BeautifulSoup # I am only interested in some particular blocks from the bitcoin blockchain url = "https://blockchain.info/block-height/521578" # Getting table from the url response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") stat_table = soup.find_all('table', class_ = 'table table-striped') stat_table = stat_table[0] for row in stat_table.find_all("tr"): for cell in row.find_all("td")[1:]: # look that I am interested only in the 2nd column print(cell.text) With the previous code I get the following as result: 521578 (Main chain) 0000000000000000002809c9ae7546964580751b506e070f15002b1c1fdd66b3 0000000000000000002d4f2f654945fda08931355e9af871a8c2135a25da9cb6 00000000000000000023583cc0df49783e50c93d807c405524168016c84c0c2a 2018-05-07 06:56:50 2018-05-07 06:56:50 BTC.com 4,022,059,196,164.95 390462291 452 5,440.06056147 BTC 233.87351861 BTC 342.123 KB 0x20000000 ee7c7e2cde5e0f3567c9f635549ec62365e2ac45da517f41cf6c32787c3d8b4d 3688672863 12.5 BTC 0.11100607 BTC But those blank lines are causing me trouble when I want to save a .csv file afterwards. Do you know how to get rid of those blank lines? If I make a small change in the code I get the data as I want except that not the column I need (I need only the second column): for row in stat_table.find_all("tr"): for cell in row.find_all("td")[:1]: # Here is the change print(cell.text) Output with the change (look there are no empty lines, but not in the column I need): Height Hash Previous Block Next Blocks Time Received Time Relayed By Difficulty Bits Number Of Transactions Output Total Estimated Transaction Volume Size Version Merkle Root Nonce Block Reward Transaction Fees Thanks in advance
tagged with: web-scraping
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/50274733
tagged with: python
type: UnansweredQuestion
has title: scraping table with undesirable blank lines in python

http://stackoverflow.com/q/50285863
has body: Friends, I'm struggling in opening specific tab of a Microstrategy dashboard where the name of dashboard is in form of image. Here is the HTML code of the header on which i need to click. M using selenium web driver in python. Please suggest:- &lt;img src="./Images/DSI Images/NewWeb/Active_/Home.png" style="width:144px;height:48px;" onclick="mstrmojo.dom.captureDomEvent('*lK36*kK258*x1*t1526016913721','click', self, event)"&gt; I tried following ways but not working:- Scenario 1:- In this scenario code is coming till "print("wait over")" but post that it fails print("waiting...") sleep(15) print("wait over") home_element = driver.find_element_by_xpath("//*[@id='*lK36*kK258*x1*t1525928239926']/div") home_element.click() Scenario 2:- driver.execute_script("document.getElementById('*lK36*kK258*x1*t1525928239926').getElementsByTagName('img')[0].click()") Scenario 3:- WebDriverWait(driver,10).until(driver.find_element_by_xpath("//img[contains(@src,'DSI Images/NewWeb/Active_/Home')]").element_to_be_clickable) Scenario 4:- shared_reports_button = driver.find_element(By.XPATH("//img[@src='./Images/DSI Images/NewWeb/Active_/Home.png']")) shared_reports_button.click() Scenario 5:- driver.find_elements_by_link_text('./Images/DSI Images/NewWeb/Inactive_/Home.png').click() Scenario 6:- driver.find_element_by_css_selector("a[href='./Images/DSI Images/NewWeb/Inactive_/Home.png')."])).click(); Scenario 7:- WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='mstrmojo-DocImage hasLink']/img src[@class='./Images/DSI Images/NewWeb/Active_/Home.png']"))).click()
upvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50293522
score: -1
has comment: http://stackoverflow.com/comment/87595589
downvote count: 1
tagged with: selenium-webdriver
tagged with: css-selectors
answer count: 1
tagged with: selenium
has title: Unable to click on a .png image link
favorite count: 0
type: Question
tagged with: xpath

http://stackoverflow.com/a/50284732
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87585696
has comment: http://stackoverflow.com/comment/87585874
has comment: http://stackoverflow.com/comment/87585671
accepted answer of: http://stackoverflow.com/q/50284708
type: Answer
answers question: http://stackoverflow.com/q/50284708
downvote count: 0
has body: What you have is a list of dictionaries within a dictionary. You can sort these dictionaries using standard list sorting methods: d={'records':[{'name':'abhi','age':23,'dept':'cse'}, {'name':'anu','age':20,'dept':'ece'}, {'name':'ammu','age':25,'dept':'cse'}, {'name':'anju','age':26,'dept':'ece'}]} d['records'].sort(key = lambda x: x['name']) &gt;&gt;&gt; d['records'] [{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}, {'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}] For your particular case: d['records'].sort(key = lambda x: (x['name'], x['dept'])) And then a list comprehension to group sublists with the same dept together: my_list = [[i for i in d['records'] if i['dept'] == de] for de in {i['dept'] for i in d['records']}] &gt;&gt;&gt; my_list [[{'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}], [{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}]]

http://stackoverflow.com/comment/129855471
has text: [Kendall distance](https://en.wikipedia.org/wiki/Kendall_tau_distance) is not to be confused with [Kendall rank coefficient](https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient) (distance of 0 is the same as rank coefficient of 1, distance of 1 is the same as rank coefficient -1).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50250300
type: Comment

http://stackoverflow.com/comment/87507663
type: AnswerComment
comment on: http://stackoverflow.com/a/50244735
has text: @Lemayzeur For sure — I agree personally. I think having both your direct answer and my indirect answer are helpful to future people stumbling upon this question with a query like OP's.
type: Comment
score: 0

http://stackoverflow.com/a/50320827
upvote count: 5
type: Answer
has body: Here is one way, reindexing each user to have a date range from your minimum date to your maximum date: # setup your dataframe as you had it before: x = pandas.DataFrame({'user': ['a','a','b','b','a'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06','2016-01-06'], 'val': [1,33,2,1,2]}) udates=x['dt'].unique() x['dt'] = pandas.to_datetime(x['dt']) # fill with new dates: filled_df = (x.set_index('dt') .groupby('user') .apply(lambda d: d.reindex(pd.date_range(min(x.dt), max(x.dt), freq='D'))) .drop('user', axis=1) .reset_index('user') .fillna(0)) &gt;&gt;&gt; filled_df user val 2016-01-01 a 1.0 2016-01-02 a 33.0 2016-01-03 a 0.0 2016-01-04 a 0.0 2016-01-05 a 0.0 2016-01-06 a 2.0 2016-01-01 b 0.0 2016-01-02 b 0.0 2016-01-03 b 0.0 2016-01-04 b 0.0 2016-01-05 b 2.0 2016-01-06 b 1.0
accepted answer of: http://stackoverflow.com/q/50320709
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/87657708
answers question: http://stackoverflow.com/q/50320709
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87657739

http://stackoverflow.com/q/50264879
upvote count: 2
score: 1
tagged with: file
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87573167
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: How can I import .trc files in python?
has body: I recently imported .trc files and can't open them on my python terminal. Is there any way to do it? If not, is there any way to convert .trc files into .csv?
tagged with: oscilloscope
answer count: 0

http://stackoverflow.com/comment/87682791
type: QuestionComment
has text: I'm voting to close this question as off-topic because OP thinks it should be deleted and IMHO it has little value for the community.
score: 4
comment on: http://stackoverflow.com/q/50333263
type: Comment

http://stackoverflow.com/a/50343564
type: Answer
has body: I am going to guess that it is the tf.concat of self.B... Because every time the function runs it concatenates self.B bigger and bigger. You can check which tensor is causing the memory error by printing its size on each iteration.
answers question: http://stackoverflow.com/q/50338209
score: 0

http://stackoverflow.com/a/50371145
type: Answer
answers question: http://stackoverflow.com/q/50370327
has body: By results, if you mean Error Rate or some Evaluation Metric Improvement. Here maybe some guidelines. Let us make it clear that Error = 100 - Evaluation Metric. If your accuracy is 99%, that means your Error is 1% (GOOD). If your accuracy is 85%, your error is 15% (NOT TOO GOOD. IT DEPENDS) If your Train Error is very high (Test Error = 16%, Train Error = 15%): You have a problem with BIAS. You need to get a BIGGER/DEEPER neural network with more layers, train using gradient descent for more number of iterations or just try a different neural network architecture (CNN, RNN). If your Test Error is much higher than your Train Error (Test Error = 11%, Train Error = 1%): It means you have a VARIANCE problem. You need to get more training data, and apply regularization or just try a different neural network architecture (CNN, RNN). If both Train Error as well as Test Error is high (Train Error: 15%, Test Error: 16%, then you have both HIGH BIAS and HIGH VARIANCE, you need to do both of what I told you above. To see if you have a BIAS problem, look at the Training Set Performance. To see if you have a VARIANCE problem, look at your Dev Set/Test Set Performance. More importantly, You need to understand, Bayes Error or Human Level Performance. If 15% is Bayes Error, meaning that NO MACHINE LEARNING ALGORITHM can do better than 15%, and if your Training Error is 16%, it means there is very little room for improvement in terms of fixing BIAS.
score: 0

http://stackoverflow.com/comment/87589981
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50286308
type: Comment
has text: Yes, that will be more likely to happen, although how will I be able to bring the other columns of **wb2.xlsx** to new excel file?

http://stackoverflow.com/q/50343137
has answer: http://stackoverflow.com/a/50343333
accepted answer: http://stackoverflow.com/a/50343315
possible better answer: http://stackoverflow.com/a/50343333
has comment: http://stackoverflow.com/comment/87702679
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87702225
has comment: http://stackoverflow.com/comment/87702233
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87702318
has comment: http://stackoverflow.com/comment/87704297
has comment: http://stackoverflow.com/comment/87702299
has comment: http://stackoverflow.com/comment/87702950
tagged with: python
score: -1
tagged with: sorting
has comment: http://stackoverflow.com/comment/87702752
tagged with: dictionary
has answer: http://stackoverflow.com/a/50343315
has title: What is the best way to trim a dictionary after sorting?
has comment: http://stackoverflow.com/comment/87702444
has comment: http://stackoverflow.com/comment/87702510
has comment: http://stackoverflow.com/comment/87702306
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87703311
has comment: http://stackoverflow.com/comment/87702277
downvote count: 3
has body: I want to reduce the number of items in a dictionary. So I need to trim dictionary after sorting by value. My question is how? So I to trim this dict so only the top TWO entries are retained— base_dic={'Cs':0,5, 'Cp':0.3, 'Os':0.6, 'Op': 0.9} I've tried— dict(sorted(base.items(), key=lambda x: x[1], reverse=True)[:2]) But is this the best way? And to display or compare the values in dictionary, is there smart way to ordering by value? Note that it is not just sorting of values, it is sorting of dictionary using values. I want to have only a few elements with maximum values. That is, from base={'Cs':0,5, 'Cp':0.3, 'Os':0.6, 'Op': 0.9, .... 100 elements} to such as base={'Op': 0.99, 'Nid': 0.97} Effectively retaining only the top TWO elements and discarding the rest.

http://stackoverflow.com/q/50322750
tagged with: python
accepted answer: http://stackoverflow.com/a/50331261
tagged with: google-bigquery
answer count: 4
has answer: http://stackoverflow.com/a/50331261
type: Question
has title: BigQuery Invalid dataset ID
has answer: http://stackoverflow.com/a/63236629
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/63250393
favorite count: 0
type: AnsweredQuestion
has body: I used to query in UI This time, I'm in cloud shell, and try to access my dataset and table through python from google.cloud import bigquery client = bigquery.Client() dataset_id = 'mytest-0001:reports_test' table_id = 'test_data' dataset_ref = client.dataset(dataset_id) dataset = client.get_dataset(dataset_ref) table_ref = dataset_ref.table(table_id) table = client.get_table(table_ref) print('Dataset ID: '.format(dataset_id)) print('Description: '.format(dataset.description)) print(table.schema) print(table.description) print(table.num_rows) I got some the error below... google.api_core.exceptions.BadRequest: 400 GET https://www.googleapis.com/bigquery/v2/projects/gcd-my-reporting/datasets/mytest-0001:reports_test: Invalid dataset ID "mytest-0001:reports_test". Dataset IDs must be al phanumeric (plus underscores, dashes, and colons) and must be at most 1024 characters long. With some reason I can't modified the dataset id, Any idea to fixed this?
possible better answer: http://stackoverflow.com/a/50323289
has answer: http://stackoverflow.com/a/50323289
upvote count: 6

http://stackoverflow.com/comment/87697759
has text: @Kalyan - the group_size is actually set based I am dividing people into quartiles and making groups from 1 person per quartile. However, because I won't necessarily have multiples of four in number of people, not all the groups might be of size 4. In the event that there are less than 4 people, there's logic elsewhere to handle that.
score: 0
comment on: http://stackoverflow.com/q/50340463
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50373288
answers question: http://stackoverflow.com/q/50369082
has body: You can parse tables to a template using: This example is made with pandas, but I hope to help you. Having a table like this: ipdst proto time count 10.3.20.102 HTTP 2017-03-20 17:08:56 1 10.3.20.102 HTTP 2017-03-20 17:08:57 1 10.3.20.102 HTTP 2017-03-20 17:08:58 1 10.3.20.102 HTTP 2017-03-20 17:08:58 1 10.3.20.102 TCP 2017-03-20 17:08:59 3 app.py import pandas as pd from sqlalchemy import create_engine import datetime as dt disk_engine = create_engine('sqlite:///test.db') df = pd.read_sql_query('SELECT * FROM data', disk_engine) @app.route('/') def index(): return render_template('index.html', tables=[df.to_html()], titles=['ipdst', 'proto']) if __name__ == '__main__': app.run(debug= True) templates/index.html &lt;div class=page&gt; {% for table in tables %} {% endfor %} &lt;/div&gt;
score: 0
type: Answer

jupyter
tags question: http://stackoverflow.com/q/50356884
tags question: http://stackoverflow.com/q/50378092
tags question: http://stackoverflow.com/q/50287990
tags question: http://stackoverflow.com/q/50367191
type: Tag
tags question: http://stackoverflow.com/q/50316719
tags question: http://stackoverflow.com/q/50333757
tags question: http://stackoverflow.com/q/50289615
tags question: http://stackoverflow.com/q/50378870
tags question: http://stackoverflow.com/q/50243667
tags question: http://stackoverflow.com/q/50268442
tags question: http://stackoverflow.com/q/50256440
tags question: http://stackoverflow.com/q/50274978
tag name: jupyter
tags question: http://stackoverflow.com/q/50304519

http://stackoverflow.com/q/50301907
answer count: 1
has answer: http://stackoverflow.com/a/50301954
accepted answer: http://stackoverflow.com/a/50301954
favorite count: 0
type: Question
has title: How to take average of one column in dataframe but for every 5 min from datetimestamp column?
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe that looks like this: Event time Event type Ignore Price 0 1526076933917 kline 0 18202362 1 1526076937493 kline 0 18202367 I convert the 'Event time' column to human readable format with this line: df['Event time'] = pd.to_datetime(df['Event time'], unit='ms') Now dataframe looks like this: Event time Event type Ignore Price 0 2018-05-11 22:15:33.917 kline 0 18202362 1 2018-05-11 22:15:37.493 kline 0 18202367 From here how do I take the average of 'Price' for every 5 min from the 'Event time' column and keep all the other columns the same?
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/comment/87634238
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50307042
has text: after some more investigation, there is an option in Django you can set: CONN_MAX_AGE that is supposed to make connections persist, but for some reason has no effect.

http://stackoverflow.com/q/50294764
score: 0
has comment: http://stackoverflow.com/comment/87607693
accepted answer: http://stackoverflow.com/a/50464988
answer count: 1
has comment: http://stackoverflow.com/comment/87705583
has answer: http://stackoverflow.com/a/50464988
has body: I'm trying to make a SOAP client in python using zeepSo far I've had zero luck in trying to get it to run. I keep getting the following error. Traceback (most recent call last): File "C:/Users/z905/PycharmProjects/Soap_Test/soap_test.py", line 14, in &lt;module&gt; client = Client(wsdl=client_location, transport=transport_with_basic_auth) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\client.py", line 134, in __init__ self.wsdl = Document(wsdl, self.transport, strict=strict) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 81, in __init__ root_definitions = Definition(self, document, self.location) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 178, in __init__ self.parse_imports(doc) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 270, in parse_imports document = self.wsdl._get_xml_document(location) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\wsdl\wsdl.py", line 140, in _get_xml_document location, self.transport, self.location, strict=self.strict) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\loader.py", line 72, in load_external content = transport.load(url) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\transports.py", line 110, in load content = self._load_remote_data(url) File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\zeep\transports.py", line 126, in _load_remote_data response.raise_for_status() File "C:\Users\z905\PycharmProjects\Soap_Test\venv\lib\site-packages\requests\models.py", line 935, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden (Forbidden port) for url: http://url:7104 I've tried the program with and without basic authentication. from zeep import Client from requests import Session from requests.auth im…
has comment: http://stackoverflow.com/comment/87606656
has comment: http://stackoverflow.com/comment/87606462
tagged with: zeep
type: AnsweredQuestion
has title: python SOAP with zeep, requests.exception: 403 client error
tagged with: soap
tagged with: python
type: Question

http://stackoverflow.com/q/50266075
tagged with: python
has comment: http://stackoverflow.com/comment/87550236
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87550320
tagged with: pip
linked to: http://stackoverflow.com/q/49748063
has comment: http://stackoverflow.com/comment/87551408
has comment: http://stackoverflow.com/comment/87554225
type: Question
tagged with: python-3.x
has title: unable to install libraries with pip3
type: UnansweredQuestion
has body: Could not find a version that satisfies the requirement Flask (from versions: ) No matching distribution found for Flask Not just Flask, i am not able to install anything with pip3. How to fix this?

http://stackoverflow.com/q/50350404
tagged with: python
has answer: http://stackoverflow.com/a/50350553
has comment: http://stackoverflow.com/comment/87716661
favorite count: 0
type: Question
answer count: 2
has body: I have a dictionary that has another dictionary as its value and that another dictionary has a list as its value. For example, {'A' : {'a' : ['1', '2', '3'], 'b' : ['4', '5'], 'c' : ['6']}, 'B' : {'a' : ['7'], 'b' : ['8', '9']}} I want to make a Pandas DataFrame which has A, B as indices, a, b, c as columns. What I did is: df = pd.DataFrame.from_dict(dictionary, orient='index') df.describe() But I got an error saying: TypeError Traceback (most recent call last) &lt;ipython-input-6-88dc07bc979e&gt; in &lt;module&gt;() 6 df = pd.DataFrame.from_dict(dict_data, orient='index') ----&gt; 7 df.describe() # print df C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in describe(self, percentiles, include, exclude) 6825 data = self.select_dtypes(include=include, exclude=exclude) 6826 -&gt; 6827 ldesc = [describe_1d(s) for _, s in data.iteritems()] 6828 # set a convenient order for rows 6829 names = [] C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in &lt;listcomp&gt;(.0) 6825 data = self.select_dtypes(include=include, exclude=exclude) 6826 -&gt; 6827 ldesc = [describe_1d(s) for _, s in data.iteritems()] 6828 # set a convenient order for rows 6829 names = [] C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in describe_1d(data) 6808 return describe_numeric_1d(data) 6809 else: -&gt; 6810 return describe_categorical_1d(data) 6811 6812 if self.ndim == 1: C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in describe_categorical_1d(data) 6782 def describe_categorical_1d(data): 6783 names = ['count', 'unique'] -&gt; 6784 objcounts = data.value_counts() 6785 count_unique = len(objcounts[objcounts != 0]) 6786 result = [data.count(), count_unique] C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\base.py in value_counts(self, normalize, sort, ascending, bins, dropna) 869 from pandas.core.algorithms import value_counts 870 result = value_counts(self, sort=sort, ascending=ascending, --&gt; 871 normalize=normalize, bi…
has answer: http://stackoverflow.com/a/50350487
type: UnansweredQuestion
has title: Pandas Unhashable type : 'list' when using describe()
linked to: http://stackoverflow.com/q/33169701
downvote count: 2
upvote count: 5
tagged with: pandas
score: 3

http://stackoverflow.com/comment/117189676
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50288573
has text: hello @SiddharthMungekar, I believe I have the same problem as you. If I manually try to run the macro it works. If I try to call it using Python an com_error is raised. Did you find a way to get over it?

cplex
tags question: http://stackoverflow.com/q/50309588
tag name: cplex
type: Tag

http://stackoverflow.com/a/50319027
answers question: http://stackoverflow.com/q/50318613
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87663072
score: 2
has body: With a bit of recursion and a dict that can be done like: Code: def build_dir_dict(dir_name_strings): def _build_dir_dict(path_pieces, dir_dict): print(path_pieces) if path_pieces: if not path_pieces[0]: _build_dir_dict(path_pieces[1:], dir_dict) else: if path_pieces[0] not in dir_dict: dir_dict[path_pieces[0]] = {} _build_dir_dict(path_pieces[1:], dir_dict[path_pieces[0]]) result = {} for dir_name_string in dir_name_strings: if dir_name_string: _build_dir_dict(dir_name_string.split('/'), result) return result Test Code: data = [x.strip() for x in """ dir1 dir1/dir1.1 dir1/dir1.2 dir1/dir1.3/dir1.3.1/dir1.3.1.1 dir1/dir1.1/dir1.1.1 dir1/dir1.1/dir1.1.2 """.split('\n')[1:-1]] print(build_dir_dict(data)) Results: {'dir1': {'dir1.1': {'dir1.1.1': {}, 'dir1.1.2': {}}, 'dir1.2': {}, 'dir1.3': {'dir1.3.1': {'dir1.3.1.1': {}}} } }

http://stackoverflow.com/q/50321879
type: Question
has title: How can FastCGI service access the wfastcgi.py file from python(root)/site-packages/wfastcgi/wfastcgi.py location
has comment: http://stackoverflow.com/comment/87661891
has comment: http://stackoverflow.com/comment/87664017
tagged with: python
has body: I was able to configure the FastCGI service so that whenever the client requests any call it will create only one process and serve all the requests. This service is working only If the wfastcgi.py file present in python root directory. If I install that python module (wfastcgi) using pip install wfastcgi, it will go to python(root)/site-packages/wfastcgi/wfastcgi.py file. If I specify the above path (python(root)/site-packages/wfastcgi/wfastcgi.py) in web.config file, it is not taking it. default IIS/FastCGI error is throwing by saying that... 500 Internal Server error: &lt;handler&gt; scriptProcessor could not be found in &lt;fastCGI&gt; application configuration We wanted to place this file in the installed directory itself meaning under site-packages. My question here is how can we specify the site-packages location to the FastCGI service (There are no folder permission errors).
score: 0
has comment: http://stackoverflow.com/comment/87668398
answer count: 0
type: UnansweredQuestion
tagged with: iis
tagged with: fastcgi
tagged with: cgi
has comment: http://stackoverflow.com/comment/87660719

http://stackoverflow.com/a/50255972
has body: When you don't get the results you expect from your code, you need to backtrack to figure out where your code broke. In this case, your first step would be to check the value of table. As it turns out, table is not None (which would signify a bad selector/soup.find call), so you at least know that you got that much right. Instead, what you'll notice is that the table_flex div is empty. This isn't terribly surprising to me, but let's pretend I don't know anything and this doesn't make any sense. So the next step would be to pull up a browser and to double check that the DOM (via your browser's inspect tool) has content in the table_flex div. It does, so now you have to do some real digging. If you run a simple search on the DOM in the inspect window for "table_flex", you'll first see the div that we already know about, but then you'll see some Javascript/jQuery further down the page that references "#table_flex". This Javascript is part of a $.ajax() call (which you would google and find out is basically a query to a webserver for information). You'll also note that $("#table_flex") has an html() method (which, after more googling, you find out sets the html content for a particular element). And now we have your answer for why the div is empty: when the webserver is queried for that page, the server sends back a document that has a blank table. The querying party is then expected to execute the Javascript to fill in the rest of the page. Generally speaking, Python modules don't run Javascript (for several reasons), so the table never gets populated. This tends to be standard operating procedure for dynamic content, as "template" webpages can be cached and quickly distributed (since no additional information is needed) and then the rest of the information is supplied as the user needs it. This can also allow the same document to be used for multiple urls and query arguments without having to generate new documents. Ultimately, what will probably be easiest for you is…
answers question: http://stackoverflow.com/q/50232555
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50232555

jquery
tags question: http://stackoverflow.com/q/50286355
tags question: http://stackoverflow.com/q/50369644
tags question: http://stackoverflow.com/q/50313153
type: Tag
tag name: jquery
tags question: http://stackoverflow.com/q/50276076
tags question: http://stackoverflow.com/q/50244957
tags question: http://stackoverflow.com/q/50296210
tags question: http://stackoverflow.com/q/50271267
tags question: http://stackoverflow.com/q/50300189
tags question: http://stackoverflow.com/q/50359271
tags question: http://stackoverflow.com/q/50255366
tags question: http://stackoverflow.com/q/50350354
tags question: http://stackoverflow.com/q/50376556
tags question: http://stackoverflow.com/q/50367227

http://stackoverflow.com/comment/87632019
score: 0
has text: How can I be able to display the output of the salam expression when the user enters the hello entry? And so on for all the components of the dictionary
comment on: http://stackoverflow.com/q/50308026
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87738699
comment on: http://stackoverflow.com/q/50359885
type: QuestionComment
has text: Please clarify whether you meant "by date" rather than "by day" (day-of-week: Monday, Tuesday, or 0..6), as you wrote.
type: Comment
score: 0

http://stackoverflow.com/comment/87768529
type: AnswerComment
has text: Not an answer to the general question, but it is definitely a good solution in my particular case!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/50376052

http://stackoverflow.com/a/50244900
has comment: http://stackoverflow.com/comment/87509550
has comment: http://stackoverflow.com/comment/87508064
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/50244848
score: 5
has body: As per the python docs: Thread identifiers may be recycled when a thread exits and another thread is created. Without the sleep statement, add_arg is getting invoked and completed before the main thread loops around again. Hence, each time you create a new Python thread, it's simply using the system thread (or thread id) of the one that most recently completed the previous task. When you add the sleep statement, a new system thread (and new id) is needed to start the next task because the previous one has not completed.
answers question: http://stackoverflow.com/q/50244848
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50370478
downvote count: 0
answers question: http://stackoverflow.com/q/50370411
score: 1
has comment: http://stackoverflow.com/comment/87757134
type: Answer
has comment: http://stackoverflow.com/comment/87757214
upvote count: 1
has body: Probably something like (assuming y is a vowel) [BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz]{5}

http://stackoverflow.com/a/50377296
type: Answer
has body: Python List : https://www.tutorialspoint.com/python/python_lists.htm has a count method. I suggest you to first zip both lists, as said in comments, and then count occurances of tuple c, 1 and occurances of tuple c, 0 and sum them up, thats what you need for (I), basically. For (II), if I understood you correctly, you have to take the zipped lists and apply filter on them with lambda x: x[0]==x[1]
answers question: http://stackoverflow.com/q/50376528
score: 0

http://stackoverflow.com/a/50398950
downvote count: 0
answers question: http://stackoverflow.com/q/50376697
has comment: http://stackoverflow.com/comment/87814084
has comment: http://stackoverflow.com/comment/87853733
score: 2
has body: The code in example-2 actually works correctly. I just needed to format the response. print RecievedData.encode('hex') This will give the hex string in a modbus response format. As Andrej Debenjak alluded to time.sleep(x) will be dependent on baud rate and message size. Side note: I found this page helpful in deciphering the modbus transmission. http://www.modbustools.com/modbus.html Edit: The ByteString I'm sending should not work on a proper modbus setup. The first byte x00 is the broadcast byte and should not solicit a response. It seems the hardware I'm working with has something funky going on. In a typical modbus setup you would need to address which device you're trying to communicate with. Thanks Marker for pointing this out.
type: Answer
has comment: http://stackoverflow.com/comment/87839064
upvote count: 2

http://stackoverflow.com/comment/87587272
score: 0
has text: Here is the [fourth way](https://github.com/dynamsoft-dbr/raspberrypi-python-barcode). Good luck :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50269401

http://stackoverflow.com/comment/87747847
has text: I ran python -V, it's 3.6.3
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50365809

http://stackoverflow.com/comment/87707973
comment on: http://stackoverflow.com/q/50345708
has text: Can you give a specific input / output example? How the merged dataframe should look?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87598686
comment on: http://stackoverflow.com/a/50259673
score: 0
type: AnswerComment
has text: Thanks a lot. So the main difference between **1.** and **2.** is that **1.** would consider only the words that are part of the CountVectorizer's vocabulary whereas **2.** will keep any word of the corpus?
type: Comment

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/50328929
tags question: http://stackoverflow.com/q/50332525
tags question: http://stackoverflow.com/q/50248524
tag name: python-packaging

http://stackoverflow.com/a/50556852
has comment: http://stackoverflow.com/comment/88197382
answers question: http://stackoverflow.com/q/50309918
has body: I noticed that in your pseudocode, upon creating each new generation, the parent generation is completely wiped out and only the child generation is retained. This can naturally lead to lowering fitness levels, since there is nothing guaranteeing that the offspring will have fitness levels comparable to those in the parent generation. In order to ensure that the fitness levels are non-decreasing, you must either merge the parent and child generations and prune the weakest members (which I would recommend), or you can require that the offspring-generating function produces offspring at least as fit as the parents (by many trials and errors). If you decide to focus on the offspring-generator, one way to (somewhat) guarantee improved offspring is to implement asexual reproduction by way of simply adding a small amount of noise to each weight vector. If the noise level is small enough, you can generate improved offspring with a success rate of up to 50%. Bigger noise levels, however, allow faster improvement and they help to jump out of local optima, even if they have success rates lower than 50%.
type: Answer
has comment: http://stackoverflow.com/comment/88198044
has comment: http://stackoverflow.com/comment/88196695
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/88157072
downvote count: 0

http://stackoverflow.com/comment/87525830
type: QuestionComment
type: Comment
has text: Possible duplicate of [Remove whitespaces in XML string](https://stackoverflow.com/questions/3310614/remove-whitespaces-in-xml-string)
comment on: http://stackoverflow.com/q/50254171
score: 2

http://stackoverflow.com/a/50322434
answers question: http://stackoverflow.com/q/50322378
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/50322378
has comment: http://stackoverflow.com/comment/87660839
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87660692
has comment: http://stackoverflow.com/comment/87660685
has body: Let's try vectorizing this. Concatenate your DataFrames, call str.get_dummies and then sum along the index. df_list = [exampledf1, exampledf2] names = [name1, name2] (pd.concat(df_list, axis=0, keys=names) .animal .str.get_dummies() .sum(level=0) ) bird cat dog store1 2 3 1 store2 2 4 0 If your data isn't in the format of df_list &amp; names, I strongly recommend finding a way to get it there. The alternative is to call df.append per loop iteration. I consider this to be slow and ugly: df = pd.DataFrame() for d, n in zip(df_list, names): df = df.append( d.animal.value_counts().to_frame().T.set_index(n) ) df bird cat dog store1 2 3 1.0 store2 2 4 NaN

http://stackoverflow.com/q/50343886
possible better answer: http://stackoverflow.com/a/50344032
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/13147914
linked to: http://stackoverflow.com/q/7593611
has answer: http://stackoverflow.com/a/50343990
accepted answer: http://stackoverflow.com/a/50343990
type: Question
tagged with: python-3.x
has title: How to execute actions on web without GUI
tagged with: linux
has body: I will need to test few things from my linux server. I wonder if it is possible to manipulate some actions on web without access to browser. I have only access to linux server via command line. I know only selenium webdriver to do that actions but but for that I need browser. What I want to do: 1) Input text to textbox on webpage using python script which is placed on linux server 2) Click button on webpage Generally it is possible to manipulate actions on webpage from linux using python scripts?
has comment: http://stackoverflow.com/comment/87703566
has answer: http://stackoverflow.com/a/50344032

http://stackoverflow.com/q/50324921
tagged with: statistics
score: 0
has body: I want to compare some curves to a 'normality corridor', and I would like to show in what regions (x values) the difference is significant.Take the example below, where I want to compare the dashed lines with the green band: Each curve represents the median of some values. The curves are not continuous: they only have values at integer x locations, therefore I compare them to the normality corridor at 1, 2, 3, etc. For the "Width" group I want to show that the difference is significant between all curves and the green band between x=1 and x=3, then only two curves between 4 and 6, then only one curve between 7-8, then two curves etc etc etc... The problem is that I have 12 groups, each with 3 curves and its own normality corridor, and each of them with 17 levels (integer values of x). That makes for a lot of p-values. Here is what I came up with for the groups in the example, with the number of asterisks representing the p-value, but I think the message can be made clearer: TL;DR: How to represent local significant differences between curves and a normality corridor, OR how to represent lots of p-values? Edit: Already ask this question on Cross-Validated, but got no answers. Acknowledging this as per netiquette Edit 2: I will be implementing the plot in either Matlab or Python (hence the tags), but I could potentially implement a visual solution obtained in any other language.
answer count: 0
has comment: http://stackoverflow.com/comment/87667018
has comment: http://stackoverflow.com/comment/87666918
type: Question
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
has title: How to represent local significant differences between curves
tagged with: plot
tagged with: matlab

http://stackoverflow.com/q/50374865
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Django 1.11 authentication set_unusable_password vs setting password to None
favorite count: 0
type: Question
has body: My team has overwritten the authenticate method for users years ago to authenticate against LDAP instead of djangos model backend. this method looks at LDAP for the user. If the user exists with correct username and password, it gets or creates the user (This means that the user doesn't have to exist as a model object in the Django database for someone to log in). The method leaves the newly created password as None. Then sets all the other information. I noticed that they, after validating the user, call the set_unusable_password on the user if they were valid. In a comment, they wrote that it overrides Django's built-in password handling... which obviously that makes sense. But I don't know why they needed to since we've already overwritten the authenticate method. I tested this out by removing the set_unusable_password so that the password is left as None and the validation worked. They were still able to log in with the password that's stored on LDAP. You still could not overwrite the password in the model to be different than that on LDAP and login with that. So basically the set_unusable_password call had no effect other than just creating a password... which wasn't used anyways. the only thing I can think of is that it may be a solution to an issue that was in older versions of Django (we're now in 1.11). After spending much time in the source code and in documentation, I couldn't figure out why we need it. Why would that be there? The people that wrote it have left by now so I have no explanation for why they did it. If I remove that, would there be any unwanted side effects?
tagged with: ldap
score: 3
has answer: http://stackoverflow.com/a/50375103
tagged with: django-authentication
tagged with: django
tagged with: python
upvote count: 3

http://stackoverflow.com/q/50260321
answer count: 2
has answer: http://stackoverflow.com/a/64514628
type: UnansweredQuestion
tagged with: python
tagged with: opencv
downvote count: 0
has title: Applying CV2 Grayscale to a Numpy 4D array
upvote count: 1
has body: While I know how to convert a single color image (32,32,3) to grayscale using CV2: img = cv2.cvtColor( img, cv2.COLOR_RGB2GRAY ) I need to convert a batch of 60,000 images in a 4D numpy array (60000,32,32,3), how can I achieve that?
score: 1
has answer: http://stackoverflow.com/a/51458343
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/87637013
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50310478
has text: This solution will let you exclude any subset of columns - are you saying you want to exclude only on the basis of groups of columns for each of a, b, c?
type: Comment

http://stackoverflow.com/a/50380948
score: 0
has body: Add this to your template (base.html probably) {% load admin_static %} if doesnt work, add this:
accepted answer of: http://stackoverflow.com/q/50380630
answers question: http://stackoverflow.com/q/50380630
type: AcceptedAnswer
type: Answer

http-status-code-404
tags question: http://stackoverflow.com/q/50240194
type: Tag
tag name: http-status-code-404

http://stackoverflow.com/comment/87875537
score: 0
comment on: http://stackoverflow.com/q/50321283
type: QuestionComment
has text: yes it returns gcc version 7.3.0 (Homebrew GCC 7.3.0). The executable is at /usr/local/bin/gfortran
type: Comment

http://stackoverflow.com/a/50353955
type: Answer
score: 13
upvote count: 13
downvote count: 0
has body: you need upgrade pyopenssl sudo pip install pyopenssl --user --upgrade
accepted answer of: http://stackoverflow.com/q/50324329
answers question: http://stackoverflow.com/q/50324329
type: AcceptedAnswer

http://stackoverflow.com/a/50305791
score: 0
answers question: http://stackoverflow.com/q/50305764
has body: When using IDLE, you are already "inside" python (in its REPL).. You should "load" (import) the file instead.. See here https://stackoverflow.com/a/21650698/5121955 (exact same situation), where you can find many solutions with their advantages..
type: Answer

http://stackoverflow.com/comment/87553872
type: Comment
type: QuestionComment
has text: Your final loop prints `hand` instead of `item`. `deal` should not be a method on card `Card`. A `deal` operation would be expected to take one card off the top of the remaining deck, which alerts us that there is no deck representation. `Card` should also take its suit and rank as part of its constructor/initializer, since it's invalid for a card to exist without these properties. Also, `Card` is a natural candidate for an immutable class; its rank and suit never need to change. `faces` should be converted to a global constant, rather than a local variable reconstructed on every call.
comment on: http://stackoverflow.com/q/50266168
score: 0

http://stackoverflow.com/q/50346390
linked to: http://stackoverflow.com/q/366422
linked to: http://stackoverflow.com/q/1132941
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87709176
has comment: http://stackoverflow.com/comment/87709374
duplicate of: http://stackoverflow.com/q/1132941
type: Question
score: 0
has comment: http://stackoverflow.com/comment/87708468
has body: I have the following code: class test: def __init__(self, a=[None,None], b=[None,None], c=[None,None]): self.a = a self.b = b self.c = c new = [test(), test()] new[0].a[0] = 15 new[1].a I cannot understand why the second entry changes as well. How did it turn out that both elements of the list "new" are the same object? EDIT: For the solution, try this link" What is the pythonic way to avoid default parameters that are empty lists?
has comment: http://stackoverflow.com/comment/87709421
tagged with: python
has comment: http://stackoverflow.com/comment/87709222
has title: Linked entries in a list of class instances

http://stackoverflow.com/comment/87582633
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/50283039
has text: Good solution. It looks like python code and it deserializes with python's `ast.literal_eval()`. JSON and python literals look similar but if it is indeed python, the JSON trick will fail sometimes and work others. For instance, what if its a unicode `u"foo"` string?

http://stackoverflow.com/q/50315140
has answer: http://stackoverflow.com/a/50315861
has body: In the tensorflow python API, tf.metrics features a few metrics for Information Retrieval. In particular: tf.precision_at_k and tf.precision_at_top_k tf.recall_at_k and tf.recall_at_top_k What is the difference between the _at_k and _at_top_k metrics? The API documentation does not seem to give information on this.
upvote count: 5
tagged with: information-retrieval
tagged with: python
favorite count: 0
type: Question
has title: In tensorflow.metrics, difference between precision_at_k and precision_at_top_k?
answer count: 1
score: 5
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/50315861
type: AnsweredQuestion

http://stackoverflow.com/comment/87704877
type: Comment
type: AnswerComment
score: 0
has text: Oh my... completely right. I'll edit it to meet the asked problem right.
comment on: http://stackoverflow.com/a/50338910

http://stackoverflow.com/q/50340717
type: Question
has title: Pandas grouping and combining rows
tagged with: group-by
accepted answer: http://stackoverflow.com/a/50340757
possible better answer: http://stackoverflow.com/a/50341028
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50340757
type: AnsweredQuestion
score: 2
has body: I have a large DataFrame that looks like this: +----------------------------------------------------------+ | Date Category Location ImpactRate | +----------------------------------------------------------+ | 2018-04-22 Outage MT 0.05194 | | 2018-04-22 Outage ND 0.02552 | | 2018-04-22 Outage SD 0.09962 | | 2018-04-24 Transport TX 0.03111 | +----------------------------------------------------------+ What I'm trying to do is create the following output: +-----------------------------------------------------------------------------------+ | Date Category ImpactRate Break Down | +-----------------------------------------------------------------------------------+ | 2018-04-22 Outage 0.17708 MT (29.3%) SD (14.4%) ND (56.3%) | | 2018-04-24 Transport 0.03111 TX (100.0%) | +-----------------------------------------------------------------------------------+ First Attempt - GroupBy grouped_df = df.groupby('Date')['ImpactRate'].apply(list).apply(pd.Series).rename(columns=df['Location'])' This creates a DataFrame that will contain NaNs where each Location isn't present and creates additional columns that require formatting. Second Attempt - Loop using itertuples(): r = [] for item in df.itertuples(): temp_x = df.loc[((df['Category'] == item[2]) &amp; (df['Date'] == item[1])) for i in range(temp_x.shape[0]): r.append(temp_x['ImpactRate'].iloc[i]) This creates one giant list of ImpactRate - which takes me back to square one. I don't know enough to understand how to troubleshoot this. I'm guessing I should make a list within a list for each iteration but I keep going in circles. How can I achieve this output in the most pythonic way? (Please explain so that I can learn!)
answer count: 2
tagged with: pandas-groupby
upvote count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/50341028
favorite count: 0

http://stackoverflow.com/comment/115462828
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50354818
has text: Can you explain what it is you require a variable number of tasks for?
type: Comment

http://stackoverflow.com/comment/87538873
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50260133
type: Comment
has text: no, i want my view to redirect to another domain which is not mine but give this domain some arguments.https://ssl.dotpay.pl/s2/login/cloudfs1/magellan_media/common_file/dotpay_technical_manual_for_payments_implementation.pdf what i want to achive is 1.3 'directed version'

http://stackoverflow.com/q/50370910
favorite count: 0
type: AnsweredQuestion
tagged with: opencv3.0
score: 1
accepted answer: http://stackoverflow.com/a/50371106
tagged with: remap
has answer: http://stackoverflow.com/a/50371106
type: Question
has title: OpenCV: error in resizing video's frame for depthmap
linked to: http://stackoverflow.com/q/12794876
has body: I am performing a depth map with opencv3.4. As I obtained the calibration file, I would like to have the disparity map true 2 stereo cameras. In order to do this i call the calibration file but when i try to resize and remap the video windows, i got the following error. Note: the same script, works with a calibration file taken from just 8 images. the current file is from 21 images. what could be the problem? Error here everything it display when i try to run the dept map File "&lt;ipython-input-5-f2eac343bb87&gt;", line 1, in &lt;module&gt; runfile('C:/Users/gaetano/Desktop/SONIDO ORIGINAL/biggerDepth2.py', wdir='C:/Users/gaetano/Desktop/SONIDO ORIGINAL') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/gaetano/Desktop/SONIDO ORIGINAL/biggerDepth2.py", line 68, in &lt;module&gt; dst= cv2.resize(dst, (0,0),dst, 2.0, 2.0, cv2.INTER_LINEAR) error: C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:4044: error: (-215) ssize.width &gt; 0 &amp;&amp; ssize.height &gt; 0 in function cv::resize Code The code interrupt in line resize in the end of this code, so the remap should be ok. Is a problem of the value I give x, y , w, h? or maybe a problem about the number of bit of the matrix? ret, frame = cap1.read() ret, frame2 = cap2.read() #cv2.imshow('frame', frame) #cv2.imshow('frame2', frame2) #imgL = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #imgR = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) ## dst = cv2.remap(frame, mapx1, mapy1, cv2.INTER_LINEAR,cv2.BORDER_CONSTANT, 0) # imgL_rectified = cv2.remap(imgL, camera_config.left_map1, camera_config.left_map2, cv2.INTER_LINEAR) dst = cv2.remap(frame, mapx1, mapy1, cv2.INTER_LINEAR) dst = dst[y:y + h, x:x + w] #print(dst) ## dst2 = cv2.remap(frame2, mapx2, mapy2,…
downvote count: 0
answer count: 1
tagged with: resize
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/31586385

http://stackoverflow.com/a/50256745
has comment: http://stackoverflow.com/comment/87532555
score: 5
downvote count: 0
has body: Adjusted for updated OP find where sum is equal to 1 df.stack().str.split('_').str[0].isin(liste).sum(level=0).eq(1).sum() 2 Old Answer stack and str accessor You can use split on '_' to scrape the first portion then use isin to determine membership. I also use stack and all with the parameter level=0 to see if membership is True for all columns df.stack().str.split('_').str[0].isin(liste).all(level=0).sum() 3 applymap df.applymap(lambda x: x.split('_')[0] in liste).all(1).sum() 3 sum/all with generators sum(all(x.split('_')[0] in liste for x in r) for r in df.values) 3 Two many map sum(map(lambda r: all(map(lambda x: x.split('_')[0] in liste, r)), df.values)) 3
answers question: http://stackoverflow.com/q/50256344
upvote count: 5
type: Answer

http://stackoverflow.com/comment/87809439
comment on: http://stackoverflow.com/q/50376463
score: 0
has text: See [this discussion](https://discuss.pytorch.org/t/understanding-net-class/2557)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50346372
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: bigdata
tagged with: python
has answer: http://stackoverflow.com/a/50347750
has title: Optimizing reading very large csv and writing it to SQLite
has body: I have a 10gb csv file of userIDs and genders which are sometimes duplicated. userID,gender 372,f 37261,m 23,m 4725,f ... Here's my code for importing csv and writing it to SQLite database: import sqlite3 import csv path = 'genders.csv' user_table = 'Users' conn = sqlite3.connect('db.sqlite') cur = conn.cursor() cur.execute(f'''DROP TABLE IF EXISTS {user_table}''') cur.execute(f'''CREATE TABLE {user_table} ( userID INTEGER NOT NULL, gender INTEGER, PRIMARY KEY (userID))''') with open(path) as csvfile: datareader = csv.reader(csvfile) # skip header next(datareader, None) for counter, line in enumerate(datareader): # change gender string to integer line[1] = 1 if line[1] == 'f' else 0 cur.execute(f'''INSERT OR IGNORE INTO {user_table} (userID, gender) VALUES ({int(line[0])}, {int(line[1])})''') conn.commit() conn.close() For now, it takes 10 seconds to process 1MB file (In reality, I have more columns and also create more tables.). I don't think pd.to_sql can be used because I want to have a primary key.
score: 0
tagged with: sqlite
answer count: 1
upvote count: 1

http://stackoverflow.com/q/50236942
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/50237058
has answer: http://stackoverflow.com/a/50238556
has comment: http://stackoverflow.com/comment/87491749
has comment: http://stackoverflow.com/comment/116433041
has title: Trying to use a double condition(?) in a definition loop
favorite count: 0
has comment: http://stackoverflow.com/comment/87491597
type: Question
has body: Using the definition below for an array defined as being (a*b) in dimension where a and b are equal, let's say 20 for example. So a=b=20. A 20*20 matrix/array. import numpy as np from numpy.linalg import inv from scipy.stats import gmean for n in range(20,21,1): X=np.random.uniform(-0.3,0.3,(n)) Y=np.random.uniform(-0.3,0.3,(n)) a,b=np.ogrid[-1:n-1:1,-1:n-1:1] def f(n, x, y): D=np.array(np.exp(1j*(5*np.pi/6)*np.abs((a+x)-(b+y)))) D[diag,diag]=1-1j/np.sqrt(3) #this diag line is just to choose the diagonal elements specifically as they never change. return D Ddiff = np.abs(np.dstack(inv([f(n, x, y) for x,y in zip(X,Y)]))) D2diff = gmean(Ddiff,axis=-1) What I think this code is producing, is that for each time the function is called, it takes the first element of X and Y and uses through the whole iteration. So in this example n=20, so when I call the function it will produce an a*b array which is 20*20. I'd like that each element of X to match with a as it changes. i.e the first element of a and first element of X called at the same time, then when the second element of a is called the second element of X is called etc. Same with b and Y. this should produce a single 20*20 array when the function is called once where all values in X and Y are used. Then I'd like to automate the code to call the function 500 times. Each time the function is called I need X and Y to generate new values. This way each time an array is produced, it will be different and I can use np.dstack to stack them and gmean to take a geometric average along the third axis (where the arrays are stacked). The code so far produces a 20*20*20 array before using gmean so that's why i think it's using one element in the arrays X and Y each time the function runs. If it works as I hope it should produce a 20*20*500 array.
tagged with: python
has comment: http://stackoverflow.com/comment/87491338
tagged with: numpy
has comment: http://stackoverflow.com/comment/87492205
type: AnsweredQuestion
tagged with: function
possible better answer: http://stackoverflow.com/a/50237058
answer count: 2
tagged with: arrays
accepted answer: http://stackoverflow.com/a/50238556
downvote count: 0

http://stackoverflow.com/q/50276786
tagged with: vlc
tagged with: libvlc
has body: i have an Python Program that show photos and videos from a folder. The files in this folder a changing so a static playlist is not possible. I can create a playlist with a media_list_player I create an instance with instance = vlc.Instance('--input-repeat=-1 --aout=alsa --alsa-audio-device=plughw:0,0') mediaList = instance.media_list_new() mediaList.add_media(instance.media_new(tmpPath + "/start.jpg")) list_player = instance.media_list_player_new() list_player.set_media_list(mediaList) list_player.audio_set_volume(100) list_player.play() And i add new files with mediaList.add_media(instance.media_new(showFile)) list_player.set_media_list(mediaList) This works but when there is an video i dont have sound. "audio_set_volume()" dosen work. I tried the normal media_player but there i cant make a playlist. So i hope someone here can help me with adding sound to the vlc.
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87785868
has comment: http://stackoverflow.com/comment/87570648
has title: Show Video with audio in VLC
score: 0
answer count: 0

http://stackoverflow.com/comment/87684204
score: 1
has text: I'm not sure why you have this problem, but using `str(x)` and ensuring you always have `str` in your series seems to work: `s.map(lambda x: x.isoformat() if isinstance(x, pd.Timestamp) else str(x)).iloc[0]`.
type: Comment
comment on: http://stackoverflow.com/q/50333866
type: QuestionComment

http://stackoverflow.com/comment/87635787
has text: https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html ?
score: 0
comment on: http://stackoverflow.com/q/50309940
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87504327
type: QuestionComment
score: 0
has text: Sir I added model profile code also
comment on: http://stackoverflow.com/q/50242278
type: Comment

http://stackoverflow.com/comment/87631066
type: QuestionComment
type: Comment
has text: Thank you for the tip. I am indeed using the 64-bit version of Python. I tried looking into your suggestion about the processor group, and I do not see an option in python's multiprocessing module to designate a processor group. Maybe I am missing something? On the other hand, my understanding of the multiprocessing library is that it spawns independent processes on the OS, and is therefore distinct from multithreading. So even if there are two processor groups, as you suggest, shouldn't the multiple processes already be able to utilize them both?
score: 0
comment on: http://stackoverflow.com/q/50306632

http://stackoverflow.com/comment/87602611
comment on: http://stackoverflow.com/a/50288189
type: AnswerComment
score: 0
has text: Well, offended is too much, thanks for asking, but I have to admit that I was surprised seeing the very same idea to solve the problem (pd -> df.resample) but not adressing the min/max-part of the question as a new answer - decorated with a comment what my answer lacks. I think I just tend to receive such absolute phrases ('never') printed in bold too personally. Perhaps if I were you, i just had accepted that the Ida was already writtenand would have added the comment as such under the existing answer.
type: Comment

http://stackoverflow.com/comment/87531689
has text: I don't think it's supported out of the box by python see documentation here for all the available features of strftime (https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior).
comment on: http://stackoverflow.com/q/50256825
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87692542
type: QuestionComment
score: 0
has text: thanks, any idea how to do that?
comment on: http://stackoverflow.com/q/50311704
type: Comment

http://stackoverflow.com/q/50242919
tagged with: django-forms
has answer: http://stackoverflow.com/a/50244588
favorite count: 0
type: Question
has body: I am trying to make a very simple Django form that has two options (buttons) once you type something in the form: one deletes what it has been written, and the other one counts the words with a function I already have. I have been trying to learn from tutorials, but all seem too complicated for what this is (which I think, quite easy). This is my HTML in the env templates Python project. Your name: This is my .py file: from django import forms class Formu(forms.Forms): nombre=forms.CharField(max_length=100) def count(self, request): # My function to count pass def reset(self, request): # Reset(?) pass I do not really know how to associate the buttons. I think I am missing some conceptual knowledge, because I do not really know what path should I follow now to associate the buttons count and reset in the Formu methods count and reset.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/87505226
accepted answer: http://stackoverflow.com/a/50244588
has comment: http://stackoverflow.com/comment/87503789
type: AnsweredQuestion
downvote count: 0
has title: Very simple Django form that counts words
upvote count: 1
score: 1
answer count: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/87503554

http://stackoverflow.com/comment/87545798
type: Comment
has text: Thanks! Glad I got actual help, I tried it on 3.6 and it worked. Most people just ignore me and downvote my question, thinking that helps me any. Thanks again.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/50263862

http://stackoverflow.com/q/50295892
favorite count: 0
has comment: http://stackoverflow.com/comment/87609274
duplicate of: http://stackoverflow.com/q/49110044
has answer: http://stackoverflow.com/a/77748975
tagged with: python
type: Question
upvote count: 2
score: 2
answer count: 2
has body: I have an include statement with lots of variables being passed in. Was wondering if there was any way to make it multiline. Ex: {% include 'foo.html' with img_src='bar.jpg' img_text='baz' %} Into: {% include 'foo.html' with img_src='bar.jpg' img_text='baz' %}
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87610029
has answer: http://stackoverflow.com/a/50296716
has title: How to have a multi line statement in Django
tagged with: django
linked to: http://stackoverflow.com/q/49110044

http://stackoverflow.com/q/50320824
has title: Create a python COM object
downvote count: 1
favorite count: 0
score: 3
has answer: http://stackoverflow.com/a/50321073
tagged with: windows
tagged with: pywin32
tagged with: python
type: Question
upvote count: 4
tagged with: c#
has comment: http://stackoverflow.com/comment/87657909
has body: I wonder if there is some way to encapsulate a python script as a COM object. I've seen that many topics talk about invoking a COM component from python, but I am interested in the opposite: to create a COM component that is in fact python. I have some libraries made in python that I want to be called from an excel spreadsheet, and I think this could be a good way to do this.
tagged with: com
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87659321

http://stackoverflow.com/q/50294494
possible better answer: http://stackoverflow.com/a/50296552
has title: python bs4 not finding div
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50296552
type: AnsweredQuestion
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50294690
favorite count: 0
has body: I am trying to scrape https://www.edsurge.com/product-reviews/curriculum-products/math When I do this : site = 'https://www.edsurge.com/product-reviews/curriculum-products/math' soup = bs.BeautifulSoup(urlopen(site),"html5lib") print soup I can find the div I am looking for &lt;div class="browse-main p1"&gt; However, when I try to find it using: for div in soup.findall('div',class_='browse-main p1'): print div I get this error (probably meaning that it can't find the div). for div in soup.findall('div',class_='browse-main p1'): TypeError: 'NoneType' object is not callable I also tried using soup.findall('div') and it can't find any. I know I could use selenium, but if it is not necessary, I would rather not. What I find odd is that the div is present when I print soup. Anyone know what is going on ? Thanks
tagged with: beautifulsoup
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/50294690

http://stackoverflow.com/comment/87763665
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50373532
has text: see [What topics can I ask about here?](https://stackoverflow.com/help/on-topic), [What types of questions should I avoid asking?](https://stackoverflow.com/help/dont-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/a/74110520
score: 0
type: Answer
has body: Yes, Celery is perfect for periodic tasks. I even wrote the article on how to dynamically update periodic tasks in Celery and Django and published a very simple project on GitHub showcasing how to update periodic tasks. My project was very simple, I was using only one worker. I used SQLite as a broker and results backend. If you plan to have more workers then you can use PostgreSQL as broker and results backend. My configuration for Celery with SQLite: # celery broker and results in sqlite CELERY_BROKER_URL = "sqla+sqlite:///celery.sqlite" CELERY_RESULT_BACKEND = "db+sqlite:///celery.sqlite" I was using Celery version 5.2.7.
answers question: http://stackoverflow.com/q/50296170

http://stackoverflow.com/comment/87756325
comment on: http://stackoverflow.com/q/50369095
has text: @mathews yes, but is it a known problem in the tool? is it a problem in your java code? ...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50247331
has answer: http://stackoverflow.com/a/50255048
possible better answer: http://stackoverflow.com/a/50255048
has body: I'm trying to recovery missing data in a cluster trace like this: I read some articles and find out I can create a tensor for this dataset, and then decompose the tensor to recover the missing data. Now I'm using Tensorly, a tensor lib on python.I built a simple tensor like this: import tensorly as tl X = tl.tensor(np.arange(24).reshape((4, 6))) X[0][5]= nan X[1][5]= nan and I got: array([[ 0., 1., 2., 3., 4., nan], [ 6., 7., 8., 9., 10., nan], [ 12., 13., 14., 15., 16., 17.], [ 18., 19., 20., 21., 22., 23.]]) and then I try to decompose it according to the official document: from tensorly.decomposition import parafac factors = parafac(X, rank=1) print(tl.kruskal_to_tensor(factors)) I got all-nan result when the parameter rank is 1 or 2 or 3: [[ nan nan nan nan nan nan] [ nan nan nan nan nan nan] [ nan nan nan nan nan nan] [ nan nan nan nan nan nan]] and error when when the parameter rank is bigger than 3: ValueError: array must not contain infs or NaNs How can I fix this? Any answer would help. Thanks in advance.
favorite count: 0
type: Question
answer count: 2
downvote count: 0
tagged with: tensor
has answer: http://stackoverflow.com/a/50247747
tagged with: python
tagged with: tensorly
type: AnsweredQuestion
has title: Missing data recovery using tensor decomposition on Python Tensorly
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50247747

http://stackoverflow.com/q/50369331
answer count: 2
tagged with: conv-neural-network
has title: Regression Activation Mapping for a given CNN
score: 7
tagged with: regression
downvote count: 0
tagged with: machine-learning
upvote count: 7
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88601539
has answer: http://stackoverflow.com/a/76972554
has answer: http://stackoverflow.com/a/64061562
type: UnansweredQuestion
tagged with: python
has body: This paper https://arxiv.org/pdf/1703.10757.pdf disucces using Regression Activation Mapping (RAM) - instead of Class Activation Mapping (CAM). There are several articles describing how to implement CAM. But i cant find any for RAM - or the code used in the paper. Anyone got code example of RAM? Update: Looking at this example: http://www.hackevolve.com/where-cnn-is-looking-grad-cam/ What should line 16 and 17 be when pred is a scalar? class_idx = np.argmax(preds[0]) class_output = model.output[:, class_idx] edit: repository for the Diabetic Retinopathy Detection paper: https://github.com/cauchyturing/kaggle_diabetic_RAM edit2: changed title from InceptionV3 to any CNN architecture

http://stackoverflow.com/comment/87610801
type: QuestionComment
score: 0
has text: If that’s your problem, you can specify `encoding='utf-8-sig'`, which is Python’s name for Microsoft’s incorrect format.
comment on: http://stackoverflow.com/q/50296880
type: Comment

http://stackoverflow.com/a/50298703
has body: There is a form of recursion, as with all iterative algorithms there will be an alternate form. However, the recursive version is rarely used because of the likelihood of generating a stack overflow which would be due to the length of the list being longer than the stack space. Recursive algorithms can be very expressive, but to me, the organisation of the data is asking to be iterated over. btw your dict can be created with a dictionary comprehension: Dict = { FOLDER_A[i]]:FOLDER_B[i] for i in range(len(FOLDER_A)) }
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50298644
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50324135
has comment: http://stackoverflow.com/comment/87664122
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Roughly equivalent code of partial
accepted answer: http://stackoverflow.com/a/50324406
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50324406
has body: In the official docs 10.2. functools about partial Roughly equivalent to: def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*args, *fargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc I guess it could be better if refactor it as: def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): return func(*args, *fargs, **fkeywords, **keywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc or def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newargs = args.copy() newkeywords.update(fkeywords) args.append(fargs) return func(*args, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc Does my assumption make sense?
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/87759210
type: QuestionComment
has text: To rule out malformed JSON: can you put your *entire* JSON through a validator, e.g. https://jsonlint.com/ and see if it comes out as valid? If not, maybe the validator can point you in the right direction.
score: 0
comment on: http://stackoverflow.com/q/50371627
type: Comment

http://stackoverflow.com/comment/87500044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50241056
has text: Possible duplicate of [How can I read inputs as integers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers)
score: 3

http://stackoverflow.com/q/50321278
answer count: 6
has body: I'm trying to get Python Selenium to work on my Windows Machine. I've upgraded to the latest versions of Firefox, Selenium, Geckodriver, but I still receive the below error: Python Script from selenium import webdriver driver = webdriver.Firefox() Error Traceback (most recent call last): File "run.py", line 17605, in &lt;module&gt; File "&lt;string&gt;", line 21, in &lt;module&gt; File "site-packages\selenium\webdriver\firefox\webdriver.py", line 77, in __init__ File "site-packages\selenium\webdriver\firefox\extension_connection.py", line 49, in __init__ File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 68, in launch_browser File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 103, in _wait_until_connectable WebDriverException: Message: Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details. I've also tried creating the firefox profile with the below code: from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary profile = webdriver.FirefoxProfile() profile.set_preference('browser.download.folderList', 2) profile.set_preference('browser.download.manager.showWhenStarting', False) profile.set_preference('browser.download.dir', os.getcwd()) profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/vnd.ms-excel')) profile.set_preference('general.warnOnAboutConfig', False) gecko_path = "path_to_geckodriver\\geckodriver.exe" path = "path_to_firefoxs\\Mozilla Firefox\\firefox.exe" binary = FirefoxBinary(path) driver = webdriver.Firefox(firefox_profile=profile,executable_path=gecko_path) Python 2.7 Firefox 60 Geckodriver-v0.20.1-win64.zip Selenium 3.12.0
score: 22
has answer: http://stackoverflow.com/a/61031427
has title: How to load firefox profile with Python Selenium?
tagged with: firefox
linked to: http://stackoverflow.com/q/15058462
tagged with: selenium
has answer: http://stackoverflow.com/a/50321929
has answer: http://stackoverflow.com/a/77901568
downvote count: 1
favorite count: 0
upvote count: 23
tagged with: firefox-profile
has answer: http://stackoverflow.com/a/60539482
type: Question
has answer: http://stackoverflow.com/a/54065166
has comment: http://stackoverflow.com/comment/123272479
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50325288

http://stackoverflow.com/a/75850911
type: Answer
answers question: http://stackoverflow.com/q/50378906
upvote count: 3
downvote count: 0
has body: I know this is 5 years old, but I came across it trying to figure out a related issue and saw it has 4k views. Just thought I'd suggest an alternative: class F1(object): def __init__(self, sick="flu"): self.sick = sick class F2(F1): def __init__(self, cure="bed rest", **kwargs): super().__init__(**kwargs) self.cure = cure a = F2(cure="wait it out") print(a.sick) # => flu print(a.cure) # => wait it out a = F2(sick="covid", cure="quarantine") print(a.sick) # => covid print(a.cure) # => quarantine a = F2(sick="anything") print(a.sick) # => anything print(a.cure) # => bed rest (Of course, above works without declaring default value for cure as well.) You could also do it without calling with requiring keyword arguments like so: class F1(object): def __init__(self, sick="flu"): self.sick = sick class F2(F1): # Without keyword arguments, must call args in order F2(cure, sick) def __init__(self, cure="bed rest", *args, **kwargs): super().__init__(*args, **kwargs) self.cure = cure a = F2("sleep") print(a.sick) # => flu print(a.cure) # => sleep a = F2(sick="covid", cure="quarantine") print(a.sick) # => covid print(a.cure) # => quarantine a = F2("sleep", "any sickness") print(a.sick) # => any sickness print(a.cure) # => sleep
score: 3

http://stackoverflow.com/a/50302763
downvote count: 0
has comment: http://stackoverflow.com/comment/87621907
has body: By default the input function in Python returns a string type. So when you enter the age, it is not being returned to your program as an int but rather a string. So: print("Your age is: " + myage) Actually looks like: print("Your age is: " + "24")
answers question: http://stackoverflow.com/q/50302730
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87622030

http://stackoverflow.com/a/50310048
answers question: http://stackoverflow.com/q/50309815
upvote count: 3
has body: Let's try using color parameter as list. fig,ax = plt.subplots() ind = np.arange(len(df)) colormat=np.where(df['Speed']&gt;0, 'g','r') ax.bar(ind, df['Speed'], width=0.5, color=colormat) Output:
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50309815
score: 3
has comment: http://stackoverflow.com/comment/87643985

http://stackoverflow.com/q/50355248
has comment: http://stackoverflow.com/comment/87727152
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50355455
type: UnansweredQuestion
score: -2
linked to: http://stackoverflow.com/q/30314910
tagged with: python
has title: how do i add all the even number together?
duplicate of: http://stackoverflow.com/q/30314910
has answer: http://stackoverflow.com/a/50355972
answer count: 3
has body: number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] godlike = [] #Check closest object def total_num(number): for x in number: if x % 2 == 0: godlike.append(x) print(x)
has answer: http://stackoverflow.com/a/50359836
upvote count: 0
downvote count: 2

http://stackoverflow.com/a/50270379
has comment: http://stackoverflow.com/comment/91279999
has body: Try to upgrade protobuf: pip install --upgrade protobuf
has comment: http://stackoverflow.com/comment/87559988
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/50269943
type: Answer

http://stackoverflow.com/a/50378755
answers question: http://stackoverflow.com/q/50378527
type: Answer
has comment: http://stackoverflow.com/comment/87773981
has comment: http://stackoverflow.com/comment/87773925
has body: An idiomatic way for checking presence in a string is using the needle in haystack syntax: def find_in_file(needle, filepath): with open(filepath, 'r') as fh: # Case-insensitive search if needle.lower() not in fh.read().lower(): print("%s wasn't found in %s" % (needle.upper(), filepath)) Note on doing case-insensitive search: this is the case for ASCII strings. See this answer and comments for discussion on handling Unicode comparison with Python
has comment: http://stackoverflow.com/comment/87773793
has comment: http://stackoverflow.com/comment/87773864
accepted answer of: http://stackoverflow.com/q/50378527
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87536167
comment on: http://stackoverflow.com/q/50258595
type: Comment
type: QuestionComment
score: 0
has text: did u se the argument sep=','?

http://stackoverflow.com/a/50273165
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50273023
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50273023
has body: The problem is that openCv is not able to open the picture. The picture is in the directory 'Database', but your script is not triggered from there. You are giving the wrong path. The appropriate path would be: img=cv2.imread(os.path.join('Database',filename))
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87647581
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50312905
has text: Looks pretty Pythonic to me
score: 0

http://stackoverflow.com/comment/87701175
has text: I'll remove from my answer then.
type: AnswerComment
comment on: http://stackoverflow.com/a/50342593
score: 0
type: Comment

http://stackoverflow.com/q/50242122
type: UnansweredQuestion
tagged with: python
has body: block1 = pygame.Surface(?,?) when I ran it it gave me an error stating ValueError: size needs to be (int width, int height)
score: 0
answer count: 2
has title: What do I put inside a pygame.Surface()?
tagged with: pygame
has answer: http://stackoverflow.com/a/50242253
has answer: http://stackoverflow.com/a/50272361
tagged with: surface
type: Question

http://stackoverflow.com/comment/87726343
type: Comment
has text: It's probably worth mentioning `yield from`. Catching `StopIteration` manually and examining the exception's attached `value` is an unusual way to use a generator's return value, in much the same way catching `StopIteration` manually is an unusual thing to do in general.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50353561

http://stackoverflow.com/comment/87531691
comment on: http://stackoverflow.com/a/50256169
type: Comment
score: 0
type: AnswerComment
has text: I am also having a Time=49.217518 ms which is different for different requested Id in the same file how can I print it RequestId=12780045-3ac2-11e7-8dc6-f7c2b766d8e7 Time=371.659573 RequestId=246ae44d-3ac6-11e7-b37d-67399e5d4706 Time=55.300253 in this form

http://stackoverflow.com/a/50291471
has comment: http://stackoverflow.com/comment/87607837
has comment: http://stackoverflow.com/comment/87607648
has comment: http://stackoverflow.com/comment/87611183
type: Answer
has body: Try using model inheritance: class Character(models.Model): character_name = models.CharField(max_length=100, default="") def __str__(self): return self.character_name class Meta: abstract = True class AllianceCharacter(Character) race = models.CharField(choices=Alliance_Races) class HordeCharacter(Character) race = models.CharField(choices=Horde_Races)
score: 0
answers question: http://stackoverflow.com/q/50290298
has comment: http://stackoverflow.com/comment/87607906
accepted answer of: http://stackoverflow.com/q/50290298
type: AcceptedAnswer

http://stackoverflow.com/q/50292048
tagged with: python-3.x
has title: Connectivity issue to connect Oracle DB from python apps using pyodbc
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87601096
upvote count: 1
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/87670055
score: 0
tagged with: oracle-database
has comment: http://stackoverflow.com/comment/87673548
downvote count: 1
has body: I'm trying to connect to a Oracle XE database from my python application using pyodbc module. Below are the code: import pyodbc; conn = pyodbc.connect('DRIVER={Oracle in XE};DBQ=localhost:1521/xe;UID=xxxx;PWD=xxxx'); conn = pyodbc.connect('DSN=myOracleXEDSN;UID=xxxx;PWD=xxxx'); cursor = conn.cursor(); cursor.execute("select * from customer"); I also set up the Oracle DSN from ODBC data source Administrator Tool as follow and tested it with connection successful message Data Source Name: myOracleXEDSN Driver Name: Oracle in XE TNS Service Name: XE UserID: xxxx Password: xxxx But I'm getting the following message while run the python app: conn = pyodbc.connect('DRIVER={Oracle in XE};DBQ=localhost:1521/xe;UID=system;PWD=sayan123'); pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I am not getting what I miss here as I'm new to use pyodbc module to connect to DB. please help me out. python version:- 3.6 pyodbc version: 4.x
favorite count: 0
type: Question

http://stackoverflow.com/q/50317667
type: UnansweredQuestion
has title: Run python program with modules from terminal
has answer: http://stackoverflow.com/a/50338459
tagged with: python
has comment: http://stackoverflow.com/comment/87651086
has body: I've been programming Python (3.6.5) with PyDev in eclipse Photon for a few months. It is a small terminal application to extract data from webs (through web scraping) on the corporate intranet that helps me to reduce times in my work, avoiding doing it manually. The structure is this: Start the application from the main.py in eclipse showing in the console of this IDE, but I would like to start it from the Windows CMD to later create an .exe with PyInstaller. If I do python main.py it does not find the package classes and returns error. What parameters does the command need to start the application from the command line in Windows?
has comment: http://stackoverflow.com/comment/87659334
has comment: http://stackoverflow.com/comment/87655794
score: 0
answer count: 1
tagged with: cmd
type: Question
has comment: http://stackoverflow.com/comment/87655136

http://stackoverflow.com/a/50385023
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: We don't need to use a class based view for it. For simplicity we can use a function based view. Change your code as below. from django.template.loader import render_to_string def generate_pdf(request): report = Brand.objects.all() template_path = 'profile_brand_report.html' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' html = render_to_string(template_path, {'report': report}) print (html) pisaStatus = pisa.CreatePDF(html, dest=response) return response We can also use wkhtmltopdf to generate PDF's in django. Read: https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/
accepted answer of: http://stackoverflow.com/q/50384613
type: Answer
answers question: http://stackoverflow.com/q/50384613

http://stackoverflow.com/comment/122445069
comment on: http://stackoverflow.com/a/55358419
score: 0
type: Comment
type: AnswerComment
has text: How do you achieve 1 & 2?

http://stackoverflow.com/q/50375834
score: 0
has comment: http://stackoverflow.com/comment/87768006
has comment: http://stackoverflow.com/comment/87768829
has comment: http://stackoverflow.com/comment/87768874
answer count: 1
has title: Convert bytes or str to str in Python 2 and 3 using the same code
type: Question
has comment: http://stackoverflow.com/comment/87769900
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87767977
has answer: http://stackoverflow.com/a/50376052
has body: I have code that uses subprocess.check_output() which returns a str in Python 2, and bytes in Python 3. Is there any way to have code that works in Python 2 and 3 and converts it to a str? I.e. I want this, but more elegantly: output = subprocess.check_output(...) if sys.version_info[0] &gt;= 3: output = output.decode() To be clear, I don't want unicode in Python 2, I want it to leave it as a str.
tagged with: python

http://stackoverflow.com/comment/87677877
has text: What does "If I were to select 3 samples" mean? You mention probability but didn't provide your desired probability. You can have an infinite variety of probabilities that all generate that specific combined 3 samples. I don't understand if you want a mechanism for generating 3 samples or 1 sample. It is best to read [mcve] and edit your post accordingly.
score: 0
comment on: http://stackoverflow.com/q/50330090
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87721736
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50351608
has text: @sato - I can get is earlier :) Super, I was really surprised why get it :)
type: Comment

http://stackoverflow.com/q/50259214
answer count: 0
has comment: http://stackoverflow.com/comment/87536657
has comment: http://stackoverflow.com/comment/87536509
type: Question
has comment: http://stackoverflow.com/comment/87536938
type: UnansweredQuestion
tagged with: python
tagged with: flask
has body: I have the following package structure This is my code in home.py import os from flask import Blueprint, render_template, request, flash, url_for from .. import db from ..models.home import Summary from ..forms.home import SummarizerForm from ..processing.summarizer import Summarizer from ..helpers import flash_errors from ..processing.newsbot import NewsBot home = Blueprint('home', __name__) @home.route('/', methods=['GET', 'POST']) def index(): summary = None url = '' form = SummarizerForm(request.form) if request.method == "POST" and form.validate(): summary = Summarizer(form.text.data, form.algorithm.data, form.length.data) if summary.error: flash(summary.error) else: source_url = form.text.data if form.text.data.startswith(('http://', 'https://')) else '' summary_db_entry = Summary( summary.bullets, summary.highlighted_text, source_url=source_url) db.session.add(summary_db_entry) db.session.commit() url_hash = summary_db_entry.url url = os.path.join(request.url, url_for('home.summary_entry', url_hash=url_hash)[1:]) flash_errors(form) return render_template( 'home/index.html', form=form, summary=summary, url=url ) @home.route('/s/&lt;url_hash&gt;') def summary_entry(url_hash): summary = Summary.query.filter_by(url=url_hash).first_or_404() source_url = summary.source_url return render_template( 'home/summary.html', summary=summary, source_url=source_url ) @home.route('/about') @home.route('/about/') def about(): return render_template('home/about.html') And the init.py out of the package from .views.home import home I get the following error on init.py which is out of the package. Traceback (most recent call last): File "/Users/johnsriskandarajah/Documents/summarizer-flask-app-master/tldrapp/__init__.py", line 35, in &lt;module&gt; from .views.home import home ValueError: Attempted relative import in non-package How can this error be fixed? I tried out most of the solutions online but couldn't find any luck. Full project structure
has title: Python:ValueError: Attempted relative import in non-package
score: 0

http://stackoverflow.com/q/50380164
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/50397613
type: Question
has comment: http://stackoverflow.com/comment/87810591
has answer: http://stackoverflow.com/a/50397613
has body: I made a request to an api and it returned b"001-1001\thazraja\t122.9668944300\t43.1858693000\t[YES]\t1456529273000\t2437.0000000000\n001-1002\tZ8s14\t122.9671153000\t43.1860681800\t[NO]\t1456529275000\t2462.0000000000\n..." It goes on like that for some time, starting again at the carriage return "\n". It always has 7 items before it starts again. print(response.headers["content-type"]) returns text/xml;charset=UTF-8 How would I access "001-1001" as well as "thajraza", etc? I'm not sure what the name is of the type of thing the api returned? Is it a list? A dictionary? Something else?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
tagged with: utf-8
tagged with: dictionary
has comment: http://stackoverflow.com/comment/87810477
has comment: http://stackoverflow.com/comment/87811917
linked to: http://stackoverflow.com/q/13857856
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/87776841
has title: Python: Splitting text/xml;charset=UTF-8
answer count: 1

http://stackoverflow.com/q/50359129
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50359996
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: python
tagged with: exec
has body: Getting a strange error, In jupyter notes I can run: df1.to_csv("{0}{1}.csv".format(report_path,db)) and my csv comes out fine. When I try execute the same thing outside of jupyter by putting the above into a file an external file and running this: #imports requred to run querys import pandas as pd from pandas import DataFrame,Series import numpy as np from pyhive import presto import matplotlib.pyplot as plt import seaborn as sn #run config file, which contains the query to generate the report def run_config(db): print args.an print ("config is = {0}".format(config)) with open(config) as cfg: v = cfg.read() exec v I get this error: lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer) File "pandas/_libs/lib.pyx", line 1035, in pandas._libs.lib.write_csv_rows UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128) I'm fairly certain its something in my DF that is causing this error because other df don't have this issue. But I'm lost as how to fix or edit the code to capture this. the fix df1.to_csv("{0}{1}.csv".format(report_path,db), encoding='utf8-8')
tagged with: jupyter-notebook
has title: pandas dataframe to csv export issue
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/50359996

http://stackoverflow.com/a/50285234
answers question: http://stackoverflow.com/q/50285193
has body: Your dictionary keys are of the type 'Int', while your list items are strings. You need to convert one into the other. for example: new_dict = {} for k in my_dict.keys(): if str(k) in my_list: new_dict[k] = my_dict[k] Note that you cannot use .append() to add key-value pairs to a dictionary.
type: Answer
score: 0

http://stackoverflow.com/comment/87626413
comment on: http://stackoverflow.com/q/50304873
score: 0
has text: Surely you had a more detailed specification when you wrote the code. It's impossible to see what might be wrong with it now.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87548478
score: 0
type: Comment
has text: @TahreenAkther: Parameters are how you can pass information to a function, but in your case the function gets everything it needs from the user, so there's no reason to have a parameter.
type: AnswerComment
comment on: http://stackoverflow.com/a/50260661

http://stackoverflow.com/a/54552194
downvote count: 0
has body: I was typing flask run and then saw this message after that I solve this issue with these: 1- Add this text in your myproject/.flaskenv : FLASK_APP=myapp.py FLASK_ENV=development also you should type "pip3 install python-dotenv" for using this file .flaskenv 2-in your project folder type in terminal your flask command which one you use : flask-3 run
answers question: http://stackoverflow.com/q/50284753
upvote count: 3
score: 3
type: Answer

http://stackoverflow.com/comment/87620901
comment on: http://stackoverflow.com/q/50302228
has text: That's still a picture... I'm asking for text edited in your question.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50427669
has comment: http://stackoverflow.com/comment/88006818
type: Answer
answers question: http://stackoverflow.com/q/50351867
score: 0
has comment: http://stackoverflow.com/comment/87995799
has comment: http://stackoverflow.com/comment/87919203
has body: Since the update script is just grabbing some numbers, your best bet is probably wrapping that thing inside an update function, processing those numbers so they fit a ColumnDataSource, then update the main CDS, which will then update the plot. Something like: def update(): # Do stuff to get new data numbers = get_usage() # Process new data into a CDS friendly format data1, data2 = process_numbers(numbers) # Update plot_source, this being whatever source is r1_source.data = data1 r2_source.data = data2 curdoc().add_periodic_callback(update, 500)
has comment: http://stackoverflow.com/comment/87936956

http://stackoverflow.com/q/50262773
type: AnsweredQuestion
has body: I have a dictionary file for a speech recognition engine that I'm trying to reduce the size of. The dictionary contains 133k+ lines like so: abella AH B EH L AH abeln AE B IH L N abelow AE B AH L OW abels EY B AH L Z abelson AE B IH L S AH N abend AE B EH N D abend(2) AH B EH N D I'm trying to reduce it to only hold the most common words and names in the U.S. from a file with 15k+ lines like so: configurations poison james john robert When I run the following script it results in a blank file, as if there no matches between the first token of lines in the dictionary and the lines of the common words dataset. Are my files too big for the way I'm doing this? What am I doing wrong? import os file_name = 'small_cmudict-en-us.dict' f = open(file_name, 'w+') with open('common_names_words.txt', 'r') as n: for line in n: line = line[:-1] #remove newline char with open('cmudict-en-us.dict', 'r') as d: for line2 in d: dict_entry = line2.split() #words with multiple pronunciations; abend, abend(2) if dict_entry[0][-3:] == '(': if dict_entry[0][:-3] in n: f.write(line) if dict_entry[0] in n: f.write(line) f.close Thank you for your time.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50262947
type: Question
upvote count: 2
downvote count: 0
tagged with: python
has title: Trying to compare lines of 2 large files and keep lines that match, but no matches
answer count: 1
accepted answer: http://stackoverflow.com/a/50262947
has comment: http://stackoverflow.com/comment/87544006
score: 2

http://stackoverflow.com/comment/87571316
has text: Your "go back a step" operation is what's commonly referred to as a [GoTo](https://en.wikipedia.org/wiki/Goto), probably the most hated operation in any programming language. It is not supported in Python, you must use other methods like loops.
comment on: http://stackoverflow.com/q/50277275
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55052831
answers question: http://stackoverflow.com/q/50346020
score: 0
has body: What if you paste the items? -------------- trans item -------------- 001 A2 001 B3 002 A4 002 B6 002 C10 003 D1 --------------- And then to transactions trans item ------------- 001 A2,B3 002 A4,B6,C10 003 D1 Then run association
type: Answer

http://stackoverflow.com/a/50360436
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50360416
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50360416
has body: The correct way of check the request method would be via request.method. if request.method == 'POST': What you're currently doing is to check if the request object is the string 'POST', which, it's not since it's the Request object that Django supplies for you.

http://stackoverflow.com/a/50297358
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50297248
type: Answer
has body: Well, one way to do this recursively that is a little more concise is def addSSS(item): if isinstance(item, list): # map takes a function, and a list and returns a # new list that is the result of applying the function # to each element. list() converts the result to a list return list(map(addSSS, item)) # if it's not a list simply append the string and return that value return "sss" + str(item) bb = list(map(addSSS, aa)) Maps are nice because they don't evaluate each element right away, only on demand, of course here it gets evaluated right away when you call list() to turn it back to a list This has the additional advantage that it works when your list nests deeper like aa = [1, 2, [1, 2, [1, 2]]]
downvote count: 0

http://stackoverflow.com/comment/87525939
type: QuestionComment
comment on: http://stackoverflow.com/q/50254177
has text: Just decide what should happen if `val` is zero. You could raise an exception, too. The title of this question doesn't seem to correspond to what you are asking, by the way.
score: 1
type: Comment

http://stackoverflow.com/q/50283124
has title: Get the value of a variable from http get or post
tagged with: http
type: Question
has body: I have this html page: Prueba TFG Introduce KeyWord I would like get the value of "name", the input of the page, using JavaScript and pass this value to python. How can i do that? Thank you so much!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50283155
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript
tagged with: python
score: 0
answer count: 1

http://stackoverflow.com/comment/87726119
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50354625
has text: both python and bash files in working directory

http://stackoverflow.com/comment/87605481
type: AnswerComment
comment on: http://stackoverflow.com/a/50294317
has text: You could simplify it more. Remove the class and leave: `//button[@options='optionsSubmitBtn']`. Pretty sure if OP is using Selenium, that should be enough and all OP needs is to add `.click()`
type: Comment
score: 0

http://stackoverflow.com/comment/87572529
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50277548
type: Comment
has text: @WoJ It is not guaranteed. See https://docs.python.org/3/library/inspect.html#inspect.currentframe . But I may suggest a simple workaround.

http://stackoverflow.com/q/50273860
has title: How to convert strings to floats after sending through TCP with Python?
type: Question
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/87564709
has body: Hi am trying to send continuous temperature data from my Raspberry Pi 3 to PC using TCP sockets with Python. I'm not unable to send float values, I am sending a continuous stream of float values in string format and want to convert all of these to float types. I am getting errors like this: "ValueError: could not convert string to float '25.69'. Here is my server code (running on the raspberry pi), I've only included the specific parts: def dataTransfer(conn): # A big loop that sends/receives data until told not to. while True: reply = GET_OBJ_TEMP() reply = str(reply) #conn.sendall(str.encode(reply)) # don't have to encode/decode, I think it's only for Python 3 conn.sendall(reply) print("Data has been sent!") #conn.close() s = setupServer() conn = setupConnection() dataTransfer(conn) And here is the client code (on PC): import socket host = '10.0.0.94' port = 5560 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) #while True: #s.send(str.encode(command)) reply = s.recv(1024) #print(reply.decode('utf-8')) #reply2 = reply.decode('utf-8') reply2 = (repr(reply)) reply2 = float(reply2) print reply2 print type(reply2) s.close() Could someone please help me to get these values as an float or help me send floats directly, i need them so i can use temperature as a threshold value.
has comment: http://stackoverflow.com/comment/87570142
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87603974
has comment: http://stackoverflow.com/comment/87567959
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87568358
tagged with: tcp
favorite count: 0
tagged with: string

http://stackoverflow.com/comment/87612338
has text: I guess that the service is sending a single json object per line. Everything else wouldn't make sense. You just need to write a program which reads the file line by line, parses a json object out of every line and does whatever with it
type: QuestionComment
comment on: http://stackoverflow.com/q/50297563
score: 0
type: Comment

http://stackoverflow.com/q/50308014
type: Question
tagged with: python-3.x
tagged with: flask-admin
tagged with: python
accepted answer: http://stackoverflow.com/a/50316094
tagged with: flask
has body: I have this flask admin interface, but I want to change the behavior of the Create link, so I can link to my own creation interface instead of letting flask admin making a create form for me. What would also work is adding another link, next to With Selected, which redirects to another page. It's complicated geometrical data, so I need a completely different data creating interface, Products is just an example. I would really prefer not to add another admin template, so it would be nice if it could be done in python. After trying out for quite some time, I managed to find this solution, which does exactly what I want: from flask_admin import Admin from flask_sqlalchemy import SQLAlchemy from flask_admin.contrib.sqla import ModelView from flask import Flask, url_for, redirect app = Flask(__name__) db = SQLAlchemy(app) admin = Admin(app) class Product(db.Model): __tablename__ = 'product' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) db.create_all() class SuperHackyFlaskAdminRedirectFakeException(Exception): pass @app.errorhandler(SuperHackyFlaskAdminRedirectFakeException) def handle_fake_errors(error): return redirect(url_for('index')) @app.route('/index') def index(): return 'this is the index' class ProductView(ModelView): column_display_pk = True def redirect_to_index_from_admin(_): raise SuperHackyFlaskAdminRedirectFakeException() create_form = redirect_to_index_from_admin admin.add_view(ProductView(Product, db.session)) As you might see, it's really hacky though, and I would prefer to find a better solution. Any suggestions?
has answer: http://stackoverflow.com/a/50316094
type: AnsweredQuestion
has title: Change link location of "create" button flask-admin
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/50357000
has answer: http://stackoverflow.com/a/51170376
type: Question
has title: Docker -Pika BlockingConnection Error
tagged with: pika
has comment: http://stackoverflow.com/comment/87733377
has body: I have a docker container which runs a python script.The script is provided with an AMQP url which Pika uses as a pika.URLParameters for a BlockingConnection.When i run the script on my computer it worked fine.Since i dockerized it and monitored the logs of the container,i saw that the script jangs when the connection is attempted.Here is the code i use in the script: AMQP_URL = __prefix__ + __username__ + ":" + __password__ + __virtual__host + session ("The programm hangs here") connection = pika.BlockingConnection(pika.URLParameters(AMQP_URL)) channel = connection.channel() channel.exchange_declare( exchange = "tmp.topic_2", exchange_type = "topic" ) result = channel.queue_declare(exclusive = True) queue_name = result.method.queue channel.queue_bind( exchange = "amq.topic", queue = queue_name, routing_key = "ui.#" ) channel.basic_consume( UiCallback, queue= queue_name, no_ack=True ) channel.start_consuming() I have included pika in the requirements.I wonder what the problem is: Maybe the container can't access the web? Maybe i need to set up a rabbitmq server in this or another container? Thank you for your help
upvote count: 2
has comment: http://stackoverflow.com/comment/87730882
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87733087
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87733271
tagged with: python
tagged with: rabbitmq
favorite count: 0
tagged with: docker
score: 2
has comment: http://stackoverflow.com/comment/87733192
has comment: http://stackoverflow.com/comment/87730683
has comment: http://stackoverflow.com/comment/87731558
has comment: http://stackoverflow.com/comment/106899289
has comment: http://stackoverflow.com/comment/87732970

http://stackoverflow.com/a/64673930
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50364968
has body: If you use the classic GAN model for alternate training, this situation is inevitable, try to change the training method
score: 1

http://stackoverflow.com/q/50283458
accepted answer: http://stackoverflow.com/a/50283621
linked to: http://stackoverflow.com/q/18837262
answer count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87584960
has title: python make hierarchy by using for-loop
tagged with: python
has body: i have some list article = ["A",'B','C','D','E','F','G','H'] quote = ['','A','A','C','C','','A','B'] pd.DataFrame({'Article':article,'Quote':quote}) It is to make a hierarchy by citing the quoted texts. I want this hierarchical format. As a result, I want to show that A quoted by B, B quoted by H. How do i code it?
tagged with: python-2.7
score: 0
tagged with: for-loop
has answer: http://stackoverflow.com/a/50283621

http://stackoverflow.com/comment/87556172
score: 2
type: AnswerComment
has text: @kntgu You can put objects (steps) in a `Pipeline` that do have the `partial_fit()` method, but also that do **not** have this method. When you call `fit()` on a `Pipeline` object, it will call this `fit()` on every step you've added. And you can only add steps to a `Pipeline` if they have this `fit()` method. However, imagine the `Pipeline` does support `partial_fit()`, only a few steps have the `partial_fit()`, so the `Pipeline` wants to call this method for each step, but the steps simply do not support it. That's why the `Pipeline` itself does not support this method, hope it's clear now.
type: Comment
comment on: http://stackoverflow.com/a/50269074

http://stackoverflow.com/a/50344448
answers question: http://stackoverflow.com/q/50344027
has body: Here's my example, is that what you wanted? from statistics import mean items = [ ['John', 1,2,3,5,21,2,3,2,1,2,5], ['Alice', 5,31,6,73,4,2,1], ['Bill', 7,4,6,78,3,1,2,21], ['Sarah', 2,3,5,6,4,7,7], ['Martin', 2,4,6,3,8,2,3,3], ] some_dict = {} for row in items: name = row[0] grades = list(map(int, row[1:])) print('Average of %s --&gt; %f' % (name, mean(grades))) some_dict.update({name: {'grades': grades, 'mean': mean(grades)}}) print(some_dict) print(sorted(some_dict.items())) Output: Average of John --&gt; 4.272727 Average of Alice --&gt; 17.428571 Average of Bill --&gt; 15.250000 Average of Sarah --&gt; 4.857143 Average of Martin --&gt; 3.875000 {'John': {'grades': [1, 2, 3, 5, 21, 2, 3, 2, 1, 2, 5], 'mean': 4.2727272727272725}, 'Alice': {'grades': [5, 31, 6, 73, 4, 2, 1], 'mean': 17.428571428571427}, 'Bill': {'grades': [7, 4, 6, 78, 3, 1, 2, 21], 'mean': 15.25}, 'Sarah': {'grades': [2, 3, 5, 6, 4, 7, 7], 'mean': 4.857142857142857}, 'Martin': {'grades': [2, 4, 6, 3, 8, 2, 3, 3], 'mean': 3.875}} [('Alice', {'grades': [5, 31, 6, 73, 4, 2, 1], 'mean': 17.428571428571427}), ('Bill', {'grades': [7, 4, 6, 78, 3, 1, 2, 21], 'mean': 15.25}), ('John', {'grades': [1, 2, 3, 5, 21, 2, 3, 2, 1, 2, 5], 'mean': 4.2727272727272725}), ('Martin', {'grades': [2, 4, 6, 3, 8, 2, 3, 3], 'mean': 3.875}), ('Sarah', {'grades': [2, 3, 5, 6, 4, 7, 7], 'mean': 4.857142857142857})]
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50344027
type: AcceptedAnswer

http://stackoverflow.com/comment/87614869
type: Comment
has text: @FHTMitchell I made some tests that confirm your benchmark. Usual time-space tradeoff (small joke: it's faster until you hit the swap...) But I think one shouldn't make a copy in such a case. It's faster in Python, but will be slower in another language. My opinion is that it's a good habit to avoid copies, unless you *have to* make a copy (performance issue, iterate twice sequentially, ...).
comment on: http://stackoverflow.com/a/50290916
score: 0
type: AnswerComment

http://stackoverflow.com/q/50256456
type: Question
type: UnansweredQuestion
tagged with: python
has body: When in the Python shell I type: import MySQLdb Con = MySQLdb.Connect(user='testuser', password='password', db='test') And I get this: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\Nickey\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "C:\Users\Nickey\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, &lt;NULL&gt;) And no description of the error at all. Please, I am waiting for help. Thanks. UPDATE: In case somebody will be having this problem, it appears to be connected with the new mysql_auth_plugin, with its new Strong Password Encryption for Authentication. I just switched to old_password_plugin(Legacy Authentication Method) in the configuration of MySQL Server and now [All works!].
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50256563
answer count: 1
has title: Python can't connect to MySQL db: OperationalError
tagged with: mysql
favorite count: 0

http://stackoverflow.com/a/50355431
answers question: http://stackoverflow.com/q/50355330
has body: I would sugest you to name the variables in a way that makes them self-explanatory. It makes the code much more readable for anyone else and reduces the need for comments. For math operations you can just use simple a and b or x and y.
type: Answer
score: -1
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/87629950
type: Comment
has text: with your code I got this: `TypeError: generate_slug() missing 1 required positional argument: 'self'`
type: AnswerComment
comment on: http://stackoverflow.com/a/50305946
score: 0

http://stackoverflow.com/comment/87632521
has text: If batch_size is None, then you need to use tf.shape() only
type: Comment
comment on: http://stackoverflow.com/a/50307810
type: AnswerComment
score: 1

http://stackoverflow.com/q/50244697
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/50283225
has answer: http://stackoverflow.com/a/50283225
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/87507012
has title: neural network xor gate classification
type: AnsweredQuestion
score: 0
tagged with: backpropagation
has body: I've written a simple neural network that can predict XOR gate function. I think I've used the math correctly, but the loss doesn't go down and remains near 0.6. Can anyone help me find the reason why? import numpy as np import matplotlib as plt train_X = np.array([[0,0],[0,1],[1,0],[1,1]]).T train_Y = np.array([[0,1,1,0]]) test_X = np.array([[0,0],[0,1],[1,0],[1,1]]).T test_Y = np.array([[0,1,1,0]]) learning_rate = 0.1 S = 5 def sigmoid(z): return 1/(1+np.exp(-z)) def sigmoid_derivative(z): return sigmoid(z)*(1-sigmoid(z)) S0, S1, S2 = 2, 5, 1 m = 4 w1 = np.random.randn(S1, S0) * 0.01 b1 = np.zeros((S1, 1)) w2 = np.random.randn(S2, S1) * 0.01 b2 = np.zeros((S2, 1)) for i in range(1000000): Z1 = np.dot(w1, train_X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(w2, A1) + b2 A2 = sigmoid(Z2) J = np.sum(-train_Y * np.log(A2) + (train_Y-1) * np.log(1-A2)) / m dZ2 = A2 - train_Y dW2 = np.dot(dZ2, A1.T) / m dB2 = np.sum(dZ2, axis = 1, keepdims = True) / m dZ1 = np.dot(w2.T, dZ2) * sigmoid_derivative(Z1) dW1 = np.dot(dZ1, train_X.T) / m dB1 = np.sum(dZ1, axis = 1, keepdims = True) / m w1 = w1 - dW1 * 0.03 w2 = w2 - dW2 * 0.03 b1 = b1 - dB1 * 0.03 b2 = b2 - dB2 * 0.03 print(J)

vector
tags question: http://stackoverflow.com/q/50247500
type: Tag
tag name: vector
tags question: http://stackoverflow.com/q/50358784
tags question: http://stackoverflow.com/q/50309792
tags question: http://stackoverflow.com/q/50309137

http://stackoverflow.com/comment/87502919
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50242565
score: 0
has text: 1) specify current dir (current dir sometimes not in path) and 2) don't use shlex, just pass the args in a list

http://stackoverflow.com/comment/124086071
comment on: http://stackoverflow.com/a/65933710
score: 0
type: Comment
type: AnswerComment
has text: Having tried `nbimporter` for the whole of 2 minutes, it seems a pretty dumb piece of software, as it tries to parse the Markdown parts of the Notebook: ```---> 14 "\n", 15 "## Actions:\n", 16 " \n", NameError: name 'actions' is not defined``` it clearly does *import* the notebook (no trouble with directories) because it can see the function I'm invoking, but then it is an epic fail.

http://stackoverflow.com/q/50286439
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has body: number=list(map(lambda x:int(x), input().split())) first=".|." second='-' median=((number[0]-1)//2)+1 def Door(number[0],number[1]): # &lt;&lt;-- this one is resulting in a syntax error. So I still fail to understand what is wrong with this code. Can you please help me? Thank you.
has title: Why is there a syntax error in my Python function?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87588964
upvote count: 0
has answer: http://stackoverflow.com/a/50287468
accepted answer: http://stackoverflow.com/a/50287468
tagged with: function
answer count: 1

http://stackoverflow.com/a/50342211
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/50342184
has body: re.sub(r'([a-z])-([a-z])', r'\1\2', "hyphen-ated Asia-Pacific 11-12") Captures the letters before and after the hyphen and preserves them when stripping the hyphen. \1 and \2 denotes the first and second captured group, which are the letters in this case. Your current code matches the two letters around the hyphen and removes the whole match. You should preserve the letters when substituting.
type: Answer
has comment: http://stackoverflow.com/comment/87700316

http://stackoverflow.com/comment/87576304
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50278818
has text: Try updating your post bringing little more clarity, otherwise one has to inspect element and apply your xpath in the broser console to find out which links you wanna parse. You should describe mentioning the visible text so that it is easier to find out what you wanna achieve. Thanks.
score: 1

http://stackoverflow.com/comment/87735384
score: 0
comment on: http://stackoverflow.com/a/50344204
type: Comment
type: AnswerComment
has text: It depends on how you choose to query. If you first extract the array and then check containment, you need the functional index on the extracted path only. If you check containment starting from the root, you need to index the whole thing.

http://stackoverflow.com/q/50268576
tagged with: python
has answer: http://stackoverflow.com/a/50268654
has answer: http://stackoverflow.com/a/50268672
has title: Python Extracting Data from JSON without a label?
has body: The API here: https://api.bitfinex.com/v2/tickers?symbols=ALL does not have any labels and I want to extract all of the tBTCUSD, tLTCUSD etc.. Basically everything without numbers. Normally, i would extract this information if they are labeled so i can do something like: data['name'] or something like that however this API does not have labels.. how can i get this info with python?
answer count: 3
upvote count: 2
score: 1
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
favorite count: 0
type: Question
tagged with: extract
has answer: http://stackoverflow.com/a/50268675
type: UnansweredQuestion
tagged with: info

http://stackoverflow.com/comment/87746332
comment on: http://stackoverflow.com/q/50324400
type: Comment
score: 0
type: QuestionComment
has text: pip list or pip freeze

http://stackoverflow.com/comment/87597831
type: QuestionComment
has text: why don't you try it yourself? you should mention what you are trying, what are yoy expecting and what's going wrong
comment on: http://stackoverflow.com/q/50290872
score: 0
type: Comment

http://stackoverflow.com/comment/87528532
comment on: http://stackoverflow.com/q/50255044
has text: One useful thing to rationalize accuracy is to understand how many frauds you have over legit transactions. If your dataset is very imbalanced, e.g. with just 1 transaction being fraudulent every 999 legit ones, the classifier that always outputs "legit" is a 99.9% accurate baseline :)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50340740
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50340289
score: 1
has body: reuse=True means that the variables have been created previously with reuse=False, so each tf.get_variable (in your case abstracted behind the LSTM interface) expects the variable to already exist. To have a mode in which variables created if they do not exist yet, and reused otherwise, you need to set reuse=tf.AUTO_REUSE (as the error message suggests). So replace all occurrences of reuse=True with reuse=tf.AUTO_REUSE Here's the documentation: https://www.tensorflow.org/api_docs/python/tf/variable_scope
type: Answer
answers question: http://stackoverflow.com/q/50340289

http://stackoverflow.com/a/50278658
score: 1
has body: As I mentioned in my comment, the likely issue is that somewhere upstream in your code, you assigned a slice of some other pd.DataFrame to df. This is a common cause of confusion and is also explained under why-does-assignment-fail-when-using-chained-indexing in the link that the Warning mentions. A minimal example: data = pd.DataFrame({'a':range(7), 'b':list('abcccdb')}) df = data[data.a % 2 == 0] #making a subselection of the DataFrame df['b'] = 'b' /home/user/miniconda3/envs/myenv/lib/python3.6/site-packages/ipykernel_launcher.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 """Entry point for launching an IPython kernel. Notice that this section: df = data[data.a % 2 == 0] #making a subselection of the DataFrame df['b'] = 'b' could just as well be rewritten this way: data[data.a % 2 == 0]['b'] = 'b' #obvious chained indexing df = data[data.a % 2 == 0] The correct way of writing this bit is the following way: data = pd.DataFrame({'a':range(7), 'b':list('abcccdb')}) df = data.loc[data.a % 2 == 0].copy() #making a copy of the subselection df.loc[:,'b'] = 'b'
accepted answer of: http://stackoverflow.com/q/50278016
type: Answer
has comment: http://stackoverflow.com/comment/87575504
answers question: http://stackoverflow.com/q/50278016
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87574044

http://stackoverflow.com/comment/87690761
type: AnswerComment
comment on: http://stackoverflow.com/a/50302455
has text: NVM I had to use the absolute path for this to work no the 'Z:' drive. For other people if you are trying to get to a drive letter use the server name instead so for me Z:\mkb is '//Your-Server/server-folder/mkb'
type: Comment
score: 0

http://stackoverflow.com/comment/88662639
type: QuestionComment
score: 0
has text: Does it help to change `jvv={'unit':'m', 'unitValue':12}` to `jvv=[{'unit':'m', 'unitValue':12}]` ?
comment on: http://stackoverflow.com/q/50284728
type: Comment

http://stackoverflow.com/a/50238241
type: Answer
has comment: http://stackoverflow.com/comment/87495653
downvote count: 1
answers question: http://stackoverflow.com/q/50237911
has comment: http://stackoverflow.com/comment/87495941
has body: You can give a timedelta object as the width keyword argument, it will be converted to milliseconds. import datetime ... c.vbar('dt', top='pct_change', width=datetime.timedelta(days=1), source=source) NumberSpec can accept datetime values, unless accept_datetime is set to false.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50237911
upvote count: 10
score: 9

http://stackoverflow.com/comment/87665645
has text: Sure; just add your code right before the `continue` statement. It is only executed (due to the prior in-line conditional) if the name is present but the number is empty. Add a new list to carry along and append `thename` to that list before `continue`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50324890

http://stackoverflow.com/a/50371257
answers question: http://stackoverflow.com/q/50370798
accepted answer of: http://stackoverflow.com/q/50370798
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87758687
score: 1
type: AcceptedAnswer
has body: All isinstance(foo, abc.Hashable) does is check that your object has a __hash__ method, this is what Python calls to hash an object. A class is itself an object and thus inherit the object.__hash__ method. class Foo: pass isinstance(Foo, object) # True Foo.__hash__ # &lt;slot wrapper '__hash__' of 'object' objects&gt; hash(Foo) # -9223371900938361605

http://stackoverflow.com/q/50249478
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/87516450
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87516338
has comment: http://stackoverflow.com/comment/87529721
has comment: http://stackoverflow.com/comment/87538819
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/87516335
type: Question
tagged with: numpy
has title: IndexError in Python with Numpy array
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50249625
has body: I have following code that keeps giving me an IndexError and I simply can't see why: mainMenu = np.array(['Load new data', 'Check for data errors', 'Generate plots', 'Display list of grades', 'Quit']) if choice == 2 or choice == 3 or choice == 4: print("Please load data before you {:s}".format(mainMenu[choice-1])) continue The last part is what's giving the error: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices Can anyone see what the problem is here?
has answer: http://stackoverflow.com/a/50249625
upvote count: 0
answer count: 1

http://stackoverflow.com/q/50260676
has comment: http://stackoverflow.com/comment/87540647
has body: I wrote a code that uses a parameter in certain file names, locations, etc. (simplified below): file_type = sys.argv[1] [...] parent_folder = 'C:/path/to/dir/' input_folder = parent_folder + file_type + '_inventory' output_folder = parent_folder + file_type + '_export' So the parameter file_type can be FOO, BAR, or FOOBAR, and that will determine which dir/files are used. But, I have been trying to find a more robust way to incorporate ALL into this parameter. Currently, I have IF ELSE statements, where one option has my script copied multiple times with each parameter choice hardcoded in; for when file_type = ALL. There should be a way to have it loop through a set of values/strings instead of duplicating the code, but I have not been able to find any semblance of it. Please let me know if I need to elaborate more.
has comment: http://stackoverflow.com/comment/87539482
tagged with: python
has comment: http://stackoverflow.com/comment/87540290
has comment: http://stackoverflow.com/comment/87539458
has comment: http://stackoverflow.com/comment/87570194
tagged with: parameters
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50281167
has comment: http://stackoverflow.com/comment/87540218
answer count: 1
upvote count: 1
has title: Python: Looping through all parameter options
has answer: http://stackoverflow.com/a/50281167
tagged with: loops
has comment: http://stackoverflow.com/comment/87539533
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50320776
accepted answer: http://stackoverflow.com/a/50320956
favorite count: 0
linked to: http://stackoverflow.com/q/37057187
type: Question
upvote count: 4
tagged with: interpolation
has answer: http://stackoverflow.com/a/50320956
has title: transform on multiple columns to interpolate/copy missing values
tagged with: python
score: 4
has body: I'm trying to fill out missing values in a pandas dataframe by interpolating or copying the last-known value within a group (identified by trip). My data looks like this: brake speed trip 0 0.0 NaN 1 1 1.0 NaN 1 2 NaN 1.264 1 3 NaN 0.000 1 4 0.0 NaN 1 5 NaN 1.264 1 6 NaN 6.704 1 7 1.0 NaN 1 8 0.0 NaN 1 9 NaN 11.746 2 10 1.0 NaN 2 11 0.0 NaN 2 12 NaN 16.961 3 13 1.0 NaN 3 14 NaN 11.832 3 15 0.0 NaN 3 16 NaN 17.082 3 17 NaN 22.435 3 18 NaN 28.707 3 19 NaN 34.216 3 I have found Pandas interpolate within a groupby but I need brake to simply be copied from the last-known, yet speed to be interpolated (my actual dataset has 12 columns that each need such treatment)
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/50276826
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
has title: When accessed similarly, why does a SQLAlchemy relationship return differently?
accepted answer: http://stackoverflow.com/a/50277707
tagged with: python
has answer: http://stackoverflow.com/a/50277707
type: AnsweredQuestion
has body: With this simplified model: class User(db.Model): id = db.Column(db.Integer, primary_key=True) # other attributes #user many-to-many size associations (using link tables) sz_shirt_dress_sleeve = db.relationship( 'SizeKeyShirtDressSleeve', secondary=LinkUserSizeShirtDressSleeve, backref=db.backref('users', lazy='dynamic')) strange = {'whyisthisdifferent': db.relationship( 'SizeKeyShirtDressNeck', secondary=LinkUserSizeShirtDressNeck, backref=db.backref('users', lazy='dynamic'))} I would assume that I can use both of these to access the relationship, but it isn't so. See this interactive session: &gt;&gt;&gt; from app import db &gt;&gt;&gt; from app.models import User &gt;&gt;&gt; u1 = User.query.first() &gt;&gt;&gt; u1 &lt;User id: 1, email: 'admin@admin.com', password_hash: 'pbkdf2:sha256:50000$n2qsqVfu$8d1bc6b0a472818175c21c1a31031ece58e78feca9c6d15a326b28bd7fd80e67'&gt; &gt;&gt;&gt; u1.strange['whyisthisdifferent'] &lt;RelationshipProperty at 0x106c6d248; no key&gt; &gt;&gt;&gt; u1.sz_shirt_dress_sleeve [Dress shirt sleeve size: 3000] Why does accessing by u1.sz_shirt_dress_sleeve actually return the result of the query when u1.strange['whyisthisdifferent'] returns the relationship signature? This reminds me of the Javascript difference between returning a function definition or a function literal, but this isn't Javascript. I do believe that reading the SQLAlchemy Association Proxy documentation will actually get me what I want, but I would still like to understand this behavior.
score: 0
answer count: 1

http://stackoverflow.com/comment/87654702
type: Comment
has text: Strange. I was pretty sure to have corrected it. Oh, well. All good now.
type: AnswerComment
comment on: http://stackoverflow.com/a/50319233
score: 0

http://stackoverflow.com/comment/87771324
type: Comment
has text: @IgorBraga You can check if the word exists in the reversed substring. Please see my recent edit.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50377104

http://stackoverflow.com/comment/87714966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50349451
score: 0
has text: Not 100% sure regex is the way to go, unless you can be sure that no street names start with a number (e.g. 5th Avenue).

http://stackoverflow.com/comment/87676474
score: 0
type: AnswerComment
has text: Thank you for your answer. I'm wondering how do I know which line I'm pulling a value from? When I try both samples in my code it now prints an empty file when I put if I = 1 do command.
comment on: http://stackoverflow.com/a/50329686
type: Comment

http://stackoverflow.com/comment/87800705
score: 1
type: QuestionComment
has text: Ohh, okay, thanks. I also found more explanation (for others having the same misconception): Note that you can use two different time unit formats: sexagesimal (HOURS:MM:SS.MILLISECONDS, as in 01:23:45.678), or in seconds. If a fraction is used, such as 02:30.05, this is interpreted as "5 100ths of a second", not as frame 5. For instance, 02:30.5 would be 2 minutes, 30 seconds, and a half a second, which would be the same as using 150.5 in seconds. https://trac.ffmpeg.org/wiki/Seeking#Timeunitsyntax
type: Comment
comment on: http://stackoverflow.com/q/50372010

http://stackoverflow.com/comment/87754096
type: Comment
type: QuestionComment
has text: Do you mean you are running Python in a virtualenv?
comment on: http://stackoverflow.com/q/50369050
score: 1

http://stackoverflow.com/comment/87492838
type: QuestionComment
comment on: http://stackoverflow.com/q/50237021
score: 0
has text: Wouldn't it be a better idea to use Azure SDK directly in your script? After all the CLI is written as an application instead of a library.
type: Comment

http://stackoverflow.com/a/50267104
downvote count: 0
has comment: http://stackoverflow.com/comment/87588907
type: Answer
accepted answer of: http://stackoverflow.com/q/50266369
upvote count: 2
type: AcceptedAnswer
has body: product.icon.url return '/media/images/myimage.png' Use this code in project url.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) image URL should be like this 'http://127.0.0.1:8000/media/images/myimage.png' in setting.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
score: 2
answers question: http://stackoverflow.com/q/50266369

google-cloud-pubsub
tags question: http://stackoverflow.com/q/50230455
type: Tag
tag name: google-cloud-pubsub

http://stackoverflow.com/a/50350826
score: 2
has comment: http://stackoverflow.com/comment/87717930
has body: Updated ... Again I misinterpreted the question. If you are using large lists then list comprehensions are the way to go and they are fairly simple once you learn how to use them. I am going to use two list comprehensions. idxs = [i for i, val in enumerate(l2) if val in l1] + [len(l2)+1] res = {l2[idxs[i]]: list(l2[idxs[i]+1: idxs[i+1]]) for i in range(len(idxs)-1)} print(res) Results: {'a': ['el1', 'el2', 'el3', 'el4'], 'b': ['some_other_el_1', 'some_other_el_2'], 'c': ['another_element_1', 'another_element_2'], 'd': ['', '', 'another_element_3', 'd4']} Speed Testing for large lists: import collections l1 = ['a', 'c', 'b', 'e', 'f', 'd'] l2 = [ 'x','q','we','da','po', 'a', 'el1', 'el2', 'el3', 'el4', *(str(i) for i in range(300)), 'b', 'some_other_el_1', 'some_other_el_2', *(str(i) for i in range(100)), 'c', 'another_element_1', 'another_element_2', *(str(i) for i in range(200)), 'd', '', '', 'another_element_3', 'd4' ] def run_comp(): idxs = [i for i, val in enumerate(l2) if val in l1] + [len(l2)+1] res = {l2[idxs[i]]: list(l2[idxs[i]+1: idxs[i+1]]) for i in range(len(idxs)-1)} def run_other(): d = collections.defaultdict(list) k = '' for x in l2: if x in l1: k = x else: d[k].append(x) import timeit print('For Loop:', timeit.timeit(run_other, number=1000)) print("List Comprehension:", timeit.timeit(run_comp, number=1000)) Results: For Loop: 0.1327093063242541 List Comprehension: 0.09343156142774986 old stuff below This is rather simple with list comprehensions. {key: [val for val in l2 if key in val] for key in l1} Results: {'a': ['a', 'a1', 'a2', 'a3', 'a4'], 'b': ['b', 'b1', 'b2', 'b3', 'b4'], 'c': ['c', 'c1', 'c2', 'c3', 'c4'], 'd': ['d', 'd1', 'd2', 'd3', 'd4'], 'e': [], 'f': []} The code below shows what is happening above. d = {} for key in l1: d[key] = [] for val in l2: if key in val: d[key].append(val) The list comprehension / dictionary comprehension (First piece of code) is actually way faster. List comprehensions are creating the list in place which is …
answers question: http://stackoverflow.com/q/50350456
has comment: http://stackoverflow.com/comment/87720442
has comment: http://stackoverflow.com/comment/87717978
has comment: http://stackoverflow.com/comment/87718274
type: Answer
has comment: http://stackoverflow.com/comment/87717850
has comment: http://stackoverflow.com/comment/87718191
has comment: http://stackoverflow.com/comment/87719903
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/50319744
has comment: http://stackoverflow.com/comment/87656391
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/87656033
has body: To remove a line break, you can try using \n not /n, i.e.: Linux, macOS tags[0].text.replace('\n',' ') Windows tags[0].text.replace('\r\n',' ') Or use strip(): tags[0].text.strip() Newline Frequently called line ending, end of line (EOL), line feed, or line break, is a control character in a character encoding specification, like e.g. ASCII. It is used to signify the end of a line of text and the start of a new one. Text editors set this special character when pressing the Enter key. Representations in different character encoding specifications Multics, Unix and Unix-like systems (Linux, macOS, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others1 - Escape sequence: \n Atari TOS, Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM operating systems - Escape sequence : \r\n Unicode The Unicode standard defines a number of characters that conforming applications should recognize as line terminators: LF: Line Feed, U+000A VT: Vertical Tab, U+000B FF: Form Feed, U+000C CR: Carriage Return, U+000D CR+LF: CR (U+000D) followed by LF (U+000A) NEL: Next Line, U+0085 LS: Line Separator, U+2028 PS: Paragraph Separator, U+2029
type: Answer
answers question: http://stackoverflow.com/q/50319663
upvote count: 1
has comment: http://stackoverflow.com/comment/87656093

smime
tags question: http://stackoverflow.com/q/50321667
type: Tag
tag name: smime

http://stackoverflow.com/a/50256638
type: Answer
score: 5
has body: I think need: #add _ to end of values liste = [record.id + '_' for record in SeqIO.parse(data, "fasta")] #liste = ["gene1_","gene2_","gene3_","gene4_","gene5_"] #get boolean mask for each column m1 = df['name1'].str.contains('|'.join(liste)) m2 = df['name2'].str.contains('|'.join(liste)) #chain masks and count Trues a = (m1 &amp; m2).sum() print (a) 3 EDIT: liste=["EOG090X00LI","EOG090X00GO","EOG090X00BA"] #extract each values before _, remove duplicates and compare by liste a = name1.str.split('_').str[0].drop_duplicates().isin(liste) b = name2.str.split('_').str[0].drop_duplicates().isin(liste) #compare a with a for equal and sum Trues c = a.eq(b).sum() print (c) 2
downvote count: 0
answers question: http://stackoverflow.com/q/50256344
has comment: http://stackoverflow.com/comment/87532215
upvote count: 5

http://stackoverflow.com/a/59989774
upvote count: 14
type: Answer
answers question: http://stackoverflow.com/q/50307707
has comment: http://stackoverflow.com/comment/125974325
has body: You can use below functions to convert any dataframe or pandas series to a pytorch tensor import pandas as pd import torch # determine the supported device def get_device(): if torch.cuda.is_available(): device = torch.device('cuda:0') else: device = torch.device('cpu') # don't have GPU return device # convert a df to tensor to be used in pytorch def df_to_tensor(df): device = get_device() return torch.from_numpy(df.values).float().to(device) df_tensor = df_to_tensor(df) series_tensor = df_to_tensor(series)
has comment: http://stackoverflow.com/comment/125991794
downvote count: 0
score: 14

http://stackoverflow.com/comment/87789489
comment on: http://stackoverflow.com/a/50376865
type: Comment
score: 0
type: AnswerComment
has text: Ho nice. Works perfectly.

test-coverage
tags question: http://stackoverflow.com/q/50370847
type: Tag
tag name: test-coverage

http://stackoverflow.com/q/50310493
has comment: http://stackoverflow.com/comment/87638004
has title: Python 3 encode error Google Translate API
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/87638083
type: Question
has answer: http://stackoverflow.com/a/50316015
tagged with: python-3.x
has body: I'm trying to translate the contents of a text file encoded in UTF16-BE using the Google Translate API as explained on this site: https://ctrlq.org/code/19909-google-translate-api. I want the output file to be in the same encoding. Here are a few snippets from my code: ... import json import urllib from urllib.request import Request, urlopen import urllib.parse ... def googletranslate(sourceLang, targetLang, sourceText): url = "https://translate.googleapis.com/translate_a/single?client=gtx&amp;sl=" + sourceLang + "&amp;tl=" + targetLang + "&amp;dt=t&amp;q=" + urllib.parse.quote_plus(sourceText) urld = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) jsonfile = urlopen(urld).read() h = json.loads(jsonfile) return h[0][0][0] ... input = [line.rstrip('\n') for line in open('input.txt', 'r', encoding="utf_16_be")] output = open('output.txt', 'w', encoding="utf_16_be") ... for y in range(offset,offset+size): text = input[y] text = googletranslate('auto', '&lt;desired language&gt;', text) text.encode('utf_16_be') print("T: " + text) output.write(text + '\n') ... However, when I try to run this, it works for most lines but eventually I'll get an error like this: T: &lt;translated text&gt; Traceback (most recent call last): File "C:\PATH\TO\translate.py", line 124, in googletranslate output.write(text + '\n') File "C:\PATH\TO\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u0259' in position 22: character maps to &lt;undefined&gt; What can I do to prevent this error? It seems to print fine in the command prompt. It only gives me an error when trying to write to the output file. Should I choose a different encoding? Is UTF16-BE not sufficient for Google Translated text? Thanks in advance!
tagged with: encoding
tagged with: python
has comment: http://stackoverflow.com/comment/87638424
accepted answer: http://stackoverflow.com/a/50316015
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/87637146
has comment: http://stackoverflow.com/comment/87637073

http://stackoverflow.com/q/50279180
has comment: http://stackoverflow.com/comment/87575678
has comment: http://stackoverflow.com/comment/87576161
tagged with: pybinding
has comment: http://stackoverflow.com/comment/87589408
tagged with: c++
type: AnsweredQuestion
tagged with: constructor
has comment: http://stackoverflow.com/comment/87576479
upvote count: 3
downvote count: 0
has body: In a C++ library that I'm not allowed to change I have a constructor that looks like this: Dfa(const int n_state, const int dim_alf, const string *alf); If I simply bind with .def(py::init&lt;const int, const int, const std::string*&gt;()) it compiles succesfully. The problem is that I can't pass a string* by python, because for example if I try to execute on python alph=['x','y'] z=Dfa(3,2,alph) It returns the following error: TypeError: __init__(): incompatible constructor arguments. The following argument types are supported: gi_gipy.Dfa(arg0: int, arg1: int, arg2: unicode) User "R zu" kindly suggested me to write a wrapper, but I can't figure out how. Given that what in python is something like: ['x','y'] , in c++ is accepted as std::list&lt;std::string&gt; , I tried writing the following code: .def(py::init([](int n_state,int dim_alf, std::list&lt;std::string&gt; alph){ std::string* alfabeto=new std::string[dim_alf]; std::list&lt;string&gt;::iterator it=alph.begin(); for(int i=0;it!=alph.end();++i,++it) alfabeto[i]=*it; Dfa::Dfa(n_state,dim_alf,alfabeto); })) but it returns to me 2 errors: cannot pass expression of type 'void' to variadic function construct&lt;Class&gt;(v_h, func(std::forward&lt;Args&gt;(args)...) and static_assert failed "pybind11::init(): init function must return a compatible pointer, holder, or value" static_assert(!std::is_same&lt;Class, Class&gt;::value /* always false */ It is clear that I'm a bit confused on how to overcome this problem, that I think is connected to the use of a pointer to string as a parameter to a constructor. I repeat that I can't change the library, I can only create the appropriate binding. Thank you for your attention
answer count: 1
has comment: http://stackoverflow.com/comment/87576709
has comment: http://stackoverflow.com/comment/87579186
has title: Pybind11: passing a string* argument to a constructor
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87577963
has comment: http://stackoverflow.com/comment/87576122
score: 3
accepted answer: http://stackoverflow.com/a/50310171
tagged with: pybind11
tagged with: python
has answer: http://stackoverflow.com/a/50310171

http://stackoverflow.com/q/50328058
answer count: 2
tagged with: printing
accepted answer: http://stackoverflow.com/a/50329172
downvote count: 0
tagged with: window
tagged with: cmd
tagged with: output
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/50328715
possible better answer: http://stackoverflow.com/a/50328715
has title: Print the output of a python code in a new cmd window
has comment: http://stackoverflow.com/comment/87673006
tagged with: python
has comment: http://stackoverflow.com/comment/87674224
has comment: http://stackoverflow.com/comment/87673224
type: AnsweredQuestion
has body: I want to open a cmd window and use it to print some variables. The problem is that, the code below, opens 5 independent windows (ovbiously). import os for i in range(0,5): command = "start cmd /K echo " + str(i+1) os.system(command) I dont know if I can have a reference or a link to the already opened window to send it the commands. The desired result would be... 1 2 3 4 5 ...on the same window The purpose is to be able to print on that window certain variables during the execution of a code. I'm stucked and I don't know if that is even possible. Im on W10 with Python 2.7 Thank you very much
upvote count: 3
has answer: http://stackoverflow.com/a/50329172

http://stackoverflow.com/comment/87758864
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50369919
type: AnswerComment
has text: how did you import `col`?

http://stackoverflow.com/comment/87484909
comment on: http://stackoverflow.com/q/50233521
type: Comment
type: QuestionComment
has text: You say your data structure looks strange. It looks OK to me. What's strange about it? What did you expect it to look like?
score: 0

http://stackoverflow.com/q/50332909
upvote count: 1
linked to: http://stackoverflow.com/q/15479928
accepted answer: http://stackoverflow.com/a/50333013
has comment: http://stackoverflow.com/comment/87681943
possible better answer: http://stackoverflow.com/a/50333042
favorite count: 0
has answer: http://stackoverflow.com/a/50333042
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: Need to generate csv output in python as below
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/50333013
has comment: http://stackoverflow.com/comment/87681916
type: AnsweredQuestion
has body: import csv d={'a':[1,3,4],'b':[2,3,4],'c':[1]} with open("result.csv","w") as csv_file: csv_writer = csv.writer(csv_file,dialect='excel') csv_writer.writerows(d.items()) need to get the output as below: a 1 3 4 b 2 3 4 c 1
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/87682048

http://stackoverflow.com/q/50265479
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50265986
accepted answer: http://stackoverflow.com/a/50265986
possible better answer: http://stackoverflow.com/a/64452555
tagged with: treeview
has answer: http://stackoverflow.com/a/64452555
type: Question
tagged with: python-3.x
tagged with: tkinter
answer count: 2
has body: I am trying to create a subclass of ttk.Treeview mostly in order to keep an list of all of the used iids in the tree. So I am trying to override the delete method but keep getting an error when I try to call the super's delete method. If I bypass the delete override then I get no errors. But with it in I get this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__ return self.func(*args) File "/home/sean/.PyCharmCE2018.1/config/scratches/scratch_1.py", line 12, in but_handle sl.delete(c) File "/home/sean/.PyCharmCE2018.1/config/scratches/scratch_1.py", line 8, in delete super(Tree, self).delete(self, items) File "/usr/lib/python3.5/tkinter/ttk.py", line 1219, in delete self.tk.call(self._w, "delete", items) _tkinter.TclError: Item .140356823468016 not found Here is the code: import tkinter as tk from tkinter import ttk class Tree(ttk.Treeview): s = 1 def delete(self, *items): super(Tree, self).delete(self, *items) # Error occurs here # in use i will delete the iid from a list here def but_handle(): for c in sl.get_children(): sl.delete(c) if __name__ == '__main__': root = tk.Tk() but = tk.Button(command=but_handle) but.pack(side='top') sl = Tree() sl.pack() sl.insert('', 'end', None, text='a') sl.insert('', 'end', None, text='b') sl.insert('', 'end', None, text='c') sl.insert('', 'end', None, text='d') sl.insert('', 'end', None, text='e') root.mainloop() What am I doing wrong here?
has title: Problems overriding delete method on ttk.Treeview
tagged with: ttk
tagged with: python

bar-chart
tags question: http://stackoverflow.com/q/50379670
tags question: http://stackoverflow.com/q/50279865
tags question: http://stackoverflow.com/q/50352511
tags question: http://stackoverflow.com/q/50239408
tags question: http://stackoverflow.com/q/50319614
tags question: http://stackoverflow.com/q/50257320
tag name: bar-chart
type: Tag

http://stackoverflow.com/q/50241038
has comment: http://stackoverflow.com/comment/87499569
has comment: http://stackoverflow.com/comment/87499529
has answer: http://stackoverflow.com/a/50241199
has body: I have to run the code every second and compare if the return values are equal or not for the current execution and a second before. I tried threading but i couldn't find a way to store the values to compare. import numpy as np import random def ran (): a = random.randint(1,101) return a
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50241257
has title: Running a function every second and compare with a value a second before.
type: Question
answer count: 2
score: 0
accepted answer: http://stackoverflow.com/a/50241199
possible better answer: http://stackoverflow.com/a/50241257

http://stackoverflow.com/q/50241441
has comment: http://stackoverflow.com/comment/87501362
tagged with: django
tagged with: keyword-argument
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50241482
has body: I have a custom Form where I need to pass in the request.user.username so I can use that to fill out forms.ModelChoiceField based on what user is accessing it. Here is what I have views.py if request.method == 'POST': form = DepartmentForm(request.POST, username=request.user.username) # Do stuff else: form = DepartmentForm(username=request.user.username) forms.py class DepartmentForm(forms.Form): def __init__(self, *args, **kwargs): self.username = kwargs.pop('username', None) super(DepartmentForm, self).__init__(*args, **kwargs) Company = forms.ModelChoiceField(queryset=Company.objects.raw(''' SELECT DISTINCT c.id, c.name, c.createdBy, c.allowedTeam_ID FROM projects_company AS c LEFT JOIN auth_user_groups AS aug ON c.allowedTeam_id=aug.group_id LEFT JOIN auth_user AS au ON aug.user_id=au.id WHERE au.username = %s OR c.createdBy = %s''', [self.username, self.username]), empty_label='Select company', widget=forms.Select(attrs={'class': 'materialSelect', 'id': 'companyDropdown'})) But when I try to select fill out self.username, I get: NameError: name 'self' is not defined I tried searching for my solution, but none of the ones I found seem to work. I would appreciate any help you guys can give. If you need more information, please don't hesitate to ask, and I will update the question accordingly. This is the error I'm getting: line 25, in DepartmentForm [self.username, self.username]), NameError: name 'self' is not defined Which is the end of the query where I select based on self.username
score: 0
has answer: http://stackoverflow.com/a/50241932
tagged with: forms
possible better answer: http://stackoverflow.com/a/50241482
has comment: http://stackoverflow.com/comment/87501190
type: Question
has title: Pass username to Django form
answer count: 2
accepted answer: http://stackoverflow.com/a/50241932

http://stackoverflow.com/comment/87694532
score: 1
type: Comment
has text: @VeltzerDoron Thank you so much for your comments and help. One quick question though, your code returns a list of [3,5,7,9,15] when I tested it with task(20) and 9, 15 are clearly not prime numbers, 17 and 19 are missing as well. Would you mind fixing your codes so I can learn where went wrong? Thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/50325085

http://stackoverflow.com/comment/87679732
has text: IIUC, the question means this: given a distribution for `GROUP`, generate 3 triplets, one per support element in the distribution, distributed according to `PROB`.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50330090

xpath
tags question: http://stackoverflow.com/q/50306719
tags question: http://stackoverflow.com/q/50248876
tags question: http://stackoverflow.com/q/50315587
tags question: http://stackoverflow.com/q/50355120
tags question: http://stackoverflow.com/q/50328482
tags question: http://stackoverflow.com/q/50279960
tag name: xpath
tags question: http://stackoverflow.com/q/50363291
tags question: http://stackoverflow.com/q/50309926
type: Tag
tags question: http://stackoverflow.com/q/50306562
tags question: http://stackoverflow.com/q/50285863
tags question: http://stackoverflow.com/q/50240686
tags question: http://stackoverflow.com/q/50294167
tags question: http://stackoverflow.com/q/50361774

http://stackoverflow.com/q/50323786
linked to: http://stackoverflow.com/q/30143417
answer count: 1
accepted answer: http://stackoverflow.com/a/50324015
has answer: http://stackoverflow.com/a/50324015
has title: compute correlation in numpy
type: AnsweredQuestion
score: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/30143417
type: Question
tagged with: numpy
has body: Suppose I have a 2d array ma with shape (n_rows_ma,n_cols_ma),and a 2d array mb with shape (n_rows_mb,n_cols_mb).Now I want to calculate the correlation between every row in ma and every row in mb. The easiest way may be import numpy as np correlation = np.corrcoef(ma,mb)[:n_rows_ma,n_rows_ma:] But this is too inefficient.So I wonder if there is a more efficient way?

http://stackoverflow.com/comment/87599937
has text: when i add the code like this `seleksi.append(p.select()) with open('test.csv','wb') as selection: selections = csv.writer(selection) for x in seleksi: selections.writerow(x)` it's just write index[0] @Netwave
comment on: http://stackoverflow.com/a/50291610
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50272352
type: UnansweredQuestion
has body: How can i install pymysql using my server. -bash-3.2$ python script.py 'US' Trace back (most recent call last): File "script.py", line 5, in import pymysql Import Error: No module named pymysql
has title: PyMySQL: I am getting an error importing PyMySQL module in python
tagged with: python
has answer: http://stackoverflow.com/a/50272394
answer count: 2
has comment: http://stackoverflow.com/comment/87562556
has comment: http://stackoverflow.com/comment/87561655
downvote count: 0
tagged with: pymysql
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50272387
tagged with: server

http://stackoverflow.com/q/50296097
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/127517500
tagged with: dictionary
linked to: http://stackoverflow.com/q/66208077
has body: I'm sure this must be simple, but I could not find the answer. I have a dictionary like: d = {'a': 1, 'b':2} I'd like to access that via dot notation, like: d.a The SimpleNamespace is designed for this, but I cannot just pass the dict into the SimpleNamespace constructor. I get the error: TypeError: no positional arguments expected How do I initialize the SimpleNamespace from a dictionary?
has answer: http://stackoverflow.com/a/50296116
type: AnsweredQuestion
upvote count: 21
duplicate of: http://stackoverflow.com/q/334655
has title: How to initialize a SimpleNamespace from a dict
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/50490856
type: Question
score: 20
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50296116

http://stackoverflow.com/comment/87754723
score: 1
type: Comment
has text: The error message is telling you everything that's needed. You're using ',' instead of ':'.
type: QuestionComment
comment on: http://stackoverflow.com/q/50369338

http://stackoverflow.com/a/50270696
has body: Firstly, about FLAGS. As far as I have understood, the tasks and the workers are all defined in it. But I am confused how. Yes, this is the standard way to run tensorflow in distributed setting (your particular case is Between-Graph Replication strategy). Basically, the same script starts different nodes (workers, parameter server, etc), which perform the training together. This tutorial discusses various strategies in tensorflow and explains well how it translates to code. Here's an example how you can work with this script. Start 4 processes (2 ps server and 2 workers): # On ps0.example.com: $ python trainer.py \ --ps_hosts=ps0.example.com:2222,ps1.example.com:2222 \ --worker_hosts=worker0.example.com:2222,worker1.example.com:2222 \ --job_name=ps --task_index=0 # On ps1.example.com: $ python trainer.py \ --ps_hosts=ps0.example.com:2222,ps1.example.com:2222 \ --worker_hosts=worker0.example.com:2222,worker1.example.com:2222 \ --job_name=ps --task_index=1 # On worker0.example.com: $ python trainer.py \ --ps_hosts=ps0.example.com:2222,ps1.example.com:2222 \ --worker_hosts=worker0.example.com:2222,worker1.example.com:2222 \ --job_name=worker --task_index=0 # On worker1.example.com: $ python trainer.py \ --ps_hosts=ps0.example.com:2222,ps1.example.com:2222 \ --worker_hosts=worker0.example.com:2222,worker1.example.com:2222 \ --job_name=worker --task_index=1 Secondly, about the parsers. What are they and why do we use them here for? It's python way to deal with command line arguments: argparse. Different options allow to specify the type and bounds for each argument (thus define the validator), assign actions and much more (check out the documentation for available features). The parser then takes the command line string and magically sets the variables with just one call: FLAGS, unparsed = parser.parse_known_args()
answers question: http://stackoverflow.com/q/50267291
has comment: http://stackoverflow.com/comment/87559260
has comment: http://stackoverflow.com/comment/87559067
upvote count: 3
accepted answer of: http://stackoverflow.com/q/50267291
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87558872
score: 3
type: Answer

http://stackoverflow.com/comment/87598051
comment on: http://stackoverflow.com/a/50290794
has text: Honestly, neither `isfile` nor `exists` are necessary - the question is if the `open` works. Checking at different times is a potential race condition. Catching the exception is the better way to go. Anything that `isfile` also `exists`, so using both is even more redundant.
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/50368934
has answer: http://stackoverflow.com/a/50369156
upvote count: 3
downvote count: 2
answer count: 1
has title: Regex to match json in python
accepted answer: http://stackoverflow.com/a/50369156
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87754211
has comment: http://stackoverflow.com/comment/87754005
has comment: http://stackoverflow.com/comment/87753887
has comment: http://stackoverflow.com/comment/115558151
score: 1
has body: iam unable to get json object from string in python. i need to get items: from response text. i have tried, [items?:?]\s(\".*\") ReactDOM.render(React.createElement(BoxedLinksListView, { initialState: { items: [{ link: "https://www.sehir.edu.tr/en/academics/college-of-humanities-and-social-sciences", sort: 1, parentTitle: "", title: "College of Humanities and Social Sciences" }, { link: "https://www.sehir.edu.tr/en/academics/graduate-school-of-business/mba-in-islamic-finance-and-economics", sort: 82, parentTitle: "Graduate School of Business", title: "MBA in Islamic Finance and Economics (Thesis)" }, { link: "https://www.sehir.edu.tr/en/academics/graduate-school-of-business/mba-in-islamic-finance-and-economics", sort: 83, parentTitle: "Graduate School of Business", title: "MBA in Islamic Finance and Economics (Non-thesis)" }] } }
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/87753794
type: AnsweredQuestion

http://stackoverflow.com/q/50373678
possible better answer: http://stackoverflow.com/a/61751739
type: Question
score: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/50373928
has answer: http://stackoverflow.com/a/50373928
type: AnsweredQuestion
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/61751739
downvote count: 0
tagged with: neural-network
has body: Given that I trained several different models on the same data and all the neural networks I trained have the same architecture I would like to know if it's possible to restore those models, average their weights and initialise my weights using the average. This is an example of how the graph might look. Basically what I need is an average of the weights I am going to load. import tensorflow as tf import numpy as np #init model1 weights weights = { 'w1': tf.Variable(), 'w2': tf.Variable() } # init model1 biases biases = { 'b1': tf.Variable(), 'b2': tf.Variable() } #init model2 weights weights2 = { 'w1': tf.Variable(), 'w2': tf.Variable() } # init model2 biases biases2 = { 'b1': tf.Variable(), 'b2': tf.Variable(), } # this the average I want to create w = { 'w1': tf.Variable( tf.add(weights["w1"], weights2["w1"])/2 ), 'w2': tf.Variable( tf.add(weights["w2"], weights2["w2"])/2 ), 'w3': tf.Variable( tf.add(weights["w3"], weights2["w3"])/2 ) } # init biases b = { 'b1': tf.Variable( tf.add(biases["b1"], biases2["b1"])/2 ), 'b2': tf.Variable( tf.add(biases["b2"], biases2["b2"])/2 ), 'b3': tf.Variable( tf.add(biases["b3"], biases2["b3"])/2 ) } weights_saver = tf.train.Saver({ 'w1' : weights['w1'], 'w2' : weights['w2'], 'b1' : biases['b1'], 'b2' : biases['b2'] }) weights_saver2 = tf.train.Saver({ 'w1' : weights2['w1'], 'w2' : weights2['w2'], 'b1' : biases2['b1'], 'b2' : biases2['b2'] }) And this what I am want to get when I run the tf session. c contains the weights I want to use in order to start the training. # Create a session for running operations in the Graph. init_op = tf.global_variables_initializer() init_op2 = tf.local_variables_initializer() with tf.Session() as sess: coord = tf.train.Coordinator() # Initialize the variables (like the epoch counter). sess.run(init_op) sess.run(init_op2) weights_saver.restore( sess, 'my_model1/model_weights.ckpt' ) weights_saver2.restore( sess, 'my_model2/model_weights.ckpt' ) a = sess.run(weights) b = sess.run(weights2) c = sess.…
tagged with: tensorflow
favorite count: 0
has title: Tensorflow - Averaging model weights from restored models

http://stackoverflow.com/q/50235933
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50236510
has answer: http://stackoverflow.com/a/50235996
type: UnansweredQuestion
tagged with: python
has title: Substitute an interval of integers by string
tagged with: regex
has body: I want to replace all integers between 100 and 200 with the string test in my data. Here are some control cases: `this is a control 150` = `this is a control test` `this is a control 160` = `this is a control test` `this is a control 150000` = `this is a control 150000` My idea is to use regular expressions, and I have the following: re.sub("\d", "test", "this is a control 150") However, this substitutes all integers by test. Is there a way to limit it to only substituting 100-200?
answer count: 2
score: 1
upvote count: 3
downvote count: 2

http://stackoverflow.com/q/50274084
has body: I'm attempting to install pynacl on a new Windows machine with Python. Ran into the following error: raise Exception("ERROR: The 'make' utility is missing from PATH") Exception: ERROR: The 'make' utility is missing from PATH ---------------------------------------- Command ""c:\users\paul miller\appdata\local\programs\python\python37\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\PAULMI~1\\AppData\\Local\\Temp\\pip-install-wxwyakn7\\pynacl\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\PAULMI~1\AppData\Local\Temp\pip-record-syh9a1l_\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\PAULMI~1\AppData\Local\Temp\pip-install-wxwyakn7\pynacl\ In an attempt to resolve the exception, I installed GnuWin and added the path to my user and system PATH variables. I opened a new command window and verified that "make" executed. However, rerunning the install attempt with the following command resulted in the same exception: pip3 install pynacl What should I try next? EDIT 1: added screenshot to show Make working EDIT 2: Tried with easy_install as well, still getting the make error
answer count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/50276615
accepted answer: http://stackoverflow.com/a/50276615
type: Question
has title: Error installing Python package: make utility is missing from PATH
tagged with: exception
tagged with: package
tagged with: python
has comment: http://stackoverflow.com/comment/87565128
has comment: http://stackoverflow.com/comment/87566646
has comment: http://stackoverflow.com/comment/87567315
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87567608
score: 0
tagged with: installation

http://stackoverflow.com/q/50299456
has answer: http://stackoverflow.com/a/50350105
has answer: http://stackoverflow.com/a/50311891
downvote count: 0
tagged with: hdfs
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: distributed-filesystem
tagged with: ceph
has body: Which distributed file systems are supported by Dask? Specifically, from which file systems one could read dask.dataframe's? From the Dask documentation I can see that HDFS is certainly supported. Are any other distributed file systems supported, e.g. Ceph, etc? I could find some discussion on thoughts to support other file systems here: https://github.com/dask/distributed/issues/33 but no final conclusion, except that HDFS is "nastier" than other options. Thank you for your help!
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/50350105
has title: Distributed file systems supported by Python/Dask
tagged with: dask
accepted answer: http://stackoverflow.com/a/50311891
answer count: 2

http://stackoverflow.com/a/50321193
answers question: http://stackoverflow.com/q/50321100
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87679768
downvote count: 0
has comment: http://stackoverflow.com/comment/87697071
has body: I was answering your first post about an hour ago but you removed it. I'm not sure if this is the best way to do it but here is what I came up with: text = [ """120 Beats Per Minute (15) Cinema""", """A Little Night Music Theatre""", """A Wrinkle in Time (PG) Cinema""" ] text = ''.join(text) #Converting list of strings to one string start = " " #Start indication end = "</" #End indication clean_area = [] index = 0 while index < len(text): index = text.find(start, index) if index == -1: break clean_area.append(text[index+len(start):text.find(end, index)]) index += len(start) print(clean_area)
upvote count: 1

http://stackoverflow.com/comment/87525380
comment on: http://stackoverflow.com/a/50252288
type: Comment
type: AnswerComment
has text: thank you, request.headers.get('X-Forwarded-For') worked!
score: 0

http://stackoverflow.com/q/50286351
has title: Pandas Change column date format
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/50286408
downvote count: 0
accepted answer: http://stackoverflow.com/a/50286387
tagged with: python
has answer: http://stackoverflow.com/a/50286408
favorite count: 0
has answer: http://stackoverflow.com/a/50286387
score: 2
type: AnsweredQuestion
tagged with: pandas
has body: I have column in pandas dataframe as follows: 0 2018-04-06 1 2018-04-06 2 2018-04-09 3 2018-04-19 4 2018-04-19 5 2018-04-17 I want to convert this column into yyyy/mm/dd for which I have coaded as follows: def change_date_format(x): if x != 'nan' and x != '' and x != ' ' and x != 0: x = parse(x, dayfirst=True).strftime("%Y-%m-%d") return x else: return '' read4['Column Name'] = read4['Column Name'].apply(lambda x : change_date_format(x) ) But it's convert as follows: 2018-06-04 2018-06-04 2018-09-04 2018-04-19 2018-04-19 2018-04-17 which ideally should be : 2018-04-06 2018-04-06 2018-04-09 2018-04-19 2018-04-19 2018-04-17 How do I force it do work as above. Basically it should consider the input also and depends on that it should work.

http://stackoverflow.com/q/50253483
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
has body: I wrote a piece of code to rotate proxies for a multithreaded crawler, but it doesn't look very good and I want to see what I can improve. What I had in mind: 1) Make a number of requests (a random range) with a proxy, then change it 2) If blocked, change the proxy (remove it from proxies list) and retry. 3) If a HTTP error occurs, retry with same proxy 4) If a proxy error occurs, change the proxy (remove it from proxies list), and retry. Usually, it works pretty decent, though I see some problems which may appear: 1) make_request function is calling itsel which may lead in some cases to an infinte loop 2) proxy errors are not handled properly Here is my code: import requests import threading import random import time import logging import os class Crawler(): def __init__(self): self.user_agents = [] with open('user_agents.txt', 'r') as inpt: for line in inpt: if line.strip(): self.user_agents.append(line.strip()) self.proxies = [] with open('proxies.txt', 'r') as inpt: for line in inpt: if not line.strip(): continue self.proxies.append({"http": ''.join(["http://", line.strip()]), "https": ''.join(["https://", line.strip()])}) self.headers = {'User-agent': random.choice(self.user_agents)} self.session = requests.Session() self.counter = 0 self.current_proxy = None self.lock = threading.Lock() self.set_proxy() def make_request(self, method, url, **kwargs): """Request a page and return its content @method - string, POST or GET @url - string @return: string, HTML page source or bytes for binary files """ # make only 10 to 20 requests using a proxy with self.lock: if self.counter &gt; random.randrange(10, 20): self.set_proxy() else: self.counter += 1 try: if method == 'GET': if kwargs.get('download', False): req = self.session.get(url, headers=self.headers, stream=True, verify=False) return req.raw req = self.session.get(url, headers=self.headers, verify=False, **kwargs) else: req = self.session.post(url, headers=self.headers, verify=False, **kwargs) if req.status_code …
tagged with: python-requests
favorite count: 0
type: Question
tagged with: proxy
tagged with: python
has title: Python: improvements for rotating proxy crawler
answer count: 0

http://stackoverflow.com/q/50343515
downvote count: 0
answer count: 1
tagged with: python
score: 4
upvote count: 4
tagged with: python-xarray
type: AnsweredQuestion
has title: python Xarray DataArray: how do you add an additional coordinate to an existing dimension
has body: I am just starting to use Xarray DataArray and I was not sure how to add an new coordinate axis to an existing dimension. Can anyone point me in the correct direction. So I have an existing array that looks like: demo_results = np.zeros([10, 20, 5]) cols = ['c1', 'c2', 'c3', 'c4', 'c5'] t = xr.DataArray(demo_results, coords={'sim': cols}, dims=('run', 'year', 'sim')) So this will give me a 3 dimensional array with 5 coordinates along the 'sim' dimension. Now I wanted to add an additional coordinate on the 'sim' dimension named 'c6', but I was not sure how to do that? I did not see any info or examples in the documentation. In pandas I would just reference the new dimension like df.loc[:, 'c6] = 0 and that would work. But I tried something like that with Xarray such as: t.loc['sim', 'c6'] = 0 but I go an error: TypeError: invalid indexer array, does not have integer dtype: array('sim', dtype='&lt;U3') I guess I am still getting the hang of DataArray indexing.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50377237
accepted answer: http://stackoverflow.com/a/50377237

http://stackoverflow.com/comment/87746351
comment on: http://stackoverflow.com/q/50363682
type: Comment
score: 1
has text: It doesn't matter if it works or not sometimes. You are reading from a server when `receiverConnected` is true. Calling `Socket.Receive` from the main Thread and in the `Update` function is awful and will block the main Thread. *You have to use Thread or the Async methods like `NetworkStream.ReadAsync`*. Until you make these changes, whatever you do will continue to hang. Even if you mange to fix it without Thread or the Async methods, expect a funny frame-rate in your game.
type: QuestionComment

http://stackoverflow.com/q/50374139
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52627199
has body: I have a basic django projects that I use as a front end interface for a (Condor) computing cluster for generating simulations. From the django app the users can start simulations (in Condor). The simulation related meta-data and the simulation state are kept in a DB. I need to add a new feature: notification when (some) simulations are done. Since I want a simple solution (and I already using background tasks) I was thinking to use repeating task that at fixed intervals query Condor about the tasks, updates the DB and if necessary sends notifications. So if I want to update every 10 min that statuses I will have something like: @background(schedule=1) def check_simulations(repeat=600): # lookup simulation statuses simulation_list = get_Simulations() for sim in simulations_list: if sim.status == Simulation.DONE: user.email_user('Simulation Complete', 'You have been notified') def initialize(): check_simulations() However this task (or better say the initialize() method) must be started (called once) to create and schedule the check_simulations() task (which will practically serialize the call and save it in the DB); after that the background-tasks thread will read it and execute and also reschedule it (if there is error) My questions: where should I put the call to the initialize() method to only be run once ? One such place could be for instance the urls.py but this is an extremely ugly solution. Is there a better way ? how to ensure that a server restart will not create and schedule a new task (if one already exist) This may happen if a task is already scheduled (so a serialized task is in the background-tasks table) and the webserver is restarted so the initialize() method is called again so a new task is created and scheduled ...
has title: Django + background-tasks how to initialize
type: AnsweredQuestion
score: 2
tagged with: background-task
answer count: 1
has answer: http://stackoverflow.com/a/52627199

http://stackoverflow.com/comment/87624916
type: QuestionComment
has text: But in my model I have 20 classes, sigmoid is usually used for 2 classes model. Am I right?
type: Comment
comment on: http://stackoverflow.com/q/50276488
score: 0

http://stackoverflow.com/comment/87747848
type: QuestionComment
comment on: http://stackoverflow.com/q/50365596
type: Comment
has text: Are you actually editing files on a production system? That not a great idea.
score: 2

http://stackoverflow.com/comment/87779034
type: QuestionComment
score: 0
has text: I'm sorry. I am new to Python. I have like 1 month of experience using it :)
comment on: http://stackoverflow.com/q/50381448
type: Comment

http://stackoverflow.com/q/50314106
has comment: http://stackoverflow.com/comment/87644312
type: Question
linked to: http://stackoverflow.com/q/14904033
accepted answer: http://stackoverflow.com/a/50314311
answer count: 1
has answer: http://stackoverflow.com/a/50314311
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: flash-message
has title: Unable to insert data to the database but it returns success every time i run it
has body: I want to insert data, which i found by iterating using for loop in jinja template, to a table. when i submit the form returns SUCCESS but nothing is registered on the database. @app.route('/submit', methods=['GET','POST']) def submit(): if request.method == 'POST': cur = connection.cursor() userDetails = request.form oracle_id = userDetails.getlist('id') name = userDetails.getlist('name') status = userDetails.getlist('status') remark = userDetails.getlist('remark') for i, id in enumerate(oracle_id): stmt = "insert into attendance( oracle_id, name, status, shift, remark) VALUES(%s, %s, %s, %s, %s)" cur.executemany(stmt, (id,oracle_id[i], name[i], status[i], remark[i])) cur.commit() return 'That is success' return render_template('take_attendance.html') The funny part is once or twice i found the data in my table while testing, but after wards nothing goes there. Is there any error i made here? The HTML form i used is Attendance ID Name Status Remark {% for data in userDetails %} select.. 1130 1122 {% endfor %} I was trying for over a week but nothing changed. Thanks in advance for your effort.
tagged with: mysql

http://stackoverflow.com/comment/87686545
type: QuestionComment
comment on: http://stackoverflow.com/q/50331792
type: Comment
has text: @Sahil I learnt something new! Came across the usage of `r` !!
score: 0

http://stackoverflow.com/q/50305301
tagged with: list
has answer: http://stackoverflow.com/a/50329343
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: Hi new to Python and trying to learn using comprehensions. Developed below code to read numbers in a string and extract the numbers however trying to replace with a single comprehension statement. Please advise sent = input('Enter a string') digit = [] for i in range(len(sent)): if sent[i].isdigit(): d = sent[i] digit.append(d) Tried below method digit = [d for i in range(len(sent)) if sent[i].isdigit() = d]
has comment: http://stackoverflow.com/comment/87755585
type: Question
has comment: http://stackoverflow.com/comment/87674977
tagged with: python
has title: Why is this list comprehension for appending digits from input not working?
type: UnansweredQuestion
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/87628701

http://stackoverflow.com/q/50267732
has title: What will happen to packages installed when the virtual environment is deleted?
has answer: http://stackoverflow.com/a/50267863
possible better answer: http://stackoverflow.com/a/50267863
favorite count: 0
type: Question
tagged with: python-venv
has comment: http://stackoverflow.com/comment/87553186
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/87553163
has body: I create a new project with the following commands: mkdir ~/my_project python -m venv ~/my_project source ～/my_project/Scripts/activate pip install flask pip install kivy pip install foo pip install bar And let's say that I decide to remove my_project and create a new project: rm -rf ~/my_project mkdir ~/new_project python -m venv ~/new_project source ~/Scripts/activate Questions: What happens to previously installed packages "flask", "kivy", "foo", and "bar"? Do I need to re-install them for my new_project's virtual environment? If I don't need to re-install these packages, then I am missing the point of virtual environment? I thought the whole point of virtual environment is that packages installed in the virtual environment is isolated in that environment. Can someone elaborate?
has answer: http://stackoverflow.com/a/50267886
has comment: http://stackoverflow.com/comment/87591110
has comment: http://stackoverflow.com/comment/87553259
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87553430
score: 0
has comment: http://stackoverflow.com/comment/87553611
answer count: 2
has comment: http://stackoverflow.com/comment/87554240
upvote count: 1
has comment: http://stackoverflow.com/comment/87553473
has comment: http://stackoverflow.com/comment/87553150
downvote count: 1
has comment: http://stackoverflow.com/comment/87553327
has comment: http://stackoverflow.com/comment/87553242
has comment: http://stackoverflow.com/comment/87553402
accepted answer: http://stackoverflow.com/a/50267886
has comment: http://stackoverflow.com/comment/87583649

http://stackoverflow.com/comment/87541583
type: Comment
has text: OMG, this solution serves more as a testament to your Pandas proficiency, than to Pandas's suitability to this problem, IMHO :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/50261662
score: 1

http://stackoverflow.com/comment/87613566
score: 0
comment on: http://stackoverflow.com/a/50297058
has text: thanks for your input. Another question, if I would like to extract part of the file name as a new column how could I do that. I tried doing the same but it failed saying "AttributeError". Could you please advice, thanks.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50281925
upvote count: 2
answers question: http://stackoverflow.com/q/50280265
has body: You need to drop the double-curly braces from your keyword. {% include 'your_template_here' with keyword=store_list %}
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50280265
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87775582
score: 0
has text: There is no class object while the class body is executing.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50379654

http://stackoverflow.com/comment/87586906
has text: Use `asyncio.Semaphore`
comment on: http://stackoverflow.com/q/50283102
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50246005
type: Question
has title: What exactly is a member function?
downvote count: 3
score: -2
has answer: http://stackoverflow.com/a/50246184
accepted answer: http://stackoverflow.com/a/50246184
tagged with: python
tagged with: class
type: AnsweredQuestion
upvote count: 1
tagged with: function
has body: I'm doing an assignment that says "The class must also have member functions to perform the following tasks" When it says member functions does it mean something like: class Example(): def __init__(self,example): self.__example def function(self,example): #Is this a member function?
answer count: 1
has comment: http://stackoverflow.com/comment/87509406
favorite count: 0

http://stackoverflow.com/comment/87614044
has text: @AlexHall, that was mistyped, wanted to say "not same as". Corrected now. thanks for pointing out
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50298327
type: Comment

http://stackoverflow.com/q/50275057
tagged with: numpy
has answer: http://stackoverflow.com/a/50284551
tagged with: geopy
has answer: http://stackoverflow.com/a/63482665
score: 10
linked to: http://stackoverflow.com/q/69556412
tagged with: python
has comment: http://stackoverflow.com/comment/87594298
has answer: http://stackoverflow.com/a/74076484
has answer: http://stackoverflow.com/a/50285182
tagged with: vectorization
answer count: 4
type: UnansweredQuestion
has body: I am trying to calculate geodesic distance from a dataframe which consists of four columns of latitude and longitude data with around 3 million rows. I used the apply lambda method to do it but it took 18 minutes to finish the task. Is there a way to use Vectorization with NumPy arrays to speed up the calculation? Thank you for answering. My code using apply and lambda method: from geopy import distance df['geo_dist'] = df.apply(lambda x: distance.distance( (x['start_latitude'], x['start_longitude']), (x['end_latitude'], x['end_longitude'])).miles, axis=1) Updates: I am trying this code but it gives me the error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Appreciate if anyone can help. df['geo_dist'] = distance.distance( (df['start_latitude'].values, df['start_longitude'].values), (df['end_latitude'].values, df['end_longitude'].values)).miles
downvote count: 0
has title: How to use Vectorization with NumPy arrays to calculate geodesic distance using Geopy library for a large dataset?
linked to: http://stackoverflow.com/q/45134554
upvote count: 10
tagged with: coordinates
favorite count: 0
type: Question

http://stackoverflow.com/comment/87724362
score: 0
type: Comment
has text: Thanks for the comment regarding the polynomial approach. Could you elaborate on what could go wrong? Is there documentation or other resources that explains what goes wrong with non-convex constraints or (even better) a simple example which exposes the problem? (I don't understand the comment about local optimum since AFAIK (almost) all scipy minimizers find local optimums (at best)).
type: AnswerComment
comment on: http://stackoverflow.com/a/50353752

http://stackoverflow.com/a/50287241
type: Answer
answers question: http://stackoverflow.com/q/50286355
has body: var myVar = setInterval(function(){ myTimer() }, 2000); function myTimer() { $('.image-area').load("{{ url_for('image',im=image_date) }}"); update(); } setInterval(function(){ clearInterval(myVar); }, 2000); try this :)
score: 0
has comment: http://stackoverflow.com/comment/87590555

http://stackoverflow.com/comment/87829367
type: Comment
has text: There must be a more elegant way to write it but I couldn't find any.
comment on: http://stackoverflow.com/a/50402887
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87683032
type: QuestionComment
type: Comment
has text: You need to split the address string into its components and then use them as keys in the nested dictionary (hint: use the `split` string method).
score: 0
comment on: http://stackoverflow.com/q/50333369

http://stackoverflow.com/comment/87634355
has text: Yeah my_portal is the name of the class in my models,, and no, I don't think Im using cache options in the app, also I realized that when I reload the page with CTRL+F5 the server invalidates my session cause it shows a message saying that the csrftoken is not valid, so I think is definitely a cache/session problem
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50302418
score: 0

http://stackoverflow.com/a/64894137
has body: If your current AWS role is allowed to assume the cross-account role, you can use boto3 to get temporary session credentials: import boto3 role_session_name = "test-s3-read" role_arn = "arn:aws:iam::1234567890:role/crossaccount-role" duration_seconds = 60*15 # durations of the session in seconds credentials = boto3.client("sts").assume_role( RoleArn=role_arn, RoleSessionName=role_session_name, DurationSeconds=duration_seconds )['Credentials'] How can I use the triplet to authenticate to AWS S3, rather than just the key and secret? You can pass the AccessKeyId, SecretAccessKey and SessionToken to Spark like this: spark = SparkSession.builder \ .appName("test bucket access") \ .config("spark.hadoop.fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \ .config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider") \ .config("spark.hadoop.fs.s3a.access.key", credentials['AccessKeyId']) \ .config("spark.hadoop.fs.s3a.secret.key", credentials['SecretAccessKey']) \ .config("spark.hadoop.fs.s3a.session.token", credentials['SessionToken']) \ .getOrCreate() Verified with Spark 2.4.4 and it might not work with older versions.
answers question: http://stackoverflow.com/q/50242843
downvote count: 1
score: 5
type: Answer
upvote count: 6

http://stackoverflow.com/a/50276303
answers question: http://stackoverflow.com/q/50275511
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50275511
score: 1
type: AcceptedAnswer
has body: Let's consider the euclidean distance, by definition you've got that in 3d-space: d(a,b)=sqrt((b[0]-a[0])**2+(b[1]-a[1])**2+(b[2]-a[2])**2) The first part of that oneliner, math.sqrt(sum(map(lambda x: x*x, seq)) is a way to calculate the euclidean distance of a sequence (python iterable). What is it seq in this case? It'd be just the vector subtraction between boundingbox[0] (which is the bounding box width) and center, which I assume is the centroid of your 3d mesh. Summing up, that ugly oneliner is a nasty way to calculate the bounding sphere radius out of the center and bounding box. Better than using map/lambda functions, a much clearer way to compute this, assuming you're working in 3d euclidean space, would be rewrite that oneliner like this (explicitely): def bounding_sphere_radius(center, boundingbox): v = [ center[0]-boundingbox[0][0], center[1]-boundingbox[0][1], center[2]-boundingbox[0][2] ] return math.sqrt(v[0]**2+v[1]**2+v[2]**2) Another way, if you've implemented your own 3d vector class and you've overrided the subtraction operator (-) could be something like this: def bounding_sphere_radius(center, boundingbox): v = [center[0]-boundingbox[0]] return math.sqrt(v[0]**2+v[1]**2+v[2]**2) Or finally, if you've got a length method in your 3d vector class (euclidean distance), something even more readable would be having: def bounding_sphere_radius(center, boundingbox): return (center[0]-boundingbox[0]).length() The zen of python says Readability counts. ;)
upvote count: 1

http://stackoverflow.com/comment/87558922
type: QuestionComment
has text: I guess 2nd line of my code(i.e) cursor.fetchall() is taking more time. Since it fetch all the 100000 rows from DB and put it a list. In my point of view if there is any way to split the fetching method that is fetching 10000 rows first and repeat the same until 100000. May be it will reduce the time right?
comment on: http://stackoverflow.com/q/50270511
type: Comment
score: 0

http://stackoverflow.com/q/50302103
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/50302147
tagged with: pandas
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/50302147
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: group-by
tagged with: python
has body: I want to count the rows by conditions on multiple columns and remove the rows by the conditions. I want to count the rows if v1 and v2 have the same value, such that my df has 2 rows on (v1=0, v2=30), 1 row on (v1 = 0, v2 = 15; v1 = 0, v2 = 20), 2 rows on (v1 = 15, v2 = 10), 3 rows on (v1 = 10, v2 = 10). Then remove the rows if the v1 and v2 don't have 2 rows, in this case, remove (v1 = 0, v2 = 15; v1 = 0, v2 = 20) and (v1 = 10, v2 = 10). df ID v1 v2 1 0 30 1 15 10 1 0 30 1 0 15 1 0 20 1 15 10 1 10 10 1 10 10 1 10 10 expected output ID v1 v2 1 0 30 1 0 30 1 15 10 1 15 10 I groupby the values first, but not sure what conditions should I write for the removal. df[df.groupby(['ID', 'v_1', 'v_2'])] Hope I explain clearly. Thanks!
has title: remove rows by conditions on multiple columns

http://stackoverflow.com/q/50274164
has body: My problem is related to the extraction of ore blocks in an open pit mine. Where the blocks have a relation of pecedência, as explained below. In this representation we have 6 blocks, where: In this case we can only "extract" block 6 if 1, 2 and 3 have already been extracted, block 7 if 2,3,4 have been extracted, block 8 if 3, 4, 5 have already been extracted and the block 9 if 6,7,8 have already been extracted. import sys blocks = [1,2,3,4,5,6,7,8,9]#list of blocks p = [[] for i in blocks]#list of direct precedents p[0] = [] p[1] = [] p[2] = [] p[3] = [] p[4] = [] p[5] = [1,2,3] p[6] = [2,3,4] p[7] = [3,4,5] p[8] = [6,7,8] From this direct list of precedents, I'd like a method that would help get the following "complete list of precedents" for instances larger than 9 blocks (something between 1060 and 100000 blocks). import sys blocks = [1,2,3,4,5,6,7,8,9]#list of blocks p = [[] for i in blocks]#full list of precedents p[0] = [] p[1] = [] p[2] = [] p[3] = [] p[4] = [] p[5] = [1,2,3] p[6] = [2,3,4] p[7] = [3,4,5] p[8] = [1,2,3,4,5,6,7,8]
tagged with: python
has title: How can I get the complete predecessors list based on a direct predecessor list in python?
has comment: http://stackoverflow.com/comment/87576334
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/87565492
has comment: http://stackoverflow.com/comment/87582917
downvote count: 0
accepted answer: http://stackoverflow.com/a/50275111
has answer: http://stackoverflow.com/a/50279330
upvote count: 1
has answer: http://stackoverflow.com/a/50275111
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87565655
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/50279330
score: 1

http://stackoverflow.com/comment/87508454
has text: so install them again after you activate the virtual environment. whats the problem ? the versions ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50234121

http://stackoverflow.com/a/50250265
has body: The entry is being set on a separate wiki frame and not the one being displayed 'e3'.
answers question: http://stackoverflow.com/q/50249633
score: 1
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50249633

http://stackoverflow.com/comment/96294544
comment on: http://stackoverflow.com/a/52787324
type: AnswerComment
has text: Thanks, @Jenny Folkesson. Can you explain what exactly what part of this tells ImageJ to use a green pseudocolor, for example? Or, what I'm really after is how would you extend this to add additional colors (e.g. blue, pink, yellow)?
score: 0
type: Comment

http://stackoverflow.com/a/50301080
answers question: http://stackoverflow.com/q/50300307
has comment: http://stackoverflow.com/comment/87624682
downvote count: 0
has comment: http://stackoverflow.com/comment/87624382
type: AcceptedAnswer
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/88462035
has body: Using wsgiref.simple_server: import wsgiref.simple_server your_app = wsgiref.simple_server.demo_app server = wsgiref.simple_server.make_server('127.0.0.1', 0, your_app) _, port = server.server_address # start the browser, perhaps on a separate thread after a delay server.serve_forever() Using Cheroot: there might be an easier way, but this kind of works: import threading, time, cheroot.wsgi server = cheroot.wsgi.Server(('127.0.0.1', 0), your_app) def get_port(): while not server.ready: time.sleep(0.1) _, port = server.bind_addr # start the browser threading.Thread(target=get_port).start() server.start()
accepted answer of: http://stackoverflow.com/q/50300307
score: 1

http://stackoverflow.com/q/50301163
type: Question
has answer: http://stackoverflow.com/a/51072684
has body: Not very experience with API authentication but I cannot figure out how to read a Google Sheet share with me from Python. I've tried: import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('/Users/alexiseggermont/Downloads/Accountable-7b29dac08324.json', scope) gc = gspread.authorize(credentials) wks = gc.open("mysheet").sheet1 This gives me ImportError: cannot import name 'opentype' on line 2. I then tried: import oauth2client.client, oauth2client.file, oauth2client.tools import gspread flow = oauth2client.client.OAuth2WebServerFlow(client_id, client_secret, 'https://spreadsheets.google.com/feeds') storage = oauth2client.file.Storage('credentials.dat') credentials = storage.get() if credentials is None or credentials.invalid: import argparse flags = argparse.ArgumentParser(parents=[oauth2client.tools.argparser]).parse_args([]) credentials = oauth2client.tools.run_flow(flow, storage, flags) gc = gspread.authorize(credentials) # when this cell is run, your browser will take you to a Google authorization page. # this authorization is complete, the credentials will be cached in a file named credentials.dat This opens a window asking if I want to give my app access to my sheets, and I click yes. But then sheet = gc.open("mysheet").sheet1 gives me a permission error: APIError: { "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } } The only suggestion I find to solve this error is to change the 'scope' variable, but there is no scope variable used in that code, so I am confused.
has title: Read google spreadsheet in pandas dataframe
score: 1
tagged with: python
tagged with: gspread
possible better answer: http://stackoverflow.com/a/51072684
type: AnsweredQuestion
answer count: 2
tagged with: oauth
tagged with: google-sheets
accepted answer: http://stackoverflow.com/a/50302071
downvote count: 0
has answer: http://stackoverflow.com/a/50302071
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/87812940
has text: *you can inject them as class attributes* — instance attributes?
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/50375022
type: Comment

http://stackoverflow.com/a/50285734
type: Answer
has body: You might want to debug your myDataset instead of using eager execution since the example you followed runs in graph mode. If your myDataset is a tf.data.Dataset object. Its batch method will return a tf.data.Dataset which cannot be unpacked into batch_x, batch_y, i.e. dataset.__iter__() is not supported in graph mode. One option is to follow the tutorial in the guide. You can make_one_shot_iterator or make_initializable_iterator (which needs to be initialized through sess.run(iterator.initializer, ...)) from the "batched" dataset. Then you can get each batch in the loop by batch_x, batch_y = iterator.get_next()
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50285097
score: 2

http://stackoverflow.com/q/50298425
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/87614570
type: UnansweredQuestion
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/87615386
tagged with: numpy
has comment: http://stackoverflow.com/comment/87619295
has comment: http://stackoverflow.com/comment/87613737
has body: I'm actually using Matplotlib and Numpy for a Python script on a ssh. I had to creat a virtual python3 environment on my ssh account. then, I made: pip3 install numpy and everything worked well: Collecting numpy Using cached https://files.pythonhosted.org/packages/7b/61/11b05cc37ccdaabad89f04dbdc2a02905cf6de6f9b05816dba843beed328/numpy-1.14.3-cp35-cp35m-manylinux1_x86_64.whl Installing collected packages: numpy Successfully installed numpy-1.14.3 pip3 show numpy Name: numpy Version: 1.14.3 Summary: NumPy: array processing for numbers, strings, records, and objects. Home-page: http://www.numpy.org Author: Travis E. Oliphant et al. Author-email: None License: BSD Location: /panhome/me/.local/lib/python3.5/site-packages Then, in my script I put the PYTHONPATH such: export PYTHONPATH=$PYTHONPATH:/panhome/me/.local/lib/python3.5/site-packages but I actually get the following error: Traceback (most recent call last): File "/pandata/me/LEPIWASP/blast_database/public_scripts-master/Diamond_BLAST_add_taxonomic_info/Diamond_blast_to_taxid.py", line 25, in &lt;module&gt; import matplotlib File "/panhome/me/.local/lib/python3.5/site-packages/matplotlib/__init__.py", line 127, in &lt;module&gt; from . import cbook File "/panhome/me/.local/lib/python3.5/site-packages/matplotlib/cbook/__init__.py", line 35, in &lt;module&gt; import numpy as np File "/panhome/me/.local/lib/python3.5/site-packages/numpy/__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "/panhome/me/.local/lib/python3.5/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/panhome/me/.local/lib/python3.5/site-packages/numpy/lib/__init__.py", line 8, in &lt;module&gt; from .type_check import * File "/panhome/me/.local/lib/python3.5/site-packages/numpy/lib/type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx File "/panhome/me/.local/lib/python3.5/site-packages/numpy/core/__init__.py", line 26, in &lt;module&gt; raise ImportE…
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87613906
favorite count: 0
has title: Cannot install NumPy using pip and import it
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90591943
has comment: http://stackoverflow.com/comment/87625799

http://stackoverflow.com/comment/87580545
has text: "Brackets appear when printing any list, but they do not when printing the contents of the list." actually implies that the scalars **are actually** contained in their own separate, dare I say invisible, lists.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50281946

http://stackoverflow.com/comment/87575929
type: QuestionComment
has text: I did it, thank you!
comment on: http://stackoverflow.com/q/50279436
score: 0
type: Comment

http://stackoverflow.com/q/50292982
has body: models.py class Employee(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL, related_name='company') views.py class Employee(CreateView): fields = ('name','company') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) comp_name = self.request.POST.get("company", "") shop_id = "" for word in dept_name.split(" "): shop_id += word[:1] self.object.nik = shop_id[-3:] self.object.save() return super(ModelFormMixin, self).form_valid(form) iam trying to get value from ForeignKey on my code self.request.POST.get("company", "") is return id of the company, i need its return the company.name. how do that?...
type: Question
has answer: http://stackoverflow.com/a/50293213
tagged with: django-views
tagged with: python
has title: django form ForeignKey as ForeignKey.name not an ForeignKey.id
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/50293213
tagged with: django-forms

http://stackoverflow.com/q/50299172
linked to: http://stackoverflow.com/q/477486
linked to: http://stackoverflow.com/q/10011302
has comment: http://stackoverflow.com/comment/115163602
has comment: http://stackoverflow.com/comment/87615217
has body: I am looking to get : input: arange(0.0,0.6,0.2) output: 0.,0.4 I want 0.,0.2,0.4,0.6 how do i achieve using range or arange. If not what is alternate ?
has answer: http://stackoverflow.com/a/68551927
possible better answer: http://stackoverflow.com/a/66919635
has answer: http://stackoverflow.com/a/76815585
tagged with: python
has answer: http://stackoverflow.com/a/66919635
has answer: http://stackoverflow.com/a/50299238
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66082278
accepted answer: http://stackoverflow.com/a/57321916
has answer: http://stackoverflow.com/a/57321916
answer count: 7
score: 26
has answer: http://stackoverflow.com/a/70230433
has comment: http://stackoverflow.com/comment/87617686
downvote count: 1
favorite count: 0
type: Question
upvote count: 27
tagged with: numpy
has title: Range or numpy Arange with end limit include

http://stackoverflow.com/comment/87657615
type: Comment
type: AnswerComment
has text: @cdarke Good point. I was targeting their specific input case, but surrounding the `z` with word boundaries would ensure this worked with any input.
comment on: http://stackoverflow.com/a/50320835
score: 0

http://stackoverflow.com/q/50260632
has comment: http://stackoverflow.com/comment/87539371
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87540471
type: UnansweredQuestion
has title: Python OOP making new classes vs function parameters
has body: I have an abstract base class for data processing. The concrete class of spectral processing inherits the ABC data processing. But now within spectral processing, I can do things in different ways. Like calculate different types of transforms or different types of filters. I have 2 ideas Make a filter function within concrete spectral processing class and pass it a string consisting of which type of filter to implement. Make a separate filter class that uses spectral processing class as a base class and implement different filtering functions in this class. Which one of the two ideas is better
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/87539365
tagged with: python
tagged with: inheritance

http://stackoverflow.com/q/50378902
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87787703
tagged with: performance
answer count: 2
has title: How do people efficiently handle repetitive event checks (python/pygame)?
score: 1
has comment: http://stackoverflow.com/comment/87776843
possible better answer: http://stackoverflow.com/a/50388665
tagged with: pygame
accepted answer: http://stackoverflow.com/a/50398910
has answer: http://stackoverflow.com/a/50388665
favorite count: 0
has answer: http://stackoverflow.com/a/50398910
type: Question
has body: This is more of a curiosity question, because I went back and managed to do what I wanted to do. The title was originally going to be something like 'Checking if an ordered tuple is in a tuple of ranges?' Until now I've been checking mouse clicks using this code - pos = pygame.mouse.get_pos() if pos[0] &gt; X and pos[0] &lt; X2 and pos[1] &gt; Y and pos[1] &lt; Y2: #Do this #Separate function with same XY's if pos[0] &gt; X and pos[0] &lt; X2 and pos[1] &gt; Y and pos[1] &lt; Y2: #Do something else - could be used for mouse hover rather than click. I was wondering how other people go about button detection, since sometimes more than one check is needed (in separate functions for example). Sometimes I will trigger an outside function, boolean or timer, or something along those lines. I've done that in the example below. But this can get messy too and I feel like there must be a simpler way. for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: gp = game.pos #Initial gbh declaration gbh = game.button_health = range(391, 527), range(179, 253) if gp[0] in gbh[0] and gp[1] in gbh[1]: player.skillpoints -= 1 player.health += 10 player.healthmax += 10 #Separate func. gp = game.pos gbh = game.button_health if gp[0] in gbh[0] and gp[1] in gbh[1]: blit(font.render(str(Z), True, BLACK), (X, Y))
tagged with: function
downvote count: 0
has comment: http://stackoverflow.com/comment/87775637
tagged with: repeat
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47639826

http://stackoverflow.com/q/50306651
tagged with: python-unicode
tagged with: python
tagged with: regex
has title: Python: using regex and tokens with accented chars (negative lookbehind)
answer count: 0
has body: I need to detect capitalized words in Spanish, but only when they are not preceeded by a token, which can have unicode chars. (I'm using Python 2.7.12 in linux). This works ok (non-unicode token [e.g. guion:] &gt;&gt;&gt; import regex &gt;&gt;&gt; s = u"guion: El computador. Ángel." &gt;&gt;&gt; p = regex.compile( r'(?&lt;!guion:\s) ( [\p{Lu}] [\p{Ll}]+ \b)' , regex.U | regex.X) &gt;&gt;&gt; print p.sub( r"**\1**", s) guion: El computador. **Ángel**. But the same logic fails to spot accented tokens [e.g. guión:]: &gt;&gt;&gt; s = u"guión: El computador. Ángel." &gt;&gt;&gt; p = regex.compile( ur'(?&lt;!guión:\s) ( [\p{Lu}] [\p{Ll}]+ \b)' , regex.U | regex.X) &gt;&gt;&gt; print p.sub( r"**\1**", s) guión: **El** computador. **Ángel**. The expected outcome would be: guión: El computador. **Ángel**. In regex101 the code works just fine (in 'pcr (php)' flavor, instead of 'python' flavor, since for some reason the first seems to give results more similar to those of command line regex package in python). Is it due to the python version I'm using: 2.7.12 instead of python 3?. It is most likely I am misunderstanding something. Thanks in advance for any directions. After plenty of bugs and weird outcomes, I've come to realize that: The regex package is the way to go, instead of re due to a better unicode support (for instance, provides differentiation of upper and lowercase unicode chars). The regex.U flag must be set. ( regex.X just allows spaces and comments for the sake of clarity) u'' unicode strings and r'' raw strings can be combined at the same time: ur'' \p{Lu} and \p{Ll} match unicode uppercase and lowercase chars, respectively.
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87629698
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87635649
has comment: http://stackoverflow.com/comment/87629549

http://stackoverflow.com/comment/87636586
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50309729
score: 0
has text: @bru02 yes. This is the same one I mentioned

http://stackoverflow.com/comment/87583638
score: 3
type: Comment
type: QuestionComment
has text: What's the problem with this? When I call it with `list(string.ascii_lowercase), 'p'`, it prints the whole list, then the o-z list, then o-t, then o-q, then returns True. When I call it with the same list and `2`, it prints the whole list, then a-m, a-f, a-c, a, nothing, then returns False. That seems like exactly what you wanted? If you have a test case that fails, please give us the input, and the desired and actual output. Read [mcve] in the help for more guidelines on asking an answerable question.
comment on: http://stackoverflow.com/q/50283619

http://stackoverflow.com/a/50291867
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87601891
answers question: http://stackoverflow.com/q/50291549
type: Answer
has body: It's hard to get a Layer object from the checkpoint only. But you can get the convolutional attributes programmatically by calling: tf.get_default_graph().as_graph_def() ... assuming that you've restored the checkpoint into a default graph. It returns the list of graph nodes (GraphDef proto to be exact), among which there are also Conv2D nodes, like this one: node { name: "conv2d/Conv2D" op: "Conv2D" input: "input_layer" input: "conv2d/kernel/read" attr { key: "T" value { type: DT_FLOAT } } attr { key: "data_format" value { s: "NHWC" } } attr { key: "padding" value { s: "SAME" } } attr { key: "strides" value { list { i: 1 i: 1 i: 1 i: 1 } } } attr { key: "use_cudnn_on_gpu" value { b: true } } } You just need to find the node that corresponds to the particular layer you're interested in.
accepted answer of: http://stackoverflow.com/q/50291549
score: 1
upvote count: 1

http://stackoverflow.com/q/50281979
type: Question
tagged with: smtplib
has comment: http://stackoverflow.com/comment/87581112
has answer: http://stackoverflow.com/a/50282628
tagged with: python
has body: import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import pdb def emailSender(emailId, password, input): fromaddr = emailId emailFile = open(input, "r") # open the generated email file with read only access msgTxt = "" server = smtplib.SMTP('outbound.___.com') server.starttls() server.login(fromaddr, password) for line in emailFile: if line.__contains__("$to$"): toaddr = line[4:] elif line.__contains__("$cc$"): cc = line[4:] elif line.__contains__("$bcc$"): bcc = line[5:] elif line.__contains__("$subj$"): subject = line[6:] elif line.__contains__("$%$"): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr subject = subject.encode('utf-8') msg['Subject'] = "hello world" msg['Cc'] = cc msg.attach(MIMEText(msgTxt, 'plain')) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) msgTxt = "" elif not line.__contains__("--------------------------------------------------------------------"): msgTxt += line server.quit() if __name__ == '__main__': password = "****" emailId = "****" input = "input" emailSender(emailId, password, input) Overall goal is to take a text file with to email, cc, subject and message and send that email and do this for several generated emails in the text file. I am reading email from a text file which is msgTxt. I also take the subject, toaddr &amp; cc from the text file. It sends the email fine with the to and from showing but it does not show the subject of the email. I have tried debugging smtplib and ssl files but can't seem to figure out. When debugging, the msg has all of the attributes properly set but doesn't get transferred to the email. Any help is much appreciated. I've been stuck on this for some time now. Thank you for the help in advanced. --Bijan
type: AnsweredQuestion
score: 0
has title: smtplib subject not showing, encoded subject in message
accepted answer: http://stackoverflow.com/a/50282628
answer count: 1
tagged with: smtp

http://stackoverflow.com/q/50358564
type: Question
upvote count: 9
answer count: 5
has body: I have a datetime attribute: d = { 'DOB': pd.Series([ datetime.datetime(2014, 7, 9), datetime.datetime(2014, 7, 15), np.datetime64('NaT') ], index=['a', 'b', 'c']) } df_test = pd.DataFrame(d) I would like to compute the mean for that attribute. Running mean() causes an error: TypeError: reduction operation 'mean' not allowed for this dtype I also tried the solution proposed elsewhere. It doesn't work as running the function proposed there causes OverflowError: Python int too large to convert to C long What would you propose? The result for the above dataframe should be equivalent to datetime.datetime(2014, 7, 12).
tagged with: python-datetime
accepted answer: http://stackoverflow.com/a/50358798
tagged with: python
has answer: http://stackoverflow.com/a/50358805
has comment: http://stackoverflow.com/comment/133996470
has title: computing the mean for python datetime
has comment: http://stackoverflow.com/comment/87734174
has answer: http://stackoverflow.com/a/50358798
has answer: http://stackoverflow.com/a/50358646
score: 9
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/27907902
tagged with: pandas
tagged with: mean
possible better answer: http://stackoverflow.com/a/50358805
has comment: http://stackoverflow.com/comment/87733823
has answer: http://stackoverflow.com/a/50358710
has answer: http://stackoverflow.com/a/57619553
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/65571339
score: 1
has body: It is an excel file generated WPS but not MS office. you can use xlwings to open it. you can save to CSV file manually and read.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/50236928
upvote count: 1

http://stackoverflow.com/a/51301860
type: Answer
has body: You have an older version of google-gax. To update you can run: npm update -g google-gax To install the latest version you can run: npm install google-gax
answers question: http://stackoverflow.com/q/50334017
score: 0

http://stackoverflow.com/comment/87515002
comment on: http://stackoverflow.com/q/50248626
type: Comment
type: QuestionComment
score: 0
has text: But where is the code that does this? Have you written extra views in the TestAdmin class?

http://stackoverflow.com/comment/139047898
comment on: http://stackoverflow.com/a/78851049
score: 1
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/late-answers/36326923)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50367437
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50367030
has body: You can try this. {a:Counter(c[2] for c in l if c[0]==a) for a in set(map(itemgetter(0),l))} That is, &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; set(map(itemgetter(0),l)) #get the zeroth element to get the keys set(['a03', 'a01', 'a04']) &gt;&gt;&gt; {a:0 for a in set(map(itemgetter(0),l))} #dict comprehension {'a03': 0, 'a01': 0, 'a04': 0} &gt;&gt;&gt; {a:[c[2] for c in l if c[0]==a] for a in set(map(itemgetter(0),l))} #if the key matches then get the 2nd index {'a03': ['s2', 's1', 's1'], 'a01': ['s1'], 'a04': ['s1', 's2', 's1', 's1']} &gt;&gt;&gt; {a:Counter(c[2] for c in l if c[0]==a) for a in set(map(itemgetter(0),l))} {'a03': Counter({'s1': 2, 's2': 1}), 'a01': Counter({'s1': 1}), 'a04': Counter({'s1': 3, 's2': 1})}

http://stackoverflow.com/comment/87773374
type: Comment
type: QuestionComment
has text: I can't fugure out what's wrong here, try change this `url(r'^$', views.IndexView.as_view(), name='index'),` to `url(r'^index/$', views.IndexView.as_view(), name='index'),'` just to see if you will still got the issue
comment on: http://stackoverflow.com/q/50378361
score: 0

http://stackoverflow.com/comment/87543302
comment on: http://stackoverflow.com/q/50262215
score: 0
type: Comment
type: QuestionComment
has text: Suggest you a) structure your code as described in the multiprocessing docs https://docs.python.org/2/library/multiprocessing.html i.e. protect the last two lines by `if __name__ == ‘__main__’` and therefore I don’t think it makes much sense/adds value for the test method to call the foo method, and b) add some more debugging print statements - e.g. in foo and in test - to add more granualrity to where the code hangs.

http://stackoverflow.com/a/50289872
has body: You can also use split directly and get just tell it to take the second element. import sys import re string="abcd#1234" string1=string.split("#")[1] # tells it to take the second element of the split print(string1) # Prints 1234
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/50289743

http://stackoverflow.com/a/50335191
has comment: http://stackoverflow.com/comment/88084331
has comment: http://stackoverflow.com/comment/88076226
type: Answer
has comment: http://stackoverflow.com/comment/88082300
answers question: http://stackoverflow.com/q/50315932
type: AcceptedAnswer
downvote count: 1
has body: Unfortunately, tf.contrib.lookup.HashTable only works with one dimensional tensors. Here's an implementation with tf.SparseTensors, which of course only works if your keys are integer (int32 or int64) tensors. For the values I'm storing the two columns in two separate tensors, but if you have many columns, you might want to just store them in a large tensor, and store the indices as values in one tf.SparseTensor. This code (tested): import tensorflow as tf lookup = tf.placeholder( shape = ( 2, ), dtype = tf.int64 ) default_value = tf.constant( [ 1, 1 ], dtype = tf.int64 ) input_tensor = tf.constant( [ 1, 1 ], dtype=tf.int64) keys = tf.constant( [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ], dtype=tf.int64 ) values = tf.constant( [ [ 4, 1 ], [ 5, 1 ], [ 6, 1 ] ], dtype=tf.int64 ) val0 = values[ :, 0 ] val1 = values[ :, 1 ] st0 = tf.SparseTensor( keys, val0, dense_shape = ( 7, 7 ) ) st1 = tf.SparseTensor( keys, val1, dense_shape = ( 7, 7 ) ) x0 = tf.sparse_slice( st0, lookup, [ 1, 1 ] ) y0 = tf.reshape( tf.sparse_tensor_to_dense( x0, default_value = default_value[ 0 ] ), () ) x1 = tf.sparse_slice( st1, lookup, [ 1, 1 ] ) y1 = tf.reshape( tf.sparse_tensor_to_dense( x1, default_value = default_value[ 1 ] ), () ) y = tf.stack( [ y0, y1 ], axis = 0 ) with tf.Session() as sess: print( sess.run( y, feed_dict = { lookup : [ 1, 2 ] } ) ) print( sess.run( y, feed_dict = { lookup : [ 1, 1 ] } ) ) will output: [4 1] [1 1] as desired (looks up the value [ 4, 1 ] for the key [ 1, 2 ] and the default value [ 1, 1 ] for [ 1, 1 ], which points to a non-existent entry.)
score: 8
upvote count: 9
accepted answer of: http://stackoverflow.com/q/50315932

http://stackoverflow.com/comment/87609302
comment on: http://stackoverflow.com/q/50295783
has text: @pault Unfortunately I cannot union because dataframe B can contain new columns as well than can be set to null in A. Is there another operation I can use there?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87725543
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50352528
has text: Could you please post a **Minimal, Complete, Verifiable Example** as required by Stack Overflow - that means the simplest **complete** program that reproduces the error - including `main()` and `#includes`. Thank you.
score: 0

http://stackoverflow.com/a/50340206
has comment: http://stackoverflow.com/comment/87696849
has comment: http://stackoverflow.com/comment/87697066
has comment: http://stackoverflow.com/comment/87696603
score: 5
upvote count: 5
has body: I think you just want itertools.product here: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; lst = ['ab', 'c', 'de'] &gt;&gt;&gt; words = product(*lst) &gt;&gt;&gt; list(words) [('a', 'c', 'd'), ('a', 'c', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e')]` Or, if you wanted them joined into words: &gt;&gt;&gt; [''.join(word) for word in product(*lst)] ['acd', 'ace', 'bcd', 'bce'] Or, with your example: &gt;&gt;&gt; lst = [["a","b"],["c","d"]] &gt;&gt;&gt; [''.join(word) for word in product(*lst)] ['ac', 'ad', 'bc', 'bd'] Of course for very large n or very large sets of letters (size m), this will be slow. If you want to generate an exponentially large set of outputs (O(m**n)), that will take exponential time. But at least it has constant rather than exponential space (it generates one product at a time, instead of a giant list of all of them), and will be faster than what you were on your way to by a decent constant factor, and it's a whole lot simpler and harder to get wrong.
type: Answer
has comment: http://stackoverflow.com/comment/87696613
has comment: http://stackoverflow.com/comment/87696622
accepted answer of: http://stackoverflow.com/q/50340163
has comment: http://stackoverflow.com/comment/87696630
has comment: http://stackoverflow.com/comment/87697047
has comment: http://stackoverflow.com/comment/87697093
answers question: http://stackoverflow.com/q/50340163
has comment: http://stackoverflow.com/comment/87696804
has comment: http://stackoverflow.com/comment/87696693
has comment: http://stackoverflow.com/comment/87697044
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87599639
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50291736
has text: parse it yourself with iterators instead to avoid memory overhead

http://stackoverflow.com/comment/87555990
score: 0
type: Comment
type: QuestionComment
has text: yes! now it works! sorry but i'm new with promgramming. thanks ;)
comment on: http://stackoverflow.com/q/50269160

http://stackoverflow.com/q/50363147
has comment: http://stackoverflow.com/comment/87742545
has comment: http://stackoverflow.com/comment/87743218
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3914667
answer count: 1
score: -3
tagged with: keyword
has comment: http://stackoverflow.com/comment/87742859
has comment: http://stackoverflow.com/comment/110045285
downvote count: 7
has comment: http://stackoverflow.com/comment/87742614
has comment: http://stackoverflow.com/comment/87742669
has answer: http://stackoverflow.com/a/50363289
has body: Are they keywords, constants, or functions? If they are constants, what are their types? It seems python has no type of boolean.
has comment: http://stackoverflow.com/comment/87742548
tagged with: python
has title: what is None,True,False in python?
has comment: http://stackoverflow.com/comment/110155094
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/q/50308057
has title: Can "floor division" of floating-point numbers (e.g. in Python) cause innaccuracy?
tagged with: python
tagged with: language-agnostic
upvote count: 4
has body: Guido van Rossum has written a blog post explaining why, in Python, integer division (for example, a // b) is "floor division" - the quotient is rounded towards negative infinity. Correspondingly, the sign of a % b matches the sign of b. This differs from C, where the quotient is rounded towards zero and the result of a % b has the sign of a. Python also uses floor division, and the corresponding "sign-of-modulo matches sign-of-divisor", for floating-point numbers. The blog post claims that this can be inaccurate in certain cases (where C's "sign-of-modulo matches sign-of-dividend" would be accurate). Is this true? Are there any concrete examples?
has answer: http://stackoverflow.com/a/50322390
favorite count: 0
type: Question
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: floating-point
has comment: http://stackoverflow.com/comment/87643349
score: 4
tagged with: floating-accuracy
has comment: http://stackoverflow.com/comment/87632090
tagged with: rounding

http://stackoverflow.com/a/50349584
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/50349451
downvote count: 0
has body: If at the end is just a single digit you could use this. Can adapt if after the last comma are multiple digits(number 3 should be incremented). text = '52A, XYZ Street, ABC District, 2' text = text[:-3].replace(",", "") + text[-3:] print(text) The output is 52A XYZ Street ABC District, 2

http://stackoverflow.com/q/50262871
type: Question
has body: This is my main.css file: body { font-family: josefin; } .splash-content { text-align: center; } .register-button { color: #6A136C; width: 300px; height: 100px; border: 5px solid #6A136C; } .btn { padding: 14px 24px; border: 0 none; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; } .btn.sharp { border-radius: 0; } .btn.outline { background: none; padding: 12px 22px; } .btn-primary.outline { border: 2px solid #6A136C; color: #6A136C; } .btn:focus, .btn:active:focus, .btn.active:focus { outline: 0 none; } .btn-primary { background: #0099cc; color: #ffffff; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open &gt; .dropdown-toggle.btn-primary { background: #33a6cc; } .btn-primary:active, .btn-primary.active { background: #007299; box-shadow: none; } However when I start my website and go to it, the styling isnt applied, then I go to the chrome dev-tools and look at the css, this is all that chrom shows: body { font-family: josefin; } .splash-content { text-align: center; } .register-button { color: #6A136C; width: 300px; height: 100px; border: 5px solid #6A136C; } And when I copy and paste the missing code, the styling works completely fine and the way it should, I have no clue whats going wrong or what Im doing wrong. Does anyone know what might be happening, this hasnt happened to me before. Im using flask, bootstrap, jquery, if that makes a difference. Thank you so much!
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87543910
tagged with: google-chrome
tagged with: flask
tagged with: css
type: AnsweredQuestion
has title: Part of CSS Code Not Rendering in Chrome
has comment: http://stackoverflow.com/comment/87544055
score: 1
accepted answer: http://stackoverflow.com/a/50263086
has comment: http://stackoverflow.com/comment/87543894
has answer: http://stackoverflow.com/a/50263086
favorite count: 0

http://stackoverflow.com/comment/87730089
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50355697
has text: https://softwareengineering.stackexchange.com/questions/325284/specifying-a-bi-directional-unique-constraint-on-a-join-table-in-postgres
type: Comment

http://stackoverflow.com/q/50254107
has comment: http://stackoverflow.com/comment/87526407
has title: Python ignore element in list/tuple if appears once over a certain time range
type: Question
has comment: http://stackoverflow.com/comment/87705946
has comment: http://stackoverflow.com/comment/87525664
tagged with: list
tagged with: filter
has body: So I'm new to python and am having some problems with a list (might even be a tuple), nevertheless I have one rogue point I want to remove in the list below i.e. 64. It is not as simple as removing / ignoring the point as the value will appear in later in the data multiple times. I've tried several things including filtering, new list and having a time check i.e if less than 25 seconds then ignore, but nothing is quite getting it. 2018-05-09T01:21:15.424999 33 2018-05-09T01:51:15.680999 33 2018-05-09T02:21:15.94 33 2018-05-09T02:51:16.211 33 2018-05-09T03:21:16.468 33 2018-05-09T03:51:16.74 33 2018-05-09T04:21:17.011 33 2018-05-09T04:51:17.262 33 2018-05-09T05:21:17.532999 33 2018-05-09T05:51:17.82 33 2018-05-09T06:21:18.092 33 2018-05-09T06:51:18.377999 33 2018-05-09T07:21:19.208999 33 2018-05-09T07:51:19.528999 33 2018-05-09T08:21:19.831 33 2018-05-09T08:28:11.1 64 2018-05-09T08:28:35.561112 33 2018-05-09T08:58:36.043 33 2018-05-09T09:28:36.255 33 2018-05-09T09:58:36.632 33 2018-05-09T10:28:36.995 33 2018-05-09T10:58:37.283 33
has comment: http://stackoverflow.com/comment/87526117
tagged with: python
has comment: http://stackoverflow.com/comment/87666159
has comment: http://stackoverflow.com/comment/87526379
answer count: 0
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/50363790
accepted answer: http://stackoverflow.com/a/50370303
has answer: http://stackoverflow.com/a/50370303
has body: I am given two vectors u and v of length m and n and want to create from them a matrix A with m rows and n columns as a generalized dyadic product of u and v, i.e. A[i][j] = f(u[i],v[j]); Is there already a boilerplate solution for that kind of matrix generation available in Python, e.g. in NumPy, resp., what would be the "most pythonic" way of solving it?
has title: Creating Matrices as Dyadic Products of Vectors
type: Question
has comment: http://stackoverflow.com/comment/87744131
linked to: http://stackoverflow.com/q/50339627
has comment: http://stackoverflow.com/comment/87743792
has comment: http://stackoverflow.com/comment/87744050
answer count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/50339627
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/50250499
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/87518536
has comment: http://stackoverflow.com/comment/87518703
has comment: http://stackoverflow.com/comment/87518497
has body: I hope the code is self explanatory. You can always ask questions. import pandas as pd # Prepping data for example dates = pd.date_range('1/1/2018', periods=7, freq='H') data = {'A' : range(7)} df = pd.DataFrame(index = dates, data = data) print df # A # 2018-01-01 00:00:00 0 # 2018-01-01 01:00:00 1 # 2018-01-01 02:00:00 2 # 2018-01-01 03:00:00 3 # 2018-01-01 04:00:00 4 # 2018-01-01 05:00:00 5 # 2018-01-01 06:00:00 6 # Creating a mask to filter the value we with to have or not. # Here, we use df.index because the index is our datetime. # If the datetime is a column, you can always say df['column_name'] mask = (df.index &gt; '2018-1-1 01:00:00') &amp; (df.index &lt; '2018-1-1 05:00:00') print mask # [False False True True True False False] df_with_good_dates = df.loc[mask] print df_with_good_dates # A # 2018-01-01 02:00:00 2 # 2018-01-01 03:00:00 3 # 2018-01-01 04:00:00 4
answers question: http://stackoverflow.com/q/50250022
type: Answer

http://stackoverflow.com/comment/87511089
has text: Look at [this](https://books.google.com.mx/books?id=GIibCgAAQBAJ&pg=PA34&lpg=PA34&dq=issubclass(exc_type,+ValueError)&source=bl&ots=dkL-A6Ofb6&sig=4U2vDlzUAHpXWh_M5Fc24htzkko&hl=es-419&sa=X&ved=0ahUKEwiNyNfz__faAhXJ61MKHbFeBVYQ6AEIKDAA#v=onepage&q=issubclass(exc_type%2C%20ValueError)&f=false) might help.
comment on: http://stackoverflow.com/q/50246680
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87526711
type: AnswerComment
comment on: http://stackoverflow.com/a/50252942
has text: Indeed, I forgot to comment about the filters :)
type: Comment
score: 0

http://stackoverflow.com/comment/87572027
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50275902
type: Comment
has text: Surprised how similar my code is to the source code of `get_dummies()`!

http://stackoverflow.com/comment/87623892
comment on: http://stackoverflow.com/q/50300412
score: 1
type: Comment
has text: Can you double-check this line: `model_RandomForest = ek.RandomForestClassifier(n_estimators = 200, max_depth = 'auto', n_jobs = 1, random_state = 5,max_features = 'auto',min_samples_leaf = 100, verbose=1)`, specifically `min_samples_leaf = 100`? I am asking since evidently this check https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tree.py#L176 returned False - somehow `min_samples_leaf` is not interpreted as integer. If I were to make a wild speculation, you load the parameter from someplace and not do the casting.
type: QuestionComment

http://stackoverflow.com/a/50306595
has comment: http://stackoverflow.com/comment/87873221
has comment: http://stackoverflow.com/comment/87857671
score: 1
has comment: http://stackoverflow.com/comment/87884413
has comment: http://stackoverflow.com/comment/87857668
has comment: http://stackoverflow.com/comment/87883476
has body: import json list_1 = [{'title': 'NEWBOOK', 'downloads': '4', 'views': '88'}] list_2 = {'title': 'MASTERMIND', 'downloads': '16', 'views': '156'} list_3 = { 'a': 'b', 'c': 'd', 'e': [{ 'f': 'g', 'l': 'm' }] } list_3['e'].append(list_1[0]) list_3['e'].append(list_2) json_list = json.dumps(list_3) if you want to add more lists to the location you do the following b= json.loads(json_list) b['e'].append(your_new_dict) json_list = json.dumps(b) if you have no idea what list_1 and list_2 are then you can test for the class type and append them accordingly. Like if(type(list_1)==list): list_3['e'].append(list_1[0]) if(type(list_2)==dict): list_3['e'].append(list_2) if you dont know at which point in list_3 you want to append the list. you do something like the following. Assuming there is only one list in list_3 for x in list_3.values(): if(type(x)==list): x.append(list_1[0]) x.append(list_2)
downvote count: 0
has comment: http://stackoverflow.com/comment/87908613
answers question: http://stackoverflow.com/q/50306363
has comment: http://stackoverflow.com/comment/87913486
has comment: http://stackoverflow.com/comment/87908669
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/87913366
has comment: http://stackoverflow.com/comment/87872982

http://stackoverflow.com/comment/87747388
type: Comment
has text: @Cris As noted in the post : `If you would like to include equality as well, i.e. <= or >=`.
score: 0
comment on: http://stackoverflow.com/a/50365462
type: AnswerComment

http://stackoverflow.com/comment/87770599
score: 0
has text: consider an arbitrary path with four points e.g. (0,0,0), (1,0,0), (2,0,0) & (2,1,0). for the first three, the radius is infinity and for the next tripple it about 0.7
comment on: http://stackoverflow.com/q/50377031
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50312125
type: Answer
has body: If you want only [4 5 6] (1 element with 3 items), your count should be your dim (i.e. 3) data = np.fromfile(f, count=dim, dtype=np.int64).reshape(-1, dim)
upvote count: 3
answers question: http://stackoverflow.com/q/50312082
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50312082
score: 3

http://stackoverflow.com/q/50239017
downvote count: 0
tagged with: python-unittest
score: 1
favorite count: 0
type: Question
has body: I have a Flask backend that I am setting up testing for. It is in the early stages, so currently there are only 4 tests set up, but each one hits a redirect endpoint that should then be redirected to a specific location (dependent on login, session, etc...). All 4 tests pass locally in a fresh pipenv environment set up using the same Pipfile as Travis. For some reason it is not behaving as expected on redirects within Travis. For reference, here is my test structure: class TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def test_blind_home_redirect(self): result = self.app.get('/') self.assertEqual(result.status_code, 302) result = self.app.get('/', follow_redirects=True) self.assertEqual(result.status_code, 200) The first assertion does not throw an error, but the second one checking that it followed the redirect returns a status_code of 404 instead of 200. A second test using the same logic for a different endpoint also passes the 302 check but fails the 200 with another 404. One checking that all "protected" endpoints redirect to login results in an unexpected object being returned: for endpoint in known_login_check: result = self.app.get('/{}'.format(endpoint)) self.assertEqual(result.status_code, 302) # Make sure all are sent to the index result = self.app.get('/{}'.format(endpoint), follow_redirects=True) sender = pathlib.Path(result.response.file.name) self.assertEqual(sender.name, 'index.html') This one fails on the sender = ... with AttributeError: 'ClosingIterator' object has no attribute 'file', but again passes locally. These all appear to be failing ONLY on redirection. Is there something that should be set up to allow this to work in Travis that for some reason my local machine is handling? Again, this is the exact same Pipfile being used, and I have deleted my local env and remade it to make sure, but it still passes locally.
answer count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
tagged with: flask
tagged with: travis-ci
has title: Respecting redirects on Flask routes in test environment
tagged with: pytest

http://stackoverflow.com/comment/87711292
score: 0
comment on: http://stackoverflow.com/a/50346682
type: Comment
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171067/discussion-between-flying-thunder-and-billal-begueradj).

http://stackoverflow.com/q/50240646
score: 1
has body: If I have a dataframe that has columns 'count', 'w', 'c', 'd' and 'y' and sample data looks like this: 131 1 dir mob 2017 244 1 dir mob 2018 311 1 org mob 2017 332 1 org mob 2018 212 2 dir dsk 2017 311 2 dir dsk 2018 401 2 org mob 2017 283 2 org mob 2018 What is the way to get the percentage change of the 'count' value grouped by 'w','c','d' for 2018 versus 2017?
type: Question
answer count: 2
has title: Getting a YoY percentage from a pandas dataframe
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50240955
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50240780
favorite count: 0
has comment: http://stackoverflow.com/comment/87498653
tagged with: pandas

http://stackoverflow.com/a/50281548
has comment: http://stackoverflow.com/comment/87580594
score: 1
downvote count: 0
has body: I don't understand the motivation for the formulas you've implemented. I'll explain my own motivation here, but if your instructor told you to do something else, I guess you should listen to them instead. If I were going to do this, I would generate a sequence of movements of a photon, stopping when distance of the photon to the center of the sun is greater than the solar radius. Each movement is a sample from a distribution which has two components: one for the distance, and one for the direction. I will assume that these are independent (this may be questioned in a more careful simulation). It seems plausible that the distribution of distance is an exponential distribution with parameter 1/(mean free path). Then the density is p(d) = (1/MFP) exp(-d/MFP). Its cdf is 1 - exp(-d/MFP) and the inverse of the cdf is -MFP log(1 - p) where p = cdf(d). Now you can sample from the distribution of distances: let p = rand(0, 1) where rand = uniform random and plug it into the inverse cdf to get d. This is called the inverse cdf method of sampling; a web search will find more info about it. As for the direction, you can let angle = rand(0, 2*pi) and then (x, y) = (cos(angle), sin(angle)). Now you can construct the series of positions. From an initial location, let the new location = previous + d*(x, y). Stop when distance of location to center is greater than radius. Looks like a great problem! Good luck and have fun. Let me know if you have any questions.
upvote count: 1
has comment: http://stackoverflow.com/comment/87580323
has comment: http://stackoverflow.com/comment/87582375
answers question: http://stackoverflow.com/q/50281288
type: Answer
has comment: http://stackoverflow.com/comment/87582562

http://stackoverflow.com/comment/87715276
comment on: http://stackoverflow.com/q/50347675
score: 0
type: Comment
type: QuestionComment
has text: /usr/include/gsl/gsl_sf.h /usr/local/include/gsl/gsl_sf.h /home/lorenzo/gsl/include/gsl/gsl_sf.h /home/lorenzo/.local/share/Trash/files/gsl.2/gsl_sf.h /home/lorenzo/.local/share/Trash/files/gsl/gsl_sf.h /home/lorenzo/.local/share/Trash/files/gsl.3/gsl_sf.h /home/lorenzo/.local/share/Trash/files/gsl_sf.h find: ‘/run/user/1000/gvfs’: Permission denied

http://stackoverflow.com/comment/87511761
score: 2
comment on: http://stackoverflow.com/q/50247117
type: Comment
type: QuestionComment
has text: [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict)

http://stackoverflow.com/comment/87739843
comment on: http://stackoverflow.com/a/50322735
has text: Still works my end - please update your question with exact steps to reproduce this problem.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87787276
has text: We need to see the definition of the `cas` variable for this to be answerable.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50322377

http://stackoverflow.com/q/50293992
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50294027
type: Question
has body: I have data in csv format of the following form: A B a1 a2 a3 a4 a5 1 0 100 34 44 1 1 2 0 101 1 44 11 3 3 0 105 3 55 21 22 4 0 45 4 52 1 45 5 0 57 5 42 3 56 6 0 89 78 1 3 67 7 0 34 99 2 4 98 8 0 57 23 2 5 2 I would like to store the data from columns a1 on in one array to give: 100 34 44 1 1 101 1 44 . . I can do this using python by reading the columns I want from the csv into a pandas dataframe. Converting each column into an array, looping through each array, and appending the values to one new array. I know this is very inefficient. Is there a better way to do this? Thanks!
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Reading all values from certain columns in csv into one array python
accepted answer: http://stackoverflow.com/a/50294027
type: AnsweredQuestion
score: 0
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/50305858
accepted answer: http://stackoverflow.com/a/50305902
tagged with: python
has title: Is it possible to add 2 lines of same text just different numerical value in File
type: AnsweredQuestion
score: 0
has body: I have a code which writes to file when user select a product for example the user select banana from program it will write in file You have purchased 2 bananas for price of 200 but what if the user purchase 3 bananas more from the program. Is it possible to make this 2 to 5 and from price from 200 to 500 You have purchased 5 bananas for price of 500 The command i am using for writing into file is print('You have purchased',quantity,'Bananas for price of',price, file=test.txt)
answer count: 1
has answer: http://stackoverflow.com/a/50305902
type: Question

http://stackoverflow.com/comment/87641184
has text: That's how non-unicode char are stored. As long as you open a connection to mysql setting charset to `UTF-8`, when you read and print the content, it will be displayed as your wish. But you won't see a *string* such as `"mão"`, you'll see `"m\xc3\xa3o"` instead.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50311978

http://stackoverflow.com/a/61951048
type: Answer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/50362923
downvote count: 0
has body: I'm going to put my 2¢ in and say that you should type-check your testsuite. Its still code and static type checking will help you write better code faster. That leaves the question of how. Ideally, if your function expects SomeComplexObject then you also pass in an instance thereof. Either by building one in your test fixtures, or by subclassing and overriding what you don't need. The best unit test is the one that operates on proper input. That still leaves the case where this is impractical or we explicitly want to test how invalid input is handled. In that case just explicitly cast your mock to the type that mypy requires: from typing import cast def test_foo(): mock_bar = cast(SomeComplexObject, MockBar()) foo(mock_bar)
has comment: http://stackoverflow.com/comment/114000685

http://stackoverflow.com/comment/87689965
comment on: http://stackoverflow.com/q/50336667
has text: @seralouk thank you!! lol it worked *facepalm* huhu
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/87571749
comment on: http://stackoverflow.com/q/50274753
score: 1
type: Comment
type: QuestionComment
has text: Alternatively, you can recover uniqueness if points in the same cluster are connected by a sequence of edges with lengths less than a given threshold.

http://stackoverflow.com/comment/87602912
has text: The first code snippet is something I want to achieve. Again, I don't see any practical usage for this, I just want to know if it's possible and how it can be done
type: Comment
comment on: http://stackoverflow.com/a/50293195
score: 0
type: AnswerComment

http://stackoverflow.com/q/50287049
linked to: http://stackoverflow.com/q/69645
tagged with: python
linked to: http://stackoverflow.com/q/860013
has comment: http://stackoverflow.com/comment/87590470
possible better answer: http://stackoverflow.com/a/50287235
has comment: http://stackoverflow.com/comment/87590241
has answer: http://stackoverflow.com/a/50287235
answer count: 2
has body: I can't focus on upload button to upload resume. Upload Resume URL: Website Link
has comment: http://stackoverflow.com/comment/87590163
downvote count: 0
has comment: http://stackoverflow.com/comment/87590379
tagged with: selenium
has comment: http://stackoverflow.com/comment/87590397
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87590132
accepted answer: http://stackoverflow.com/a/50287254
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50287254
has comment: http://stackoverflow.com/comment/87590115
type: AnsweredQuestion
has title: I can't focus on upload button to upload resume

http://stackoverflow.com/comment/87643587
has text: Sruthi I dont want to use string as the string parameters are generic.
score: 0
comment on: http://stackoverflow.com/q/50313785
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50356584
has answer: http://stackoverflow.com/a/50356988
tagged with: python
type: Question
score: 0
answer count: 2
type: UnansweredQuestion
has title: index out of range with BeautifulSoup
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/50356893
tagged with: indexoutofrangeexception
has body: I tried to understand this nasty index out of range error for some time but I can not figure out why it shows up. The output is what I am expecting with a correct number of results. I cannot catch the empty one that I guess it raising the error. In the code below I tried to capture the error but I must to something wrong. I tried as well the len() method. I'm counting the number of iteration as well. #Import lib needed from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup #-----------------------------------------Importing data -----------------------------------------------------------------# #Page with number of adds per location my_url_nb_Nimes_building = 'https://www.leboncoin.fr/ventes_immobilieres/offres/?th=1&amp;q=immeuble&amp;it=1&amp;location=N%EEmes&amp;ret=1&amp;ret=2&amp;ret=5' #Opening connection, grabbing the page, close connection uClientnimesbuild = uReq(my_url_nb_Nimes_building) page_htmlnimesbuild = uClientnimesbuild.read() uClientnimesbuild.close() page_soupnimesbuild = soup(page_htmlnimesbuild, "html.parser") containglobalnbnimesbuild = ((page_soupnimesbuild).find_all("section",{"class":"item_infos"})) count = 0 for contain in containglobalnbnimesbuild: try: titlecontain = contain.find_all("h2",{"class":"item_title"}) title = titlecontain[0] print("Titre:", title) count = count +1 print(count) except ValueError: print("inerror") Would you have any idea what I am doing wrong to catch this. title = titlecontain[0] IndexError: list index out of range Thanks a lot

http://stackoverflow.com/q/50304296
has comment: http://stackoverflow.com/comment/87625209
has comment: http://stackoverflow.com/comment/87625121
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50310195
accepted answer: http://stackoverflow.com/a/50310195
answer count: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/87625205
has title: Find fluctuations in a NumPy array
has comment: http://stackoverflow.com/comment/87625281
has body: Is it possible to find fluctuations in a list, such that ones graph reaches a certain peak, it will start fluctuating between two values that are unknown. I was considering to focus on all the numbers above the threshold I've wrote bit of python code to simulate this issues. The graph firstly increases to n value and it will fluctuate between two values m and k. Background: The code is simulating a compartmental SIS model on a temporal network. That is each node of that is in one of the compartments (Susceptible - Infected - Susceptible). The infection spreads by each infected node tryign to infect neighbouring node with probability and recover with probability at each time step. The infection will die out if it's below the threshold where . So what the code does, it runs in a while(True) loop checking if the infection dies out, and if it is above the coverage of infected is 40%. Between those two if statements, the infection goes into a steady state, that is it's above the threshold but below 40% coverage, and it fluctuates for infinite amount of time. I'm trying to find a way to find those fluctuations in a list. The code for simulating this situation (the graph): import random import numpy as np import matplotlib.pyplot as plt n = 10 m = 11 k = 17 a = np.arange(0, n, 1) a = np.asarray(a) for i in range(100): a = np.append(a, random.randint(m, k)) plt.plot(a) plt.show()
has comment: http://stackoverflow.com/comment/87625540
tagged with: python

http://stackoverflow.com/comment/87609022
score: 0
has text: thank you, this is originally what I was trying to do, but I am quite new to programming :)
comment on: http://stackoverflow.com/a/50295949
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50343523
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87705087
downvote count: 0
has body: I want to use bool_and aggregate function for GROUP BY, but I do not understand how to implement it in SQLAlchemy. I have tried func.and_ but it does not seem to work.
answer count: 1
linked to: http://stackoverflow.com/q/36956867
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: postgresql
has answer: http://stackoverflow.com/a/50343646
type: UnansweredQuestion
has title: Does SQLAlchemy have bool_and aggregate function?
tagged with: python

http://stackoverflow.com/q/50362479
tagged with: arrays
has answer: http://stackoverflow.com/a/50362671
tagged with: python
has body: I have an ensemble of sorted (one-dimensional) arrays of unequal lengths (say M0, M1 and M2). I want to find how many elements of each of these arrays is inside specific number ranges (where the number ranges are specified by neighboring elements from another sorted array, say zbin). I want to know what is the fastest way to achieve this. Here, I am giving a small example of the task that I want to do (and also the method that I am following presently to achieve the desired functionality): """ Function to do search query """ def search(numrange, lst): arr = np.zeros(len(lst)) for i in range(len(lst)): probe = lst[i] count = 0 for j in range(len(probe)): if (probe[j]&gt;numrange[1]): break if (probe[j]&gt;=numrange[0]) and (probe[j]&lt;=numrange[1]): count = count + 1 arr[i] = count return arr """ Some example of sorted one-dimensional arrays of unequal lengths """ M0 = np.array([5.1, 5.4, 6.4, 6.8, 7.9]) M1 = np.array([5.2, 5.7, 8.8, 8.9, 9.1, 9.2]) M2 = np.array([6.1, 6.2, 6.5, 7.2]) """ Implementation and output """ lst = [M0, M1, M2] zbin = np.array([5.0, 5.5, 6.0, 6.5]) zarr = np.zeros( (len(zbin)-1, len(lst)) ) for i in range(len(zbin)-1): numrange = [zbin[i], zbin[i+1]] zarr[i,:] = search(numrange, lst) print zarr Output: [[ 2. 1. 0.] [ 0. 1. 0.] [ 1. 0. 3.]] Here, the final output zarr gives me the number of elements of each of the arrays (M0, M1 and M2) inside each of the bins possible from zbin (viz. [5.0, 5.5], [5.5, 6.0] and [6.0, 6.5].) For example consider the bin [5.0, 5.5]. The array M0 has 2 elements inside that bin (5.1 and 5.4), M1 has 1 element (5.2) and M2 has 0 elements in that bin. This gives the first row of zarr i.e. [2,1,0]. One can get the other rows of zarr in a similar manner. In my actual task, I will be dealing with zbin of lengths much larger than what I have given in this example, and also bigger and many more arrays like M0, M1, ... Mn. All Ms and the array zbin would be sorted always. I am wondering if the function that I have desig…
type: AnsweredQuestion
score: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/50362539
accepted answer: http://stackoverflow.com/a/50362671
upvote count: 2
has comment: http://stackoverflow.com/comment/87741404
has comment: http://stackoverflow.com/comment/87741433
has answer: http://stackoverflow.com/a/50362539
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has title: Number of elements of numpy arrays inside specific bins

http://stackoverflow.com/comment/92370351
has text: Thanks though it was still on my bug list!
type: Comment
comment on: http://stackoverflow.com/a/52669966
score: 0
type: AnswerComment

http://stackoverflow.com/q/50381004
upvote count: 2
answer count: 1
has body: I am in the process of writing an AI for the game 2048. At the moment, I can pull the game state from the browser and send moves to the game, but I don't know how to integrate that with TensorFlow. The nature of the project isn't conducive to training data, so I was wondering if it's possible to pass in the state of the game, have the network chuck out a move, run the move, repeat until the game is over, and then have it do the training?
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/2048
has answer: http://stackoverflow.com/a/50381176
tagged with: neural-network
tagged with: python
tagged with: artificial-intelligence
accepted answer: http://stackoverflow.com/a/50381176
has title: TensorFlow neural network as an API?
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/50346411
answer count: 1
has title: Why and how would you not use a python GUI framework and make one yourself like many applications including Blender do?
has body: I have looked at a few python GUI frameworks like PyQt, wxPython and Kivy, but have noticed there aren’t many popular (used widely) python applications, from what I can find, that use them. Blender, which is pretty popular, doesn’t seem to use them. How would one go about doing what they did/what did they do and what are the potential benefits over using the previously mentioned frameworks?
type: AnsweredQuestion
score: 0
tagged with: blender
has answer: http://stackoverflow.com/a/50404266
accepted answer: http://stackoverflow.com/a/50404266
tagged with: python
type: Question
tagged with: python-3.x
tagged with: user-interface

http://stackoverflow.com/comment/91984552
has text: Im so sorry I forgot to accept your answer the day I asked this!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50331928
type: Comment

http://stackoverflow.com/comment/87689706
has text: Thanks for @today I will test it and let you know.
comment on: http://stackoverflow.com/q/50333532
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/87610156
score: 0
type: QuestionComment
type: Comment
has text: @MatiasCicero Thanks for making it clear!
comment on: http://stackoverflow.com/q/50296546

http://stackoverflow.com/comment/87778779
type: Comment
score: 0
has text: It physically hurts that @AdamSmith stole my accept. :(
type: AnswerComment
comment on: http://stackoverflow.com/a/50342593

http://stackoverflow.com/a/50379382
has body: read the data into a pandas DataFrame df = pd.read_csv('my_file.csv') Here, I'm assuming the column is called place. Use groupby to group all rows that start with a state (all-caps) until the next state, pick the first place for each group (the state) and assign it to a new column in the data frame df['state'] = df.groupby(df.place.str.isupper().cumsum()).place.transform('first') Then remove rows where the place is null or place == state df[pd.notnull(df.place) &amp; (df.place != df.state)] outputs: place state 2 Birmingham ALABAMA 3 Montgomery ALABAMA 4 Huntsville ALABAMA 8 Los Angeles CALIFORNIA 9 San Diego CALIFORNIA 10 Fresno CALIFORNIA
answers question: http://stackoverflow.com/q/50378554
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87805862

http://stackoverflow.com/a/50272361
upvote count: 1
has body: pygame.Surface((width, height), flags=0, depth=0, masks=None) -&gt; Surface Reading the docs really helps understanding it.
answers question: http://stackoverflow.com/q/50242122
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/comment/87595177
has text: How to improve your code? Get it working, then post it on https://codereview.stackexchange.com/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50289308
score: 0

http://stackoverflow.com/q/50250451
accepted answer: http://stackoverflow.com/a/50254496
has comment: http://stackoverflow.com/comment/87526370
has answer: http://stackoverflow.com/a/50254496
tagged with: python
has title: How to give database id as many2one field in odoo load method
type: AnsweredQuestion
score: 0
tagged with: odoo-10
answer count: 1
has body: I'm trying to create records(category, products ...) in bulk using load orm method in odoo v10. The problem I'm having is about how to reference m2o field as database id. # get list of categ name from input data parent_categ_codes = [categ['name'] for categ in categ_data] # get product.category by name parent_categ_objs = self.env['product.category'].search([('name','in',parent_categ_codes)]) parent_dict = {categ.name: categ for categ in parent_categ_objs} data = [] fields_name = ['name', 'parent_id'] # populate data for categ in categ_data: # this works but very slow beacuse of name_search lookup data.append([categ['name'], parent_dict[categ['parent_id']].name]) self.env['product.category'].load(fields_name,data) How can I just create a reference for parent_id as id? data.append([categ['name'], parent_dict[categ['parent_id']].id]) does not work reference link thanks
type: Question

http://stackoverflow.com/comment/90252850
type: AnswerComment
has text: Thank you for your answer but at that time I already tried that. and DEBUG = True helps in so that we do not have to restart our session of flask each time we run our code
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51627468

http://stackoverflow.com/comment/87547230
type: Comment
score: 0
type: AnswerComment
has text: Feel free to do a timeit test, but I can guarantee this regex replacement is the slowest, followed by your loopy replace. The fastest and second fastest by far is translate and the list comp.
comment on: http://stackoverflow.com/a/50264226

http://stackoverflow.com/comment/87605083
comment on: http://stackoverflow.com/q/50293645
has text: Thanks AK47 and Guillaume , that works !!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87654115
type: Comment
type: QuestionComment
has text: You aren't converting ascii to unicode, you are converting utf-8 encoded binary to unicode. The reason why your fix works is that it decodes the utf-8 encoded strings. But you shouldn't do all that work. Remove the utf-8 stuff from your original code and work in unicode the whole time.
comment on: http://stackoverflow.com/q/50318856
score: 1

http://stackoverflow.com/a/50262730
has comment: http://stackoverflow.com/comment/87543669
has comment: http://stackoverflow.com/comment/87543639
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50262594
has comment: http://stackoverflow.com/comment/87543553
has comment: http://stackoverflow.com/comment/87543659
accepted answer of: http://stackoverflow.com/q/50262594
downvote count: 0
upvote count: 1
has body: The problem is that you're incrementing i by NewDict[item][1] * 2 before you extract the parameter after the operator. You should do this after extracting. You also don't need the for item in NewDict: loop, just access the element of NewDict directly. while i &lt; len(data): op = data[i:i+2] if op in NewDict: opname, oplen = NewDict[op] param = data[i+2:i+2+oplen*2] L.append(opname + " " + param) i += 2 + oplen*2 else: i += 2 Even after fixing this you don't get ADD in the result because the last op in data is 10, not 12.
type: AcceptedAnswer

http://stackoverflow.com/q/50336110
tagged with: keras
accepted answer: http://stackoverflow.com/a/50342977
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87698148
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50342977
has body: I am trying to predict using the learned .h5 file. The learning model is as follows. model =Sequential() model.add(Dense(12, input_dim=3, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) And I wrote the form of the input as follows. x = np.array([[band1_input[input_cols_loop][input_rows_loop]],[band2_input[input_cols_loop][input_rows_loop]],[band3_input[input_cols_loop][input_rows_loop]]]) prediction_prob = model.predict(x) I thought the shape was correct, but the following error occurred. ValueError: Error when checking : expected dense_1_input to have shape (3,) but got array with shape (1,) The shape of x is obviously (3,1), but the above error doesn't disappear (the data is from a csv file in the form of (value 1, value 2, value 3, class)). How can I solve this problem?
favorite count: 0
has title: ValueError: Error when checking : expected dense_1_input to have shape (3,) but got array with shape (1,)
type: Question
upvote count: 2
tagged with: numpy
tagged with: neural-network
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/87690404
tagged with: python

http://stackoverflow.com/a/50307267
has comment: http://stackoverflow.com/comment/87630826
has comment: http://stackoverflow.com/comment/87630722
has comment: http://stackoverflow.com/comment/87630607
accepted answer of: http://stackoverflow.com/q/50306696
type: Answer
answers question: http://stackoverflow.com/q/50306696
has comment: http://stackoverflow.com/comment/87630893
score: 1
has body: You can use np.where, like this: import numpy as np df.length1, df.legth2 = np.where(df.seq1_id.str.contains('t1_0035'), df.length1, df.legth2), np.where(df.seq1_id.str.contains('t1_0042'), df.length1, df.legth2) df.seq1_id, df.seq2_id = np.where(df.seq1_id.str.contains('t1_0035'), df.seq1_id, df.seq2_id), np.where(df.seq1_id.str.contains('t1_0042'), df.seq1_id, df.seq2_id) &gt;&gt;&gt; df seq1_id seq2_id dN 0 g66097.t1_0035_0035 g13600.t1_0042_0042 0.10 1 g1464.t1_0035_0042 g45594.t1_0042_0035 0.67 2 g50055.t1_0035_0035 g34744.t1_0042_0035 0.08 3 g12096.t1_0035_0042 g34020.t1_0042_0035 0.43 Edit to your followup question:
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/50381064
has comment: http://stackoverflow.com/comment/91645425
tagged with: python
linked to: http://stackoverflow.com/q/29280470
linked to: http://stackoverflow.com/q/52349507
has answer: http://stackoverflow.com/a/50389889
tagged with: greatest-n-per-group
type: AnsweredQuestion
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51047693
has body: I'm selecting one max row per group and I'm using groupby/agg to return index values and select the rows using loc. For example, to group by "Id" and then select the row with the highest "delta" value: selected_idx = df.groupby("Id").apply(lambda df: df.delta.argmax()) selected_rows = df.loc[selected_idx, :] However, it's so slow this way. Actually, my i7/16G RAM laptop hangs when I'm using this query on 13 million rows. I have two questions for experts: How can I make this query run fast in pandas? What am I doing wrong? Why is this operation so expensive? [Update] Thank you so much for @unutbu 's analysis! sort_drop it is! On my i7/32GRAM machine, groupby+idxmax hangs for nearly 14 hours (never return a thing) however sort_drop handled it LESS THAN A MINUTE! I still need to look at how pandas implements each method but problems solved for now! I love StackOverflow.
downvote count: 0
accepted answer: http://stackoverflow.com/a/50389889
has answer: http://stackoverflow.com/a/51047693
upvote count: 7
has title: Select the max row per group - pandas performance issue
favorite count: 0
type: Question
tagged with: performance
score: 7

http://stackoverflow.com/comment/87614637
score: 0
type: Comment
type: QuestionComment
has text: Editing code into post.
comment on: http://stackoverflow.com/q/50298042

http://stackoverflow.com/comment/87596156
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50289445
has text: I am getting an error **AttributeError: 'str' object has no attribute 'iter'** and also an **ERROR: Spider error processing** in the debug window @VMRuiz
type: Comment

http://stackoverflow.com/q/50359589
upvote count: 1
type: UnansweredQuestion
score: 1
has body: I'm currently working on a web app, and I'm using config files to upload the names for certain models. How would I go about associating these created models to a ForeignKey associated to a parent model class that already exists in a different app? For example, I have the following models: # Base models.py class Parent(models.Model): name = models.CharField() # Child models.py class child(models.Model): name = models.CharField() parent = models.foreignKey('Parent', on_delete = models.CASCADE) The first base models will already exist within the database and will be used in a previous view. Then in the current views I'll call a function that will get or create a certain amount of child models, based on the number of rows in the csv file, and pass these generated models into the html template. What I'm not sure how to do is making sure that the models created in the function will have the appropriate foreign key that associates it to the right specific model used in the previous view.
has title: Django: How to create a new model with a foreign key associated to a previously visited model
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50359843
tagged with: http://stackoverflow.com/tag/csv
tagged with: django
tagged with: django-models
tagged with: python
downvote count: 0

http://stackoverflow.com/a/54359054
has comment: http://stackoverflow.com/comment/95532720
answers question: http://stackoverflow.com/q/50337237
type: Answer
has body: df = pd.DataFrame({'x': [0, 1], 'y': [2, 3]}) sns.barplot(x = df.mean().index, y = df.mean()) plt.show()
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/119657394
type: Comment
comment on: http://stackoverflow.com/a/53918402
type: AnswerComment
score: 0
has text: @alper for one that's development and is not secure. `gevent` is one option for running the app in production.

http://stackoverflow.com/comment/134469292
comment on: http://stackoverflow.com/a/53014524
type: AnswerComment
score: 0
type: Comment
has text: I think it should be MockTarget instead of MockFile

http://stackoverflow.com/q/50384592
has answer: http://stackoverflow.com/a/50384688
type: Question
score: 0
answer count: 3
tagged with: python
has body: I am try to reference an object variable inside the class without passing it in parameters but it is throwing error class Sample: def __init__(self): v = [] v.append(name) v.append(email) s = Sample() s.name = "xxxx" s.email = "ss@ss.com" print s.v error: NameError: global name 'name' is not defined I am assigning the variable name in the object now how can i call it inside the class without adding parameters to function
tagged with: class
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50384892
has answer: http://stackoverflow.com/a/50385060
has title: how can i reference to an object variable without passing it as parameter in python classes

http://stackoverflow.com/q/50270294
has title: tkinter TreeView: disable selection highlight
has body: I have a tkinter TreeView and used tags to mark multiple selected items as shown below in yellow. Unfotunately the last clicked item will always appear in blue regardless of the tag. How do I prevent the TreeView from coloring the last clicked item? Here is the code snippet I use to select items: def on_click(self, event): """Set tag for selected datasets.""" # Remove 'plotted' tag if existent if 'plotted' in self.tree.item(self.tree.selection())['tags']: # FIXME: Only remove tag 'plotted' self.tree.item(self.tree.selection(), tags=()) # Select only items that have no children elif not self.tree.get_children(self.tree.selection()): self.tree.item(self.tree.selection(), tags='plotted') self.tree.column('#0', anchor=tk.E) And here is a sample how it could look like. Note you can't tell if DNTP_iDL_... is supposed to be white (b/c it has been yellow and I clicked on it to deactivate it):
tagged with: python
has comment: http://stackoverflow.com/comment/87650471
has comment: http://stackoverflow.com/comment/87655414
type: AnsweredQuestion
answer count: 2
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/61807659
score: 0
tagged with: treeview
tagged with: tk-toolkit
accepted answer: http://stackoverflow.com/a/50333852
type: Question
has answer: http://stackoverflow.com/a/50333852
has comment: http://stackoverflow.com/comment/87612482
has comment: http://stackoverflow.com/comment/87650454
has answer: http://stackoverflow.com/a/61807659

pandas-groupby
tags question: http://stackoverflow.com/q/50379203
tags question: http://stackoverflow.com/q/50306914
tags question: http://stackoverflow.com/q/50261144
type: Tag
tags question: http://stackoverflow.com/q/50277117
tags question: http://stackoverflow.com/q/50360326
tags question: http://stackoverflow.com/q/50357837
tags question: http://stackoverflow.com/q/50256937
tags question: http://stackoverflow.com/q/50242695
tags question: http://stackoverflow.com/q/50375913
tags question: http://stackoverflow.com/q/50274268
tags question: http://stackoverflow.com/q/50260451
tags question: http://stackoverflow.com/q/50276334
tags question: http://stackoverflow.com/q/50268723
tags question: http://stackoverflow.com/q/50273308
tags question: http://stackoverflow.com/q/50352702
tags question: http://stackoverflow.com/q/50321512
tags question: http://stackoverflow.com/q/50319733
tags question: http://stackoverflow.com/q/50381064
tags question: http://stackoverflow.com/q/50340717
tags question: http://stackoverflow.com/q/50302228
tags question: http://stackoverflow.com/q/50297174
tags question: http://stackoverflow.com/q/50357257
tags question: http://stackoverflow.com/q/50359885
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/50259463
tags question: http://stackoverflow.com/q/50366883
tags question: http://stackoverflow.com/q/50231495
tags question: http://stackoverflow.com/q/50302103
tags question: http://stackoverflow.com/q/50243181

http://stackoverflow.com/comment/87752805
has text: need `df_new = df.copy()`, check also [this](https://stackoverflow.com/a/46939443)
comment on: http://stackoverflow.com/q/50368386
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50239641
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87498411
has body: In image processing and classification networks, a common task is the convolution or cross-correlation of input images with some fixed filters. For example, in convolutional neural nets (CNNs), this is an extremely common operation. I have reduced the general version task to this: Given: a batch of N images [N,H,W,D,...] and a set of K filters [K,H,W,D,...] Return: a ndarray that represents the m-dimensional cross-correlation (xcorr) of image N_i with filter K_j for every N_i in N and K_j in K Currently, I am using scipy.spatial.cdist on a custom function that represents the max of the xcorr of two m-dim images, namely scipy.signal.correlate. The code looks something like this: from scipy.spatial.distance import cdist from scipy.signal import correlate def xcorr(u,v): '''unfortunately, cdist only takes 2D arrays, so need to do this''' u = np.reshape(u, [96,96,3]) v = np.reshape(v, [96,96,3]) return np.max(correlate(u,v,mode='same',method='fft')) batch_images = np.random.random([500,96,96,3]) my_filters = np.random.random([1000,96,96,3]) # unfortunately, cdist only takes 2D arrays, so need to do this batch_vec = np.reshape(batch_images, [-1,np.prod(batch_images.shape[1:])]) filt_vec = np.reshape(my_filters, [-1,np.prod(my_filters.shape[1:])]) answer = cdist(batch_vec, filt_vec, xcorr) The method works, and its nice that cdist is automatically parallelized across threads, but it is actually quite slow. I am guessing this is due to a number of reasons, including non-optimal use of the cache between threads (e.g. keep one filter fixed in cache while you filter all the images, or vice versa), the reshape operation inside xcorr, etc. Does the community have any ideas how to speed this up? I realize in my example xcorr takes the maximum over the cross-correlation between both images, but this was just an example that was fit to work with cdist. Ideally, you could perform this batch operation and use some other function (or none) to get the output you wanted. Ideal solution…
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/87498228
favorite count: 0
type: Question
score: 3
has title: Multi-Dimensional Batch-Image Convolution using Numpy
tagged with: python
tagged with: image-processing
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/87498391
tagged with: conv-neural-network

http://stackoverflow.com/q/50230309
tagged with: scrollbar
has body: I have looked through all the answered questions available here but to no avail. I'm working on Mac OS X High Sierra and my Scrollbar widget shows up but doesn't scroll the window, any advice? from tkinter import * root = Tk() root.geometry('400x500') root.resizable(False, False) def window(): popup = Toplevel() vertScrollbar = Scrollbar(popup, orient='vertical') vertScrollbar.pack(side='right', fill='y') scrollCanvas = Canvas(popup, width='400', height='500', yscrollcommand=vertScrollbar.set) vertScrollbar.config(command=scrollCanvas.yview) scrollFrame = Frame(scrollCanvas, width='400', height='500') scrollCanvas.create_window(0, 0, window=scrollFrame, anchor='n') for words in range(150): test = Label(scrollCanvas) test.config(text='this is a test') test.pack() scrollCanvas.config(scrollregion=scrollCanvas.bbox('all')) #scrollCanvas.config(scrollregion=(0,0,400,800)) doesn't work either scrollCanvas.pack(side='top', fill='both') scrollFrame.pack(side='top', fill='both') openWindow = Button(root, text='Push Me', command=window) openWindow.pack(ipadx='5', ipady='3', pady='10') root.mainloop()
score: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/50232054
answer count: 1
tagged with: macos
type: Question
has title: Scrollbar in python tkinter Toplevel() shows up but does not scroll
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51478276
answers question: http://stackoverflow.com/q/50255981
upvote count: 2
has body: To get the TIFF output that you're interested in - from PIL import Image, TiffImagePlugin TiffImagePlugin.DEBUG = True Image.open('my_picture.tif')
has comment: http://stackoverflow.com/comment/89925924
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/50255981
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50334927
score: 0
accepted answer of: http://stackoverflow.com/q/50334782
type: AcceptedAnswer
has body: You could transform the Region to a numeric representation, and use that as a "key" to your colormap. Below are two methods to do that (one is commented out, pick whichever you choose, the result should be the same): plt.scatter(x = data['LifeExpec'], y = data['GDPperCapita'], s = data['PopX1000'], c = pd.factorize(data['Region'])[0], # Alternatively: # c = data['Region'].astype('category').cat.codes cmap=cm.viridis, edgecolors = 'none', alpha = 0.7)
answers question: http://stackoverflow.com/q/50334782
type: Answer

http://stackoverflow.com/comment/87575676
comment on: http://stackoverflow.com/a/50279534
type: AnswerComment
has text: Love it, einsum is a difficult beast to tame.
score: 2
type: Comment

http://stackoverflow.com/q/50299479
tagged with: beautifulsoup
tagged with: python-3.x
type: Question
has body: Here is the source of the of the page I am looking for. Page Source. If page source is not working here is the link for the source only. "view-source:https://sports.bovada.lv/baseball/mlb" Here is the Link: Link to page I am not to familiar with using bs4 but here is the script below which works, but does not return anything I need. import requests from bs4 import BeautifulSoup r = requests.get('https://sports.bovada.lv/baseball/mlb/game-lines-market-group') soup = BeautifulSoup(r.content, 'lxml') print(soup.prettify()) I can return the soup just fine. But what see from just inspecting the site and the returned soup are not the same. Here is a sample of what I can see from inspect. The goal is to remove the Team, pitcher, odds and total runs. Which I can clearly see in the inspect version. When I print soupthat information does not come with. Then I dove a little further and on the bottom of the Page source i can see an iFrame and below that it looks like json dictionary with everything I am looking to extract but running a similar script to retrieve json data does not work like I had hoped: import requests req = requests.get('view-source:https://sports.bovada.lv//baseball/mlb/game-lines-market-group') data = req.json()['itemList'] print(data) I believe i should be using bs4 but I am confused on why the same html is not being returned.
tagged with: python
has title: Using requests with bs4 and or json
accepted answer: http://stackoverflow.com/a/50300136
type: AnsweredQuestion
score: 0
tagged with: iframe
has answer: http://stackoverflow.com/a/50300136
has comment: http://stackoverflow.com/comment/87616768
answer count: 1

http://stackoverflow.com/comment/87622129
comment on: http://stackoverflow.com/q/50302827
type: Comment
has text: I think you should look to the last line of the traceback. See if encoding your string as bytes work.
type: QuestionComment
score: 0

http://stackoverflow.com/q/50291005
upvote count: 1
tagged with: imshow
has answer: http://stackoverflow.com/a/50292596
type: AnsweredQuestion
has body: I am trying to plot a correlation matrix with values shows in plot. Instead of a single value of correlation coefficient, I want a range on the tiles (confidence interval). To achieve this I am first plotting the matrix with a colorbar using matshow and individual writing values of low and high intervals on the plot using centering option. Here is the snippet of that code. cax = ax.matshow(data, interpolation='nearest', cmap=GnRd, vmin=-1, vmax=1 ,alpha=1 ) fig.colorbar(cax, ticks=[-1,0,1], shrink=0.8) for (i, j), z in np.ndenumerate(data2): if i&gt;=j and z &gt; -0.5 and z &lt; 1: ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', **hfont) if z &lt; -0.5 : ax.text(j, i, '{:0.2f}'.format(z), ha='left', va='center', size=28, color='black', fontweight='bold', **hfont) if z == 1 : ax.text(j, i, '{:0.2f}'.format(z), ha='center', va='center', size=28, color='black', fontweight='bold', **hfont) for (i, j), z in np.ndenumerate(data3): if i&gt;=j and z &gt; -0.5 and z &lt;1: ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', **hfont) if z &lt; -0.5 : ax.text(j, i, '{:0.2f}'.format(z), ha='right', va='center', size=28, color='black', fontweight='bold', **hfont) plt.show() and here is my plot : The problem with this plot is coloring in the tiles is not correct and I am not sure how to color the tiles for a range. Also, there is a wasted space on the tiles which can be reduced by making titles rectangular but I believe matshow doesn't that option. I found a few work around based on object drawing, which will probably make my life more complicated. Any help will be appreciated.
score: 1
tagged with: pearson-correlation
tagged with: matplotlib
has title: plotting number range in a correlation matrix with colorbar with rectangular tiles [matshow (matplotlib)]
tagged with: python
favorite count: 0
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50292596

http://stackoverflow.com/q/50323357
has title: Regex expression to capture '*' while excluding comment section
has comment: http://stackoverflow.com/comment/87662433
upvote count: 2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87662424
has answer: http://stackoverflow.com/a/50323470
linked to: http://stackoverflow.com/q/171480
linked to: http://stackoverflow.com/q/47666018
has comment: http://stackoverflow.com/comment/87662474
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87662426
has comment: http://stackoverflow.com/comment/87662531
has comment: http://stackoverflow.com/comment/87662403
type: UnansweredQuestion
tagged with: python
has body: I want to capture all the * in the code except the comment section. The regex for comment section is: (\/\*\[\S\s\]*?\*\/) I tried excluding the the comment section and search for any * character preceded/succeeded by 0 or more spaces. Regex : [^\/\*[\S\s]*?\*\/\]\s*\*\s* /** * This function is useless * * @return sth */ public void testMe() { int x = 5*4; x*=7; x = x**2; } It should match all the * inside testMe.
has comment: http://stackoverflow.com/comment/87662488
tagged with: regex
score: 0

http://stackoverflow.com/comment/87761637
type: QuestionComment
comment on: http://stackoverflow.com/q/50372660
has text: You can always ask another question. Sometimes it is even appropriate to update your current question with new information if the new question arises from comments on the current question.
score: 0
type: Comment

http://stackoverflow.com/comment/87825004
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50380333
type: Comment
has text: I updated again. Could you explain what timestamp format is?

http://stackoverflow.com/q/50321856
has title: The pattern of `clean_ops = [str.strip, remove_punctuation, str.title]`
has comment: http://stackoverflow.com/comment/87659541
type: Question
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87659598
linked to: http://stackoverflow.com/q/16739290
has body: I learned a tricks to pass functions as argument def remove_punctuation(value): return re.sub('[!#?]', '', value) clean_ops = [str.strip, remove_punctuation, str.title] def clean_strings(strings, ops): result = [] for value in strings: for function in ops: value = function(value) result.append(value) return result print(clean_strings(states, clean_ops)) I find it amazing to encapsulate required functions to a list which even helps in the thinking process. What's the pattern of the such a practice?
answer count: 0
has comment: http://stackoverflow.com/comment/87659516
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87659761

http://stackoverflow.com/a/50257404
type: Answer
score: -1
has body: You can use dictionary comprehension in this way: {a: {b:100 for b in d} for (a,d) in x.items()}
upvote count: 0
answers question: http://stackoverflow.com/q/50257201
downvote count: 1

http://stackoverflow.com/comment/87697980
type: QuestionComment
comment on: http://stackoverflow.com/q/50340463
has text: Your question says your approach "is less efficient than I'd like", so I assumed you had a real efficiency problem with your real data. If you do, that same problem may well apply to Coldspeed's answer—so you should explain the size and shape of your data and why it's too slow, so we can tell you whether that answer is good enough or provide something more complicated but faster if necessary.
score: 0
type: Comment

http://stackoverflow.com/a/52627199
type: AcceptedAnswer
upvote count: 5
downvote count: 0
type: Answer
has body: i had a similar problem and i solved it this way. i initialize my task in urls.py, i dont know if you can use other places to put it ,also added and if, to check if the task its allready in the database from background_task.models import Task if not Task.objects.filter(verbose_name="update_orders").exists(): tasks.update_orders(repeat=300, verbose_name="update_orders") i have tested it and it works fine, you can also search for the order with other parameters like name, hash ,... you can check the task model here: https://github.com/arteria/django-background-tasks/blob/master/background_task/models.py
accepted answer of: http://stackoverflow.com/q/50374139
score: 5
answers question: http://stackoverflow.com/q/50374139

http://stackoverflow.com/comment/87778705
score: 0
has text: `for x in random.randrangec(chars,length):` There's no Python function called `randrangec()` as far as I am aware. Please explain what you want this to do - hint: even if it existed, you are very likely using it wrongly...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50381134

http://stackoverflow.com/comment/87562279
type: QuestionComment
has text: It’s not usually a good idea to override the `get` or `post` methods for generic class based views, because you can either break functionality or have to duplicate code. In your case, the `post` method doesn’t seem to do anything different to the `FormView`’s post method, so I would remove it.
comment on: http://stackoverflow.com/q/50272631
score: 1
type: Comment

http://stackoverflow.com/comment/87527594
type: Comment
comment on: http://stackoverflow.com/q/50254997
score: 1
has text: You can convert data to binary with the package struct and then send them with pyserial
type: QuestionComment

http://stackoverflow.com/comment/87621148
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50302195
type: Comment
has text: @user8834780 The context isn't the same. `df'labels'` and `df[LABELS]` do very different things (LABELS is a list of strings it seems, so `df[LABELS]` is the same as `dfcol1, col2, ...`.)

http://stackoverflow.com/comment/87498215
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50240187
has text: Then you do not distribute 7, but distribute the 6.

http://stackoverflow.com/comment/87634423
comment on: http://stackoverflow.com/q/50302418
score: 0
type: QuestionComment
type: Comment
has text: Wait you’re saying the creation of a new my_portal object is handled in an AJAX request? You can’t send a HttpResponseRedirect back to an AJAX request.

http://stackoverflow.com/comment/87561052
type: AnswerComment
comment on: http://stackoverflow.com/a/50271990
type: Comment
has text: You're a true lifesaver ! Thanks for the link it will definitely be useful to me in the future
score: 0

http://stackoverflow.com/a/50318631
upvote count: 1
type: Answer
has body: Checkout Celery, there are many good tutorials online. It works with workers so it also doesn't block you api listening. Also it could provide the option to process multiple files at once concurently if you'd want.
answers question: http://stackoverflow.com/q/50318604
score: 1
downvote count: 0

http://stackoverflow.com/comment/87656797
type: Comment
type: AnswerComment
has text: What does random.seed(0) at the beginning do? Also I am getting a value error "weights should have the same shape as x"
score: 0
comment on: http://stackoverflow.com/a/50320378

http://stackoverflow.com/a/50263910
has body: Do you mean to raise SystemExit in your done() function to exit? If so, you don't need to track your ambiguously named variable i and deal with scoping problems. See here for some useful explanation. You should also move your player name inputs out of your game loop and input() will return a string. I've tidied the code and removed some of the unnecessarily repeated sections. def done(): """Prompt user to continue or exit""" quit_value = input("Play Again?(y/n): ").lower() if quit_value == 'n': raise SystemExit def rps(play1, play2): """Play a single round of Rock, Paper, Scissors""" # Check Winner of Game if play1 == play2: print("It's a tie!") elif play1 == 'r': if play2 == 's': print(play1name + " Wins!") else: print(play2name + " Wins!") elif play1 == 'p': if play2 == 'r': print(play1name + " Wins!") else: print(play2name + " Wins!") elif play1 == 's': if play2 == 'p': print(play1name + " Wins!") else: print(play2name + " Wins!") # get player names play1name = input("Player 1 Name?: ") play2name = input("Player 2 Name?: ") # Player Input while True: # done() exits the program, so loop forever play1 = input(play1name + " Choose Rock(r),Paper(p), Scissors(s): ") play2 = input(play2name + " Choose Rock(r),Paper(p), Scissors(s): ") # resolve the plays rps(play1, play2) # check for a rematch done() You might also want to check for valid moves in the rps() function.
type: Answer
answers question: http://stackoverflow.com/q/50263686
score: 0

http://stackoverflow.com/comment/87690063
comment on: http://stackoverflow.com/a/50336865
has text: @ThelMi, I updated data for `None` values, just use `filter(None, chain...)`. Note this method will remove all `False` values (e.g. `None`, 0, `False`, empty string, etc). Otherwise you can apply your own filtering logic.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87714586
score: 0
has text: question edited to show groupby('A')
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50349236

http://stackoverflow.com/a/50298971
score: 0
has comment: http://stackoverflow.com/comment/87615218
type: Answer
has body: You should use DictReader and DictWriter. You can learn how to use them by below link. https://docs.python.org/2/library/csv.html
answers question: http://stackoverflow.com/q/50298896

http://stackoverflow.com/comment/87714678
has text: Note that if it comes from a SQL database, most python database adapters have a way to retrieve rows as dicts instead of tuples (cf `DictCursor` for MySQL as an example).
comment on: http://stackoverflow.com/q/50349202
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50249681
type: Question
upvote count: 9
possible better answer: http://stackoverflow.com/a/75032036
has body: I'm new on flask.I configured a server with flask+gunicorn. the code file called test.py like this: from flask import Flask app = Flask(__name__) @app.route('/') def test(): return aa+"world!" if __name__ == '__main__': aa = "hello" app.run() run it using：gunicorn -b 0.0.0.0:8080 test:app I got a mistake：NameError: name 'aa' is not defined. I want some codes like variable aa runing before gunicorn. How to do that？
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/87516737
has comment: http://stackoverflow.com/comment/87516616
has answer: http://stackoverflow.com/a/75032036
linked to: http://stackoverflow.com/q/73570041
tagged with: python
tagged with: flask
answer count: 4
has title: how to run the code before the app.run() in flask?
type: AnsweredQuestion
score: 9
downvote count: 0
has answer: http://stackoverflow.com/a/77783722
has answer: http://stackoverflow.com/a/50250389
has answer: http://stackoverflow.com/a/50249774
accepted answer: http://stackoverflow.com/a/50249774
has comment: http://stackoverflow.com/comment/87516898
favorite count: 0

http://stackoverflow.com/a/50246378
has comment: http://stackoverflow.com/comment/87549664
has comment: http://stackoverflow.com/comment/87548762
has body: Kafka is not meant for sending huge payloads/messages. You should see it as a Distributed Message BUS which gives you all the privileges of a distributed system. Kafka limits the size of the messages which could be sent across because of the following reasons Huge messages increases the memory pressure in the broker. Large messages slows down the broker and handling them is very expensive. Solution: You could very well use a Reference Based Messaging where you send the location of the huge message to the consumer rather than sending huge data as is. This will allow you to use the capabilities of an external datastore and also reduces the pressure on the Kafka Brokers. You could also chunk the data and send it inline and re-assemble at the sink. Playing with Batch Size: batch.size measures batch size in total bytes instead of the number of messages. It controls how many bytes of data to collect before sending messages to the Kafka broker. Set this as high as possible, without exceeding available memory. The default value is 16384. If you increase the size of your buffer, it might never get full. The Producer sends the information eventually, based on other triggers, such as linger time in milliseconds. Although you can impair memory usage by setting the buffer batch size too high, this does not impact latency. If your producer is sending all the time, you are probably getting the best throughput possible. If the producer is often idle, you might not be writing enough data to warrant the current allocation of resources. Since, your data is a gzip you can use the Reference Based Messaging. Instead of playing with the fetch size and message max byte size which cannot cover all the file size store your files on a distributed file system like NFS/HDFS/S3 and send the reference to the consumer. The consumer can pick the location and unzip the data.
has comment: http://stackoverflow.com/comment/87547909
type: Answer
has comment: http://stackoverflow.com/comment/87549677
answers question: http://stackoverflow.com/q/50232186
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87547175
has comment: http://stackoverflow.com/comment/87549622
has comment: http://stackoverflow.com/comment/87548699

http://stackoverflow.com/comment/87553747
comment on: http://stackoverflow.com/q/50267828
score: 0
has text: @coldspeed, can /should I delete my question ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87654419
type: Comment
type: QuestionComment
has text: Serial.println() equal to on python `ser.readline()` (so your delimiter is `\n`) another point is : C++ and python no diference, like ` while (Serial.available())(ardu) == while True: while ser.inWaiting() > 0: (python)`
score: 0
comment on: http://stackoverflow.com/q/50318058

http://stackoverflow.com/a/50321980
type: Answer
has body: Metrics, losses, and the entire model are "symbolic" tensors. This means, they have absolutely no data (or value) until the moment you start fitting or predicting. When you call K.get_value you're trying to get a value that doesn't exist. (It will only exist when you "feed the data" to the model. What it calls a placeholder is an empty input tensor that is expecting to receive the data when fitting or predicting). The solution to your problem is simply not trying to get the values. (The numpy version will not work either, the values don't exist at the moment this function is compiled). You gotta keep all operations symbolic, and they will be performed when you feed the data. So: def symbol_acc(true, predicted): isEqual = K.cast(K.equal(true,predicted),K.floatx()) return K.mean(isEqual)
has comment: http://stackoverflow.com/comment/87686222
has comment: http://stackoverflow.com/comment/87685790
has comment: http://stackoverflow.com/comment/87686414
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/87685874
downvote count: 0
has comment: http://stackoverflow.com/comment/87686099
has comment: http://stackoverflow.com/comment/87686540
has comment: http://stackoverflow.com/comment/87686667
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87686331
has comment: http://stackoverflow.com/comment/87695581
has comment: http://stackoverflow.com/comment/87686944
has comment: http://stackoverflow.com/comment/87686002
accepted answer of: http://stackoverflow.com/q/50321139
has comment: http://stackoverflow.com/comment/87686576
answers question: http://stackoverflow.com/q/50321139

http://stackoverflow.com/q/50316317
has answer: http://stackoverflow.com/a/77042986
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87648489
tagged with: python
favorite count: 0
type: Question
answer count: 2
score: 5
has body: I'm trying to sum a complete field after filtering objects using pk. Views.py def items(request, pk): current_user = request.user selected_itemz = get_object_or_404(ItemIn, pk=pk) all_cats = Category.objects.all() cat_count = all_cats.count() item_count = ItemIn.objects.values_list('item_name', flat=True).distinct().count() # returns a list of tuples.. #all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum'] ItemOut_table = ItemOut.objects.all().filter(item_name=selected_itemz) ItemOut_quantity = ItemOut_table.aggregate(Sum('item_quantity'))['item_quantity__sum'] context = { #'all_units': all_units, 'item_count': item_count, 'cat_count': cat_count, 'current_user': current_user, 'ItemOut_quantity': ItemOut_quantity, 'selected_itemz':selected_itemz, } return render(request, 'townoftech_warehouse/item_details.html', context) Then I used an extra filter that I created which is subtract in my HTML HTML &lt;br&gt; &lt;br&gt; &lt;p align="right"&gt; الكمية الموجودة: &lt;/p&gt; &lt;br&gt; &lt;br&gt; and here is the tempaltetags file from django import template register = template.Library() @register.filter def subtract(value, arg): return value - arg Now I get the error : TypeError at /item/1/ unsupported operand type(s) for -: 'int' and 'NoneType'
tagged with: django-queryset
accepted answer: http://stackoverflow.com/a/50316334
upvote count: 5
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50316334
possible better answer: http://stackoverflow.com/a/77042986
has title: Django aggregate(sum error

qfilesystemmodel
tag name: qfilesystemmodel
tags question: http://stackoverflow.com/q/50357948
tags question: http://stackoverflow.com/q/50283851
type: Tag

http://stackoverflow.com/comment/97694279
comment on: http://stackoverflow.com/a/50394788
type: AnswerComment
has text: @jtlz2: it's already a MCVE, for the `cv2.Boost` type. As I already state in my answer, I can't test this with the specific type, but the general principle should be the same for `cv2.ORB()`. Create a function that returns the constructor and a tuple of values given an instance, then register that function for the actual class object for `cv2.ORB()` instances.
score: 0
type: Comment

http://stackoverflow.com/comment/87663128
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50323707
type: Comment
has text: Hint: try it and find out ;-) *spoiler alert*: you can.

pearson-correlation
tags question: http://stackoverflow.com/q/50291005
type: Tag
tag name: pearson-correlation

http://stackoverflow.com/comment/87776300
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50380017
score: 2
has text: *because utf-16 words are separated by spaces*. I'm not sure what you mean there, but UTF-16 doesn't separate words out.

http://stackoverflow.com/comment/87692402
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50336535
has text: Consider setting column order with DataFrame's `columns=['Start', 'End']` and resetting index at end. Also, we are missing the one second different endpoint for 23:59:59.

http://stackoverflow.com/comment/87590768
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50287345
type: Comment
has text: @xxyao - There should be another problem, because for me it working. If close is in input data, what is expected output? What is MultiIndex?

http://stackoverflow.com/q/50268234
score: 6
tagged with: dataframe
tagged with: python
tagged with: type-conversion
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/50268265
accepted answer: http://stackoverflow.com/a/50268265
answer count: 1
has body: I have a data frame like this: import pandas as pd test_df = pd.DataFrame({'foo':['1','2','92#']}) test_df foo 0 1 1 2 2 92# I want to convert the type to int64: test_df.foo.astype('int64') but I got error message because '92#' can't be convert to int64: ValueError: invalid literal for int() with base 10: '92#' So I want to drop all rows that can't convert to int64, and got my result like this: foo 0 1 1 2
favorite count: 0
type: Question
has title: how to drop rows of wrong type in python?
upvote count: 6

turtle-graphics
tags question: http://stackoverflow.com/q/50295255
tags question: http://stackoverflow.com/q/50275991
tags question: http://stackoverflow.com/q/50304718
tags question: http://stackoverflow.com/q/50238523
tags question: http://stackoverflow.com/q/50306024
tags question: http://stackoverflow.com/q/50361449
tag name: turtle-graphics
tags question: http://stackoverflow.com/q/50350944
type: Tag
tags question: http://stackoverflow.com/q/50370233

http://stackoverflow.com/a/50268625
has body: Your lambda is not correct. import tkinter as tk from tkinter import ttk listname = ['f1', 'f2', 'f3'] def download(file): print(file) win = tk.Tk() fr = tk.Frame(win) fr.grid(row=0, column=0) for row, file in enumerate(listname): tk.Label(fr, text=file).grid(row=row, column=0) tk.Button(fr, text='download', command=lambda f=file: download(f)).grid(row=row, column=1) win.mainloop()
has comment: http://stackoverflow.com/comment/87556161
type: Answer
answers question: http://stackoverflow.com/q/50268186
score: 0
accepted answer of: http://stackoverflow.com/q/50268186
type: AcceptedAnswer

http://stackoverflow.com/comment/87697073
type: AnswerComment
type: Comment
has text: Im using Linux, not working ... do I have to add something in script too?
comment on: http://stackoverflow.com/a/50340461
score: 0

http://stackoverflow.com/q/50248618
type: AnsweredQuestion
has title: Python Record Linkage, Fuzzy Match and Deduplication
has comment: http://stackoverflow.com/comment/87516783
has answer: http://stackoverflow.com/a/54239671
tagged with: record-linkage
has body: I have 3 dataset of customers with 7 columns. CustomerName Address Phone StoreName Mobile Longitude Latitude every dataset has 13000-18000 record. I am trying to fuzzy match for deduplication between them. my data set columns don't have same weight in this matching. How i can handle it???? Do you know good library for my case?
tagged with: duplicates
tagged with: python
favorite count: 0
type: Question
upvote count: 4
score: 2
accepted answer: http://stackoverflow.com/a/54239671
has comment: http://stackoverflow.com/comment/87936935
downvote count: 2
answer count: 1
tagged with: python-dedupe
tagged with: fuzzywuzzy

http://stackoverflow.com/comment/87658927
has text: Yes you are correct. It's kind of superfluous. Maybe I will edit my answer to a solution using only Selenium.
type: Comment
comment on: http://stackoverflow.com/a/50319160
score: 0
type: AnswerComment

http://stackoverflow.com/a/50320378
score: 0
answers question: http://stackoverflow.com/q/50320275
has comment: http://stackoverflow.com/comment/87656883
type: Answer
has comment: http://stackoverflow.com/comment/87657145
has comment: http://stackoverflow.com/comment/87657132
accepted answer of: http://stackoverflow.com/q/50320275
has comment: http://stackoverflow.com/comment/87657218
has body: You need to get the frequencies of the combined histogram and then normalize them by 4 to get the average. You can do the following: import pandas as pd import matplotlib.pyplot as plt import numpy as np import random random.seed(0) Elevations1 = np.zeros(100) Elevations2 = np.zeros(100) Elevations3 = np.zeros(100) Elevations4 = np.zeros(100) for a in np.arange(len(Elevations1)): Elevations1[a] = random.randrange(-10000, 10000) Elevations2[a] = random.randrange(-10000, 10000) Elevations3[a] = random.randrange(-10000, 10000) Elevations4[a] = random.randrange(-10000, 10000) df1 = pd.DataFrame(Elevations1) df2 = pd.DataFrame(Elevations2) df3 = pd.DataFrame(Elevations3) df4 = pd.DataFrame(Elevations4) df_merged = pd.concat([df1, df2, df3, df4], ignore_index=True) # Get the frequencies of the combined histogram hist, bins = np.histogram(df_merged) # Normalize by 4 hist_norm = hist / 4.0 width = 0.9 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 # plot the Un-normalited frequencies plt.bar(center, hist, align='center', width=width) plt.title('Non- Normalized Histogram') plt.show() # plot the normalized frequencies plt.bar(center, hist_norm, align='center', width=width) plt.title('Normalized Histogram') plt.show()
has comment: http://stackoverflow.com/comment/87656549
has comment: http://stackoverflow.com/comment/87656694
has comment: http://stackoverflow.com/comment/87657110
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/87656557
has comment: http://stackoverflow.com/comment/87656729
has comment: http://stackoverflow.com/comment/87656797
has comment: http://stackoverflow.com/comment/87657043

http://stackoverflow.com/comment/87767985
has text: Use word.count(letter), find only returns the index of the letter not the amount.
score: 0
comment on: http://stackoverflow.com/q/50375825
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50240724
type: Answer
upvote count: 37
score: 37
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50240029
downvote count: 0
answers question: http://stackoverflow.com/q/50240029
has comment: http://stackoverflow.com/comment/97902403
has body: wordpunct_tokenize is based on a simple regexp tokenization. It is defined as wordpunct_tokenize = WordPunctTokenizer().tokenize which you can find here. Basically it uses the regular expression \w+|[^\w\s]+ to split the input. word_tokenize on the other hand is based on a TreebankWordTokenizer, see the docs here. It basically tokenizes text like in the Penn Treebank. Here is a silly example that should show how the two differ. sent = "I'm a dog and it's great! You're cool and Sandy's book is big. Don't tell her, you'll regret it! 'Hey', she'll say!" &gt;&gt;&gt; word_tokenize(sent) ['I', "'m", 'a', 'dog', 'and', 'it', "'s", 'great', '!', 'You', "'re", 'cool', 'and', 'Sandy', "'s", 'book', 'is', 'big', '.', 'Do', "n't", 'tell', 'her', ',', 'you', "'ll", 'regret', 'it', '!', "'Hey", "'", ',', 'she', "'ll", 'say', '!'] &gt;&gt;&gt; wordpunct_tokenize(sent) ['I', "'", 'm', 'a', 'dog', 'and', 'it', "'", 's', 'great', '!', 'You', "'", 're', 'cool', 'and', 'Sandy', "'", 's', 'book', 'is', 'big', '.', 'Don', "'", 't', 'tell', 'her', ',', 'you', "'", 'll', 'regret', 'it', '!', "'", 'Hey', "',", 'she', "'", 'll', 'say', '!'] As we can see, wordpunct_tokenize will split pretty much at all special symbols and treat them as separate units. word_tokenize on the other hand keeps things like 're together. It doesn't seem to be all that smart though, since as we can see it fails to separate the initial single quote from 'Hey'. Interestingly, if we write the sentence like this instead (single quotes as string delimiter and double quotes around "Hey"): sent = 'I\'m a dog and it\'s great! You\'re cool and Sandy\'s book is big. Don\'t tell her, you\'ll regret it! "Hey", she\'ll say!' we get &gt;&gt;&gt; word_tokenize(sent) ['I', "'m", 'a', 'dog', 'and', 'it', "'s", 'great', '!', 'You', "'re", 'cool', 'and', 'Sandy', "'s", 'book', 'is', 'big', '.', 'Do', "n't", 'tell', 'her', ',', 'you', "'ll", 'regret', 'it', '!', '``', 'Hey', "''", ',', 'she', "'ll", 'say', '!'] so word_tokenize does …

djongo
tag name: djongo
tags question: http://stackoverflow.com/q/50333569
type: Tag

http://stackoverflow.com/q/50380630
accepted answer: http://stackoverflow.com/a/50380948
has answer: http://stackoverflow.com/a/50380948
has title: How to use admin Form in a custom page Django
tagged with: python
tagged with: django-forms
type: Question
tagged with: python-3.x
tagged with: django-templates
upvote count: 3
answer count: 1
tagged with: django
has body: I'm trying to use the same form for date and time used in admin page but in a custom page. I've created a form class like this: from django import forms from django.contrib.admin import widgets as adminWidget class RequestData(forms.Form): data = forms.DateField(widget=adminWidget.AdminDateWidget()) When I show this form in a template it doesn't look like in the admin page
has comment: http://stackoverflow.com/comment/87777979
favorite count: 0
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/comment/87657106
comment on: http://stackoverflow.com/a/50318387
type: Comment
has text: You can run `export CC=gcc-5 && sudo python3 setup.py install` . ( I just showed the possible options.) ... And you can run the original commands "!easy_install greenlet" and "!easy_install gevent", when `tsne` is present as installed OK, I guess. Or better : use `pip3` for { greenlet, gevent }.
type: AnswerComment
score: 1

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/50258775
tags question: http://stackoverflow.com/q/50289484
tags question: http://stackoverflow.com/q/50368044
tags question: http://stackoverflow.com/q/50307985
tags question: http://stackoverflow.com/q/50243393
tags question: http://stackoverflow.com/q/50270844
tags question: http://stackoverflow.com/q/50330601
tags question: http://stackoverflow.com/q/50255346
tags question: http://stackoverflow.com/q/50259785
tags question: http://stackoverflow.com/q/50258021
tags question: http://stackoverflow.com/q/50339895
tags question: http://stackoverflow.com/q/50296720
tags question: http://stackoverflow.com/q/50280144
type: Tag
tags question: http://stackoverflow.com/q/50346402
tags question: http://stackoverflow.com/q/50257458
tags question: http://stackoverflow.com/q/50372479
tags question: http://stackoverflow.com/q/50295889

http://stackoverflow.com/a/50580799
score: 0
has body: Remove the gevent and try installing gevent == 1.2.2.This might address the issue.
answers question: http://stackoverflow.com/q/50368744
type: Answer

http://stackoverflow.com/comment/87603845
has text: self.sale_sgid_in_test = ''.join(i) is used in one method which is then used in other methods and the main function too. I want to eliminate the loop. The code works but I think this is not the right way to do this
type: Comment
comment on: http://stackoverflow.com/q/50293645
type: QuestionComment
score: 0

http://stackoverflow.com/q/50242564
has answer: http://stackoverflow.com/a/50242736
score: 0
answer count: 2
tagged with: loops
has body: My question may be a basic one, but I haven't found any answers. My goal is to write a program that parses new entries in a text file and outputs them whenever the line has greater than 5 chars. Consider the following code which works as intended: from pygtail import Pygtail def parse(input): for line in input: if len(line) &gt; 5: print(line) def main(): tail = Pygtail('D:\\test.txt') while True: parse(tail) main() However if I want the parse function to return a value and the main function to print what's returned, I get None over and over again in the output. Bad code: from pygtail import Pygtail def parse(input): for line in input: if len(line) &gt; 5: return line def main(): tail = Pygtail('D:\\test.txt') while True: x = parse(tail) print(x) main() I understand that None is the default return value, but what I don't get is that when I try and save a longer line in the file, it doesn't seem to matter and will always keep printing out None. Could it somehow be messing up the file's offset? It seems to me that both versions of the code should behave the same way but they don't. Could anyone shed some light on why this is?
has comment: http://stackoverflow.com/comment/87503058
tagged with: parsing
type: Question
has title: Python: Print results of a parsing function in the function itself, or have the function return the result and print it an external calling function?
tagged with: return
has answer: http://stackoverflow.com/a/50242610
has comment: http://stackoverflow.com/comment/87504512
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/87509114
comment on: http://stackoverflow.com/a/50245304
score: 0
type: Comment
has text: I had to change the html, but I made sure that my data variable would have the same value as yours and is a string variable--- `var playersData = JSON.parse('\x5B\x7B\x22id\...`
type: AnswerComment

http://stackoverflow.com/q/50319617
answer count: 4
score: 14
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53815323
has answer: http://stackoverflow.com/a/50319782
downvote count: 1
tagged with: image-processing
has answer: http://stackoverflow.com/a/53815323
has body: I am trying to convert an image from BGR to grayscale format using this code: img = cv2.imread('path//to//image//file') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) This seems to be working fine: I checked the data type of the img variable which turns out to be numpy ndarray and shape to be (100,80,3). However if I give an image of a native numpy ndarray data type with same dimensions of the input of the cvtColor function, it gives me the following error: Error: Assertion failed (depth == 0 || depth == 2 || depth == 5) in cv::cvtColor, file D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp, line 11109 cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\imgproc\src\color.cpp:11109: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cv::cvtColor The code for the second case is (making a custom np.ndarray over here): img = np.full((100,80,3), 12) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) Can anyone clarify what is the reason for this error and how to rectify it?
has title: Error in OpenCV color conversion from BGR to grayscale
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58969896
tagged with: opencv
has answer: http://stackoverflow.com/a/50319797
accepted answer: http://stackoverflow.com/a/50319797
tagged with: python
upvote count: 15

http://stackoverflow.com/a/50317998
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/96905569
has body: You should select Conda environment in Pycharm, not create a new, blank Virtualenv Or at the very least - System interpreter, then find the Python executable for Anaconda What is venv folder under "pycharmprejcts"? Is it a virtual environment? Yes, it allows your project to be more portable - you define the minimum set of dependencies for your code rather than rely on everything installed only locally on your machine
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50317974

aes
tag name: aes
type: Tag
tags question: http://stackoverflow.com/q/50319454

http://stackoverflow.com/comment/87562566
has text: Thanks a lot @Jacobr
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50257542

http://stackoverflow.com/a/50303773
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50276329
type: Answer
answers question: http://stackoverflow.com/q/50276329
has body: A couple errors: self.b should have size self.b is size (10, ) not (128, 10) (as bias is per-unit, not per-unit-pair). self.W_grad should be np.dot(self.X.T, (dz * dy)), not np.dot(self.X.T, dy). Same for self.b_grad - it should be np.sum(dz * dy, axis=0) As for the rest dy := dL/dy should be (N, 10), as it contains the gradient of the loss with respect to each element in y. dz := df(z)/d(z) should be (N, 10) for an elementwise activation function, since dz[i] contains df(z[i])/dz[i]. self.d := dL/dX should be (N, 128) because it contains the gradient of the loss with respect to each element in X.
upvote count: 1

http://stackoverflow.com/q/50301879
downvote count: 0
has body: I have been trying to implement a CNN that, given a (75x75) image of a detector, will output the (x,y) coordinate of the source for that image. Each image has features that make it possible to determine the source. The issue I am coming up with is that the regressor, which outputs the x, y coordinate, always returns the mean pixel value for all the training data. I've tried to implement the regressor outlined in this paper: https://arxiv.org/abs/1803.10698 but it still gives the mean pixel value as all the predictions. A short version of my model is here: model = Sequential() # Base Conv layer model.add(Conv2D(32, kernel_size=patch_size, strides=(1, 1), activation='relu', padding='same', input_shape=(75, 75, 1))) model.add(Conv2D(64, patch_size, strides=(1, 1), activation='relu', padding=optimizer)) model.add(MaxPooling2D(pool_size=(2, 2), padding='same')) for i in range(num_conv): model.add(Conv2D(64, patch_size, strides=(1, 1), activation='relu', padding='same)) model.add(Conv2D(64, patch_size, strides=(1, 1), activation='relu', padding='same)) model.add(MaxPooling2D(pool_size=(2, 2), padding='same')) model.add(Flatten()) for i in range(num_dense): model.add(Dense(512, activation='linear')) model.add(Dropout(dropout_layer)) # Final Dense layer # 2 so have one for x and one for y model.add(Dense(2, activation='linear')) model.compile(optimizer='adam', loss='mse', metrics=['mae']) I don't have the rep to post images of the sources, but here is truth and outputs when it is trained on 42000 images: As you can see, its horribly off, all the estimations are in that one dot at the mean value of all the x,y coordinates. while the actual values create a circle covering the whole detector. I am not sure how to get it to actually output correct values. I get that the mean squared error as the loss probably should make the estimation the center value, as it is the minimum squared distance from all the sources, but I am not sure how else to try it, since I want to minimize the…
tagged with: keras
tagged with: tensorflow
score: 2
tagged with: python
tagged with: image-processing
favorite count: 0
type: Question
has title: Keras CNN Coordinate Regression Only Gives Mean Value
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: regression

openexr
tags question: http://stackoverflow.com/q/50324495
tag name: openexr
type: Tag

http://stackoverflow.com/q/50309412
tagged with: discord
has title: message.content to json file python discord bot
type: Question
tagged with: message
tagged with: python
has body: I have a json file that stores power to people, I'm trying to make a command to give the power directly without needing to edit the json file: if message.content.lower().startswith('addpower'): text_in = message.content text_out = text_in[text_in.find("(") + 1:text_in.find(")")] for user in message.mentions:] try: user_add_power(user.id, int(text_out)) await Bot.send_message(message.channel, "add {} power to {}".format(text_out, user.name)) except: None the user_add_power it's a part of another command that give power to everyone that type in my server. According to my command, to give power to people, I need to type "addpower @username (100)" to give 100 power to the @username person. I'm having trouble with this: text_out = text_in[text_in.find("(") + 1:text_in.find(")")]. I would like to remove the () and just need to type "addpower @username 100" to give 100 power to the @username person. How can I do this?
type: AnsweredQuestion
score: 0
tagged with: bots
accepted answer: http://stackoverflow.com/a/50309701
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has answer: http://stackoverflow.com/a/50309701

http://stackoverflow.com/q/50338865
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87703482
score: 1
has answer: http://stackoverflow.com/a/50338983
accepted answer: http://stackoverflow.com/a/50338983
tagged with: python
has title: Keras LSTM XOR gate
tagged with: lstm
has body: I was learning about Keras for a project, for trial I try to make a simple machine learning using LSTM (what I will use for the project) for simple XOR gate prediction. But, even though I change number of neuron, layer, loss function, epoch, or optimizer I can't get the correct prediction. Is there something I miss about Keras or this code? import numpy as np from keras.models import Sequential from keras.layers import Dense, LSTM data = [[[0, 0]], [[0, 1]], [[1, 0]], [[1, 1]]] output = [[1, 0], [0, 1], [0, 1], [1,0]] model = Sequential() model.add(LSTM(10, input_shape=(1, 2), return_sequences=True)) model.add(LSTM(10)) model.add(Dense(2)) model.compile(loss='mae', optimizer='adam') # print(model.summary()) model.fit(np.asarray(data), np.asarray(output), epochs=50) print(model.predict_classes(np.asarray(data)))
type: AnsweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/comment/87680070
type: QuestionComment
comment on: http://stackoverflow.com/q/50331920
has text: what your `del` statement supposed to do? `Python` has gc
score: 1
type: Comment

http://stackoverflow.com/q/50323770
downvote count: 2
has body: I am writing program for calculating prediction using randomforest classifier algorithm of machine learning in python, and I am getting prediction in values. I want prediction percentage or prediction probablity in percentage. Can you help me on it?
duplicate of: http://stackoverflow.com/q/30814231
has comment: http://stackoverflow.com/comment/87663578
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/87663554
favorite count: 0
has title: How can I calculate probablity of prediction in random forest classifier?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50323870
tagged with: random-forest
has comment: http://stackoverflow.com/comment/87663361
tagged with: python
linked to: http://stackoverflow.com/q/30814231
upvote count: 2
score: 0

http://stackoverflow.com/comment/87601707
comment on: http://stackoverflow.com/q/50292631
type: Comment
type: QuestionComment
has text: A viewport's resolution is not enough information for ray casting. You must be able to construct a viewport matrix.
score: 0

http://stackoverflow.com/q/50268298
has answer: http://stackoverflow.com/a/50268376
has answer: http://stackoverflow.com/a/50268667
has title: Append String to each line of .txt file in python?
tagged with: python
score: 4
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/87554359
tagged with: readline
answer count: 4
has comment: http://stackoverflow.com/comment/87554231
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87556241
downvote count: 0
linked to: http://stackoverflow.com/q/3277503
possible better answer: http://stackoverflow.com/a/50268395
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50268376
has answer: http://stackoverflow.com/a/50268395
has answer: http://stackoverflow.com/a/50268534
has body: I want to append some text to every line in my file Here is my code filepath = 'hole.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: #.......... #want to append text "#" in every line by reading line by line text from .txt file line = fp.readline() cnt += 1

http://stackoverflow.com/comment/87513527
comment on: http://stackoverflow.com/a/50247608
type: AnswerComment
has text: I thought round was the default method of python. Do I need a definition for round?
score: 0
type: Comment

http://stackoverflow.com/q/50297355
tagged with: python
accepted answer: http://stackoverflow.com/a/50297467
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
tagged with: dataframe
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50297467
has title: Count occurrences of items in 2 data frames and then checking to compare 2 dates
has body: I am currently trying to take 2 data frames, see if there are occurrences of 2 columns in one, and then compare and see if those happened on the same day so an example of the data would be: df1: user Last_used user1 10-7-2017 user2 10-20-2018 user3 1-12-2015 df2: user occurence user1 10-7-2017 user1 10-7-2017 user2 10-10-2017 user2 10-20-2018 user3 1-12-2015 user3 09-14-2016 My results would then be: df1 user Last_used occurrences_that_day user1 10-7-2017 2 user2 10-20-2018 1 user3 1-12-2015 1 I know that i can use map do do this with 1 of the values, but if i try to map last used and occurrence and there are multiples on this date it will show even when the user id is differet One thing I should also should note is that my dataframes both have rows of over 150k.

http://stackoverflow.com/comment/87630377
type: QuestionComment
comment on: http://stackoverflow.com/q/50306145
has text: Yes, you are right, my bad. The totally correct form would be `{img_str.size*img_str.dtype.itemsize*8}` but in this case we can probably assume that it's one byte per item.
score: 0
type: Comment

http://stackoverflow.com/comment/87858995
score: 0
type: AnswerComment
has text: @JeruLuke yeah... you got my point but now what is need to be corrected? Is there any solution on it? Because I am trying to make canvas using Tkinter and displaying image on it.
comment on: http://stackoverflow.com/a/50344336
type: Comment

http://stackoverflow.com/comment/87739816
comment on: http://stackoverflow.com/a/50361307
score: 1
has text: should it not be `for report in user_reports: banned_user.report_reason.add(request.user.profile.user_reported_report.all())`
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50348192
score: 1
type: Question
has comment: http://stackoverflow.com/comment/87714550
has answer: http://stackoverflow.com/a/58814160
tagged with: apache-spark-sql
upvote count: 1
type: UnansweredQuestion
tagged with: bigdata
tagged with: pyspark
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/87865999
tagged with: python
has title: Error when using pyspark load to read data
has body: I am trying to load a file using Pyspark as below from pyspark.sql import SparkSession spark = SparkSession.builder.appName('mylogreg').getOrCreate() from pyspark.ml.classification import LogisticRegression my_data = spark.read.format('libsvm').load('cars.csv') but it keeps giving me the following error: Py4JJavaError: An error occurred while calling o231.load. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 6.0 failed 1 times, most recent failure: Lost task 0.0 in stage 6.0 (TID 6, localhost, executor driver): java.lang.NumberFormatException: For input string: "YEAR,Make,Model,Size,(kW),Unnamed:" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.lang.Double.parseDouble(Double.java:538) at scala.collection.immutable.StringLike$class.toDouble(StringLike.scala:284) at scala.collection.immutable.StringOps.toDouble(StringOps.scala:29) at org.apache.spark.mllib.util.MLUtils$.parseLibSVMRecord(MLUtils.scala:128) at org.apache.spark.mllib.util.MLUtils$$anonfun$parseLibSVMFile$4.apply(MLUtils.scala:123) at org.apache.spark.mllib.util.MLUtils$$anonfun$parseLibSVMFile$4.apply(MLUtils.scala:123) at scala.collection.Iterator$$anon$11.next(Iterator.scala:409) at scala.collection.Iterator$$anon$11.next(Iterator.scala:409) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.TraversableOnce$class.reduceLeft(TraversableOnce.scala:185) at scala.collection.AbstractIterator.reduceLeft(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$reduce$1$$anonfun$14.apply(RDD.scala:1015) at org.apache.spark.rdd.RDD$$anonfun$reduce$1$$anonfun$14.apply(RDD.scala:1013) at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:2123) at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:2123) at org.apache.spark.scheduler.ResultTask.runT…
favorite count: 0

http://stackoverflow.com/comment/87741851
type: Comment
comment on: http://stackoverflow.com/a/50362671
type: AnswerComment
has text: @SpghttCd I would encourage OP to evaluate, or at least I would hope they do.
score: 1

http://stackoverflow.com/q/50260231
has comment: http://stackoverflow.com/comment/87545560
has comment: http://stackoverflow.com/comment/87545270
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50263791
score: 0
has comment: http://stackoverflow.com/comment/87545405
has title: Folium Polylines connects the plots with Python
tagged with: leaflet
has comment: http://stackoverflow.com/comment/87545462
has comment: http://stackoverflow.com/comment/87541283
has answer: http://stackoverflow.com/a/50263791
has comment: http://stackoverflow.com/comment/87545518
has body: I am working on the Folium Map Python Library, and Its connects the two different points together (PolyLine), is there any best example with folium which doesn't connect lines on map or I can color them with unique ids, I was trying some JSON thing with my Data, but that didn't work with my code, still it connects all the different lines as mentioned in below picture? can any one suggest any best solution, which doesn't connect these lines, but I have to still use the folium. lat = filteredData.lat lon = filteredData.lon data = { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'LineString', 'coordinates': [[lon, lat] for (lat, lon) in zip(lat, lon)], }, 'properties': {'fillcolor': 'black'} }, ], } m = folium.Map(location=[36.862317, -76.3151], zoom_start=6) m.add_child(folium.features.GeoJson(data)) m this is the reference link I am using s.
tagged with: folium
downvote count: 1
has comment: http://stackoverflow.com/comment/87545484
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87545231
answer count: 1
has comment: http://stackoverflow.com/comment/87545434
upvote count: 1
tagged with: python

http://stackoverflow.com/a/50378945
score: 0
type: Answer
has body: Okey, @bastibe the owner of the Soundfile repository on Github has answered this question for me in a precise and clear way. Here is the link for the thread: https://github.com/bastibe/SoundFile/issues/226
answers question: http://stackoverflow.com/q/50294664

http://stackoverflow.com/q/50262750
type: AnsweredQuestion
tagged with: systemd
score: 0
tagged with: exception
has title: "Crash-proofing" script vs.using systemd to guarantee near-constant operation
accepted answer: http://stackoverflow.com/a/50263853
answer count: 1
has answer: http://stackoverflow.com/a/50263853
has body: Perhaps this is a broad question, but I haven't found an answer elsewhere, so here goes. The Python script I'm writing needs to run constantly (in a perfect world, I recognize this may not be exactly possible) on a deployed device. I've already dedicated time to adding "try...except" statements throughout so that, should an issue arise, the script will recover and continue to work. The issue is that I'm not sure I can (nor should) handle every single possible exception that may be thrown. As such, I've decided it may be better to allow the script to die and to use systemd to restart it. The three options: Making no attempt to handle any exception, and just allowing systemd to restart it whenever it dies. Meticulously creating handlers for every possible exception to guarantee that, short of loss of power, interpreter bug, or heat death of the universe, the script will always run. A mix of the two -- making an effort to prevent crashes in some cases while allowing them in others and letting systemd restart the script. The third choice seems the most reasonable to me. So the question is this: What factors should be considered when optimizing between "crash-proof" code and allowing a crash and restart by systemd? For some more application specific information: there is a small but noticeable overhead involved with starting the script, the main portion will run between 50 to 100 times per second, it is not "mission critical" in that there will be no death/damage in the event of failure (just some data loss), and I already expect intermittent issues with the network it will be on.
favorite count: 0
type: Question
tagged with: crash
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/a/50254160
has comment: http://stackoverflow.com/comment/87527576
has comment: http://stackoverflow.com/comment/87525845
has comment: http://stackoverflow.com/comment/87527925
type: AcceptedAnswer
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/87527732
accepted answer of: http://stackoverflow.com/q/50253985
has comment: http://stackoverflow.com/comment/87527229
has body: Use stack + pandas.Series.str.get_dummies df.assign( D=df.stack().str.get_dummies(';').sum(level=0).gt(1).any(1).astype(int) ) A B C D 0 mom;dad;son; sister;son; yes;no;maybe; 1 1 dad; daughter;niece; no;snow; 0 2 son;dad; cat;son;dad; tree;dad;son; 1 3 daughter;mom; niece; referee; 0 4 dad;daughter; cat; dad; 1 Details Notice that when we stack and get dummies, the interim result looks like this: cat dad daughter maybe mom niece no referee sister snow son tree yes 0 A 0 1 0 0 1 0 0 0 0 0 1 0 0 B 0 0 0 0 0 0 0 0 1 0 1 0 0 C 0 0 0 1 0 0 1 0 0 0 0 0 1 1 A 0 1 0 0 0 0 0 0 0 0 0 0 0 B 0 0 1 0 0 1 0 0 0 0 0 0 0 C 0 0 0 0 0 0 1 0 0 1 0 0 0 2 A 0 1 0 0 0 0 0 0 0 0 1 0 0 B 1 1 0 0 0 0 0 0 0 0 1 0 0 C 0 1 0 0 0 0 0 0 0 0 1 1 0 3 A 0 0 1 0 1 0 0 0 0 0 0 0 0 B 0 0 0 0 0 1 0 0 0 0 0 0 0 C 0 0 0 0 0 0 0 1 0 0 0 0 0 4 A 0 1 1 0 0 0 0 0 0 0 0 0 0 B 1 0 0 0 0 0 0 0 0 0 0 0 0 C 0 1 0 0 0 0 0 0 0 0 0 0 0 Where the prior columns are embedded in the second level of the index. So I want to sum over the first level in order to see how many times that word appears. That summation interim looks like: cat dad daughter maybe mom niece no referee sister snow son tree yes 0 0 1 0 1 1 0 1 0 1 0 2 0 1 1 0 1 1 0 0 1 1 0 0 1 0 0 0 2 1 3 0 0 0 0 0 0 0 0 3 1 0 3 0 0 1 0 1 1 0 1 0 0 0 0 0 4 1 2 1 0 0 0 0 0 0 0 0 0 0 Notice that we catch 'son' in row 1, 'dad' and 'son' in row 3 and so on. If it appears in more than 1 column (hence gt(1)) then I want to count it as a 1 (hence any(1).astype(int)).
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87525739
answers question: http://stackoverflow.com/q/50253985

http://stackoverflow.com/a/50356484
downvote count: 1
has comment: http://stackoverflow.com/comment/87803806
answers question: http://stackoverflow.com/q/50350456
type: Answer
score: 1
has body: Your code is readable, does the job and is reasonably efficient. There's no need to change much! You could use more descriptive variable names and replace l1 with a set for faster lookup: keys = ('a', 'c', 'b', 'e', 'f', 'd') keys_and_values = [ 'x','q','we','da','po', 'a', 'el1', 'el2', 'el3', 'el4', 'b', 'some_other_el_1', 'some_other_el_2', 'c', 'another_element_1', 'another_element_2', 'd', '', '', 'another_element_3', 'd4' ] current_key = None result = {} for x in keys_and_values: if x in keys: current_key = x result[current_key] = [] elif current_key: result[current_key].append(x) print(result) # {'a': ['el1', 'el2', 'el3', 'el4'], # 'c': ['another_element_1', 'another_element_2'], # 'b': ['some_other_el_1', 'some_other_el_2'], # 'd': ['', '', 'another_element_3', 'd4']}
upvote count: 2

http://stackoverflow.com/a/50280238
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50280199
answers question: http://stackoverflow.com/q/50280199
has body: You need to set ensure_ascii=False when calling json.dumps(). For example, mydict_str = json.dumps(mydict, ensure_ascii=False)

http://stackoverflow.com/q/50319439
favorite count: 0
type: Question
has title: Most pythonic style for function calls with multiple params
type: UnansweredQuestion
upvote count: 0
score: -2
downvote count: 2
has body: Which is more Pythonic: Style one: self.partitions.append( Partition( self.current.bottom, self.current.lower, boundary)) Style two: self.partitions.append(Partition(self.current.upper, self.current.top, boundary))
answer count: 1
has answer: http://stackoverflow.com/a/50319459
tagged with: python

http://stackoverflow.com/comment/87905202
type: Comment
comment on: http://stackoverflow.com/a/50378386
has text: Thanks. Yeah, I am thinking to use ir.cron model for calling my method which will counting new value of field b. Then compare it with old field b value and the difference write into dictionary.
type: AnswerComment
score: 1

http://stackoverflow.com/q/50317948
has comment: http://stackoverflow.com/comment/87652730
tagged with: python
has title: Multiple versions of python and tkinter module
score: 2
has comment: http://stackoverflow.com/comment/87652335
has comment: http://stackoverflow.com/comment/87652497
has body: I use 3 versions of python on Linux mint 18.3 silvock@silvock-TM1701 ~ $ python -V Python 2.7.12 silvock@silvock-TM1701 ~ $ python3 -V Python 3.5.2 silvock@silvock-TM1701 ~ $ python3.6 -V Python 3.6.5 I'm able to import Tkinter with python2.7 and tkinter python3.6... silvock@silvock-TM1701 ~ $ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import Tkinter &gt;&gt;&gt; silvock@silvock-TM1701 ~ $ python3.6 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. &gt;&gt;&gt; import tkinter &gt;&gt;&gt; ... but with python3 (python 3.5) it doesn't work. silvock@silvock-TM1701 ~ $ python3 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; import tkinter Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in &lt;module&gt; import _tkinter ImportError: No module named '_tkinter' 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 "/usr/lib/python3.5/tkinter/__init__.py", line 38, in &lt;module&gt; raise ImportError(str(msg) + ', please install the python3-tk package') ImportError: No module named '_tkinter', please install the python3-tk package &gt;&gt;&gt; quit() whereas python3-tk is already installed : silvock@silvock-TM1701 ~ $ sudo apt-get install python3-tk Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait python3-tk est déjà la version la plus récente (3.6.5-3~16.04.york0.2). 0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour. I would like to tkinter work with python3.5. I try in vain silvock@silvock-TM1701 ~ $ sudo apt-get …
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87653544
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/87673480
upvote count: 2
has comment: http://stackoverflow.com/comment/87652054
has comment: http://stackoverflow.com/comment/87654226
type: UnansweredQuestion

http://stackoverflow.com/comment/118819670
has text: I'd use `-1 * idx` instead of calls to `abs()`
comment on: http://stackoverflow.com/a/57067313
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/50368355
has body: Since for commenting the code would be too complicated and it is based on juanpa.arrivillaga's answer, I'll add a full post with a short explanation what I mean by updating the reference to the arrays: def fun1(*, x, y): # easy minimal example function 1 print(x * y) arr = np.random.rand(5) f1_lam = lambda:fun1(x=arr, y=5.) f1_par = partial(fun1, x=arr, y=5.) f1_lam() # Out[01]: [0.55561103 0.9962626 3.60992174 2.55491852 3.9402079 ] f1_par() # Out[02]: [0.55561103 0.9962626 3.60992174 2.55491852 3.9402079 ] # manipulate array so that the memory address changes and # passing as reference is "complicated": arr = np.append(arr, np.ones((2,1))) f1_lam() # Out[03]: [0.55561103 0.9962626 3.60992174 2.55491852 3.9402079 5. 5.] f1_par() # Out[02]: [0.55561103 0.9962626 3.60992174 2.55491852 3.9402079 ] The behaviour of lambda is exactly what I was looking for in this question. My examples with dict and decorators don't work, as well as functools.partial. Any idea why lambda is working? And just out of interest: Would there be any way to update the references to the arrays in the dict so that it would also work this way?
type: Answer
has comment: http://stackoverflow.com/comment/87958989
has comment: http://stackoverflow.com/comment/87767578
score: 0
has comment: http://stackoverflow.com/comment/87958865
answers question: http://stackoverflow.com/q/50366851
has comment: http://stackoverflow.com/comment/87767512

http://stackoverflow.com/comment/87726080
score: 0
type: Comment
has text: Tacking on my .02 here, implicit waits in selenium have saved me before.
comment on: http://stackoverflow.com/a/50354827
type: AnswerComment

http://stackoverflow.com/comment/87566313
has text: Please provide the complete error message
score: 0
comment on: http://stackoverflow.com/q/50274830
type: QuestionComment
type: Comment

for-loop
tags question: http://stackoverflow.com/q/50333247
tags question: http://stackoverflow.com/q/50291216
tags question: http://stackoverflow.com/q/50288459
tags question: http://stackoverflow.com/q/50337415
tags question: http://stackoverflow.com/q/50334125
tags question: http://stackoverflow.com/q/50378610
tags question: http://stackoverflow.com/q/50318951
tags question: http://stackoverflow.com/q/50314541
tags question: http://stackoverflow.com/q/50341008
tags question: http://stackoverflow.com/q/50332342
tags question: http://stackoverflow.com/q/50356839
tags question: http://stackoverflow.com/q/50325598
tags question: http://stackoverflow.com/q/50302238
tags question: http://stackoverflow.com/q/50340232
tags question: http://stackoverflow.com/q/50323005
tags question: http://stackoverflow.com/q/50350944
tags question: http://stackoverflow.com/q/50237664
tags question: http://stackoverflow.com/q/50265969
tags question: http://stackoverflow.com/q/50283458
type: Tag
tags question: http://stackoverflow.com/q/50363797
tags question: http://stackoverflow.com/q/50313185
tags question: http://stackoverflow.com/q/50306898
tags question: http://stackoverflow.com/q/50313310
tags question: http://stackoverflow.com/q/50231400
tags question: http://stackoverflow.com/q/50255903
tag name: for-loop
tags question: http://stackoverflow.com/q/50304272
tags question: http://stackoverflow.com/q/50298022
tags question: http://stackoverflow.com/q/50270232
tags question: http://stackoverflow.com/q/50248548
tags question: http://stackoverflow.com/q/50353277
tags question: http://stackoverflow.com/q/50309338
tags question: http://stackoverflow.com/q/50336690
tags question: http://stackoverflow.com/q/50235071
tags question: http://stackoverflow.com/q/50379319
tags question: http://stackoverflow.com/q/50307812
tags question: http://stackoverflow.com/q/50317825
tags question: http://stackoverflow.com/q/50320803

http://stackoverflow.com/q/50306012
tagged with: patch
favorite count: 0
type: Question
tagged with: matplotlib
has title: Get coordinates of the rotated patch (rectangle) matplotlib
tagged with: python
has body: I want to achieve the following: 1) get coordinates of the rotated patch 2) get all points of the patch (here: rectangle) ** I have an impression that the rotated rectangle does not have 90 degree between faces. Is that just visualization? My snippet below. The coordinates of the rotated patch are the same as of the original though .. How to achieve 1) and 2) ? import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib as mpl from matplotlib.transforms import Affine2D fig = plt.figure() ax = fig.add_subplot(111) angle = np.deg2rad(45) r1 = patches.Rectangle((8,4), 5,3, fill=False, color="red", alpha=0.50) r2 = patches.Rectangle((8,4), 5,3, fill=False, color="blue", alpha=0.50) trafo = mpl.transforms.Affine2D().rotate_around(8,4,angle) + ax.transData r2.set_transform(trafo) ax.add_patch(r1) ax.add_patch(r2) plt.xlim(0,15) plt.ylim(0,15) plt.grid(False) plt.show() print(r1.get_bbox()) print(r1.get_xy()) print(r2.get_bbox()) # why are they the same as for r1? print(r2.get_xy()) #print(r1.get_all_points()) # how to achieve it?
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50315897
accepted answer: http://stackoverflow.com/a/50315897
has comment: http://stackoverflow.com/comment/87649301
answer count: 1

http://stackoverflow.com/comment/87687871
comment on: http://stackoverflow.com/q/50335857
score: 1
type: QuestionComment
type: Comment
has text: Can you show the code you have tried? As well as a sample input and expected output?

http://stackoverflow.com/comment/87615150
type: Comment
score: 0
type: QuestionComment
has text: I can add a 300 second timeout, but then my except will just loop back to the try and keep timing out without information.
comment on: http://stackoverflow.com/q/50298042

http://stackoverflow.com/comment/87776572
type: Comment
type: QuestionComment
has text: Maybe try through polar coordinates use radians though. X = radius * cos(angle). y = radius * sin(angle). Setup up loop for angle. An adjust resolution of circle by changing step of the angle.
score: 0
comment on: http://stackoverflow.com/q/50380137

http://stackoverflow.com/q/50359216
tagged with: python
accepted answer: http://stackoverflow.com/a/50360140
has title: Python sympy equations to matrix
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50360140
has body: I am trying to convert 4 equations into matrix form with the following, but the 4th row in the output is incorrect. Any help would be appreciated: from sympy import linear_eq_to_matrix, symbols, simplify, sin, cos, Eq, pprint A, B, C, D, z, L, k = symbols('A, B, C, D, z, L, k') fnc = A + B*z + C*sin(k*z) + D*cos(k*z) bc1 = Eq(0, fnc.subs(z,0)) bc2 = Eq(0, fnc.subs(z,L)) bc3 = Eq(0, fnc.diff(z,2).subs(z,0)) bc4 = Eq(0, fnc.diff(z,2).subs(z,L)) a, b = linear_eq_to_matrix([bc1, bc2, bc3, bc4], [A, B, C, D]) pprint(bc1) pprint(bc2) pprint(bc3) pprint(bc4) pprint(a) I get the following output: Expected output:
tagged with: sympy
has comment: http://stackoverflow.com/comment/87736614
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/a/50341422
answers question: http://stackoverflow.com/q/50341353
has comment: http://stackoverflow.com/comment/87698986
type: Answer
accepted answer of: http://stackoverflow.com/q/50341353
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: When you say you "terminate" sub.py, does this mean you press Ctrl+C on it? On windows, this actually sends CTRL_C_EVENT to the process, unlike terminate() method which calls TerminateProcess WinAPI method. Looks like you need to import signal and then do proc.send_signal(signal.CTRL_C_EVENT) instead of proc.terminate()

http://stackoverflow.com/comment/136102706
has text: I doubt you tested this code…
comment on: http://stackoverflow.com/a/67880268
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50246124
answers question: http://stackoverflow.com/q/50245888
accepted answer of: http://stackoverflow.com/q/50245888
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: In [1]: x = np.arange(24).reshape(2,3,4) In [2]: idx = np.where(x%2) In [3]: idx Out[3]: (array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=int32), array([0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2], dtype=int32), array([1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3], dtype=int32)) In [4]: x[idx] Out[4]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]) In [5]: idx1 = np.transpose(np.transpose(idx)) In [6]: idx1 Out[6]: array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2], [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3]], dtype=int32) the wrong way to use idx1: In [7]: x[idx1] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-7-ffe1818b2257&gt; in &lt;module&gt;() ----&gt; 1 x[idx1] IndexError: index 2 is out of bounds for axis 0 with size 2 The right way: In [8]: x[tuple(idx1)] Out[8]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]) Test this with a where taken on a slice of x (I don't like assuming code works): In [22]: idx = np.where(x[:,:,2]%3) In [23]: idx Out[23]: (array([0, 0, 1, 1], dtype=int32), array([0, 2, 0, 2], dtype=int32)) In [24]: idx1 = np.transpose(np.transpose(idx)) In [25]: x[idx] Out[25]: array([[ 0, 1, 2, 3], [ 8, 9, 10, 11], [12, 13, 14, 15], [20, 21, 22, 23]]) In [26]: x[tuple(idx1)] Out[26]: array([[ 0, 1, 2, 3], [ 8, 9, 10, 11], [12, 13, 14, 15], [20, 21, 22, 23]]) Indexing with a n-row array is not the same as indexing with a n-tuple of arrays. The elements of a tuple are applied to successive dimensions. The elements of the array are applied to just one dimension, the first.
type: Answer
has comment: http://stackoverflow.com/comment/87510057

http://stackoverflow.com/comment/92266811
has text: In that case y=x1_norm*x2_norm will not work because say if x1_norm =0 then y=0 and also if x2_norm=0 then also y=0 so we can't get back y. however if we use y=y_norm (that is yi-min(yi) / max - min ) then that may work. But not sure so asked.
comment on: http://stackoverflow.com/a/50320784
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/87650171
comment on: http://stackoverflow.com/q/50317196
has text: Well you should aim to vectorize and not use for-loops. How about you share your dataset here and expected output --> Much easier to help. Nice effort though!
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87491778
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50237058
score: 0
has text: Granted, the 500 didn't show up in the code of the question, either.

http://stackoverflow.com/q/50368416
has comment: http://stackoverflow.com/comment/87756206
accepted answer: http://stackoverflow.com/a/50368802
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87753539
downvote count: 0
has comment: http://stackoverflow.com/comment/87753088
upvote count: 1
score: 1
has title: Generating 3-D surface plot with data from different sized grid points in python
tagged with: matplotlib
answer count: 1
has body: I learned to merge mesh grid points from two rectangles in python from this question. The merged grid points are: Here each grid points contains their respective values and I want to plot a 3-D surface plot of it. For the full grid (without blank spot), I'd write the following code: fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') x=np.arange(0,10,1) y=np.arange(0,12,1) X, Y = np.meshgrid(x,y) print (Y) Z = gridValue.reshape(X.shape) cset = ax.pcolormesh(X, Y, Z, cmap=cm.coolwarm, linewidth =0, antialiased = False) ax.clabel(cset, fontsize=9, inline=1) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('σ ') fig.colorbar(cset, shrink=0.5, aspect =5) plt.show() When I try to plot the grid values (80 points) with above code, I get an obvious error: ValueError: cannot reshape array of size 80 into shape (12,10) I'm expecting the following figure (not exactly but similar way) as the final 3-D surface plot: How can I draw a 3-D surface plot is my situation? Thank you. EDIT: I tried to plot using the following code snippet: fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') x1=np.arange(0,2,1) x2 = np.arange(0,10,1) y1 =np.arange(0,5,1) y2=np.arange(5,12,1) Y1, X1 = np.meshgrid(x1,y1) Y2, X2 = np.meshgrid(x2,y2) gridValue1 = gridValue[:10] gridValue2 = gridValue[10:] Z1 = gridValue1.reshape(X1.shape) Z2 = gridValue2.reshape(X2.shape) cset1 = ax.plot_surface(X1, Y1, Z1, cmap=cm.coolwarm, linewidth =0, antialiased = False) cset2 = ax.plot_surface(X2, Y2, Z2, cmap=cm.coolwarm, linewidth =0, antialiased = False) ax.clabel(cset1, fontsize=9, inline=1) ax.clabel(cset2, fontsize=9, inline=1) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('σ ') plt.show() I got following figure with this code: Now the problem is to illustrate the figure. The color code (red color for high value, blue color for low value) is not valid any longer. Because the gridValues of blue gird points (in the first figure) are high, so most of them should have red color in the…
has answer: http://stackoverflow.com/a/50368802
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
linked to: http://stackoverflow.com/q/50330251
tagged with: python

http://stackoverflow.com/comment/87508556
type: QuestionComment
has text: yes the schema is the same
score: 0
comment on: http://stackoverflow.com/q/50245102
type: Comment

http://stackoverflow.com/comment/87633094
score: 0
type: Comment
type: QuestionComment
has text: Is `7 7 5 7` the `bitwise_operation`'s expected output for `[[2,5],[2,5],[5,5],[2,5,5]]`??
comment on: http://stackoverflow.com/q/50308212

http://stackoverflow.com/comment/87650058
has text: Yep, I agree. Thanks for updating. Still closer, but now we have good benchmarks.
comment on: http://stackoverflow.com/a/50316945
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87666081
has text: @PrateekGupta if there is no pattern in the ranges, you will need to evaluate all possibilities. At best, you might want to optimize how you start searching.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50325063
score: 0

http://stackoverflow.com/a/50362204
accepted answer of: http://stackoverflow.com/q/50353176
has body: This process is called finetuning and setting requires_grad to False is a good way to do this. From the pytorch docs: Every Tensor has a flag: requires_grad that allows for fine grained exclusion of subgraphs from gradient computation and can increase efficiency. ... If there’s a single input to an operation that requires gradient, its output will also require gradient. Conversely, only if all inputs don’t require gradient, the output also won’t require it. Backward computation is never performed in the subgraphs, where all Tensors didn’t require gradients. See this pytorch tutorial for a relevant example. One simple way of checking to see this is working is looking at the initial error rates. Assuming the task is similar to the task the net was originally trained on, they should be much lower than for a randomly initialized net.
answers question: http://stackoverflow.com/q/50353176
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/50323809
has comment: http://stackoverflow.com/comment/87664060
tagged with: pandas
tagged with: python
tagged with: regex
favorite count: 0
has answer: http://stackoverflow.com/a/50324431
type: Question
tagged with: google-maps
has body: I have a pandas dataframe: df id Description 1 POS Transfer A&amp;W MONTREAL QC 2 MKLI QC Montreal DOLLARAMA 3 PC - PAYMENT FROM - *****11*22 I am trying to get the address from the description. What I did: provinces=["qc","on"] b=[] for index, row in df.iterrows(): c=0 for i in provinces: if i in row["Description"].lower().split(): a=[row["id"],row["description"]] c=1 break if(c==1): b.append(a) b [[0, 'POS Transfer A&amp;W MONTREAL QC'], [1, ' MKLI QC Montreal DOLLARAMA ']] Here I am capturing the information in an array. Can I directly capture it in an additional pandas column Here, I captured all the description where there is an address. In order to send this to google api, I just want to select the 1 word on left and right of the province. That is in the case of : POS Transfer A&amp;W MONTREAL QC I want to capture: A&amp;W MONTREAL QC In the case of MKLI QC Montreal DOLLARAMA I want to capture QC Montreal DOLLARAMA How do I do this?
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/87664353
tagged with: string
has title: Find longitude and latitude of a column in pandas dataframe
answer count: 1
has comment: http://stackoverflow.com/comment/87663793

http://stackoverflow.com/comment/139771201
score: 0
type: Comment
comment on: http://stackoverflow.com/a/75614375
type: AnswerComment
has text: I noticed this problem in a slurm + modules cluster, typically a module for python sets different path.

http://stackoverflow.com/comment/88084180
has text: Thanks a lot. I thought that Cartopy has some argument like width and height in the basemap function(http://basemaptutorial.readthedocs.io/en/latest/basemap.html) that controls the width and height of the image. I think that it will be nice if Cartopy has similar capabilities. Thanks
comment on: http://stackoverflow.com/a/50394345
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50271647
has title: Twitter API sending me "incomplete" statuses
tagged with: python
tagged with: twitter
type: UnansweredQuestion
tagged with: tweepy
has body: Hey everyone ! I have weird problem with the Twitter API(I am using Tweepy), when i use statuses = api.search('pokemon') and then try to print everything with for status in statuses: if not status.truncated: print(status.text) print('\n----------------------') it sometimes prints weird incomplete statuses with '…' character at the end. And as you can see, they aren't truncated if they get to be printed Examples: RT @CodeNamePizza: Open my first pack ever of the new Forbidden Light Pokemon Set and get the Energy Recycler Secret Rare https://t.co… RT @michaelsenbay: Pokemon GOをやる私「ピカチュウ捕まえた」 我が子「ママ、そのピカチュウにもパパとママがいるよ」 私「お……おう」 我が子「今頃、ピカチュウのパパとママは、そのピカチュウを探しているよ」 私「お……う」 我が子「だから、ライチュウに… An other interesting fact: Every status with that '…' is 140 chars long Hoping you can help me, Thanks !
score: 0
has comment: http://stackoverflow.com/comment/87616777
answer count: 0
has comment: http://stackoverflow.com/comment/87562614
has comment: http://stackoverflow.com/comment/87564658
has comment: http://stackoverflow.com/comment/87600576
type: Question

http://stackoverflow.com/q/50306536
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
has title: Iterating over n-dimensional Tensors, Tensorflow
score: 1
has body: There is a three dimensional tensor, which I need to compute the expected values for the elements of the second dimension. I have tried to do it through a for-loop like below, but the error 'tensor is not iterable' has been raised. for i in tf.range(start=0, limit=softed_mul.shape[0]): elems = (softed_mul[i, :, :], indexs) softed_arg_maxs[i, :, :] = tf.map_fn(lambda x:x[0] * x[1], elems, dtype=tf.float32)
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/50313206
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/50313206
upvote count: 1

http://stackoverflow.com/q/50377493
has answer: http://stackoverflow.com/a/50377657
answer count: 4
tagged with: python
accepted answer: http://stackoverflow.com/a/50379408
tagged with: regex
has answer: http://stackoverflow.com/a/50379927
has comment: http://stackoverflow.com/comment/87771668
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
has title: Python - Regex match multiple patterns in multiple lines
score: 0
has comment: http://stackoverflow.com/comment/87771287
has answer: http://stackoverflow.com/a/50379408
has body: So I am just now getting into building regexes and have had some great success overall. However I have a particular case that is puzzling me. I can get my desired match but its not pretty and not well done in any way, shape, or form. I am regex matching some html documents with multiple lines. There are blocks of information i need out of these documents that match a variable pattern in each block and then pull my needed information in. there are multiple blocks of html with information i need that look like this: 6880880 Universal Installer: Patch OPatch 9i, 10.1 10.1.0.0.0 08-JUL-2011 25M I am currently working in Python and my regex is: re.compile(r"/Orion/PatchDetails/process_form.+?release=80102000.*\n.*\n.*\n.*\n.*\n.*\n.*zip[^\"]*", re.MULTILINE) my desired output is: 20180516140046EDT - DEBUG - ['/Orion/PatchDetails/process_form?patch_num=6880880&aru=13116068&release=80102000&plat_lang=226P&patch_num_id=979663&\' title="View Patch Details">6880880 \n Universal Installer: Patch OPatch 10.2 \n 10.2.0.0.0 \n 18-NOV-2010 \n 26M \n \n <a href="https://updates.oracle.com/Orion/Download/process_form/p6880880_102000_Linux-x86-64.zip?aru=13116068&file_id=34545782&patch_file=p6880880_102000_Linux-x86-64.zip&'] I am pulling a list of releases, and then applying them as search criteria to pull download urls. I would normally be open to different solutions. However I would like to keep the scope of this to using regex as that is the tag i used, if this is a gross miss use of regex let me know can anyone help me not just optimize this but explain to me the logic using said suggested regex. TLDR: I need to match a leading pattern to a variable (80102000 is the variable in this example) ignoring \n till my second pattern is matched. pattern 1: /Orion/PatchDetails/process_form.+?release=80102000 need the text between... pattern 2: *zip[^\"]* Thank you in advanced!
has answer: http://stackoverflow.com/a/50377658
type: Question
possible better answer: http://stackoverflow.com/a/50377657

http://stackoverflow.com/a/50493150
has comment: http://stackoverflow.com/comment/88060215
has comment: http://stackoverflow.com/comment/88049905
has comment: http://stackoverflow.com/comment/88052182
type: Answer
answers question: http://stackoverflow.com/q/50383706
score: 7
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/88056979
accepted answer of: http://stackoverflow.com/q/50383706
has body: I am not an expert with Matplotlib, but I found a way to get a similar result by using the data files included in the source folder of basemap. They can be combined into a meshgrid to plot some data, in the example below we plot the altitude at every point. One of the tricks I used is to set matplotlib to an orthogonal projection so that there is no distortion in the vertical spacing of the maps. I have put the parameters at the beginning of the code as you may find it useful to adjust. One thing I couldn't get my head around is the shadow under the maps. from mpl_toolkits.mplot3d import proj3d from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1.inset_locator import inset_axes import numpy as np import matplotlib.pyplot as plt # Parameters n_maps = 5 # Number of maps z_spacing = 4. # Spacing of maps along z z_reduction = 1E-8 # Reduction factor for Z data, makes the map look flat view_angles = (14., -100.) # Set view port angles colbar_bottom = 0.2 # Space at the bottom of colorbar column colbar_spacing = .132 # Space between colorbars colbar_height = 0.1 # Height of colorbars # Set orthogonal projection def orthogonal_proj(zfront, zback): a = (zfront+zback)/(zfront-zback) b = -2*(zfront*zback)/(zfront-zback) return np.array([[1,0,0,0], [0,1,0,0], [0,0,a,b], [0,0,-0.0001,zback]]) proj3d.persp_transformation = orthogonal_proj fig = plt.figure(figsize=[30, 10*n_maps]) ax = fig.gca(projection='3d') etopo = np.loadtxt('etopo20data.gz') lons = np.loadtxt('etopo20lons.gz') lats = np.loadtxt('etopo20lats.gz') # Create Basemap instance for Robinson projection. m = Basemap(projection='robin', lon_0=0.5*(lons[0]+lons[-1])) # Compute map projection coordinates for lat/lon grid. X, Y = m(*np.meshgrid(lons,lats)) # Exclude the oceans Z = etopo.clip(-1) # Set the colormap cmap = plt.cm.get_cmap("terrain") cmap.set_under("grey") for i in range(n_maps): c = ax.contourf(X, Y, z_spacing*i + z_reduction*Z, 30, cmap=cmap, vmin=z_spacing*i, extend='neither') cax = inse…
upvote count: 7

http://stackoverflow.com/a/50379248
has body: I don't think you have any issue in your code. print("[{}] {}{} ...{}".format(bar, percents, "%", status), **end="\r"**, flush=True) the end="\n" argument in print() method should print the progress bar i one line. if you run this code in terminal it should work fine. I have previously seen an issue with PyCharm IDE where end="\r" doesn't work. It is probably a bug in the terminal emulator in the IDE.
score: 0
has comment: http://stackoverflow.com/comment/87776904
has comment: http://stackoverflow.com/comment/87774707
has comment: http://stackoverflow.com/comment/87779342
answers question: http://stackoverflow.com/q/50379042
has comment: http://stackoverflow.com/comment/87774699
type: Answer

http://stackoverflow.com/a/50241573
accepted answer of: http://stackoverflow.com/q/50237676
score: 3
upvote count: 3
has body: However, I don't know when reader has data to read. What can I do with it? The obvious way to know when a reader stream has data to read is to await it: data = await reader.read(1024) This will either return the data right away, or suspend the current coroutine, allowing other coroutines to make progress, and only resuming this one when the reader has some data to read. Instead of storing the reader/writer for future communication, you can write a coroutine that does the communication, and store the task that drives it: async def communicate(): reader, writer = await asyncio.open_connection(addr) # an echo server while True: line = await reader.readline() if not line: break writer.write(line) await writer.drain() # backpressure, see https://tinyurl.com./hqylfay task = loop.create_task(communicate()) # the task can itself be awaited, canceled, etc. The idea behind the asyncio stream API is to write such sequential-looking code, leaving it to asyncio to handle polling of file descriptors and scheduling of tasks. You can use combinators like asyncio.gather and asyncio.wait to run thousands of such lightweight coroutines in parallel. Is there a way to make a handler, when the reader is ready? If you need a callback-based API, you should probably use the lower-level transports and protocols instead. However, if you are already working with streams, but still occasionally need an ordinary callback, you can get it by obtaining a Future: future = asyncio.ensure_future(reader.read(1024)) future.add_done_callback(your_callback) Future has the role equivalent to a coroutine handler. Once read would no longer block, the done-callback will be invoked by the event loop with a single argument, the future. The future will have finished, and its result() method can be used to retrieve the received data or an exception. (The above applies to any coroutine or future-compatible object in asyncio, not just to StreamReader methods.)
type: Answer
answers question: http://stackoverflow.com/q/50237676
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/50310432
has comment: http://stackoverflow.com/comment/87636876
downvote count: 0
type: AcceptedAnswer
has body: Through nested list comprehension: &gt;&gt;&gt; [[seq[i: i + 5] for i in range(j, len(seq), 5) if i + 5 &lt;= len(seq)] for j in range(5)] [['SDLKF', 'JSOID', 'HFSOD'], ['DLKFJ', 'SOIDH', 'FSODI'], ['LKFJS', 'OIDHF', 'SODIF'], ['KFJSO', 'IDHFS'], ['FJSOI', 'DHFSO']]
accepted answer of: http://stackoverflow.com/q/50310358
answers question: http://stackoverflow.com/q/50310358
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/a/50350070
has body: Can't you turn the wrapper into a factory? def create_service(): mode = ... service_classes = {'Message Broker': ServiceMessageBroker, 'API': ServiceAPI } try: service_cls = service_classes[mode] except KeyError: raise WrongModeException service_obj = service_cls() return service_obj
answers question: http://stackoverflow.com/q/50349653
has comment: http://stackoverflow.com/comment/87730623
type: Answer
has comment: http://stackoverflow.com/comment/87724023
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87571204
has text: any1 please tell me how to list the all students result
type: Comment
comment on: http://stackoverflow.com/a/50275259
score: 0
type: AnswerComment

http://stackoverflow.com/a/50295858
accepted answer of: http://stackoverflow.com/q/50295727
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/50295727
has body: If you are running on macOS 10.12+ and an older version of pip (&lt; 9.0.3), you might be running into the TLS1.2 issue mentioned in the Python warehouse blog entry. To solve this, you need to update pip to 9.0.3+ by running: curl https://bootstrap.pypa.io/get-pip.py | python
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/87609409
type: AcceptedAnswer

http://stackoverflow.com/comment/87614687
score: 3
type: Comment
has text: Is this for a code golf? (I see no other reason why that extra line of code is a problem...)
comment on: http://stackoverflow.com/q/50298982
type: QuestionComment

http://stackoverflow.com/comment/87781127
type: QuestionComment
score: 0
has text: According to https://keras.io/layers/convolutional/ `input_shape` is `(batch, height, width, channels)`. Whereas you have width before height.
type: Comment
comment on: http://stackoverflow.com/q/50382382

http://stackoverflow.com/a/50375958
accepted answer of: http://stackoverflow.com/q/50375825
has comment: http://stackoverflow.com/comment/87768414
downvote count: 0
type: Answer
has body: you can just do: word = raw_input ("Give me a word! ") letter = raw_input ("Give me a letter! ") print(word.count(letter)) and it will print the frequency of the word do you want to know why your code is not working or this is good enough?
has comment: http://stackoverflow.com/comment/87768201
has comment: http://stackoverflow.com/comment/87768224
score: 1
answers question: http://stackoverflow.com/q/50375825
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/50286206
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/50286308
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/50286266
score: 1
upvote count: 1
has body: I have two Excel files, say, wb1.xlsx and wb2.xlsx. wb1.xlsx adsl svc_no port_stat adsl.1 Comparison result 2/17 2/24 2/27 2/33 2/37 3/12 wb2.xlsx caller_id status adsl Comparison result n/a SP 2/37 Not Match n/a RE 2/24 Not Match n/a SP 2/27 Match n/a SP 2/33 Not Match n/a SP 2/17 Match What I want to do is match the adsl of wb2.xlsx to wb1.xlsx and get the other values to the other columns. My expected output is to update wb1.xlsx with the values from wb2.xlsx adsl svc_no port_stat adsl.1 Comparison result 2/17 n/a SP 2/17 Match 2/24 n/a RE 2/24 Not Match 2/27 n/a SP 2/27 Match 2/33 n/a SP 2/33 Not Match 2/37 n/a SP 2/37 Not Match 3/12 Upon searching, I was able to check that pd.merge() is able to do the matching. I tried it this way: result = pd.merge(df2, pri_df, on=['adsl', 'adsl']) Unfortunately, it creates new columns and do not update the existing. Also, it only gets the values that it was able to matched and disregard the other rows. I also tried to get the indices of the columns in wb2.xlsx and assigned it to the columns wb1.xlsx but it just copied it literally. Any reference that would help will do.
has answer: http://stackoverflow.com/a/50286266
tagged with: excel
favorite count: 0
has answer: http://stackoverflow.com/a/50286308
has title: Match two columns in Excel file and get other column values - Python Pandas
type: Question

http://stackoverflow.com/q/50234149
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/87485686
favorite count: 0
has comment: http://stackoverflow.com/comment/87485941
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50235305
has title: Different querysets in one view
has answer: http://stackoverflow.com/a/50235305
score: 1
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/87486926
has body: I am trying to make the standard blog post web application using Django. I have multiple models in one applications. I want to display at a few posts from all the models to create an index, for which I will need to have multiple queryset inside my view for each model, which I don't know how to do. blog/models.py class topicone(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title class topictwo(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title class topicthree(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() def __str__(self): return self.title blog/urls.py urlpatterns = [ path('', views.indeview.as_view(), name="indexview"), path('&lt;int:pk&gt;', DetailView.as_view( model = topicone, template_name = "blogs/topicone.html" )), ] blog/views.py class indeview(ListView): model = topicone template_name = "blog/index.html" def get_queryset(self): return topicone.objects.all() views.py is quite useless as I am only using one model here. I tried writing a standalone view that didn't inherit from any other generic view so I could just create different contexts and pass multiple dictionaries in a view but that didn't seem to work. Here's how I tried to work that out blogone = topicone.objects.all() blogdict = { 'id': blogone } blogtwo = topictwo.objects.all() blog2dict = {'id': blogtwo} return render (request, 'blog/index.html', blogdict, blogtwo) this view only displayed data from only one model, blogtwo
has comment: http://stackoverflow.com/comment/87485809
answer count: 1
has comment: http://stackoverflow.com/comment/87485761
downvote count: 0

http://stackoverflow.com/a/50300536
has comment: http://stackoverflow.com/comment/87617931
answers question: http://stackoverflow.com/q/50300189
has body: I think you need something like this: var win = window.open("", "_blank",); win.document.write(' External html Externally created '); when you open the popup, this executes JavaScript. You could add data and do whatever you want inside
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87618004
has comment: http://stackoverflow.com/comment/87617976
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50300189

http://stackoverflow.com/q/50324565
type: Question
has body: At the moment, I know how to write a list to one row in csv, but when there're multiple rows, they are still written in one row. What I would like to do is write the first list in the first row of csv, and the second list to the second row. Code: for i in range(10): final=[i*1, i*2, i*3] with open ('0514test.csv', 'a') as file: file.write(','.join(str(i) for i in kk))
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87665212
has answer: http://stackoverflow.com/a/50324597
accepted answer: http://stackoverflow.com/a/50324597
has answer: http://stackoverflow.com/a/50324831
possible better answer: http://stackoverflow.com/a/50324831
has title: Python: write multiple lists to multiple rows in csv

http://stackoverflow.com/comment/87738686
score: 1
has text: You can just rename the parameter to something other than `lowest_eigenvectors`.
comment on: http://stackoverflow.com/a/50361034
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/112192950
type: AnswerComment
comment on: http://stackoverflow.com/a/50308132
score: 1
type: Comment
has text: Tensors are multidimensional (otherwise we call them vectors and matrices). Can you please show construction of a 3D torch tensor from a column (series) of a DataFrame?

http://stackoverflow.com/q/50271726
tagged with: python
possible better answer: http://stackoverflow.com/a/50271793
has body: I need help to search a value in a range inside a list list.append((5,range(10,15))) if (5,12) in list : Print("yes")
has answer: http://stackoverflow.com/a/50271881
answer count: 4
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50271820
score: 0
tagged with: list
downvote count: 2
has title: Python, list condition in range
has comment: http://stackoverflow.com/comment/87560466
has answer: http://stackoverflow.com/a/50271793
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50271836
accepted answer: http://stackoverflow.com/a/50271836

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/50353362

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/50236517
tags question: http://stackoverflow.com/q/50252481

http://stackoverflow.com/a/50295706
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/50294715
has body: I don't know what you are trying to accomplish, but I can offer some suggestions: It looks like there is no covariance between realizations from your simulation, so to speed up the computation and make the code a little clearer, you can draw the data from a joint multivariate normal distribution. I hate for loops, so vectorization is better whenever it can be done. Here is some code import numpy as np import matplotlib.pyplot as plt N = 10000 mean_vector = np.array([200, #Area 100, #Thickness 0.85, #NTG 0.32, #POR 0.80, #GS 0.0024 #BG ]) covariance = np.diag([50, 25, 0.2, 0.02, 0.2, 0.0001]) simulated = np.random.multivariate_normal(mean_vector, covariance, size = N) area, thickness, ntg, por, gs, bg = simulated.T result= (area*thickness*ntg*por*gs*43560)/bg The result array contains the results of your simulation. Now you can plot a histogram or compute means if needed.

http://stackoverflow.com/q/50272647
has comment: http://stackoverflow.com/comment/87576526
has comment: http://stackoverflow.com/comment/87606968
favorite count: 0
answer count: 2
score: 5
downvote count: 0
type: UnansweredQuestion
type: Question
has title: Passing options to a function
upvote count: 5
has body: In ruby it is idiomatic to write a function that may be called like this: open_database(:readonly) // or open_database(:readonly, :remote, :force) In these cases the :readonly are "symbols" and are used as "flags" to modify the behavior of the open_database call. We would implement this as follows in ruby: def func(*params) if params.include? :readonly puts "readonly" end end What is the idiomatic way to do this in Python?
has answer: http://stackoverflow.com/a/50837060
has comment: http://stackoverflow.com/comment/87600360
tagged with: python
has answer: http://stackoverflow.com/a/50272897

http://stackoverflow.com/q/50294478
has answer: http://stackoverflow.com/a/50409579
type: Question
type: UnansweredQuestion
has title: Pyglet - Getting sound frequency
tagged with: python
has body: I would like to get the frequency of a sound that I load using media.load(), so I can later visualize it, is there any way to do this using pyglet?
tagged with: pyglet
score: 0
answer count: 1

http://stackoverflow.com/a/54092155
score: 11
accepted answer of: http://stackoverflow.com/q/50350844
answers question: http://stackoverflow.com/q/50350844
downvote count: 0
upvote count: 11
has body: The compression parameter of the function to_csv() does not work when writing to a stream. You have to do the zipping and uploading separately. import gzip import boto3 from io import BytesIO, TextIOWrapper buffer = BytesIO() with gzip.GzipFile(mode='w', fileobj=buffer) as zipped_file: df.to_csv(TextIOWrapper(zipped_file, 'utf8'), index=False) s3_resource = boto3.resource('s3') s3_object = s3_resource.Object('bucket_name', 'key') s3_object.put(Body=buffer.getvalue())
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/87506534
type: Comment
score: 1
type: QuestionComment
has text: have you tried importing `password_reset_done`?
comment on: http://stackoverflow.com/q/50244342

http://stackoverflow.com/q/50259152
has body: I have a swigged C++ class container, MyContainer, holding objects of type MyObject, also a C++ class. The following is the C++ header code (freemenot.h) #ifndef freemenotH #define freemenotH #include &lt;vector&gt; #include &lt;string&gt; using std::string; class MyObject { public: MyObject(const string&amp; lbl); ~MyObject(); string getLabel(); private: string label; }; class MyContainer { public: MyContainer(); ~MyContainer(); void addObject(MyObject* o); MyObject* getObject(unsigned int t); int getNrOfObjects(); private: std::vector&lt;MyObject*&gt; mObjects; }; #endif and this is the source (freemenot.cpp) #include "freemenot.h" #include &lt;iostream&gt; using namespace std; /* MyObject source */ MyObject::MyObject(const string&amp; lbl) : label(lbl) { cout&lt;&lt;"In object ctor"&lt;&lt;endl; } MyObject::~MyObject() { cout&lt;&lt;"In object dtor"&lt;&lt;endl; } string MyObject::getLabel() { return label; } /* MyContainer source */ MyContainer::MyContainer() { cout&lt;&lt;"In container ctor"&lt;&lt;endl; } MyContainer::~MyContainer() { cout&lt;&lt;"In container dtor"&lt;&lt;endl; for(unsigned int i = 0; i &lt; mObjects.size(); i++) { delete mObjects[i]; } } int MyContainer::getNrOfObjects() { return mObjects.size(); } void MyContainer::addObject(MyObject* o) { mObjects.push_back(o); } MyObject* MyContainer::getObject(unsigned int i) { return mObjects[i]; } Observe that the objects are stored as RAW POINTERS in the vector. The class is such designed, and the container is thus responsible to free the objects in its destructor, as being done in the destructors for loop. In C++ code, like below, an object o1 is added to the container c, which is returned to client code MyContainer* getAContainerWithSomeObjects() { MyContainer* c = new MyContainer(); MyObject* o1 = new MyObject(); c.add(o1); return c; } The returned container owns its objects, and are responsible to de-allocate these objects when done. In C++, access to the containers objects is fine after the funct…
favorite count: 0
possible better answer: http://stackoverflow.com/a/50285009
has answer: http://stackoverflow.com/a/72512095
tagged with: swig
has answer: http://stackoverflow.com/a/50285009
has comment: http://stackoverflow.com/comment/87967574
type: Question
has comment: http://stackoverflow.com/comment/87967532
score: 3
has comment: http://stackoverflow.com/comment/87585747
tagged with: python
tagged with: c++
accepted answer: http://stackoverflow.com/a/50482240
has answer: http://stackoverflow.com/a/50482240
type: AnsweredQuestion
upvote count: 3
has title: Adding swig pythoncode to set thisown flag on Python object
has comment: http://stackoverflow.com/comment/87739262
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87967722
has comment: http://stackoverflow.com/comment/87967339

http://stackoverflow.com/comment/87604037
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50290771
has text: or without indexing: `res_df = reduce(lambda a, b: a.union(b), dataframes)`

http://stackoverflow.com/comment/87549401
comment on: http://stackoverflow.com/q/50265630
score: 0
type: Comment
has text: If the API doesn't support it, then it doesn't support it. What can you do?
type: QuestionComment

http://stackoverflow.com/a/50289371
has body: Now when I try to use numpy 'shortcuts' You are not using Numpy shortcuts. Each [...] is a separate operation returning a new array object, so you are slicing three times in each example, twice with [:] and once with [0]. array[:] just creates a new view on the whole array: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; all_data = np.zeros((145, 145, 220)) &gt;&gt;&gt; all_data.shape (145, 145, 220) &gt;&gt;&gt; all_data[:].shape (145, 145, 220) &gt;&gt;&gt; np.array_equal(all_data[:], all_data) # the slice is equal to the original True Adding another [:] then just creates another view, and in the end the only operation that actually produces a different result is the [0] indexing operation, which then creates a view on just the first element of 3-dimensional (145, 145, 220) array, (so a 2 dimensional matrix): &gt;&gt;&gt; all_data[:][:].shape (145, 145, 220) &gt;&gt;&gt; np.array_equal(all_data[:][:][0], all_data[0]) True You may as well not have used [:] slicing at all. You need to pass in your dimension slices as a tuple to a single [...] indexing operation: &gt;&gt;&gt; all_data[0, :, :].shape # the same result as all_data[0] (145, 220) &gt;&gt;&gt; all_data[:, 0, :].shape (145, 220) &gt;&gt;&gt; all_data[:, :, 0].shape (145, 145) Now you are given a view on the two-dimensional matrix at the specific index.
answers question: http://stackoverflow.com/q/50289136
has comment: http://stackoverflow.com/comment/87595774
upvote count: 3
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/87626093
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50304874
type: QuestionComment
has text: So put the `if` statement **before** the `print()`?

http://stackoverflow.com/a/50373953
score: 12
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87812939
has comment: http://stackoverflow.com/comment/112632369
accepted answer of: http://stackoverflow.com/q/50371298
has body: The derivative of a cubic spline is a quadratic spline. SciPy only has a built-in method to find the roots of a cubic spline. So there are two approaches: Use a 4th degree spline for interpolation, so that the roots of its derivative can be found easily. Use a cubic spline (which is often preferable), and write a custom function for the roots of its derivative. I describe both solutions below. 4th degree spline Use InterpolatedUnivariateSpline.which had .derivative method returning a cubic spline, to which .roots method can be applied. from scipy.interpolate import InterpolatedUnivariateSpline f = InterpolatedUnivariateSpline(x_axis, y_axis, k=4) cr_pts = f.derivative().roots() cr_pts = np.append(cr_pts, (x_axis[0], x_axis[-1])) # also check the endpoints of the interval cr_vals = f(cr_pts) min_index = np.argmin(cr_vals) max_index = np.argmax(cr_vals) print("Maximum value {} at {}\nMinimum value {} at {}".format(cr_vals[max_index], cr_pts[max_index], cr_vals[min_index], cr_pts[min_index])) Output: Maximum value 6.779687224066201 at 2.1824928509277037 Minimum value 0.34588448400295346 at 2.2075868177297036 Cubic spline We need a custom function for the roots of a quadratic spline. Here it is (explained below). def quadratic_spline_roots(spl): roots = [] knots = spl.get_knots() for a, b in zip(knots[:-1], knots[1:]): u, v, w = spl(a), spl((a+b)/2), spl(b) t = np.roots([u+w-2*v, w-u, 2*v]) t = t[np.isreal(t) & (np.abs(t) <= 1)] roots.extend(t*(b-a)/2 + (b+a)/2) return np.array(roots) Now proceed exactly as above, except for using the custom solver. from scipy.interpolate import InterpolatedUnivariateSpline f = InterpolatedUnivariateSpline(x_axis, y_axis, k=3) cr_pts = quadratic_spline_roots(f.derivative()) cr_pts = np.append(cr_pts, (x_axis[0], x_axis[-1])) # also check the endpoints of the interval cr_vals = f(cr_pts) min_index = np.argmin(cr_vals) max_index = np.argmax(cr_vals) print("Maximum value {} at {}\nMinimum value {} at {}".format(cr_vals[max_index], cr_pts[m…
type: Answer
answers question: http://stackoverflow.com/q/50371298
has comment: http://stackoverflow.com/comment/87815005
upvote count: 12

http://stackoverflow.com/q/50263637
answer count: 1
has body: I'd like to convert the following into a series. Trades Before Trades After Predicted Change count 31540.000000 1000.000000 1000.000000 -0.968294 mean 39.151712 42.216000 90.144811 0.078267 std 130.948917 143.153156 1.345089 0.093198 min -1611.000000 -1371.000000 88.234987 -0.148976 25% 29.000000 34.000000 89.052902 0.172414 50% 74.000000 79.000000 89.979200 0.067568 75% 99.000000 109.000000 91.127657 0.101010 max 184.000000 179.000000 93.915568 -0.027174 Where the index is the combination of the row name and the column name, for example: Trades After 50% 79.000000
tagged with: pandas
type: AnsweredQuestion
has title: Convert multiple column dataframe into series
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/50263847
has answer: http://stackoverflow.com/a/50263847
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/87697260
type: Comment
score: 0
type: AnswerComment
has text: Thank you for explaining anf help! How to check if data are not str type? Cause this solution not working for multi type table which I have (numbers and strings, depends column). `lower()` not possible use for int or float. But it works cool about strings!
comment on: http://stackoverflow.com/a/50332395

http://stackoverflow.com/comment/87760498
type: QuestionComment
has text: df2=df.copy() followed by df2['b']="" ?
comment on: http://stackoverflow.com/q/50372272
score: 3
type: Comment

http://stackoverflow.com/comment/87634720
type: QuestionComment
comment on: http://stackoverflow.com/q/50306988
has text: Have you tried increasing the number of `epochs`, for example to 20 or 50 or 100? Since your keras model is very small (i.e. has very few parameters), I suspect it takes more epochs to see any increase in accuracy, since the loss is decreasing so there is some progress happening.
score: 1
type: Comment

scikit-learn
tags question: http://stackoverflow.com/q/50355483
tags question: http://stackoverflow.com/q/50230385
tags question: http://stackoverflow.com/q/50305223
tags question: http://stackoverflow.com/q/50265993
tag name: scikit-learn
tags question: http://stackoverflow.com/q/50310515
tags question: http://stackoverflow.com/q/50345072
tags question: http://stackoverflow.com/q/50325786
tags question: http://stackoverflow.com/q/50232473
tags question: http://stackoverflow.com/q/50296498
tags question: http://stackoverflow.com/q/50316344
tags question: http://stackoverflow.com/q/50261604
tags question: http://stackoverflow.com/q/50346850
type: Tag
tags question: http://stackoverflow.com/q/50317701
tags question: http://stackoverflow.com/q/50245684
tags question: http://stackoverflow.com/q/50232599
tags question: http://stackoverflow.com/q/50329426
tags question: http://stackoverflow.com/q/50257227
tags question: http://stackoverflow.com/q/50244854
tags question: http://stackoverflow.com/q/50375482
tags question: http://stackoverflow.com/q/50313521
tags question: http://stackoverflow.com/q/50247900
tags question: http://stackoverflow.com/q/50322384
tags question: http://stackoverflow.com/q/50332786
tags question: http://stackoverflow.com/q/50356091
tags question: http://stackoverflow.com/q/50371227
tags question: http://stackoverflow.com/q/50264334
tags question: http://stackoverflow.com/q/50322799
tags question: http://stackoverflow.com/q/50373189
tags question: http://stackoverflow.com/q/50333374
tags question: http://stackoverflow.com/q/50265501
tags question: http://stackoverflow.com/q/50238812
tags question: http://stackoverflow.com/q/50323770
tags question: http://stackoverflow.com/q/50271807
tags question: http://stackoverflow.com/q/50236372
tags question: http://stackoverflow.com/q/50379374
tags question: http://stackoverflow.com/q/50319858
tags question: http://stackoverflow.com/q/50316231
tags question: http://stackoverflow.com/q/50287891
tags question: http://stackoverflow.com/q/50238979
tags question: http://stackoverflow.com/q/50329184
tags question: http://stackoverflow.com/q/50376169
tags question: http://stackoverflow.com/q/50272416
tags question: http://stackoverflow.com/q/50282280
tags question: http://stackoverflow.com/q/50261094
tags question: http://stackoverflow.com/q/50258960
tags question: http://stackoverflow.com/q/50334915
tags question: http://stackoverflow.com/q/50285973
tags question: http://stackoverflow.com/q/50312012
tags question: http://stackoverflow.com/q/50304293
tags question: http://stackoverflow.com/q/50382699
tags question: http://stackoverflow.com/q/50268691
tags question: http://stackoverflow.com/q/50368930
tags question: http://stackoverflow.com/q/50338576
tags question: http://stackoverflow.com/q/50243520
tags question: http://stackoverflow.com/q/50272689

proxy
tags question: http://stackoverflow.com/q/50326662
tags question: http://stackoverflow.com/q/50253483
tags question: http://stackoverflow.com/q/50320915
type: Tag
tags question: http://stackoverflow.com/q/50253997
tag name: proxy
tags question: http://stackoverflow.com/q/50382727

http://stackoverflow.com/comment/87535827
score: 0
comment on: http://stackoverflow.com/a/50235610
type: Comment
has text: Thanks, but I was looking for something like marshmallow. It's something like that.
type: AnswerComment

http://stackoverflow.com/comment/87646980
comment on: http://stackoverflow.com/a/50315601
type: Comment
type: AnswerComment
score: 0
has text: Thanks, I can see that changing to `text` works, BUT, what about scoring? I will be combining this with queries on other fields, and I want what I'm doing here to ONLY act as a filtering mechanism, returning docs which contain the location specified and not contributing to score at all

http://stackoverflow.com/a/50275379
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50274628
has body: By default, items are centered in a grid cell without you having to do anything. The problem you have is that the column that contains the cell is only wide enough for the largest item in that column, which in this case is the title. Thus, it's centered in its cell, but the cell is exactly as wide as the label so it doesn't look centered. If you want the title to span the width of the window (rather than the cell), you need to use the columnspan option so that it goes across all of the columns that you are using. For example: l1 = Label(window, ...) l1.grid(row=0, columnspan=2) However, it still will not appear centered, because columns 0 and 1 will only be as large as their largest items, which leaves some extra space in the GUI since you explicitly set the width of the window. You need to do one of two things: make the window smaller (or let Tkinter determine the best size for you, which is usually the right solution), or designate that either column 0 or 1 (or both) will expand to fill any extra space. For the first case, simply remove the call to geometry. For the second, use columnconfigure on the root to have one or both columns have a "weight", which means they will expand to take up extra space. window.grid_columnconfigure(1, weight=1) As a general rule of thumb when using grid, you should always give at least one row and at least one column a weight, so that the widgets will expand to fit the available space.

http://stackoverflow.com/q/50362262
tagged with: numpy
tagged with: indexing
accepted answer: http://stackoverflow.com/a/50362288
linked to: http://stackoverflow.com/q/28491230
type: Question
has title: Indexing a numpy array with a numpy array of indexes
has answer: http://stackoverflow.com/a/50362288
has comment: http://stackoverflow.com/comment/87745392
has comment: http://stackoverflow.com/comment/87741874
tagged with: python
duplicate of: http://stackoverflow.com/q/28491230
has comment: http://stackoverflow.com/comment/87741699
duplicate of: http://stackoverflow.com/q/42483211
has body: I have a 3D numpy array data and another array pos of indexes (an index is a numpy array on its own, which makes the latter array a 2D array): import numpy as np data = np.arange(8).reshape(2, 2, -1) #array([[[0, 1], # [2, 3]], # # [[4, 5], # [6, 7]]]) pos = np.array([[1, 1, 0], [0, 1, 0], [1, 0, 0]]) #array([[1, 1, 0], # [0, 1, 0], # [1, 0, 0]]) I want to select and/or mutate the elements from data using the indexes from pos. I can do the selection using a for loop or a list comprehension: [data[tuple(i)] for i in pos] #[6, 2, 4] datai for i in pos.T #array([6, 2, 4]) But this does not seem to be a numpy way. Is there a vectorized numpy solution to this problem?
has comment: http://stackoverflow.com/comment/87742112
has comment: http://stackoverflow.com/comment/87745358
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
score: 7
upvote count: 7
answer count: 1
favorite count: 0

http://stackoverflow.com/q/50323756
favorite count: 0
has answer: http://stackoverflow.com/a/50329602
type: Question
has title: tensorflow u-net python package filter map dimention
type: UnansweredQuestion
tagged with: semantic-segmentation
tagged with: python
has body: is it possible to change the filter map dimension of the first layer of a CNN and increase it by 1 ( instead of 5*5*64) I want it to be (5*5*33*64) in a python u-net package? I want my batch size to be 33 so that I could use a 2D unet for a 3D image with 33 slices
tagged with: image-segmentation
tagged with: conv-neural-network
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/87732256
has text: At the moment I have only 1 output, and i need to do different things for each word :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50357767
score: 0

http://stackoverflow.com/comment/87745559
score: 0
comment on: http://stackoverflow.com/a/50364252
type: Comment
type: AnswerComment
has text: i tried your answer and get rid off if else and delete sep =" " but still when i try to enter multi-inputs doesn't work

http://stackoverflow.com/comment/87714108
has text: Expect row in MySQL 2018-05-01 // Переходы из поисковых систем // Смартфоны // Google, результаты поиска // Москва // Россия // null // 13.0 // 38.0
comment on: http://stackoverflow.com/q/50348570
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55246936
type: Answer
answers question: http://stackoverflow.com/q/50304156
downvote count: 0
score: 23
upvote count: 23
has body: I was having the same problem while running Tensorflow container with Docker and Jupyter notebook. I was able to fix this problem by increasing the container memory. On Mac OS, you can easily do this from: Docker Icon &gt; Preferences &gt; Advanced &gt; Memory Drag the scrollbar to maximum (e.g. 4GB). Apply and it will restart the Docker engine. Now run your tensor flow container again. It was handy to use the docker stats command in a separate terminal It shows the container memory usage in realtime, and you can see how much memory consumption is growing: CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 3170c0b402cc mytf 0.04% 588.6MiB / 3.855GiB 14.91% 13.1MB / 3.06MB 214MB / 3.13MB 21

http://stackoverflow.com/a/50237945
score: 9
downvote count: 0
answers question: http://stackoverflow.com/q/50237918
upvote count: 9
has body: Use drop by all index values: df1 = df.drop(df.index) Or DataFrame constructor with columns parameter only: df1 = pd.DataFrame(columns=df.columns) Sample: df = pd.DataFrame({'a':list('ab'), 'b':range(2)}) df1 = df.drop(df.index) print (df1) Empty DataFrame Columns: [a, b] Index: []
type: Answer

http://stackoverflow.com/comment/87583324
type: Comment
has text: Can we clean up/ improve/ canonicalize/ close [how to debug python in visual studio](https://stackoverflow.com/questions/47988796/how-to-debug-python-in-visual-studio), [How to start debugging Python 3.6 in Visual Studio Code?](https://stackoverflow.com/questions/47273900/how-to-start-debugging-python-3-6-in-visual-studio-code) etc?
score: 0
comment on: http://stackoverflow.com/q/50283382
type: QuestionComment

http://stackoverflow.com/a/50336051
has comment: http://stackoverflow.com/comment/87691900
has body: No, although you can alias the module to a shorter name: In [1]: from decimal import Decimal as d In [2]: d(10) Out[2]: Decimal('10')
score: 1
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/87688283
downvote count: 1
answers question: http://stackoverflow.com/q/50336008

http://stackoverflow.com/a/50321715
type: Answer
has comment: http://stackoverflow.com/comment/87659257
has body: You jsut try to loop through and safe the last element used df=pd.DataFrame(['x','x','y','y','x','x','x','y','y','y','y','x']) df2=pd.DataFrame() old = df[0].iloc[0] # get the first element for column in df: df[column].iloc[0] != old: df2.append(df[column].iloc[0]) old = df[column].iloc[0] EDIT: Or for a vector use a list &gt;&gt;&gt; L=[1,1,1,1,1,1,2,3,4,4,5,1,2] &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; [x[0] for x in groupby(L)] [1, 2, 3, 4, 5, 1, 2]
score: 0
answers question: http://stackoverflow.com/q/50321673
has comment: http://stackoverflow.com/comment/87659572

http://stackoverflow.com/comment/87579381
type: QuestionComment
comment on: http://stackoverflow.com/q/50281288
score: 3
has text: Since `distance` seems to be an `ndarray`, your if statement should read: `if np.all(distance > Sun_radius):`. For the moment you a comparing an integer/float to a boolean.
type: Comment

http://stackoverflow.com/q/50381664
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87779500
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50382390
has body: i have python 3.6 and django 2.0 installed. i keep having this same error...Type error:View must be a callable or a list/tuple in the case of include() in django 2.0 my app urls the app's name is catalog from django.urls import path from django import views urlpatterns = [ path('index/', views.catalog_home, name='catalog_home'), path('category/&lt;category_slug&gt;/', views.show_category, name='show_category'), path('product/&lt;product_slug&gt;/', views.show_product, name='show_product') ] my project urls this is the projects urls from django.contrib import admin from django.urls import path, include from django.views import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls'),), path('static/', static, { 'document_root': 'C:/Users/USER1/PycharmProjects/untitled13/static' }), ] my views from django.shortcuts import get_object_or_404, render_to_response from catalog.models import Category, Product from django.template import RequestContext def index(request, template_name='catalog/index.html'): page_title = 'online shop for all items' return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_category(request, category_slug, template_name='catalog/category.html'): c = get_object_or_404(Category, slug=category_slug) products = c.product_set.all() page_title = c.name meta_keywords = c.meta_keywords meta_description = c.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request)) def show_product(request, product_slug, template_name='catalog/product.html'): p = get_object_or_404(Product, slug=product_slug) categories = p.categories.filter(is_active=True) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request))
has answer: http://stackoverflow.com/a/50382390
type: AnsweredQuestion
score: 1
answer count: 1
has title: Type error:View must be a callable or a list/tuple in the case of include() in django 2.0

http://stackoverflow.com/comment/87547322
comment on: http://stackoverflow.com/q/50264597
score: 0
type: QuestionComment
has text: you'd better put your expect result as example, cause your describe isn't clear .
type: Comment

http://stackoverflow.com/q/50345795
accepted answer: http://stackoverflow.com/a/50346167
tagged with: python
has answer: http://stackoverflow.com/a/50346167
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87708180
answer count: 2
possible better answer: http://stackoverflow.com/a/50345960
upvote count: 0
has comment: http://stackoverflow.com/comment/87708132
has answer: http://stackoverflow.com/a/50345960
downvote count: 2
has comment: http://stackoverflow.com/comment/87708270
has comment: http://stackoverflow.com/comment/87707566
has title: Python: sum column if matches
has comment: http://stackoverflow.com/comment/87707429
has comment: http://stackoverflow.com/comment/87707813
has body: i have a huge file with thousand of lines that looks like this: `C509.TCGA-78-7159-10A-01D-2036-08.1-C509. 1 0 0 1 0 0 C509.TCGA-78-7159-10A-01D-2036-08.1-C509. 0 1 1 0 1 1` If the first column of rows matches I want to sum second column of one row with second column of second row, third with third etc, not using pandas. And probably it would be better to use python, not awk because of the size. The output should be: C509.TCGA-78-7159-10A-01D-2036-08.1-C509. 1 1 1 1 1 1 Thank you for help :)
tagged with: multiple-columns
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87707428
has comment: http://stackoverflow.com/comment/87707559
score: -2
tagged with: sum

http://stackoverflow.com/q/50374610
has title: How do I read(open) an ASN.1 file in python
tagged with: openssl
has body: I want to get a certificates serial number using python: der = open('/Users/me/MyApp/Payload/codesign0').read()``` cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der cert.get_serial_number() Unfortunately it fails in the first line: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 1: invalid start byte How do I read an ASN.1 file format (DER) in Python?
type: Question
accepted answer: http://stackoverflow.com/a/50375466
score: 1
has answer: http://stackoverflow.com/a/73259052
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50375254
type: AnsweredQuestion
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50375254
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/50375466
tagged with: pyopenssl
favorite count: 0

http://stackoverflow.com/q/50362253
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87741009
tagged with: python
has answer: http://stackoverflow.com/a/50362324
tagged with: regex
accepted answer: http://stackoverflow.com/a/50362324
has title: How to match word in regex -python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87740962
tagged with: python-2.7
score: 0
answer count: 2
has body: How to match word in list when i used demo in https://regex101.com/ it's match with \w+ but when I threw in my code the word not detected, So this is my code: def MultiTrain(self): for fitur in self.fiturs: if (fitur[0] == 'F7') or (fitur[0] == 'F8') or (fitur[0] == 'F9') or (fitur[0] == 'F10') or ( fitur[0] == 'F13') or (fitur[0] == 'F14') or (fitur[0] == 'F15') or (fitur[0] == 'F16') or ( fitur[0] == 'F17') or (fitur[0] == 'F23') or (fitur[0] == 'F24') or (fitur[0] == 'F25') or ( fitur[0] == 'F26') or (fitur[0] == 'F27') or (fitur[0] == 'F28') or (fitur[0] == 'F29') or ( fitur[0] == 'F30') or (fitur[0] == 'F37') or (fitur[0] == re.findall('\w+', fitur[0])) : print fitur and this is the word i want to match with regex: F37,0,1,0,1,1,1,0,1,0,2 F7,0,0,0,0,0,0,1,0,1,0 F11,0,0,1,0,0,1,0,0,0,0 angkasa,1,0,1,0,0,0,0,0,0,0 action,0,1,0,0,0,0,0,0,0,0 acu,0,0,0,0,1,0,0,0,0,0 ampun,0,0,0,0,0,0,0,1,0,0 The output of the program is: F37,0,1,0,1,1,1,0,1,0,2 F7,0,0,0,0,0,0,1,0,1,0 F11,0,0,1,0,0,1,0,0,0,0 but my expectation is: F37,0,1,0,1,1,1,0,1,0,2 F7,0,0,0,0,0,0,1,0,1,0 F11,0,0,1,0,0,1,0,0,0,0 angkasa,1,0,1,0,0,0,0,0,0,0 action,0,1,0,0,0,0,0,0,0,0 acu,0,0,0,0,1,0,0,0,0,0 ampun,0,0,0,0,0,0,0,1,0,0 the fitur[0] with word not detected just the F37-F11 How can I fix the regex?
upvote count: 1
has answer: http://stackoverflow.com/a/50362342
possible better answer: http://stackoverflow.com/a/50362342
downvote count: 1
has comment: http://stackoverflow.com/comment/87741220

http://stackoverflow.com/a/50312629
answers question: http://stackoverflow.com/q/50312524
has body: Iterate over the lines: check if they start with what you are interested in; for the interesting lines take the slice that you want. d = {} for line in f: if line.startswith('Loading '): line = line.strip() # len('Loading ') --&gt; 8 key = line[9:] elif line.startswith('Percentage of adjacent deep bass frames: '): line = line.strip() # len('Percentage of adjacent deep bass frames: ') --&gt; 41 value = line[42:] print((key,value)) d[key] = value key, value = '','' Relies on the sequence of lines being predictable: key line, other lines, value line, other lines, key line, ...
type: Answer
score: 0

http://stackoverflow.com/comment/87600010
score: 2
type: Comment
has text: @jpp dict is 74.2 ns, ternary is 84 ns on my machine. So basically no different.
type: AnswerComment
comment on: http://stackoverflow.com/a/50291734

http://stackoverflow.com/comment/87614693
has text: If you're launching `baz.py` from the `pkg` directory, then there *is* no package `pkg`: in that scenario the `pkg` folder is not a package, but a root of `sys.path`. This is one of the reasons why you shouldn't mix executable scripts in among your folder structure of importable packages.
score: 0
comment on: http://stackoverflow.com/q/50298964
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87609502
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50296281
has text: The C++ code increments `count` inside the `if flag` block, and the Python code increments `count` inside the `if cnt == len(A):` block. I wonder if that has anything to do with anything.
score: 3

http://stackoverflow.com/a/50354749
answers question: http://stackoverflow.com/q/50354622
downvote count: 0
score: 1
upvote count: 1
has body: In Python, when creating an if, elif, for loop, etc. The correct syntax is to have a colon at the end of the initialization line. So in your code you would need to update it to the following: for row in data: if row[data.Terms] == term: researcher1 += 1 elif data.Terms == term: researcher2 += 1 elif data.Terms == term: researcher3 += 1 else: print("Sorry!", term, "not found in the database!") Also, once you correct this, based on your code it looks like you will have a bug as well. You are setting the user input to lowercase but you are not doing the same to the data read from the CSV file. So none of the terms will equal the user input.
type: Answer

http://stackoverflow.com/a/50283013
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50282878
has body: There isn't a built in way for Channels to get a list of groups but you can achieve this by adding/removing group names to a model field with some logic in your consumer's connect() and disconnect() methods.
type: Answer
score: 1

http://stackoverflow.com/q/50316719
type: Question
has answer: http://stackoverflow.com/a/50336200
has title: Jupyter Python Markdown: Evaluated Inline code in LaTeX output
upvote count: 5
tagged with: python
type: UnansweredQuestion
has body: Python Markdown is a very nice extension for the jupyter notebook, which is in turn great for literate programming, i.e. mixing text and code. Python Markdown makes it possible to include short inline code in Markdown cells in Jupyter like in the following example: Python cell: a = 3.1415 Markdown cell: The value of a was {{a}}. Everything works fine in the browser interface, but when I export it to LaTeX (or PDF via LaTeX), the output will still contain {{a}} as an unevaluated expression. It would of course be really helpful to have the evaluated expression in the output for generating reports.
answer count: 1
score: 4
tagged with: jupyter
tagged with: pandoc
downvote count: 1
tagged with: jupyter-notebook
favorite count: 0
tagged with: latex

http://stackoverflow.com/comment/87521593
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50251874
has text: Not really, I just haven't learned itertools yet. Thank you! I'll check it out.
type: Comment

http://stackoverflow.com/comment/87545570
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50263363
score: 0
has text: Do you realize that the decorator `bypass_upgrade_check` will run only once, just after the interpreter processes the function definition of `cmd2`? It will not produce any output that you can see at that point, nor will it call the original `cmd2`. It's not clear what you are trying to do here. You seem to want clicks to execute some particular function "by default" but don't want "developers" of future event handlers to forget to call that function. But you don't tell us what your environment is or how those developers go about adding a handler.

http://stackoverflow.com/a/50292336
has body: This is one way to avoid a nested for loop. Setup fruit = [{'Type':'Tree', 'Name':'Pear', 'Color':'Red,Green'}, {'Type':'Bush', 'Name':'Raspberry', 'Color':'Red,White'}, {'Type':'Tree', 'Name':'Apple', 'Color':'Red,Green'}] tree_types = [{'Type':'Tree', 'Fruit':'Pear', 'Height':'25ft'}, {'Type':'Tree', 'Fruit':'Apple', 'Height':'15ft'}, {'Type':'Root', 'Fruit':'Carrot', 'Height':'2ft'}] Note: don't name variables after built-ins, e.g. type. Solution tree_types_d = {(i['Type'], i['Fruit']): i['Height'] for i in tree_types} for item in fruit: tup = (item['Type'], item['Name']) if tup in tree_types_d: item['Height'] = tree_types_d[tup] Result [{'Color': 'Red,Green', 'Height': '25ft', 'Name': 'Pear', 'Type': 'Tree'}, {'Color': 'Red,White', 'Name': 'Raspberry', 'Type': 'Bush'}, {'Color': 'Red,Green', 'Height': '15ft', 'Name': 'Apple', 'Type': 'Tree'}] Explanation Restructure tree_types as a dictionary of tuples, tree_types_d. Iterate fruit and add Height item where there is a match with tree_types_d. The one-off cost of constructing a new dictionary is often preferable to nested for loops.
answers question: http://stackoverflow.com/q/50292184
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/87609184
comment on: http://stackoverflow.com/q/50294023
has text: That's ok, I just wanted its return type. My answer should work. Does it run any quicker for you?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/50246228
type: UnansweredQuestion
tagged with: raspberry-pi3
tagged with: python
has comment: http://stackoverflow.com/comment/87510105
has title: Python button timeout
score: 0
answer count: 0
has body: There are two buttons on raspberry pi. I want the functionality in such way: If button 1 is pressed - it will wait for 10 seconds to check if the button 2 is pressed. If in that 10 seconds button 2 is pressed then the code of button 2 should execute. And if button 2 is not pressed in that 10 seconds then code of button 1 should execute. Please tell me how i can achieve this functionality in python. My button code is as below: #Button One button_state = GPIO.input(17) if button_state == False: GPIO.output(5,GPIO.HIGH) print('Button One Pressed') time.sleep(10) else: GPIO.output(5,GPIO.LOW) #Button Two button_state = GPIO.input(24) if button_state == False: GPIO.output(26,GPIO.HIGH) time.sleep(1) GPIO.output(26,GPIO.LOW) print('exit') break else: GPIO.output(26,GPIO.LOW)
has comment: http://stackoverflow.com/comment/87509927
tagged with: timeout
type: Question

http://stackoverflow.com/comment/87738734
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50360809
has text: It would be helpful if you provided a [Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve). Now we can only guess for which modules `np` and `plt` stand for, and where `interp1d` comes from.
type: Comment

http://stackoverflow.com/a/50284388
answers question: http://stackoverflow.com/q/50283992
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50283992
score: 3
type: Answer
has body: One of the properties of decimal addition is that the least-significant digit of the sum only depends on the least-significant digit of the two numbers being added. So you can do all the calculations with only one digit: def calcFibonacciLastDigit(n): if n &lt;= 1: return n a=0 b=1 for i in range(2,n+1): c = a+b if c &gt;= 10: #max value for c is 18 c -= 10 #so subtracting 10 will keep c as one digit a = b b = c return c print(calcFibonacciLastDigit(331)) #prints 9

http://stackoverflow.com/comment/87627431
comment on: http://stackoverflow.com/q/50305601
type: QuestionComment
has text: hmm I found this: https://stackoverflow.com/a/28609523/7757415
type: Comment
score: 0

http://stackoverflow.com/a/50316427
downvote count: 0
has body: Using a dict comprehension Ex: first={'a': '1000', 'b': '2000', 'c': '3000'} second={'a': '1000', 'b': '3000', 'c': '5000'} print(dict((k, second[k])for k in second if second[k] &gt; first[k])) Output: {'c': '5000', 'b': '3000'}
answers question: http://stackoverflow.com/q/50316414
type: Answer
has comment: http://stackoverflow.com/comment/87648624
has comment: http://stackoverflow.com/comment/87648749
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/87652347

http://stackoverflow.com/q/50277199
has title: Numpy compare array to multiple scalars at once
type: Question
tagged with: python
has body: Suppose I have an array a = np.array([1,2,3]) and I want to compare it to some scalar; this works fine like a == 2 # [False, True, False] Is there a way I can do such a comparison but with multiple scalars at once? The default behavior when comparing two arrays is to do an elementwise comparison, but instead I want each element of one array to be compared elementwise with the entire other array, like this: scalars = np.array([1, 2]) some_function(a, scalars) [[True, False, False], [False, True, False]] Obviously I can do this, e.g., with a for loop and then stacking, but is there any vectorized way to achieve the same result?
favorite count: 0
upvote count: 4
score: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/50277375
type: AnsweredQuestion
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50277375

http://stackoverflow.com/q/50260775
has comment: http://stackoverflow.com/comment/87541835
upvote count: 3
score: 3
has title: scipy.optimize.minimize -- how to specify bounds when one is a numpy array
favorite count: 0
type: Question
has body: I am running an optimization with scipy.optimize.minimize sig_init = 2 b_init = np.array([0.2,0.01,0.5,-0.02]) params_init = np.array([b_init, sig_init]) mle_args = (y,x) results = opt.minimize(crit, params_init, args=(mle_args)) The problem is, I need to set a bound on sig_init. But the opt.minimize() requires that I specify bounds for each of the input parameters. But one of my inputs is a numpy array. How can I specify the bounds given that one of my inputs is a numpy array?
has answer: http://stackoverflow.com/a/50275564
downvote count: 0
tagged with: python
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/50267622
type: Answer
score: 2
upvote count: 2
has body: Your dataset.append() method is appending the entire list into your list (making a list of lists). To append each item of the new list into the dataset (If I'm understanding you correctly) use += like so: dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0] this will result in a list like so: [0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
downvote count: 0
answers question: http://stackoverflow.com/q/50267427

http://stackoverflow.com/comment/87717028
has text: Can you show how you'd change the inner lists to tuples?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50350487

http://stackoverflow.com/q/50267803
tagged with: python
has answer: http://stackoverflow.com/a/50268118
tagged with: templates
has title: Error using DjangoFramework in template
type: AnsweredQuestion
score: 2
tagged with: django-templates
answer count: 3
upvote count: 2
tagged with: frameworks
possible better answer: http://stackoverflow.com/a/50268085
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50268085
favorite count: 0
has answer: http://stackoverflow.com/a/50268680
type: Question
has body: new try of dev here. Im trying to make a project and I alredy having some issues that i dont know why dont work... I put my code and explain it... url.py app_name = 'opotest' urlpatterns = [ url(r'^$', views.indexView, name='index'), url(r'^inicio/$', views.ListaView.as_view(), name='inicio'), url(r'^test/(?P<tipo>.+)/$', views.TestList.as_view(), name='test'), url(r'^test/(?P<tipo>.+)/run/$', views.TestDetail.as_view(), name='run'), # this one View.py class TestDetail(generic.DetailView): model = Pregunta context_object_name = 'lista' def get_queryset(self): return Pregunta.objects.all() HTML template {% for test in lista %} Pregunta: {{ pregunta.textopregunta }} {% endfor %} Models.py class Pregunta(models.Model): id = models.AutoField(primary_key=True) textopregunta = models.CharField('Texto pregunta', max_length=1000) test = models.ForeignKey(Test, on_delete=models.CASCADE) def __str__(self): return self.textopregunta This code should bring me some 'pregunta' that i have alredy created but it doesnt work... can you please tell me what im doing wrong? the for bring me Pregunta: the textopregunta do not appears... Thanks everyone D...
accepted answer: http://stackoverflow.com/a/50268118

http://stackoverflow.com/q/50275646
possible better answer: http://stackoverflow.com/a/52320299
tagged with: python
score: 15
tagged with: queue
accepted answer: http://stackoverflow.com/a/50275738
type: AnsweredQuestion
upvote count: 15
answer count: 2
has answer: http://stackoverflow.com/a/50275738
has body: I am building REST API with Flask-restplus. One of my endpoints takes a file uploaded from client and run some analysis. The job uses up to 30 seconds. I don't want the job to block the main process. So the endpoint will return a response with 200 or 201 right away, the job can still be running. Results will be saved to database which will be retrieved later. It seems I have two options for long-running jobs. Threading Task-queue Threading is relatively simpler. But problem is, there is a limit of thread numbers for Flask app. In a standalone Python app, I could use a queue for the threads. But this is REST api, each request call is independent. I don't know if there is a way to maintain a global queue for that. So if the requests exceed the thread limit, it won't be able to take more requests. Task-queue with Celery and Redis is probably better option. But this is just a proof of concept thing, and time line is kind of tight. Setting up Celery, Redis with Flask is not easy, I am having lots of trouble on my dev machine which is a Windows. It will be deployed on AWS which is kind of complex. I wonder if there is a third option for this case?
has title: How do I run background job in Flask without threading or task-queue
tagged with: multithreading
downvote count: 0
tagged with: flask
has answer: http://stackoverflow.com/a/52320299
tagged with: celery
favorite count: 0
type: Question

http://stackoverflow.com/a/76184457
has body: After doing this: Create autorun-file: 2.1 LXTerminal: cd /home/pi/.config/autostart 2.2 LXTerminal: sudo nano pythonscript.desktop 2.3 pythonscript.desktop: [Desktop Entry] Version=1.0 Name=YourName Comment=Your comment Exec=/home/pi/pythonscript.py -nograb #-nograb for comboBox on touch Screen Icon=/usr/share/pixmaps/python.xpm Path=/home/pi/ Terminal=false StartupNotify=true Type=Application Categories=Utility;Application;` I discovered that just this line was missing: chmod +x /home/pi/.config/autostart/pythonscript.desktop
score: 0
answers question: http://stackoverflow.com/q/50367837
type: Answer

http://stackoverflow.com/q/50334718
has title: Find boost_python version from setup.py
tagged with: boost-python
upvote count: 3
score: 3
tagged with: python
has body: I have developed a Python module using Boost Python. This extension has a setup.py file to install it. This file requests the extension to be linked against libboost_python by doing something like the following: my_module = Extension('_mymodule', files=... libraries=['boost_python'], ...) Recently, the boost developers seem to have changed the naming convention of Boost Python from naming the library libboost_python to naming it libboost_python27 (to reflect the fact that they were calling libboost_python3 the corresponding library for Python 3.x). What is the best way, from the setup.py script, to detect how the Boost Python library should be named (given that it is installed in a non-standard location)?
tagged with: c++
answer count: 0
type: UnansweredQuestion
tagged with: boost
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/50340463
has answer: http://stackoverflow.com/a/50340583
accepted answer: http://stackoverflow.com/a/50340583
has comment: http://stackoverflow.com/comment/87697437
has comment: http://stackoverflow.com/comment/97311080
downvote count: 0
has comment: http://stackoverflow.com/comment/87697080
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/97311262
possible better answer: http://stackoverflow.com/a/50340820
type: AnsweredQuestion
tagged with: performance
has comment: http://stackoverflow.com/comment/87697663
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/87697759
has comment: http://stackoverflow.com/comment/97310787
has comment: http://stackoverflow.com/comment/97310955
favorite count: 0
has body: I have the following dict: groups = {"group 1": [1, 2, 3, 4], "group 2": [5, 6, 7, 8], "group 3": [9, 10, 11, 12], "group 4": [13, 14]} When the length of a group is smaller than a minimum size (group_size=4), I want to redistribute the members to the other groups. The result in this case would be something like: groups = {"group 1": [1, 2, 3, 4, 13], "group 2": [5, 6, 7, 8, 14], "group 3": [9, 10, 11, 12]} I have the following code, which works, but is less efficient than I'd like: # Identify small groups small_groups = [] for group_name, group_members in groups.items(): if len(group_members) &lt; group_size: small_groups.append(group_name) # Redistribute members of small groups to the larger groups to_redistribute = [] for group_name in small_groups: to_redistribute.extend(groups.pop(group_name)) for group_name, group_members in groups.items(): if not to_redistribute: break group_members.append(to_redistribute.pop()) Important note: The real members of groups are strings, not integers. Is there a better way to redistribute dictionary value lists?
type: Question
has answer: http://stackoverflow.com/a/50340820
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87697980
has comment: http://stackoverflow.com/comment/87697067
answer count: 2
has comment: http://stackoverflow.com/comment/87697762
has title: Redistribute dictionary value lists

http://stackoverflow.com/q/50232385
has comment: http://stackoverflow.com/comment/87482129
has title: regular expressions: why '$' is not working with '\n'
has comment: http://stackoverflow.com/comment/87482754
score: 1
has comment: http://stackoverflow.com/comment/87482366
tagged with: python
has comment: http://stackoverflow.com/comment/87482657
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/87482844
linked to: http://stackoverflow.com/q/36696895
answer count: 0
has body: import re def ipv4_address(address): match = re.search(r"^((2[0-5][0-5]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(2[0-5][0-5]|1[0-9][0-9]|[1-9][0-9]|[0-9])$", address) if match: return True else: return False print(ipv4_address("127.0.0.1\n")) I don`t understand why '$' is not working with '\n' simpler test: &gt;&gt;&gt; bool(re.match("^ABC$","ABC\n")) True
has comment: http://stackoverflow.com/comment/87482970
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87482524
has comment: http://stackoverflow.com/comment/87482453
downvote count: 0
has comment: http://stackoverflow.com/comment/87482304
upvote count: 1
has comment: http://stackoverflow.com/comment/87482494
has comment: http://stackoverflow.com/comment/87482631
duplicate of: http://stackoverflow.com/q/36696895
favorite count: 0
linked to: http://stackoverflow.com/q/3462784
has comment: http://stackoverflow.com/comment/87482419
has comment: http://stackoverflow.com/comment/87482471

http://stackoverflow.com/q/50263518
answer count: 0
tagged with: seaborn
type: UnansweredQuestion
has title: change violinplot stick color in seaborn
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/87555037
tagged with: matplotlib
score: 1
has body: Id like to be able to change the color of individual sticks in seaborn's violin plot to highlight a specific datapoint. Any seaborn pros have ideas how to do this?
type: Question

http://stackoverflow.com/comment/87583943
comment on: http://stackoverflow.com/a/50283756
has text: I think I get it now, I tried to use this: https://stackoverflow.com/questions/21956683/enable-access-control-on-simple-http-server, however id did not work
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/50286297
type: Answer
accepted answer of: http://stackoverflow.com/q/50286190
score: 2
upvote count: 2
downvote count: 0
has body: The problem is here: line=','.join(r) print(line) write.writerow(line) The writerow method wants a list of columns. It will add the commas between the columns (and quote or escape anything that needs it, etc.). But you're not giving it a list of columns; you're giving it a single string. That's what ','.join(r) does: turns a list of columns into a single comma-separated string. When you give writerow a string, instead of a list of strings, it treats the string as a sequence of characters. (That's not specific to csv; in Python, a string is a sequence of characters.) So it treats each character as a column, and adds commas between them. Just do this: write.writerow(r)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87588690
answers question: http://stackoverflow.com/q/50286190

http://stackoverflow.com/a/50385360
type: Answer
answers question: http://stackoverflow.com/q/50370929
has comment: http://stackoverflow.com/comment/88030315
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50370929
has comment: http://stackoverflow.com/comment/88020782
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87786682
has body: Creating subfolders is possible using exchangelib, and your example should work. If you want to create a sub-subfolder, just use the subfolder as parent: subfolder = Folder(parent=account.inbox, name="subfolder_name") subfolder.save() subsubfolder = Folder(parent=subfolder, name="subsubfolder_name") subsubfolder.save()
score: 1
has comment: http://stackoverflow.com/comment/88029989

http://stackoverflow.com/a/50257103
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50241587
type: Answer
has body: I see that John answered your question. I dont know all the details of what you are doing, so you may have a reason for looping, but I wanted to suggest an alternative implementation that didn't require looping K times if all you want is the final answer: def rotate_array(A,K): A_length = len(A) B = [None] * A_length for A_index in range(len(A)): B_index = (A_index + K) % A_length B[B_index] = A[A_index] return(B) A = list(range(10)) print("A = ", A) for K in range(10): B = rotate_array(A,K) print("K = ",K, "B = ", B) A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] K = 0 B = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] K = 1 B = [9, 0, 1, 2, 3, 4, 5, 6, 7, 8] K = 2 B = [8, 9, 0, 1, 2, 3, 4, 5, 6, 7] K = 3 B = [7, 8, 9, 0, 1, 2, 3, 4, 5, 6] K = 4 B = [6, 7, 8, 9, 0, 1, 2, 3, 4, 5] K = 5 B = [5, 6, 7, 8, 9, 0, 1, 2, 3, 4] K = 6 B = [4, 5, 6, 7, 8, 9, 0, 1, 2, 3] K = 7 B = [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] K = 8 B = [2, 3, 4, 5, 6, 7, 8, 9, 0, 1] K = 9 B = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

http://stackoverflow.com/a/50577801
answers question: http://stackoverflow.com/q/50255983
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: After many tests I found out that the program is working also in other PC after declaring some objects like function parameters and after compiling running the program as compatible with Windows 7. Before the objects were created like variables and those variables were passed as parameters, (in this case, reasonably the first thought is that the problem is "pass by reference" mechanism and that some values are not inserted in the right mode, but this is not the case because: - the same exactly code did function very well in most PC (compatibility problem) - the same exactly mechanism is used to specify the objects attributes and to make calculations In this conditions I would say that it is not clear where the problem was. In the first version installing the SQL Server Express made possible for the program to work well even without last modifications.
accepted answer of: http://stackoverflow.com/q/50255983
type: Answer

http://stackoverflow.com/comment/87776560
score: 0
type: Comment
has text: Nice solution. But why would we need to encapsulate the chain iterable to a list?
type: AnswerComment
comment on: http://stackoverflow.com/a/50379990

http://stackoverflow.com/a/50262705
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50262652
downvote count: 0
has body: You're printing the dictionary on each iteration, rather than the new item to the dictionary on each iteration. You could either do: for line in lines: # &lt;snip&gt; newgtdict[str(filePath)+str(linenumber)] = box print box or for line in lines: # &lt;snip&gt; newgtdict[str(filePath)+str(linenumber)] = box # don't print here for line in newgtdict: print(line) Do note that you're not using an OrderedDict, which you should (if you want ordered results in versions of Python earlier than 3.7) newgtdict = collections.OrderedDict() # rather than = {}
has comment: http://stackoverflow.com/comment/87543871
score: 3
has comment: http://stackoverflow.com/comment/87543654
has comment: http://stackoverflow.com/comment/87543802
type: Answer
has comment: http://stackoverflow.com/comment/87543514
has comment: http://stackoverflow.com/comment/87543565
answers question: http://stackoverflow.com/q/50262652
upvote count: 3
has comment: http://stackoverflow.com/comment/87543892
has comment: http://stackoverflow.com/comment/87543546
has comment: http://stackoverflow.com/comment/87543726

http://stackoverflow.com/a/50316389
type: Answer
has body: So I havd come up with an answer: def non_unique(data): tempLst = [] for letter in data: if type(letter) == type('a'): if letter.lower() in tempLst or letter.upper() in tempLst: tempLst.append(letter) elif data.count(letter.lower()) + data.count(letter.upper()) &gt; 1: tempLst.append(letter) else: if data.count(letter) &gt; 1: tempLst.append(letter) return tempLst If anyone has a shorter version please comment :)
answers question: http://stackoverflow.com/q/50316132
score: 0

http://stackoverflow.com/comment/87581057
score: 0
comment on: http://stackoverflow.com/q/50281723
type: Comment
has text: Sure. Update your question.
type: QuestionComment

http://stackoverflow.com/a/50335246
upvote count: 1
has comment: http://stackoverflow.com/comment/87687354
has comment: http://stackoverflow.com/comment/87687175
score: 1
answers question: http://stackoverflow.com/q/50335016
downvote count: 0
has body: You could do this just to avoid writing out self every time. However, it could also be that there is a more important reason to do this: it could completely change the semantics. Example: def __init__(self, x): self.x = 42 def theMethod(self): x = self.x self.x = 58 print(x) print(self.x) In this example, x and self.x are not interchangeable, even though you have assigned x = self.x in the first line of theMethod. The first print will output 42, the second print will output 58. This can happen every time that some member variable is assigned to a local variable and then overridden. How this impacts performance is not entirely obvious, because both lookups self.x and x will have to look for the symbol in a dictionary: in the first case, the dictionary of the member variables of self, in the second case, in the current scope. It could impact the performance both positively and negatively, depending on how many and what other variables are defined in each scope. In most non-contrived cases, it could have a tiny positive effect on performance. EDIT: As @zvone has pointed out, the last paragraph does not necessarily hold for all implementations of the python interpreter.
has comment: http://stackoverflow.com/comment/87687101
has comment: http://stackoverflow.com/comment/87687159
has comment: http://stackoverflow.com/comment/87687230
type: Answer

http://stackoverflow.com/q/50287930
has comment: http://stackoverflow.com/comment/87591936
tagged with: distribution
score: 0
answer count: 0
has title: how to split data not normally distributed into some samples that should be normally distributed
has body: when I plot my data (vector of 1000 elements or more) I get something not normally distributed. however I believe that I can divide the data into smaller sets which are normally distributed. I am not sure how I can do it in python or what the fitting criteria should be! Any Advice please?
has comment: http://stackoverflow.com/comment/87591932
type: Question
has comment: http://stackoverflow.com/comment/87591868
has comment: http://stackoverflow.com/comment/87592081
has comment: http://stackoverflow.com/comment/87606491
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/50378782
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has title: `TooManyRedirects` with `pipenv lock` and `pipenv install`
type: Question
tagged with: pipenv
has body: An exception is being raised for pipenv lock and pipenv install commands which indicates that too many requests are being performed. Locking [dev-packages] dependencies… ", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python3.6/site-packages/pipenv/vendor/requests/sessions.py", line 617, in send history = [resp for resp in gen] if allow_redirects else [] File "/usr/lib/python3.6/site-packages/pipenv/vendor/requests/sessions.py", line 617, in &lt;listcomp&gt; history = [resp for resp in gen] if allow_redirects else [] File "/usr/lib/python3.6/site-packages/pipenv/vendor/requests/sessions.py", line 110, in resolve_redirects raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp) requests.exceptions.TooManyRedirects: Exceeded 30 redirects. Related: pip upgrade TooManyRedirects exception python3.6 -m virtualenv test_me fails error 400
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50378783
tagged with: python
linked to: http://stackoverflow.com/q/49862266
linked to: http://stackoverflow.com/q/49860980

http://stackoverflow.com/comment/87773149
comment on: http://stackoverflow.com/q/50378491
has text: pyperclip module?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50340583
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/50340463
has body: Your solution is good, but you can combine the pop and re-distribution logic together using itertools.cycle. from itertools import cycle for k in list(groups.keys()): if len(groups[k]) &lt; group_size: for v, k_ in zip(groups.pop(k), cycle(groups.keys())): groups[k_].append(v) The idea is to keep cycling through keys to re-distribute the data equally. It determines—at each iteration—whether a group is over the threshold or not. If a group is valid, then augmenting it later (via re-distribution) will never bring it under the threshold. However groups that are initially under the threshold (but are not reached until later during future iterations) can possibly become valid if and when you augment values to it from another group that was removed. If that does not happen, then it will be removed and its data redistributed on a future iteration. Keep in mind, groups that were initially slated for removal may now become valid after redistribution, so our solutions will differ in the output for some inputs. print(groups) {'group 1': [1, 2, 3, 4, 13], 'group 2': [5, 6, 7, 8, 14], 'group 3': [9, 10, 11, 12]}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87697841
has comment: http://stackoverflow.com/comment/87697885
has comment: http://stackoverflow.com/comment/87697907
type: Answer
has comment: http://stackoverflow.com/comment/87697818
accepted answer of: http://stackoverflow.com/q/50340463

http://stackoverflow.com/comment/87589320
comment on: http://stackoverflow.com/q/50257687
type: Comment
type: QuestionComment
score: 0
has text: Any feedback on the updated solutions?

http://stackoverflow.com/a/50251486
answers question: http://stackoverflow.com/q/50251417
has comment: http://stackoverflow.com/comment/87520253
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50251417
type: AcceptedAnswer
score: 2
type: Answer
has body: You need to call data = [r for r in reader] after csv.reader, if there's a header call header = next(reader)

http://stackoverflow.com/comment/87516429
score: 0
comment on: http://stackoverflow.com/q/50234680
has text: Hi as you suggest I imported file in **view.py** file. but it give me error my code in `python_code` folder and script name is `myscript`. I created small function call `run` in it so I am calling that function. `from python_code.myscript import run` `ModuleNotFoundError: No module named 'python_code'`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87569490
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50275969
has text: @splinter Cool! That solves it. I understand it now. I tried to put everything as a parameter, could've used `return`. Thanks!
type: Comment

http://stackoverflow.com/comment/87675390
type: AnswerComment
comment on: http://stackoverflow.com/a/50311771
has text: Additionally, discussing weights in terms of standard deviations makes them equally understood in many different experimental contexts precisely *because* the weights would then be dimensionless.
type: Comment
score: 0

http://stackoverflow.com/q/50301837
answer count: 1
has comment: http://stackoverflow.com/comment/87620215
type: Question
has answer: http://stackoverflow.com/a/50301908
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87620456
tagged with: performance
type: UnansweredQuestion
has body: I have the a script similar to this: import random import pandas as pd FA = [] FB = [] Value = [] df = pd.DataFrame() df_save = pd.DataFrame(index=['min','max']) days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] numbers = list(range(24)) # FA.unique() mix = '(pairwise combination of days and numbers, i.e. 0Monday,0Tuesday,...1Monday,1Tuesday,....)' 'I dont know how to do this combination btw' def Calculus(): global min,max min = df['Value'][boolean].min() max = df['Value'][boolean].max() for i in range(1000): FA.append(random.randrange(0,23,1)) FB.append(random.choice(days)) Value.append(random.random()) df['FA'] = FA df['FB'] = FB df['FAB'] = df['FA'].astype(str) + df['FB'].astype(str) df['Value'] = Value mix_factor = df['FA'].astype(str) + df['FB'].astype(str) for i in numbers: boolean = df['FA'] == i Calculus() df_save[str(i)] = [min,max] for i in days: boolean = df['FB'] == i Calculus() df_save[str(i)] = [min,max] for i in mix_factor.unique(): boolean = df['FAB'] == i Calculus() # df_save[str(i)] = [min,max] My question is: there is another way to do the same but more time efficiently? My real data (df in this case) is a csv with millions of rows and this three loops are taking forever. Maybe using 'apply' but I never have worked with it before. Any insight will be very appreciate, thanks.
has comment: http://stackoverflow.com/comment/87620599
tagged with: python
has comment: http://stackoverflow.com/comment/87620626
tagged with: apply
score: 0
tagged with: pandas
has title: Time efficiency by eliminating three for loops

semaphore
type: Tag
tags question: http://stackoverflow.com/q/50379009
tag name: semaphore

http://stackoverflow.com/a/50358229
upvote count: 1
score: 1
type: Answer
has body: def find_index(): idxs = [l2.index(i) for i in set(l1).intersection(set(l2))] idxs.sort() idxs+= [len(l2)+1] res = {l2[idxs[i]]: list(l2[idxs[i]+1: idxs[i+1]]) for i in range(len(idxs)-1)} return(res) Comparison of methods, using justengel's test: justengel run_comp: .455 run_other: .244 mkrieger1 group_by_keys: .160 me find_index: .068 Note that my method ignores keys that don't appear l2, and doesn't handle cases where keys appear more than once in l2. Adding in empty lists for keys that don't appear in l2 can be done by {**res, **{key: [] for key in set(l1).difference(set(l2))}}, which raises the time to .105.
answers question: http://stackoverflow.com/q/50350456
downvote count: 0

http://stackoverflow.com/comment/87493404
score: 0
comment on: http://stackoverflow.com/q/50237688
type: Comment
has text: I'm getting: TypeError: unhashable type: 'list'
type: QuestionComment

http://stackoverflow.com/q/50243600
type: Question
has comment: http://stackoverflow.com/comment/87507021
has comment: http://stackoverflow.com/comment/87523682
tagged with: sas
has comment: http://stackoverflow.com/comment/87506079
answer count: 0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/95273596
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87508288
downvote count: 0
has comment: http://stackoverflow.com/comment/87507789
has title: Loading large SAS file in R gives "Error: cannot allocate vector of size 109.3 Mb"
has comment: http://stackoverflow.com/comment/87506558
has comment: http://stackoverflow.com/comment/87506066
has comment: http://stackoverflow.com/comment/87508858
has comment: http://stackoverflow.com/comment/87504904
favorite count: 0
has comment: http://stackoverflow.com/comment/87543291
tagged with: http://stackoverflow.com/tag/r
tagged with: pandas
has comment: http://stackoverflow.com/comment/87505754
has comment: http://stackoverflow.com/comment/87507781
has comment: http://stackoverflow.com/comment/87504969
has body: Issue I have an 11.3GB SAS file (mydata.sas7bdat, see Sidenote #1 below) that I wanted to load with the sas7bdat package in R, but I get: Error: cannot allocate vector of size 109.3 Mb. Using RStudio, which tries to import the file with haven, I also get: Is this a valid SPSS, SAS or STATA file? Evaluation error: cannot allocate vector of size 109.3 Mb. I have also tried using pandas in Python with the similar outcome of memory running out. Sidenotes 1) mydata.sas7bdat is a merger of file1, file2, file3, and file4. 2) I am using a computer with Win10 x64, 32GB RAM, and all unnecessary apps and processes closed. 3) I cannot get the data file in a truncated or alternate file format (eg, CSV)
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/87537228
has comment: http://stackoverflow.com/comment/87506916

http://stackoverflow.com/comment/87638489
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50311057
has text: @chepner, The top answer on the duplicate has an explanation at the end that discusses why you end up with the same value.

http://stackoverflow.com/comment/87749279
type: QuestionComment
score: 0
has text: Babel claims to follow the rules from http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns. I don't see any mentioning there that the mantissa is *not* localized; quite to the contrary, it explicitely mentions using a localized plus sign, which would indicate to me that localization still happens.
type: Comment
comment on: http://stackoverflow.com/q/50365433

http://stackoverflow.com/a/50345196
has body: Passing a variable from one function to another function and changing it there does not update it in the original function. Since you are passing player_score from game_screen() to question1(), update it in question1() and then call draw_score() with this updated value, you see the change for a moment, but player_score value doesn't get updated in your source function game_screen(), so in next call you again pass the original value and not the updated one. One solution is to use global variable, but global variables are not recommended. You could try something like this (I am describing an idea instead of updating your code): def game_screen(): player_score = 25 # your start score. while True: # receive question score here, update player's score and display it. question_score = question1() player_score += question_score draw_score(player_score) def question1(): # return question score from here regardless of player's current score. if correct_answer: return 1 # or return your value for correct answer else: return -1 # or return your value for incorrect answer def draw_score(score): # your draw logic here.
has comment: http://stackoverflow.com/comment/87739704
has comment: http://stackoverflow.com/comment/87739379
type: Answer
has comment: http://stackoverflow.com/comment/87739382
answers question: http://stackoverflow.com/q/50341569
score: 0

http://stackoverflow.com/comment/87649977
type: AnswerComment
comment on: http://stackoverflow.com/a/50316872
has text: so `sorted()` is a reason to install Pandas?
type: Comment
score: 0

http://stackoverflow.com/comment/87490523
type: QuestionComment
score: 0
has text: @Evhz `MyDjangoEnv) MacBook-Pro:firstProject eLmaesTro$ which python` `/Users/eLmaesTro/anaconda3/envs/MyDjangoEnv/bin/python` `(MyDjangoEnv) MacBook-Pro:firstProject eLmaesTro$ which pip` `/Users/eLmaesTro/anaconda3/envs/MyDjangoEnv/bin/pip`
comment on: http://stackoverflow.com/q/50236442
type: Comment

http://stackoverflow.com/comment/87486488
score: 0
comment on: http://stackoverflow.com/q/50234541
type: QuestionComment
type: Comment
has text: What do you mean by `but obviously I have to do some things more in order to call the GCP Vision API on Heroku and do the same task`? You need to provide us with more information. What is the error you're getting? Do you just mean you have to switch to relative pathing for the location of your Google Credentials config file?

http://stackoverflow.com/a/50241875
has body: You have a different file called inspect.py on your path, and that's the one being imported. Add import inspect print(inspect.__file__) to the start of your program to help find this. By itself, this is a duplicate of lots of questions. What's interesting about yours is that the redirect is changing the path. If we add print(sys.path[:3]) to an import of fs.sshfs after creating a local inspect.py, I get: (36) dsm@winter:~/coding$ python &lt;(cat tump.py) /home/dsm/sys/miniconda3/envs/36/lib/python3.6/inspect.py ['/dev/fd', '/home/dsm/sys/miniconda3/envs/36/lib/python36.zip', '/home/dsm/sys/miniconda3/envs/36/lib/python3.6'] (36) dsm@winter:~/coding$ python tump.py /home/dsm/coding/inspect.py ['/home/dsm/coding', '/home/dsm/sys/miniconda3/envs/36/lib/python36.zip', '/home/dsm/sys/miniconda3/envs/36/lib/python3.6'] Traceback (most recent call last): File "tump.py", line 6, in &lt;module&gt; from fs.sshfs import SSHFS [...] AttributeError: module 'inspect' has no attribute 'getmro' and the reason the file descriptor version works is because the effective "local" path is now /dev/fd and not /home/dsm/coding, and /dev/fd doesn't contain the inspect.py collision. There will be minor differences (I'm using 3.6, etc.) but probably this is the same cause.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50241728
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50241728
score: 1

http://stackoverflow.com/q/50314777
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50314796
has body: I kept the module pickle in my directory. Now, I want to store the variable i.e. Arpan in a created file called spdict.data So, when i enter the code as follows: import pickle Arpan = "My name is Arpan" fh = open("spdict.data","w") pickle.dump(Arpan,fh) fh.close() I would expect the variable Arpan to get stored, but I get the following error. Traceback (most recent call last): File "C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py", line 173, in pickle.dump(Arpan,fh) TypeError: write() argument must be str, not bytes Also, when I enter the program import pickle Arpan = {"One":1,"Two":2,"Three":3} fh = open("spdict.data","w") pickle.dump(Arpan,fh) fh.close() Then also, following error comes: Traceback (most recent call last): File "C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py", line 173, in pickle.dump(Arpan,fh) TypeError: write() argument must be str, not bytes Please help.. My python version is 3.6.4
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13906623
tagged with: python
score: -1
has title: Pickle: Storing the contents of variable
duplicate of: http://stackoverflow.com/q/13906623
upvote count: 0
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/87732779
comment on: http://stackoverflow.com/q/50357504
has text: I was indeed asking why my model was not learning. Milind below answered the question. I added his suggestion, still do see not much learning, but this might have to do with the data. I have no experience in order to estimate what to expect in terms improvement in Loss and Accuracy.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87609854
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50288355
has text: @ArashMousavi add the code of `TimesheetForm` to the question. But it looks a design flaw for the way you need to bubble up those form errors.

http://stackoverflow.com/comment/87721755
type: QuestionComment
has text: @Some programmer dude he said his compiler suggested him to use `lu`, so I think it's clear he is using the `UINT` from the library.
comment on: http://stackoverflow.com/q/50352528
type: Comment
score: 0

http://stackoverflow.com/comment/87598838
comment on: http://stackoverflow.com/a/50290340
score: 0
type: Comment
has text: @Dhouha Marks the answer as correct or vote it if it was useful, please. Thanks
type: AnswerComment

http://stackoverflow.com/a/50322631
accepted answer of: http://stackoverflow.com/q/50322197
has body: The utility of partial is to easily create specialised versions of functions from a general definition. The case of adding numbers can be illustrating here add_numbers is the general case. from functools import partial def add_numbers(x, y): return x + y add5 = partial(add_nums, 5) Here add5 is a specialised case of add_numbers roughly equivalent to def add5(x): return add_numbers(x, 5) Adding numbers is a very trivial example and does not show the utility of partial The following is a simple example that may better show the utility of partial. Consider writing a procedure to compute the square root of a number using the Babylonian method. def square_root(x, tolerance, convergence_test): y = 1 while not convergence_test(x, y, tolerance): y = (y + x/y)/2 return y For most numbers, the convergence test can simply check the difference between y squared and x is 0. Let's call this the absolute error of the estimate def absolute_error(x, y, tolerance): return abs(x - y**2) &lt;= tolerance For very large and small numbers, using absolute error of the estimate can lead to wrong answers for various reasons. In those cases, it is better to use the relative error: def relative_error(x, y, tolerance): return abs(x/(y**2) - 1) &lt;= tolerance With partial, we can easily create specialised functions for using the either absolute and relative error. sqrt_rel_err = partial(square_root, convergence_test=relative_error) sqrt_abs_err = partial(square_root, convergence_test=absolute_error) Now using either is trivial &gt;&gt;&gt; sqrt_rel_err(2, 0.00001) 1.4142156862745097 &gt;&gt;&gt; sqrt_abs_err(2, 0.00001) 1.4142156862745097 And for small numbers: we see using absolute error gives the wrong answer (especially when the tolerance is greater than the number we are trying to get the square root of) &gt;&gt;&gt; x = sqrt_abs_err(1e-6, 0.00001) &gt;&gt;&gt; x**2 4.4981362843183905e-06 Whilst the relative error method yields a more accurate answer. &gt;&gt;&gt; x = sqrt_rel_err(1e-6, 0.0…
type: Answer
answers question: http://stackoverflow.com/q/50322197
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87584591
type: Comment
comment on: http://stackoverflow.com/q/50272689
type: QuestionComment
has text: Have you seen this: https://stackoverflow.com/questions/49482417/how-to-solve-a-notimplementederror-from-nltk-classify-classifieri/49483816#49483816 ?
score: 0

http://stackoverflow.com/comment/87785195
has text: try `f.write(bytearray(9153-3183))`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50384713
score: 0

http://stackoverflow.com/q/50364766
score: 7
has answer: http://stackoverflow.com/a/50580199
favorite count: 0
has body: I want to write an application which is portable. With "portable" I mean that it can be used to access these storages: amazon s3 google cloud storage Eucalyptus Storage The software should be developed using Python. I am unsure how to start, since I could not find a library which supports all three storages.
has comment: http://stackoverflow.com/comment/88166572
type: Question
possible better answer: http://stackoverflow.com/a/50364799
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/88114041
has answer: http://stackoverflow.com/a/50364799
tagged with: python
has comment: http://stackoverflow.com/comment/87745912
accepted answer: http://stackoverflow.com/a/50444948
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/50444948
type: AnsweredQuestion
has title: Portable application: s3 and Google cloud storage
answer count: 3
tagged with: portability
downvote count: 0
upvote count: 7

http://stackoverflow.com/comment/87602702
comment on: http://stackoverflow.com/a/50291808
has text: I can't get your code to run in 2.7 without commenting out the winfo_children line out (no window appears) but not sure if this sheds any light on it but if you define an intvar outside of the class and pass it into MainFrames init it works then the checkbox then gets checked but I want the row class to contain the intvar as I want a method to report on the state of the row per row - if that makes sense
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87753008
comment on: http://stackoverflow.com/q/50356795
has text: I suspect that the"missing" x,y values have y=0, which then becomes a NaN when you log-transform the data. NaNs are ignored in plotting with matplotlib. We would need to see the whole data files to check, though.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50378669
accepted answer of: http://stackoverflow.com/q/50377124
has comment: http://stackoverflow.com/comment/87776656
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87776493
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50377124
has body: Yeah it appears that @skrx is correct, there's something blocking by not clearing the event buffer. This code works for me: import pygame pygame.init() gameDisplay = pygame.display.set_mode((400, 433)) pygame.display.set_caption('Pac Man') clock = pygame.time.Clock() background = pygame.image.load('/Path/To/Background.png') gameDisplay.blit(background, (100, 0)) run = True while run: for e in pygame.event.get(): if e.type == pygame.QUIT: run = False gameDisplay.blit(background, (0, 0)) pygame.display.update() pygame.quit() quit()
type: Answer

http://stackoverflow.com/comment/87621348
score: 0
has text: Sorry, hit enter too soon. So, as @PanagiotisKanavos says above, why not use `pyodbc`. E.g. you open the `json` file in python, parses out the data you want to insert into the table and use the various `pyodbc` commands to insert the data.
type: QuestionComment
comment on: http://stackoverflow.com/q/50296126
type: Comment

http://stackoverflow.com/a/50258327
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87551536
has body: Here's another "manual" way using only numpy: org_arr = np.array(org) key1 = np.unique(org_arr[:,0]) key2 = np.unique(org_arr[:,1]) values = org_arr[:,2].reshape((len(key1),len(key2))).transpose() np.block([ ["\t", key1 ], [key2[:,None], values] ]) """ # alternatively, for numpy &lt; 1.13.0 np.vstack(( np.hstack(("\t", key1)), np.hstack((key2[:, None], values)) )) """ For simplicity, it requires the input matrix to be strictly ordered (first col is major and ascending ...). Output: Out[58]: array([['\t', 'A', 'B', 'C'], ['a', '1', '4', '7'], ['b', '2', '5', '8'], ['c', '3', '6', '9']], dtype='&lt;U1')
has comment: http://stackoverflow.com/comment/87551393
has comment: http://stackoverflow.com/comment/87548865
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/50256984

http://stackoverflow.com/q/50260449
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87575197
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87538905
tagged with: python
has title: No module named Crypto error when trying to calculate / verify signature
has comment: http://stackoverflow.com/comment/87539157
answer count: 0
has body: from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 message = "I want this stream signed" digest = SHA256.new() digest.update(message) # Read shared key from file private_key = False with open ("private_key.pem", "r") as myfile: private_key = RSA.importKey(myfile.read()) # Load private key and sign message signer = PKCS1_v1_5.new(private_key) sig = signer.sign(digest) # Load public key and verify message verifier = PKCS1_v1_5.new(private_key.publickey()) verified = verifier.verify(digest, sig) assert verified, 'Signature verification failed' print('Successfully verified message') I have been trying example code but it makes a mistake when i upload Crypto libraries . I'm using Python 3.6 The error is: from Crypto.Hash import SHA256 ModuleNotFoundError: No module named 'Crypto'
downvote count: 0
tagged with: cryptography
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/87539266
has comment: http://stackoverflow.com/comment/87539139

http://stackoverflow.com/q/50235020
has comment: http://stackoverflow.com/comment/87487494
has comment: http://stackoverflow.com/comment/87487409
has answer: http://stackoverflow.com/a/50235641
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87487827
answer count: 2
upvote count: 2
has body: I'm new to the world of Python. My question is what is the best way (if any way is already done without doing it by hand) to perform validations of object attributes in Python. The task is that when I receive data coming to me in a JSON from the client (for example an HTTP request to create an article), I want to check that this data is good (It is not a string when it should be an int (age), etc). I have an object, and the object has the field age, i don't want to do this always. I want somethig that do it for me. if age &gt;= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") I've looked for several things but I can't find a good module or library to perform this important validation task. If anyone knows one with good documentation or shows an example, it would be appreciated.
tagged with: validation
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87487588
has comment: http://stackoverflow.com/comment/87487443
tagged with: python
has title: JSON Data validation in python
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/50235610
score: 1
linked to: http://stackoverflow.com/q/5142418

http://stackoverflow.com/comment/87653354
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50318618
type: Comment
has text: I need to use cookie

http://stackoverflow.com/comment/87738829
has text: @Wen Thank you so much! Worked out seamlessly, idk why the operation that seems so simple won't come out from my head haha. Def need alot of practice
score: 0
comment on: http://stackoverflow.com/a/50360082
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50323240
has title: Getting flattened list of all values in dictionary
has comment: http://stackoverflow.com/comment/87662126
type: Question
linked to: http://stackoverflow.com/q/952914
has comment: http://stackoverflow.com/comment/87662150
duplicate of: http://stackoverflow.com/q/952914
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/87662156
score: 0
answer count: 0
has body: I have python dictionary like this: d = {1:['x','y'], 2: ['a','b']} I want to get all the values of dictionary. Doing d.values() gives me [['x', 'y'], ['a', 'b']] But I would like to have something like this - ['x', 'y', 'a', 'b'] How can I achieve this?

http://stackoverflow.com/comment/87749063
score: 0
type: Comment
has text: @wasp256 Also, could you please show the whole project structure? I'm pretty sure the problem is in your main `urls.py` (and the one you are showing seems to belong to one of the applications). My guess is that you either not including URLs of your application properly or adding a namespace to them.
comment on: http://stackoverflow.com/q/50365436
type: QuestionComment

selenium-webdriver
tags question: http://stackoverflow.com/q/50250580
tags question: http://stackoverflow.com/q/50271772
tags question: http://stackoverflow.com/q/50270576
tags question: http://stackoverflow.com/q/50348040
tags question: http://stackoverflow.com/q/50248876
tags question: http://stackoverflow.com/q/50287106
tags question: http://stackoverflow.com/q/50253744
tags question: http://stackoverflow.com/q/50315587
tags question: http://stackoverflow.com/q/50310148
tags question: http://stackoverflow.com/q/50243867
tags question: http://stackoverflow.com/q/50355120
tags question: http://stackoverflow.com/q/50351258
tags question: http://stackoverflow.com/q/50233072
tags question: http://stackoverflow.com/q/50339055
tags question: http://stackoverflow.com/q/50298553
tags question: http://stackoverflow.com/q/50317447
type: Tag
tags question: http://stackoverflow.com/q/50354157
tags question: http://stackoverflow.com/q/50354465
tags question: http://stackoverflow.com/q/50257491
tags question: http://stackoverflow.com/q/50337244
tags question: http://stackoverflow.com/q/50353960
tags question: http://stackoverflow.com/q/50353906
tags question: http://stackoverflow.com/q/50377687
tags question: http://stackoverflow.com/q/50324563
tags question: http://stackoverflow.com/q/50347024
tags question: http://stackoverflow.com/q/50253997
tags question: http://stackoverflow.com/q/50253037
tags question: http://stackoverflow.com/q/50340985
tags question: http://stackoverflow.com/q/50285863
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/50233004
tags question: http://stackoverflow.com/q/50294167
tags question: http://stackoverflow.com/q/50334940
tags question: http://stackoverflow.com/q/50269191

http://stackoverflow.com/comment/87571043
comment on: http://stackoverflow.com/a/50273675
type: Comment
has text: Thank you very much it is very interesting, Ok but if I am not wrong you are missing the min and max values `i_min = 0 i_max = 1` variables, they can be changed to anything else . in your idea you are assuming the upper and lower bounds 0-1
type: AnswerComment
score: 0

http://stackoverflow.com/q/50254450
accepted answer: http://stackoverflow.com/a/50254514
has answer: http://stackoverflow.com/a/50254514
possible better answer: http://stackoverflow.com/a/50254518
tagged with: list
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50254518
score: 0
has title: How to generate a 2D list which will contain numbers from 1..n without using numpy?
has body: The 2D list should be like this: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] I am unable to find the logic for this. I have done this using numpy's reshape function. But unable to do without numpy.
has answer: http://stackoverflow.com/a/50254577
has answer: http://stackoverflow.com/a/50254561
type: Question
has answer: http://stackoverflow.com/a/50254692
answer count: 5
tagged with: python

http://stackoverflow.com/a/50295014
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50282054
type: Answer
has body: Answer by OP, edited out of their question: Solution Here is an example for a solution based on Attersons answer. The scaling function was taken from this answer. from matplotlib import pyplot as plt def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0] # Actual data data = [20, 50, 100, 250, 600, 200, 150, 100, 40, 30, 25, 20] source_scale = (100, 600) # Scale values between 100 and 600 destination_scale = (100, 150) # to a scale between 100 and 150 # Apply scale to all items of data that are above or equal to 100 data_scaled = [x if x &lt; 100 else scale(x, source_scale, destination_scale) for x in data] # Set up a simple plot fig = plt.figure() ax = plt.Axes(fig, [0.,0.,1.,1.]) fig.add_axes(ax) # Set the y-ticks to a custom scale ax.set_yticks([0,20,40,60,80,100,110,120,130,140,150]) ax.set_ylim(0, 150) # Set the labels to the actual values ax.set_yticklabels(["0","20","40","60","80","100","200","300","400","500","600"]) ax.plot(data_scaled)

http://stackoverflow.com/comment/87595821
type: QuestionComment
type: Comment
has text: What scipy function? I don't see you making single call other than to `Series.unique()` and `list.append()`. And generally we pass a variable number of arguments using `func(*args)` or `func(*position_args, **keyword_args)`.
score: 0
comment on: http://stackoverflow.com/q/50289810

http://stackoverflow.com/comment/87700017
type: Comment
comment on: http://stackoverflow.com/a/50341713
type: AnswerComment
has text: When the script stopped after ten hours, I re-execute the script , can still be successful. At this point, the token didn't change.
score: 0

http://stackoverflow.com/a/50254176
downvote count: 2
upvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/87525754
has body: You could use a nested for loop: f = """ 3074 88, 3074 1935, 3478-3480 3074, 3478-3479 27015-27030, 27036-27037 4380, 27000-27031, 27036 """ l = [] for x in f.split('\n'): for y in x.split(','): l += [z.strip() for z in y.split('-')] for x in l: print(x) &gt;&gt; 3074 88 3074 1935 3478 3480 3074 3478 3479 27015 27030 27036 27037 4380 27000 27031 27036 Of course, if this is a file, use with open("filename.txt") as f: l = [] for row in f: for y in x.split(','): l += [z.strip() for z in y.split('-')]
type: Answer
answers question: http://stackoverflow.com/q/50254018

http://stackoverflow.com/comment/94323304
type: AnswerComment
has text: Thanks! @scanny, I add a textbox to the corner of a slide, then put the index number into it :-)
score: 0
comment on: http://stackoverflow.com/a/50279321
type: Comment

http://stackoverflow.com/comment/87647868
score: 0
has text: Ok in Jupyter the `print(df.head(10))` and then plot works fine but in PyCharm it is not
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50315791

http://stackoverflow.com/q/50328506
tagged with: python
possible better answer: http://stackoverflow.com/a/50328621
has comment: http://stackoverflow.com/comment/87673344
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87674313
answer count: 3
has answer: http://stackoverflow.com/a/50328646
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50328621
has comment: http://stackoverflow.com/comment/87674697
has comment: http://stackoverflow.com/comment/87673077
linked to: http://stackoverflow.com/q/26477866
accepted answer: http://stackoverflow.com/a/50328770
has comment: http://stackoverflow.com/comment/87674679
has title: Python, How long decimal point can a float have?
has body: I made a pi calculator. But it just corrects first 7 decimal points and starts returning the same results. By the look of the things it is about my float values getting bigger because I use a limit. But is there a limit for decimal numbers in python? I read some documents but there are numbers with even 100 decimal points but I can just get to 11. My code: import math import decimal import datetime sqrtt=1. sumn=0. tryc=0 outerrepeat=1000000000 while outerrepeat&gt;0: tryc+=1 repeat=10000000 a=datetime.datetime.now() print "\n&gt;&gt;&gt;Processing...\n" while repeat&gt;0: sumn+=1/(sqrtt**2) sqrtt+=1 repeat-=1 b=datetime.datetime.now() print "&gt;&gt;&gt;Process complete.\n" print "&gt;&gt;&gt;Calculate time: "+str(b-a) + " Try-" + str(tryc) +" "+ str(math.sqrt(sumn*6)) + "\n" outerrepeat-=1 print "\nThis is all I can do." May help: Running on IDLE. Calculation is done by basel problem. Always gets stuck at 3.14159264498. Also never gets further than 11 decimal points but sometimes gets lower. Should say that my limit (sqrtt) hits 8th power of 10 (Maybe lower but higher than 7th power of 10.) Thanks.
has answer: http://stackoverflow.com/a/50328770
has comment: http://stackoverflow.com/comment/87674470

http://stackoverflow.com/comment/87542712
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50251765
has text: Well i thought that iptables always tracked the state of every connection that is made, but i've done a bit of research now and that is not necessarily true. Anyway, i was trying to find a socket function that would drop the packet but i wasn't able to find one. maybe there isn't ?

http://stackoverflow.com/comment/87756638
has text: Yes, you have to define a url for that view
type: AnswerComment
comment on: http://stackoverflow.com/a/50369972
score: 0
type: Comment

http://stackoverflow.com/comment/87611279
type: AnswerComment
has text: what do you get when you run "python path/to/yourScript.py" through the code? as python environment variable set..
comment on: http://stackoverflow.com/a/50296668
score: 0
type: Comment

treeview
tags question: http://stackoverflow.com/q/50281987
tags question: http://stackoverflow.com/q/50319159
tags question: http://stackoverflow.com/q/50265479
tag name: treeview
type: Tag
tags question: http://stackoverflow.com/q/50270294

http://stackoverflow.com/q/50266675
answer count: 1
downvote count: 0
has title: calling python code inside rshiny for building simple interface
upvote count: 1
tagged with: python
has body: I have a certain python code(shared below) to display the similar descriptions as entered by the user(validation data) to the historical information. Now due to some reason, I want to use Rshiny to create a simple interface, which would take two fields such as: Enter the description: Enter the region: And gives me the similar text Code used is: new_description='EDAP Scenario is' from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() description_list=train_data['description'].unique().tolist() ##train_data has historical descriptions similar_description=[] for description in description_list: result=similar(new_description, description) if result &gt;=0.8: similar_CR.append(cr) Here the new_description which I have entered explicitly needs to be taken from the interface. I am very novice in R/Rshiny. Any help/starting point would be appreciated
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: shiny
score: 1
has answer: http://stackoverflow.com/a/50326081
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/107604374
type: AnswerComment
comment on: http://stackoverflow.com/a/50341395
has text: Can you explain why this works but a for loop does not?
score: 0
type: Comment

http://stackoverflow.com/a/50240895
upvote count: 1
has comment: http://stackoverflow.com/comment/87629492
answers question: http://stackoverflow.com/q/50240752
has comment: http://stackoverflow.com/comment/87601010
score: 1
has body: The model.fit_generator function call looks like this in the jupyter notebook: model.fit_generator(train_batches, steps_per_epoch=4, validation_data=valid_batches, validation_steps=4, epochs=5, verbose=2) You are passing the train_batches variable as a parameter. What does that look like? train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(224,224), classes=['dog', 'cat'], batch_size=10) That assignment is looking in the train_path location for images. train_path = 'cats-and-dogs/train' which is a relative path. Your error message says that it cannot find an image at the location 'D:\\PDF\\Train\\notfactors\\notfactors59.jpg which is not defined anywhere in the notebook provided in the link. Can you update your question and provide the values for the calls from the notebook you are using? It does not appear you are using the exact code in the notebook. That will help troubleshoot this further.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/88631804
score: 0
has text: Success! Thanks so much, this was the key. I added the full URL into `calendar.html` and the error disappeared. If you add this an an answer I will accept.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50336493

http://stackoverflow.com/comment/88080787
type: AnswerComment
has text: Just to let you know I've decided to give the full ammount of bounties to this answer to keep my promise (i'd reward the closest answer meeting all requirements), otherwise you'd only received half of bounties and that'd be quite sad as you've put a lot of effort. That said, I won't accept the answer as valid because what I've explained on my previous comments.
comment on: http://stackoverflow.com/a/50431088
score: 0
type: Comment

http://stackoverflow.com/comment/87551161
comment on: http://stackoverflow.com/a/50266619
type: Comment
has text: Changing the value is not making much of a difference, the output is still somewhere between 0.7 and 0.8
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87644886
comment on: http://stackoverflow.com/a/50313811
has text: @Joey Thank you so much. This is perfect for me. And thanks for explaining the concept as well
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/99884120
comment on: http://stackoverflow.com/a/53166037
type: AnswerComment
has text: @DaviWesley, you don't need that environment variable, but you should use this value in `EMAIL_HOST_PASSWORD`.
score: 1
type: Comment

http://stackoverflow.com/q/50242955
has comment: http://stackoverflow.com/comment/87531911
accepted answer: http://stackoverflow.com/a/59321214
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59321214
upvote count: 9
answer count: 1
tagged with: python-unittest
has body: I have a class, which use a class variable to choose which logic to execute. #in file1: class SomeHelper(): def __init__(self): self.my_var = 0 #in file2: import file1 class MyClass(): ... ... def calculate(): inst = file1.SomeHelper() if x &gt; inst.my_var: etc etc I am writing a unit test and mocking SomeHelper() in another file: from file 2 import MyClass # tried both @patch('file2.file1') OR @patch('file2.file1.SomeHelper') def test_calculate(self, mock_helper): mock_helper.my_var = 0 to_test = MyClass.calculate() And I get the following error: TypeError: '>' not supported between instances of 'MagicMock' and 'int'. I thought I defined my_var after I patched the module.
favorite count: 0
has comment: http://stackoverflow.com/comment/87528743
score: 9
type: Question
tagged with: magicmock
tagged with: mocking
has title: Comparing integer to MagicMock not working inside unittest in python
has comment: http://stackoverflow.com/comment/87503585
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/87687941
type: AnswerComment
has text: @Mrowkacala my code works for me. What User-Agent are you using in settings.py ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50321886

http://stackoverflow.com/q/50242939
tagged with: opencv
type: AnsweredQuestion
has body: Using Opencv to make a face recognition This is the code I am using to recognize faces in my webcam, but once the camera do not recognize a face, it is stopping to record and I want it countinuous. import cv2 import logging as log from time import sleep import datetime as dt import numpy as np cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) cam = cv2.VideoCapture(0); anterior = 0 log.basicConfig(filename='webcam.log',level=log.INFO) rec = cv2.face.LBPHFaceRecognizer_create(); rec.read('recognizer/trainningData.yml') id=0 font = cv2.FONT_HERSHEY_SIMPLEX fontscale = 1 fontcolor = (255,255,255) while(True): if not cam.isOpened(): print('Unable to load camera.') sleep(5) pass ret, img = cam.read(); gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1,minNeighbors=5,minSize=(30, 30)) for(x, y, w, h) in faces: cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0),2) id, conf = rec.predict(gray[y:y+h,x:x+w]) if(id == 1): id = "Nome do usuário detectado"; cv2.putText(img,str(id),(x,y-10),font,0.55,(0,255,0),1); cv2.imshow("Face", img); if(conf&lt;=20): if(id!=None): cv2.putText(img,str(id),(x,y-10),font,0.55,(0,255,0),1); else: cv2.putText(img,"Unknown",(x,y+h-10),font,0.55, (0,255,0),1); if anterior != len(faces): anterior = len(faces) log.info("ID: " + str(id) + " faces: "+str(len(faces))+" at "+str(dt.datetime.now())) if(cv2.waitKey(1)==ord('q')): break; cam.release() cv2.destroyAllWindows()
accepted answer: http://stackoverflow.com/a/50249280
answer count: 1
has title: Opencv face detection. The Video is not working when the face is not recognized. How do I make a continuous recording?
has answer: http://stackoverflow.com/a/50249280
downvote count: 1
tagged with: face-recognition
favorite count: 0
type: Question
upvote count: 0
tagged with: python
score: -1

http://stackoverflow.com/a/50328646
score: 1
has comment: http://stackoverflow.com/comment/87675499
downvote count: 0
has comment: http://stackoverflow.com/comment/87673623
has comment: http://stackoverflow.com/comment/87813240
has comment: http://stackoverflow.com/comment/87674410
upvote count: 1
has comment: http://stackoverflow.com/comment/87674432
has comment: http://stackoverflow.com/comment/87673233
has comment: http://stackoverflow.com/comment/87675363
has comment: http://stackoverflow.com/comment/87674342
has comment: http://stackoverflow.com/comment/87673804
type: Answer
has comment: http://stackoverflow.com/comment/87675225
has comment: http://stackoverflow.com/comment/87674207
has body: Python uses 64 bit floats which have 15 to 17 decimal digits of precision. Proof can be found here where we can see the python float value is stored as a C double (which is almost always a 64 bit floating point number). typedef struct { PyObject_HEAD double ob_fval; // this is the actual float value } PyFloatObject; You can use the decimal.Decimal object for infinite precision. An example with calculating e import decimal import math decimal.getcontext().prec = 100 # set the precision, can be as large as you like e = decimal.Decimal(0) next_e = decimal.Decimal('NaN') # init as not a number i = 0 while e != next_e: e, next_e = next_e, e + decimal.Decimal(1) / math.factorial(i) i += 1 e #--&gt; Decimal('2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166428')
answers question: http://stackoverflow.com/q/50328506
has comment: http://stackoverflow.com/comment/87673130

http://stackoverflow.com/q/50335782
has comment: http://stackoverflow.com/comment/87690110
possible better answer: http://stackoverflow.com/a/50335929
has comment: http://stackoverflow.com/comment/87690016
tagged with: dataframe
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50335929
type: AnsweredQuestion
has title: Compare values of a dictionary and return a count of matching values
downvote count: 0
answer count: 3
tagged with: pandas
tagged with: crosstab
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/50336510
has body: I have a dictionary comprised of product names and unique customer emails who have purchased those items that looks like this: customer_emails = { 'Backpack':['customer1@gmail.com','customer2@gmail.com','customer3@yahoo.com','customer4@msn.com'], 'Baseball Bat':['customer1@gmail.com','customer3@yahoo.com','customer5@gmail.com'], 'Gloves':['customer2@gmail.com','customer3@yahoo.com','customer4@msn.com']} I am trying to iterate over the values of each key and determine how many emails match in the other keys. I converted this dictionary to a DataFrame and got the answer I wanted for a single column comparison using something like this customers[customers['Baseball Bat'].notna() == True]['Baseball Bat'].isin(customers['Gloves']).sum() What I'm trying to accomplish is to create a DataFrame that essentially looks like this so that I can easily use it for correlation charts. Backpack Baseball Bat Gloves Backpack 4 2 3 Baseball Bat 2 3 1 Gloves 3 1 3 I'm thinking the way to do it is to iterate over the customer_emails dictionary but I'm not sure how you would pick out a single key to compare its values to all others and so on, then store it.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50336034
accepted answer: http://stackoverflow.com/a/50336034
has comment: http://stackoverflow.com/comment/87690048
has comment: http://stackoverflow.com/comment/87688347

http://stackoverflow.com/comment/87587959
score: 0
has text: @ChanchalDixit So you want each contour to have a unique number and store the corresponding coordinates of that contour as well?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50246672

http://stackoverflow.com/q/50276854
tagged with: python
has title: How to retrieve a listening history object by spotipy?
accepted answer: http://stackoverflow.com/a/50329969
type: AnsweredQuestion
tagged with: spotipy
has answer: http://stackoverflow.com/a/50329969
score: 2
tagged with: spotify
answer count: 1
downvote count: 0
has body: I'm working at a recommendation system for Spotify and I'm using spotipy on Python. I can't use the function current_user_recently_played, because Python says that the attribute current_user_recently_played isn't valid. I don't know how to solve this problem, I absolutely need of this information to continue with my work. This is my code: import spotipy import spotipy.util as util import json def current_user_recently_played(self, limit=50): return self._get('me/player/recently-played', limit=limit) token = util.prompt_for_user_token( username="212887@studenti.unimore.it", scope="user-read-recently-played user-read-private user-top-read user-read-currently-playing", client_id="xxxxxxxxxxxxxxxxxxxxxx", client_secret="xxxxxxxxxxxxxxxxxxxxxx", redirect_uri="https://www.google.it/") spotify = spotipy.Spotify(auth=token) canzonirecenti= spotify.current_user_recently_played(limit=50) out_file = open("canzonirecenti.json","w") out_file.write(json.dumps(canzonirecenti, sort_keys=True, indent=2)) out_file.close() print json.dumps(canzonirecenti, sort_keys=True, indent=2) and the response is: AttributeError: 'Spotify' object has no attribute 'current_user_recently_played'
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/50271165
has answer: http://stackoverflow.com/a/50271765
tagged with: time-series
downvote count: 0
possible better answer: http://stackoverflow.com/a/50271538
tagged with: python
has answer: http://stackoverflow.com/a/50271538
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87567923
has body: import pandas as pd mydate = ["01/01/2018","19/01/2018","24/01/2018" , "27/01/2018","29/01/2018","30/01/2018" , "22/02/2018","23/03/2018"] mydate = pd.to_datetime(mydate) events = ["a" , "b" , "c" , "d" , "e" , "f" ,"g" , "h"] df = pd.DataFrame({"date" :mydate,"events" :events}) df date events 0 2018-01-01 a 1 2018-01-19 b 2 2018-01-24 c 3 2018-01-27 d 4 2018-01-29 e 5 2018-01-30 f 6 2018-02-22 g 7 2018-03-23 h I want to slice data on every 20 days and store them in separate data frame. I have looked group-by , date_range and other functionality but could not find solution for my problem. I can do this using typical for loop but I am looking to do using some pandas functionality. Expected result df = [df1 , df2 , df3 , df4] where df1 contain row 0 ,1 df2 contains row 2,3,4,5 df3 contain row 6 df4 contain row 7
has answer: http://stackoverflow.com/a/50271992
answer count: 3
tagged with: pandas
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/50271992
has title: Split Single Pandas DataFrame into N DataFrame in Python using Time Series Data
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87559612

http://stackoverflow.com/comment/87633078
type: AnswerComment
has text: I do not know how `os.walk(path)` works, so I used `os.listdir`. I hope that figures it out for you.
comment on: http://stackoverflow.com/a/50308460
score: 0
type: Comment

http://stackoverflow.com/q/50380800
accepted answer: http://stackoverflow.com/a/50380853
has comment: http://stackoverflow.com/comment/87777931
tagged with: numbers
has comment: http://stackoverflow.com/comment/87778020
has comment: http://stackoverflow.com/comment/87777950
has answer: http://stackoverflow.com/a/50380853
has answer: http://stackoverflow.com/a/50380998
has comment: http://stackoverflow.com/comment/87777793
tagged with: python
has title: Python:Find if all elements in lists are the same except exactly 2 numbers
has comment: http://stackoverflow.com/comment/87777852
possible better answer: http://stackoverflow.com/a/50380845
has comment: http://stackoverflow.com/comment/87777786
tagged with: int
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/50380845
answer count: 3
has body: I wonder how to check if two lists of numbers are the same except exactly 2 numbers if list1 == list2: # + except 2 numbers
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87789779
has comment: http://stackoverflow.com/comment/87777809
favorite count: 0
type: Question

http://stackoverflow.com/q/50356688
upvote count: 3
answer count: 1
tagged with: python
tagged with: scipy
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50356712
downvote count: 0
has body: I have this pandas dataframe containing two samples X and Y for each row: import pandas as pd import numpy as np df = pd.DataFrame({'X': [np.random.normal(0, 1, 10), np.random.normal(0, 1, 10), np.random.normal(0, 1, 10)], 'Y': [np.random.normal(0, 1, 10), np.random.normal(0, 1, 10), np.random.normal(0, 1, 10)]}) I want to use a function ttest_ind() (a statistical test taking two samples as input) on each row, and take the first element of the response (the function returns two elements): If I do it for a given row, e.g. 1st row, it works: from scipy import stats stats.ttest_ind(df['X'][0], df['Y'][0], equal_var = False)[0] # Returns a float However, if I use apply to do it on each row, I get an error: df.apply(lambda x: stats.ttest_ind(x['X'], x['Y'], equal_var = False)[0]) # Throws the following error: Traceback (most recent call last): File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item TypeError: an integer is required During handling of the above exception, another exception occurred: ... KeyError: ('X', 'occurred at index X') What am I doing wrong?
has answer: http://stackoverflow.com/a/50356712
has title: Function works on each row of data frame, but not using df.apply
type: AnsweredQuestion
score: 3
tagged with: pandas

http://stackoverflow.com/comment/87649218
type: Comment
comment on: http://stackoverflow.com/q/50316521
score: 0
type: QuestionComment
has text: What you are trying to achieve with `int(ipaddress.ip_address(my_net[i]))` in the first place. Why not just use `s.connect((my_net[i],port))` since `my_net[i] is already the IP address you want to use.

http://stackoverflow.com/comment/87759133
score: 1
comment on: http://stackoverflow.com/q/50367656
type: Comment
type: QuestionComment
has text: What is your question?

apache-spark
tags question: http://stackoverflow.com/q/50306421
tags question: http://stackoverflow.com/q/50321549
tags question: http://stackoverflow.com/q/50326780
tags question: http://stackoverflow.com/q/50330593
tags question: http://stackoverflow.com/q/50243847
tags question: http://stackoverflow.com/q/50374435
tags question: http://stackoverflow.com/q/50339462
tags question: http://stackoverflow.com/q/50377394
tags question: http://stackoverflow.com/q/50346998
tags question: http://stackoverflow.com/q/50289566
tags question: http://stackoverflow.com/q/50317601
tags question: http://stackoverflow.com/q/50361096
tags question: http://stackoverflow.com/q/50349633
tags question: http://stackoverflow.com/q/50338012
tags question: http://stackoverflow.com/q/50253560
tags question: http://stackoverflow.com/q/50326058
tags question: http://stackoverflow.com/q/50363947
tags question: http://stackoverflow.com/q/50338026
tags question: http://stackoverflow.com/q/50247667
tags question: http://stackoverflow.com/q/50278985
tags question: http://stackoverflow.com/q/50284760
tags question: http://stackoverflow.com/q/50381076
tags question: http://stackoverflow.com/q/50241000
tags question: http://stackoverflow.com/q/50256573
tags question: http://stackoverflow.com/q/50311732
tags question: http://stackoverflow.com/q/50286139
tags question: http://stackoverflow.com/q/50366604
tags question: http://stackoverflow.com/q/50348188
type: Tag
tags question: http://stackoverflow.com/q/50287363
tags question: http://stackoverflow.com/q/50338747
tags question: http://stackoverflow.com/q/50353999
tags question: http://stackoverflow.com/q/50321506
tags question: http://stackoverflow.com/q/50346213
tags question: http://stackoverflow.com/q/50246487
tag name: apache-spark
tags question: http://stackoverflow.com/q/50361495
tags question: http://stackoverflow.com/q/50346020
tags question: http://stackoverflow.com/q/50350496
tags question: http://stackoverflow.com/q/50359384
tags question: http://stackoverflow.com/q/50309000
tags question: http://stackoverflow.com/q/50244187

http://stackoverflow.com/q/50341158
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87698587
has answer: http://stackoverflow.com/a/50341262
type: Question
accepted answer: http://stackoverflow.com/a/50341222
downvote count: 2
has answer: http://stackoverflow.com/a/50341222
tagged with: python
score: -2
tagged with: python-2.7
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/50341228
has title: Only getting a single element from a mapping function
answer count: 3
has body: I am currently learning about mapping functions and have the following: t = ['a','b','c'] def capitalize_all(t): res = [] for s in t: res.append(s.capitalize()) return res capitalize_all(res) [A] You can also use: capitalize_all('b') [B] capitalize_all('c') [C] and etc. But my question is, why does this function only return one element in the list? Wouldn't res end up having three elements?
has answer: http://stackoverflow.com/a/50341228

image-segmentation
tags question: http://stackoverflow.com/q/50363071
tags question: http://stackoverflow.com/q/50239137
tags question: http://stackoverflow.com/q/50288416
tag name: image-segmentation
tags question: http://stackoverflow.com/q/50255438
type: Tag
tags question: http://stackoverflow.com/q/50250332
tags question: http://stackoverflow.com/q/50323756

http://stackoverflow.com/a/50336353
downvote count: 0
has comment: http://stackoverflow.com/comment/87689287
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/50334940
score: 2
has body: This is a different approach using requests. I think that Selenium should be the last option to use when doing webscraping. Usually, It is possible to retrieve the data from a webpage emulating the requests made by the web application import requests from bs4 import BeautifulSoup as BS headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'} ## Starts session s = requests.Session() s.headers = headers url_base = 'https://burocomercial.profeco.gob.mx/' ind = 'index.jsp' resp0 = s.get(url_base+ind) ## First request, to get the 'name' parameter that is dynamic soup0 = BS(resp0.text, 'lxml') param_name = soup0.select_one('input[id="txtbuscar"]')['name'] action = 'BusGeneral' ### The action when submit the form keyword = 'inmobiliaria' # Word to search data_buscar = {param_name:keyword,'yy':'2017'} ### Data submitted resp1 = s.post(url_base+action,data=data_buscar) ## second request: make the search resp2 = s.get(url_base+ind) # Third request: retrieve the results print(resp2.text) queja = 'Detalle_Queja.jsp' ## Action when Quejas selected data_queja = {'Lookup':'2','Val':'1','Bus':'2','FI':'28-Nov-2016','FF':'28-Feb-2017','UA':'0'} # Data for queja form ## Lookup is the number of the row in the table, FI is the initial date and FF, the final date, UA is Unidad Administrativa ## You can change these parameters to obtain different queries. resp3 = s.post(url_base+queja,data=data_queja) # retrieve Quejas results print(resp3.text) With this I got: '\r\n\r\n\r\n\r\n\r\n\r\n1| ABITARE PROMOTORA E INMOBILIARIA, SA DE CV |0|0|0|0.00|0.00|0|0.00|0.00|0.00|0.00|0 % |0 % ||2' Which contains the data that is used in the webpage. Maybe this answer is not exactly what you are looking for, but I think it could be easier for you to use requests.

http://stackoverflow.com/comment/87622423
type: Comment
comment on: http://stackoverflow.com/a/50302758
has text: To be fair, and I forgot this, but `__int__` enforces returning an `int`. But, the point still stands, some user-defined `array` could easily be *consumed* by the `int` function.
score: 0
type: AnswerComment

http://stackoverflow.com/a/50254640
has body: You can use the fact that every article is contained within a div.article to iterate over them: def scrapeCoindesk(url): bs = getPage(url) articles = [] for article in bs.find_all("div", {"class": "article"}): title = article.find("h3").text body = article.find("p", {"class": "desc"}).text article_url = article.find("a", {"class": "fade"})["href"] articles.append(Content(article_url, title, body)) return articles # Pulling the article from coindesk url = 'https://www.coindesk.com/category/markets-news/markets-markets-news/markets-bitcoin/' content = scrapeCoindesk(url) for article in content: print(article.url) print(article.title) print(article.body) print("-------------")
accepted answer of: http://stackoverflow.com/q/50254397
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50254397
type: Answer
upvote count: 4
score: 4

http://stackoverflow.com/comment/132456657
has text: Note your edit requests. The equations look terrible to the point of unreadability.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50313657

http://stackoverflow.com/comment/87711147
has text: @avinash `wait = WebDriverWait(driver, 10)` is not a wait for page to load. This line does nothing actually
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50347024

http://stackoverflow.com/a/50389860
accepted answer of: http://stackoverflow.com/q/50376540
has body: From your description, I am assuming you are trying to do the following: From: Test 2 └── PDFs ├── i_suck_at_python.xlsx └── python_test.xlsx To: Test 2 └── PDFs ├── Lex sucks at Python │ └── i_suck_at_python.xlsx └── Python Test └── python_test.xlsx Firstly, you need to add an r prefix to your path strings. This stops Python trying to escape any backslashes. Alternatively you could use forward slashes instead. When using a csv.reader() the file should be opened with the newline='' parameter in Python 3.x, previously in Python 2.x it needed rb. Using in will not test if your file is present in a given folder, instead it just check if the string on the left can be found in the string on the right. To actually test if a file exists, you could use os.path.exists(), but if it is just to ensure that you can copy it, then it is better to use exception handling around the move, i.e. if it can't find the file it will generate the exception. import csv import os import shutil def main(): csv_file = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\EB Mapping.csv" from_folder = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\PDFs" to_folder = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\PDFs" with open(csv_file, 'r', newline='') as f: reader = csv.reader(f) for row in reader: file_name = row[0] folder_name = row[1] from_filename = os.path.join(from_folder, file_name) to_filename = os.path.join(to_folder, folder_name, file_name) try: shutil.move(from_filename, to_filename) print("Moved - '{}' -&gt; '{}'".format(from_filename, to_filename)) except shutil.Error as e: print("Failed - '{}' -&gt; '{}'".format(from_filename, to_filename)) main()
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/87799155
answers question: http://stackoverflow.com/q/50376540
type: Answer

http://stackoverflow.com/q/50375489
tagged with: distance
has title: Real width of detected face
tagged with: measure
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50375996
downvote count: 0
upvote count: 1
tagged with: python
tagged with: opencv
tagged with: face-detection
has body: I've been researching like forever, but couldn't find an answer. I'm using OpenCV to detect faces, now I want to calculate the distance to the face. When I detect a face, I get a matofrect (which I can visualize with a rectangle). Pretty clear so far. But now: how do I get the width of the rectangle in the real world? There has to be some average values that represent the width of the human face. If I have that value (in inch, mm or whatever), I can calculate the distance using real width, pixel width and focal length. Please, can anyone help me? Note: I'm comparing the "simple" rectangle solution against a Facemark based distance measuring solution, so no landmark based answers. I just need the damn average face / matofrectwidth :D Thank you so much!
score: 1
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/50248484
tagged with: python
has answer: http://stackoverflow.com/a/50248698
answer count: 4
has comment: http://stackoverflow.com/comment/87514354
possible better answer: http://stackoverflow.com/a/50248639
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87514325
has comment: http://stackoverflow.com/comment/87514699
has comment: http://stackoverflow.com/comment/87514441
accepted answer: http://stackoverflow.com/a/50248641
has answer: http://stackoverflow.com/a/50248641
type: Question
has title: how to print 100 random numbers of "set" in python and add them to empty set()
has comment: http://stackoverflow.com/comment/87514322
has answer: http://stackoverflow.com/a/50248663
has body: how to print 100 random numbers of "set" in python, means I have to take 100 random numbers from given range and add it to an empty set(). I need solution in Python.I have tried in following way but its not taking 100 numbers exact. import random s=set() for i in range(200): s.add((random.randint(0,101))) print(s) print(len(s))
has comment: http://stackoverflow.com/comment/87514312
has answer: http://stackoverflow.com/a/50248639
has comment: http://stackoverflow.com/comment/87514483
has comment: http://stackoverflow.com/comment/87514590
has comment: http://stackoverflow.com/comment/87514381
linked to: http://stackoverflow.com/q/12354515

http://stackoverflow.com/comment/87547377
score: 1
comment on: http://stackoverflow.com/a/50264639
has text: @Frank it takes an iterable. Such as a generator
type: Comment
type: AnswerComment

http://stackoverflow.com/q/50286017
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/50287260
has body: I have a csv file few columns are as Yes/No's I have tried most of the solutions on stack over flow nothing seems to be working. sample['colval'] = sample['colval'].apply(lambda x: 0 if x=='N' else 1) For example, I used the above code on my data. It converted everything to 1's, as in Y to 1 and N to 1. So many other examples too, all yielded similar results, few resulting in 'None' as output for Y/N. sample.colval[0:20] 0 N 1 N 2 N 3 N 4 N 5 N 6 N 7 N 8 N 9 N 10 N 11 Y 12 N 13 N 14 N 15 N 16 N 17 N 18 Y 19 N Name: colval, dtype: object Please help, Thank you
has comment: http://stackoverflow.com/comment/87589454
has comment: http://stackoverflow.com/comment/87588266
has comment: http://stackoverflow.com/comment/87588465
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/87588953
answer count: 1
has comment: http://stackoverflow.com/comment/87588012
upvote count: 1
has comment: http://stackoverflow.com/comment/87587967
has comment: http://stackoverflow.com/comment/87588009
has comment: http://stackoverflow.com/comment/87588325
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87587929
has comment: http://stackoverflow.com/comment/87588670
accepted answer: http://stackoverflow.com/a/50287260
score: -2
has title: Converting Yes to 1 and No to 0 in python

http://stackoverflow.com/comment/87728227
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50353627
has text: @Prune The code is working and executable. comproc.exe is a part of big development environment. My question here is more general - what can be the reasons for this strange behavior? Thanks!

http://stackoverflow.com/q/50322294
tagged with: python
has comment: http://stackoverflow.com/comment/87660499
tagged with: flask
has title: Flask: Unicode error when trying to parse POST payload
has answer: http://stackoverflow.com/a/50322730
answer count: 3
upvote count: 2
score: 1
downvote count: 1
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/50322552
type: Question
has answer: http://stackoverflow.com/a/50322654
type: UnansweredQuestion
has body: I'm trying to build a Flask API endpoint that takes an image url from the JSON payload. I'm using flask.request.get_json() which has worked for me before: @app.route("/caption", methods=["POST"]) def caption(): image_url = flask.request.get_json().get('image_url') image_info = get_caption(image_url) return flask.jsonify(image_info) However, when trying to post a URL to the endpoint with content type application/json I get an AttributeError: 'unicode' object has no attribute 'image_url' I tried printing out the contents of flask.request.get_json() and I get {u'image_url': u'https://images.pexels.com/photos/66997/pexels-photo-66997.jpeg'} How can I get my payload as a dictionary instead of a unicode object?
has comment: http://stackoverflow.com/comment/87660489

http://stackoverflow.com/q/50382591
answer count: 3
tagged with: pandas
has title: Round decimals row-wise instead of column-wise in pandas
has body: According to the pandas.DataFrame.round documentation I can decide the rounding also column-wise. However, there is nothing written about a row-wise rounding. For instance, I have A count 1010.00009 measure 54.45678 average 0.50483 How could I make it that A count 1010 measure 54.46 average 0.5048
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50382624
accepted answer: http://stackoverflow.com/a/50382624
has answer: http://stackoverflow.com/a/64405736
tagged with: rounding
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50382654
possible better answer: http://stackoverflow.com/a/50382654
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/87567228
type: Comment
type: QuestionComment
has text: How It will update? It will insert a new object. you might want to do `lines[i+1]=self.revenue`
score: 0
comment on: http://stackoverflow.com/q/50274830

http://stackoverflow.com/q/50252138
tagged with: python
possible better answer: http://stackoverflow.com/a/50252573
accepted answer: http://stackoverflow.com/a/50252394
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50252394
answer count: 2
tagged with: pycharm
has body: Newbie to automation with Selenium/Python. I'm getting blocked automating a sign up form. The drop down is a required element but I'm getting the following error... AttributeError: 'str' object has no attribute 'tag_name' I've posted my code below and can't find any answer online as to why this would be. Any/all help greatly appreciated. from selenium import webdriver from selenium.webdriver.support.select import Select teamElement = browser.find_element_by_id('id_team') time.sleep(2) sel = Select('teamElement') sel.select_by_value("12") The error is coming from the sel = Select('teamElement') line. Traceback (most recent call last): File "/Users/jamesstott/PycharmProjects/basics/RunChromeTests.py", line 40, in &lt;module&gt; sel = Select('teamElement') File "/Users/jamesstott/PycharmProjects/venv/lib/python3.6/site-packages/selenium/webdriver/support/select.py", line 36, in __init__ if webelement.tag_name.lower() != "select": AttributeError: 'str' object has no attribute 'tag_name'
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/87521859
has comment: http://stackoverflow.com/comment/87521788
favorite count: 0
has comment: http://stackoverflow.com/comment/87521772
type: Question
has title: Selenium w/Python3 - AttributeError: 'str' object has no attribute 'tag_name'
has answer: http://stackoverflow.com/a/50252573
upvote count: 2

http://stackoverflow.com/comment/87521354
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50246672
has text: What exactly do you mean by labeling them?
score: 0

rest
tags question: http://stackoverflow.com/q/50293645
tags question: http://stackoverflow.com/q/50298877
tags question: http://stackoverflow.com/q/50275675
tags question: http://stackoverflow.com/q/50233844
tags question: http://stackoverflow.com/q/50242222
type: Tag
tags question: http://stackoverflow.com/q/50278042
tags question: http://stackoverflow.com/q/50242820
tags question: http://stackoverflow.com/q/50338673
tags question: http://stackoverflow.com/q/50319280
tag name: rest
tags question: http://stackoverflow.com/q/50230155

http://stackoverflow.com/a/50265233
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50264196
has body: Using numpy: x = np.flatnonzero(np.greater(scores, min_score_thresh)).tolist() NOTE: .tolist() is not necessary if you can live with numpy.ndarrays.

http://stackoverflow.com/a/50232648
answers question: http://stackoverflow.com/q/50232369
has comment: http://stackoverflow.com/comment/87482633
score: 8
downvote count: 0
type: AcceptedAnswer
has body: Instead of using @login_required decorator, use @method_decorator(login_required) on your post method, like so: from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator class HomeView(TemplateView): # ... @method_decorator(login_required) def post(self, request): # ... The reason why you're seeing an error message is because login_required is a function decorator - so it expects the request object to be the first argument passed to your view. Your post definition is a method, therefore self (HomeView) is the first argument that's getting passed, and this is what login_required tries to use as a Request instance. method_decorator is used to transform every function decorator to a method decorator. See the docs for more info.
upvote count: 8
accepted answer of: http://stackoverflow.com/q/50232369
type: Answer

google-cloud-datastore
tags question: http://stackoverflow.com/q/50303675
tag name: google-cloud-datastore
type: Tag
tags question: http://stackoverflow.com/q/50353735
tags question: http://stackoverflow.com/q/50321300
tags question: http://stackoverflow.com/q/50279083

http://stackoverflow.com/q/50238832
score: 1
tagged with: python
tagged with: scheduled-tasks
tagged with: pythonanywhere
tagged with: urllib
has answer: http://stackoverflow.com/a/50239920
type: Question
upvote count: 1
type: UnansweredQuestion
answer count: 1
has body: I have a .py script that works when I run it in the console but seems to fail when I schedule it as an automatic task. The script uses the urllib.request (I made sure to set the Hashbang to run Python 3.6 which supports that package) to hit and download a file from a specific URL.. Again no problems when I run it manually, but when its run as a scheduled task I get this error: Traceback (most recent call last): File "/home/laiAdmin/Scripts/FullAutoSubStats.py", line 32, in &lt;module&gt; urllib.request.urlretrieve(URL, dlFileName) File "/usr/lib/python3.6/urllib/request.py", line 258, in urlretrieve tfp = open(filename, 'wb') FileNotFoundError: [Errno 2] No such file or directory: '/home/laiAdmin/Data_Files/Downloads/FWdirect-Daily-Stats-Parser-autoDl-2018-05-08.json' 2018-05-08 16:48:11 -- Completed task, took 6.00 seconds, return code was 1. The code snippet it is pointing to is the following (hiding the full URL for security purposes): #Get timestamp and PWD cwd = os.getcwd() now = DT.datetime.utcnow()-DT.timedelta(hours=6) todayStr = DT.datetime.strftime(now,"%Y-%m-%d") nowStr = DT.datetime.strftime(now,"%m/%d/%Y %H:%M:%S") #Request to download a new json file: rootdir = cwd+'/Data_Files/Downloads/' URL = "https://files.mailparser.io/d/*****" #(hiding the full URL here for security purposes) fn = "FWdirect-Daily-Stats-Parser-autoDl-"+todayStr+".json" dlFileName = rootdir+fn urllib.request.urlretrieve(URL, dlFileName) The last line is where the traceback takes place. Please help me to understand why this runs when I hit run in the console, but fails when I schedule it as a task.
tagged with: python-3.6
has title: request.urlretrieve fails when run as a Scheduled Task in PythonAnywhere
favorite count: 0
downvote count: 0

http://stackoverflow.com/comment/87733351
type: QuestionComment
has text: Storing debug log for failure in /home/pi/.pip/pip.log
score: 0
comment on: http://stackoverflow.com/q/50358113
type: Comment

http://stackoverflow.com/comment/87701053
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50342560
has text: it's for `tuple`.
type: AnswerComment

http://stackoverflow.com/comment/87719936
score: 1
has text: Yes, they definitely are operators.
type: Comment
comment on: http://stackoverflow.com/a/50351699
type: AnswerComment

http://stackoverflow.com/q/50286580
downvote count: 1
has comment: http://stackoverflow.com/comment/87589199
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87589109
has body: I am making a word chain game in python but I am stuck at one place. The thing I wanted to do is The game begins by asking how many people wish to play, and then prompting you to enter a name for each of the players. For this, I have created a code def inputWord(): Players = str(input("Enter Number of Players:")) Name = [] WordChain = 0 ls = list() PlayerNames = {} for i in range(0, int(Players)): Name = input("Enter Player Name:") PlayerNames = ls.append(Name) print(PlayerNames) print(PlayerNames) inputWord() the Output that I am getting is Enter Number of Players:2 Enter Player Name:David None Enter Player Name:Martin None None Instead, I need this Enter Number of Players:2 Enter Player Name:David David Enter Player Name:Martin Martin [David, Martin] #list of the names for later use I am new to python please help me.
linked to: http://stackoverflow.com/q/16641119
tagged with: python
score: -1
has title: Python: How to get multiple values from user?
accepted answer: http://stackoverflow.com/a/50286839
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87589243
has answer: http://stackoverflow.com/a/50286839
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/87711417
type: Comment
has text: "module 'urllib' has no attribute 'urlopen'" Also, python 3.6
comment on: http://stackoverflow.com/a/50347345
score: 0
type: AnswerComment

http://stackoverflow.com/a/50386374
has body: If you are struggling with the concepts and logic behind solving this problem, I would recommend perhaps stepping back a little and going through easier coding tutorials and interactive exercises. You might also enjoy experimenting with JavaScript, where it might be easier to get creative right from the outset, building out snippets and/or webpages that one can immediately interact with in the browser. Then when you get more fun coding vocabulary under your belt, the algorithmic part of it will seem more familiar and natural. I also think letting your own creativity and imagination guide you can be a very powerful learning process. Let's forget about the alphabetical part for the moment. Imagine we have a bag of letters that we pull out one at a time without knowing which is next and we have to record the longest run of Rs in a row. How would you do it? Let's try to describe the process in words, then pseudocode. We'll keep a container for the longest run we've seen so far and another to check the current run. We pull letters until we hit two Rs in a row, which we put it in the "current" container. The next letter is not an R, which means our run ended. The "longest-so-far" run is empty so we pour the "current" container in it and continue. The next four letters are not Rs so we just ignore them. Then we get one R, which we put in "current" and then an H. Our run ended again but this time our one R in "current" was less than the two we already have in "longest-so-far" so we keep those and empty "current." We get an A, a B, and a C, and then a run of five Rs, which we put into the "current" container one by one. Our bag now contains the last letter, a T. We see that our run ended again and that "current" container has more than the "longest-so-far" container so we pour out "longest" and replace its contents with the five Rs in "current." That's it, we found the longest run of Rs in the bag. (If we had more runs, each time one ended we'd choose whether to replace the …
accepted answer of: http://stackoverflow.com/q/50366484
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/50366484
has comment: http://stackoverflow.com/comment/87818457
downvote count: 0
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/89170597

http://stackoverflow.com/comment/87538655
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50260339
has text: Where did you see this `addCleanup()` function? Are you writing tests?

http://stackoverflow.com/comment/87487951
score: 0
comment on: http://stackoverflow.com/q/50234927
type: Comment
type: QuestionComment
has text: Your code appears to be correctly reading the output of the script. Is it possible that you are getting something on stderr instead of stdout? Maybe check that stream too, or you could try pb.redirectOutput(File) and pb.redirectError(File) and see if they contain anything.

http://stackoverflow.com/a/50308202
type: Answer
answers question: http://stackoverflow.com/q/50308026
has comment: http://stackoverflow.com/comment/87632502
has comment: http://stackoverflow.com/comment/87632587
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87632539
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87632635
accepted answer of: http://stackoverflow.com/q/50308026
has body: Read user input. Repeat for that many number of times - get items from dictionary using get attribute which handles KeyError itself: dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'} n = int(input()) for _ in range(n): print(dic.get(input(), 'Wrong Input')) EDIT: dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'} n = int(input()) for _ in range(n): usrinp = input() print(dic.get(usrinp, usrinp))

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/50357252

http://stackoverflow.com/comment/87539516
comment on: http://stackoverflow.com/a/50257862
score: 0
type: Comment
has text: Well, actually, it would fail if any desired index does not have at least one True value at or behind it. I'll edit my answer to take this into account.
type: AnswerComment

http://stackoverflow.com/comment/87514929
type: Comment
comment on: http://stackoverflow.com/a/50248214
type: AnswerComment
has text: Print result type is string i want integer type.
score: 0

http://stackoverflow.com/q/50286057
linked to: http://stackoverflow.com/q/50207218
has comment: http://stackoverflow.com/comment/87640932
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87728369
accepted answer: http://stackoverflow.com/a/50286464
has title: How can I convert this SQL statement to Django QuerySet?
upvote count: 3
has answer: http://stackoverflow.com/a/50286464
answer count: 1
has comment: http://stackoverflow.com/comment/87589847
downvote count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/87625412
tagged with: django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87844856
score: 3
tagged with: python
has body: PLEASE NOTE: This question is a follow-up to this question I asked a few days ago. It is not a duplicate. There are slight but significant differences in the SQL Query I'm trying to model in Django and the dummy data I have loaded. I'm writing a Python/Django application to do some stock analysis. I have two very simple models that look like this: class Stock(models.Model): symbol = models.CharField(db_index=True, max_length=5, null=False, editable=False, unique=True) class StockHistory(models.Model): stock = models.ForeignKey(Stock, related_name='StockHistory_stock', editable=False) trading_date = models.DateField(db_index=True, null=False, editable=False) close = models.DecimalField(max_digits=12, db_index=True, decimal_places=5, null=False, editable=False) class Meta: unique_together = ('stock', 'trading_date') This is the dummy data I have populated them with: import datetime a = Stock.objects.create(symbol='A') b = Stock.objects.create(symbol='B') c = Stock.objects.create(symbol='C') d = Stock.objects.create(symbol='D') StockHistory.objects.create(trading_date=datetime.date(2018,1,1), close=200, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,1,2), close=150, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,1,3), close=120, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,4,28), close=105, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,5,2), close=105, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,5,3), close=105, stock=a) StockHistory.objects.create(trading_date=datetime.date(2017,5,2), close=400, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,11), close=200, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,12), close=300, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,13), close=400, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,14), close=500, stock=b) Stoc…
has comment: http://stackoverflow.com/comment/87626267

http://stackoverflow.com/comment/87596631
comment on: http://stackoverflow.com/q/50290286
has text: It does return the dictionary. That's what `return count` does.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50276634
accepted answer: http://stackoverflow.com/a/50276677
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50276677
has answer: http://stackoverflow.com/a/50276778
has body: I have a dictionary TestDict = {'Group1': 'Crew 1', 'Group2': 'Crew 2', 'Group3': 'Crew 3'} And I'd like to edit the value in the dictionary to have this desired output {'Group1': 'Group1_Crew_1', 'Group2': 'Group2_Crew_2', 'Group3': 'Group3_Crew_3'} So in the above, the key is now a part of the value and the space have been replaced with _ So far I've only tried to tackle appending the key to the value with for key, value in TestDict.items(): newDict = {key: key + "_" + value for key in TestDict} Problematically, this outputs in the proper dictionary, however, all of the values are Group3_Crew 3. I'm not sure how to navigate this issue.
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50276778
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50276662
has title: Edit values within dictionary
answer count: 3
score: 1
downvote count: 0
upvote count: 1

time
tags question: http://stackoverflow.com/q/50318589
tags question: http://stackoverflow.com/q/50234823
type: Tag
tag name: time
tags question: http://stackoverflow.com/q/50243949
tags question: http://stackoverflow.com/q/50236669
tags question: http://stackoverflow.com/q/50362886
tags question: http://stackoverflow.com/q/50305803
tags question: http://stackoverflow.com/q/50303845

http://stackoverflow.com/comment/87657019
type: Comment
has text: No, you should take a look at the `abc` module to see how it is implement. That said, `Meta.__new__` should look at each class in `bases` as well to see if *they* implement `some_method`, if `some_method` is not defined locally. (And that check needs to be recursive, because none of *them* may have defined `some_method` either, but relied on an inherited definition.)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50320346

http://stackoverflow.com/q/50307722
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/87631401
has comment: http://stackoverflow.com/comment/87631432
has comment: http://stackoverflow.com/comment/87631392
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87631525
accepted answer: http://stackoverflow.com/a/50308276
has body: 1) What is the most pythonic way to use multiple conditional if statements in a list comprehension? 2) Len() returns an error if strings are concatenated when calling the function. Len(str(x) + str(y)) is not allowed Point 2 is incorrect but left for future readers Is lambda the appropriate function to use when using an if len() statement as follows: ? for j in blah: for i in range(4): inputs = set([ str(j) + "".join(x) for x in itertools.permutations(total, i) if 14 &gt; len(lambda j,x : str(j) + "".join(x)) and len(lambda j, x : str(j) + "".join(x)) &gt; 9])
upvote count: 2
tagged with: syntax
has answer: http://stackoverflow.com/a/50308276
downvote count: 2
answer count: 1
has title: Most pythonic way to use len() based conditions with multiple arguments in a list comprehension
has comment: http://stackoverflow.com/comment/87631679
has comment: http://stackoverflow.com/comment/87631445
tagged with: lambda
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87631446
has comment: http://stackoverflow.com/comment/87632039
tagged with: python

http://stackoverflow.com/a/50318653
answers question: http://stackoverflow.com/q/50318086
accepted answer of: http://stackoverflow.com/q/50318086
type: Answer
has body: You should use manage.py rather than django-admin, as that sets the DJANGO_SETTINGS_MODULE variable for you.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/87767284
comment on: http://stackoverflow.com/q/50375207
has text: @MihaiAlexandru-Ionut How do I compile method paramaters? And I want to loop thru the fitting. It's not the biggest deal that I'm not getting good metrics, I care that the model isn't being trained at all. It actually makes a whole model, but when I use this model to make predictions, it just comes out at a bunch of NaN's as predictions and I'm assuming that's because it's being trained incorrectly.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50367739
has comment: http://stackoverflow.com/comment/87754785
downvote count: 0
tagged with: django
tagged with: django-rest-framework
score: 28
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/88130586
has body: I tried documenting the APIs while writing viewsets and using django rest docs. I am having the following problems: if I try to send values for reverse related field, it takes list of values, but when sending the data in Form-data, it comes as a string. There is no option for file upload in the docs UI. Following is my code: models.py class Area(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) address = models.TextField() image = models.ImageField(upload_to='area/') created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) zipcode = models.CharField(max_length=15, null=True) is_verified = models.BooleanField(default=False) class Meta: ordering = ('-modified_on',) class Email(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField() area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='email') class Phone(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) phone = models.CharField(max_length=15) area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name='phone') view.py class AreaViewSet(viewsets.ModelViewSet): """ create: Create a new area instance. """ serializer_class = AreaSerializer parser_classes = (FormParser, MultiPartParser,FileUploadParser) queryset = User.objects.all() permission_classes = [AllowAny, ] filter_backends = (DjangoFilterBackend,) filter_fields = ('first_name',) def create(self, request): data = self.request.data with transaction.atomic(): name = data['name'] address = data['address'] email = json.loads(data['email']) phone = json.loads(data['phone']) zipcode = data['zipcode'] area = Area.objects.create(name=name,address=address, zipcode=zipcode) for i in email: Email.objects.create(email=i['email'], area = area) for i in phone: Phone.objects.create(phone=i['phone'], area=…
upvote count: 28
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87753778
has answer: http://stackoverflow.com/a/50474071
tagged with: python
has comment: http://stackoverflow.com/comment/87764271
has comment: http://stackoverflow.com/comment/87755318
has comment: http://stackoverflow.com/comment/87755771
has answer: http://stackoverflow.com/a/51917683
tagged with: django-swagger
tagged with: api-doc
answer count: 2
has comment: http://stackoverflow.com/comment/88093524
has title: Django rest APIs, automate documentation?

http://stackoverflow.com/comment/87698826
type: Comment
type: AnswerComment
has text: Interesting approach, and I get the same results from above - not sure why it doesn't work for you. It should be noted that all the list slicing would make it a bit slower (3X).
comment on: http://stackoverflow.com/a/50341217
score: 0

http://stackoverflow.com/comment/130932052
comment on: http://stackoverflow.com/a/53384575
type: AnswerComment
score: 0
has text: I disagree that adding a bit of sed around an [already existing answer](https://stackoverflow.com/a/50471073/674039) is a useful contribution. If anything it could be an edit to that answer. Anyway both python 2.7 and 3.6 are EOL now.
type: Comment

http://stackoverflow.com/comment/87863356
comment on: http://stackoverflow.com/a/50356988
has text: I think you right indeed. For I have managed to handle all error and get the output wanted. Big thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87507425
type: Comment
type: AnswerComment
has text: Awesome thanks! If I already have a bunch of records saved in my retailer field, will that automatically slugify my fields or would I need to do it manually?
score: 0
comment on: http://stackoverflow.com/a/50244541

http://stackoverflow.com/q/50324495
tagged with: openexr
accepted answer: http://stackoverflow.com/a/50328055
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/87700023
has answer: http://stackoverflow.com/a/50328055
has comment: http://stackoverflow.com/comment/87730730
score: 2
upvote count: 3
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87731443
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87741947
tagged with: data-conversion
has body: I'm using OpenEXR to read EXR files in Python. I have R, G and B channels with Half data (float16). Using Numpy, I tried, unsuccessfully to convert the data from float16 to uint8 (0-255 colors). rCh = getChanEXR(imageFile, 'R','HALF') rCh = np.array(rCh).astype('uint8') So, I put the R channel pixel values to a variable rCh. Then I convert the array.array to an np.array so that I can use the astype method to convert it to uint8. I am new to this, so I clearly do not have it right as all values become 0. Originally, the values are like this: 0.0, 2.9567511226945634e-14, 1.2295237050707897e-10 etc. In addition to the float16 values, I also have some regular float values that need to be normalized. I think I need to normalize the float16 values before they can be set in a range from 0-255. Any ideas? Thank you. Adding the code for the def mentioned in here getChanEXR (just a custom def based on code from the python OpenEXR docs for getting channel data. def getChanEXR(curEXRStr, curChannel, dataType): #import OpenEXR, Imath, array pt = 'none' if dataType == 'HALF': pt = Imath.PixelType(Imath.PixelType.HALF) if dataType == 'FLOAT': pt = Imath.PixelType(Imath.PixelType.FLOAT) if dataType == 'UINT': pt = Imath.PixelType(Imath.PixelType.UINT) chanstr = OpenEXR.InputFile(curEXRStr).channel(curChannel, pt) chan = array.array('f', chanstr) return chan
tagged with: python
has title: How to convert float16 to uint8 in Python for EXR files

http://stackoverflow.com/comment/114784800
type: Comment
comment on: http://stackoverflow.com/a/50344879
has text: if I'm not mistake it is default for the functions
score: 0
type: AnswerComment

http://stackoverflow.com/q/50240752
linked to: http://stackoverflow.com/q/47645115
tagged with: conv-neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/57793277
has answer: http://stackoverflow.com/a/50240895
type: Question
answer count: 2
has title: Keras - OSError: cannot identify image file
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
tagged with: keras
favorite count: 0
has body: I'm trying to train a CNN with Keras and when running the model.fit_generator line of code, I get the following error: OSError: cannot identify image file 'D:\\PDF\\Train\\notfactors\\notfactors59.jpg The wierd thing is, that .jpg does not exist in the folder. Below is all of my code. I'm using the exact same code (different data) from the following github address: https://github.com/deeplizard/Keras_Jupyter_Notebooks/blob/master/CNN.ipynb This problem was dicussed here: OSError: cannot identify image file 'dataSet/.DS_Store' But for this question, the images actually exists. I'm lost. Does anyone have an idea?
score: 3
upvote count: 3

http://stackoverflow.com/comment/87649604
has text: What makes you think that it should be `s.connect(int(ip,port))` in the first place? It should be `s.connect((ip,port))`, i.e. without any kind of `int`. I recommend to actually have a look at the documentation.
comment on: http://stackoverflow.com/q/50316521
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50381288
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87778807
has body: Typically if you want your output to sum to 1 you add a softmax layer as the last layer in your neural net, which outputs a sort of pseudo-probability measure. This should work: model = Sequential([ Dense(32, input_shape=(100,), activation='sigmoid'), Dense(64, activation='sigmoid'), Dense(3, activation='softmax') ]) model.compile(Adam(lr=0.0001),loss='categorical_crossentropy', metrics = ['accuracy']) model.fit(bets, results, validation_split= 0.20, batch_size=10, epochs=200, shuffle=True, verbose=3)
has comment: http://stackoverflow.com/comment/95953022
accepted answer of: http://stackoverflow.com/q/50381050
type: Answer
answers question: http://stackoverflow.com/q/50381050

http://stackoverflow.com/a/50399219
has comment: http://stackoverflow.com/comment/87818534
answers question: http://stackoverflow.com/q/50328246
type: AcceptedAnswer
downvote count: 0
has body: There's actually a bit of hidden overhead in zip(df.A.values, df.B.values). The key here comes down to numpy arrays being stored in memory in a fundamentally different way than Python objects. A numpy array, such as np.arange(10), is essentially stored as a contiguous block of memory, and not as individual Python objects. Conversely, a Python list, such as list(range(10)), is stored in memory as pointers to individual Python objects (i.e. integers 0-9). This difference is the basis for why numpy arrays are smaller in memory than the Python equivalent lists, and why you can perform faster computations on numpy arrays. So, as Counter is consuming the zip, the associated tuples need to be created as Python objects. This means that Python needs to extract the tuple values from numpy data and create corresponding Python objects in memory. There is noticeable overhead to this, which is why you want to be very careful when combining pure Python functions with numpy data. A basic example of this pitfall that you might commonly see is using the built-in Python sum on a numpy array: sum(np.arange(10**5)) is actually a bit slower than the pure Python sum(range(10**5)), and both of which are of course significantly slower than np.sum(np.arange(10**5)). See this video for a more in depth discussion of this topic. As an example specific to this question, observe the following timings comparing the performance of Counter on zipped numpy arrays vs. the corresponding zipped Python lists. In [2]: a = np.random.randint(10**4, size=10**6) ...: b = np.random.randint(10**4, size=10**6) ...: a_list = a.tolist() ...: b_list = b.tolist() In [3]: %timeit Counter(zip(a, b)) 455 ms ± 4.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [4]: %timeit Counter(zip(a_list, b_list)) 334 ms ± 4.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) The difference between these two timings gives you a reasonable estimate of the overhead discussed earlier. This isn't quite the end of the story…
upvote count: 21
accepted answer of: http://stackoverflow.com/q/50328246
score: 21
type: Answer
has comment: http://stackoverflow.com/comment/87819005

http://stackoverflow.com/comment/87577465
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50280360
has text: Sure I'll , Thanks

http://stackoverflow.com/q/50348542
type: UnansweredQuestion
has body: I installed pyrouge on windows 7 (python3.6). When trying to excute the method convert_and_evaluate() of the class Rouge155 i got this error: OSError: [WinError 193] %1 n'est pas une application Win32 valide
tagged with: python
upvote count: 2
score: 2
answer count: 0
downvote count: 0
tagged with: summarization
favorite count: 0
type: Question
tagged with: python-3.x
has title: Error when running pyrouge

http://stackoverflow.com/comment/87681728
score: 0
type: Comment
type: QuestionComment
has text: @bereal I only plan on using one instance of this class. Normally, in such a case I want a class not an instance.
comment on: http://stackoverflow.com/q/50332764

http://stackoverflow.com/a/51187935
upvote count: 1
answers question: http://stackoverflow.com/q/50264129
score: 1
type: Answer
has body: Go https://anaconda.org/anaconda/intel-openmp/files Download win-64/intel-openmp-2018.0.3-0.tar.bz2 Extract files under its Library/bin/ to any directory Add the directory in Step 3 to your PATH environment Restart This solved ImportError on my computer with Windows 10 + Python 3.6.6 + PyTorch 0.4.0. Hope it helps.
downvote count: 0

http://stackoverflow.com/comment/87494546
has text: There's nothing like POSIX signals in Windows to asynchronously interrupt *any wait* on a kernel dispatcher object, which in this case is the semaphore that's waited on to acquire a lock in the `join` method. Internally, the wait could be modified in two ways to allow interruption in the main thread. Either switch to using `WaitForMultipleObjects` and include an Event that gets set by the `SIGINT` handler (which gets called by the C runtime's console control handler) or switch to using an alertable `WaitForSingleObjectEx` wait and have the SIGINT handler queue an APC to alert the main thread.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50238135

http://stackoverflow.com/q/50342165
type: AnsweredQuestion
answer count: 2
has body: I am not sure why this code is failing for a few inputs (from CodingBat, link to question : Exercise Link). Problem details are below, I could probably do this question with if elif statements, but I want to use dictionaries. Also, I have read that it is not recommended to fetch key values from a dictionary as used below. But I will appreciate it if the issue in below program can be pointed out. You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. caught_speeding(60, False) → 0 caught_speeding(65, False) → 1 caught_speeding(65, True) → 0 def caught_speeding(speed, is_birthday): Bir_dict = {0:speed&lt;=60,1:61&lt;=speed&lt;=80,2:speed&gt;=81} NoBir_dict = {0:speed&lt;=65,1:66&lt;=speed&lt;=85,2:speed&gt;=86} def getKey(dict,value): return [key for key in dict.keys() if (dict[key] == value)] if is_birthday: out1=getKey(Bir_dict,True) return out1[0] else: out2=getKey(NoBir_dict,True) return out2[0] The programs is failing for caught_speeding(65, False) caught_speeding(65, True) And working for caught_speeding(70, False) caught_speeding(75, False) caught_speeding(75, True) caught_speeding(40, False) caught_speeding(40, True) caught_speeding(90, False) caught_speeding(60, False) caught_speeding(80, False)
has answer: http://stackoverflow.com/a/50342263
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50342286
has title: Using Python dictionary values to return key as result
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/50342286
accepted answer: http://stackoverflow.com/a/50342263

http://stackoverflow.com/comment/87829488
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50368728
has text: Also, what is the output of `redis-cli --latency -h host -p port` ?

http://stackoverflow.com/a/50324754
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50324651
has body: As the docs say: To parse a document, pass it into the BeautifulSoup constructor. You can pass in a string or an open filehandle: A Response object is neither a string nor an open filehandle. The simplest way to get one of the two, as shown in the first example in the requests docs, is the .text attribute. So: http = requests.get("https://www.imdb.com/title/tt6738136/?ref_=inth_ov_tt") soup = BeautifulSoup(http.text, 'lxml') For other options see Response Content—e.g., you can get the bytes with .content to let BeautifulSoup guess at the encoding instead of reading it from the headers, or get the socket (which is an open filehandle) with .raw.

http://stackoverflow.com/a/50336865
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50335857
has comment: http://stackoverflow.com/comment/87690119
accepted answer of: http://stackoverflow.com/q/50335857
has comment: http://stackoverflow.com/comment/87690063
type: Answer
has comment: http://stackoverflow.com/comment/87690000
score: 2
has body: You can use itertools.chain, which allows you to flatten a list of lists, which you can then slice according to the length of your dataframe. Data from @ak_slick. import pandas as pd from itertools import chain df = pd.DataFrame({'sent': [0, 0, 0, 1, 1, 1], 'token': ['a', 'b', 'b', 'a', 'b', 'c']}) lst = [['b','c',None],['b',None,'u'], ['b','i','o']] df['pred'] = list(filter(None, chain.from_iterable(lst)))[:len(df.index)] print(df) sent token pred 0 0 a b 1 0 b c 2 0 b d 3 1 a b 4 1 b a 5 1 c u
upvote count: 2

http://stackoverflow.com/comment/87544637
has text: @David542 BTW, be careful with `itertools.groupby` the array needs to be sorted, (you probably know that).
comment on: http://stackoverflow.com/a/50260788
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/50256787
tagged with: glob
upvote count: 5
has comment: http://stackoverflow.com/comment/87531648
has comment: http://stackoverflow.com/comment/87531740
tagged with: python
accepted answer: http://stackoverflow.com/a/50257185
has comment: http://stackoverflow.com/comment/87531688
has answer: http://stackoverflow.com/a/50257185
has comment: http://stackoverflow.com/comment/87532159
score: 5
answer count: 1
downvote count: 0
has body: Say I have a list of directories dirs. dirs = ['C:\\path\\to\\dir1','C:\\path\\to\\dir2','C:\\path\\to\\dir3'] And in each of these directories, there are several excel files I want to get a list of. If I just use glob.glob("*.xls*") this only gives me a list of excel files in my current working directory, but I want to specifically get a list of the excel files in "C:\path\to\dir1", "C:\path\to\dir2" etc. I have tried import glob for direc in dirs: print(glob.glob(direc + "*.xls*") &gt;&gt;&gt;[] but this just produces empty lists. What am I doing wrong here? How can I get a list of the excel files in each of the directories in dirs?
favorite count: 0
type: Question
type: AnsweredQuestion
has title: How to specify directory using glob in python?
has comment: http://stackoverflow.com/comment/87531542

http://stackoverflow.com/comment/87779210
comment on: http://stackoverflow.com/q/50379042
score: 0
has text: Yes. I'm looking for an progress bar that is overwritten while updating... It just writes every new line when updating.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50249340
score: 0
has comment: http://stackoverflow.com/comment/87526217
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87522249
has comment: http://stackoverflow.com/comment/87516495
has comment: http://stackoverflow.com/comment/87521915
type: Question
has title: Filter reversed rows in a dataframe (pandas)
tagged with: filtering
has body: I actually have a problem with my dataframe, indeed let's say I have a dataframe such: cluster_name qseqid sseqid pident_x qstart qend sstar send 2 1 seq1_0035_0035 seq13_0042_0035 0.73 42 133 46 189 3 1 seq1_0035_0035 seq13_0042_0035 0.73 146 283 287 389 4 1 seq1_0035_0035 seq13_0042_0035 0.73 301 478 402 503 5 1 seq13_0042_0035 seq1_0035_0035 0.73 46 189 42 133 6 1 seq13_0042_0035 seq1_0035_0035 0.73 287 389 146 283 7 1 seq13_0042_0035 seq1_0035_0035 0.73 402 503 301 478 8 2 seq4_0042_0035 seq2_0035_0035 0.71 256 789 125 678 9 2 seq4_0042_0035 seq2_0035_0035 0.71 802 1056 706 985 10 2 seq4_0042_0035 seq7_0035_0042 0.83 123 745 156 723 12 4 seq11_0035_0035 seq14_0042_0035 0.89 145 647 236 921 13 4 seq11_0035_0035 seq17_0042_0042 0.97 148 623 241 1002 14 5 seq17_0035_0042 seq17_0042_0042 0.94 188 643 179 746 ... (200 000 ROWS) As you can see in the lines 2,3 and 4 in the cluster 1: cluster_name qseqid sseqid pident_x qstart qend sstar send 2 1 seq1_0035_0035 seq13_0042_0035 0.73 42 133 46 189 3 1 seq1_0035_0035 seq13_0042_0035 0.73 146 283 287 389 4 1 seq1_0035_0035 seq13_0042_0035 0.73 301 478 402 503 there are the reciprocal (reversed) ones in 5, 6 and 7 in the cluster 1: cluster_name qseqid sseqid pident_x qstart qend sstar send 1 1 seq13_0042_0035 seq1_0035_0035 0.73 46 189 42 133 6 1 seq13_0042_0035 seq1_0035_0035 0.73 287 389 146 283 7 1 seq13_0042_0035 seq1_0035_0035 0.73 402 503 301 478 If you do not see it well it would be like: seq 1 vs seq 2 : (here seq1_0035_0035 vs seq13_0042_0035) and seq 2 vs seq 1 : ( here seq13_0042_0035 vs seq1_0035_0035) It is the same comparison and I do want to keep one of them only, not both. Here for example, it's to only keep 2,3 and 4 OR 4,5 and 6 in my final dataframe, if I only keep the first ones it would give: cluster_name qseqid sseqid pident_x qstart qend sstar send 2 1 seq1_0035_0035 seq13_0042_0035 0.73 42 133 46 189 3 1 seq1_0035_0035 seq13_0042_0035 0.73 146 283 287 389 4 1 seq1_0035_0035 seq13_0042_0035 0.73 301 4…
tagged with: pandas
has comment: http://stackoverflow.com/comment/87518078
tagged with: python
has comment: http://stackoverflow.com/comment/87519189
has comment: http://stackoverflow.com/comment/87521329
has comment: http://stackoverflow.com/comment/87521411

http://stackoverflow.com/q/50275077
score: 4
tagged with: pandas
linked to: http://stackoverflow.com/q/39124934
tagged with: io
has title: How to store a class instance in HDF5
tagged with: hdf5
favorite count: 0
type: Question
upvote count: 4
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: data-structures
has body: TL;DR: Question is in the title. See code snippet. I need to store pandas.DataFrame objects in a dictionary-like data structure and to save them to disk. In my current implementation, I'm using a non-nested Python dict in the form Dict[str, pandas.DataFrame] and I save all pandas.DataFrame to disk every minute as csv file. However, these two responsibilities (data storage in memory and to disk) might be elegantly unified using data structures such as HDF5. One important constraint is that I cannot change the type of what is stored in the pandas.DataFrame and apparently not all object types can be stored in a HDF5. The reason is that I'm implementing an 3rd party interface with predefined data types which need to be handled in their native form. Mapping instances to different object (e.g. instance to dict) will require to write an additional layer of logic to map different types of object back and forth (dict to instance), which is bad. A similar question with answer here. However, I'm not necessarily interested in querying the stored instances afterwards. In addition, I would ideally keep the amount of extra logic to serialise the instance at its minimum (if needed at all). Data compression is also not a problem. Alternatively, a potential answer could also point to a well established python package which has already encapsulated the logic to store class instances in HDF5 or a similar data model. import pandas as pd class C: def __init__(self, a=0): self.a = a def return_42(self): return self.a df = pd.DataFrame([C()]) df.dtypes # 0 object # dtype: object store = pd.HDFStore('store1.hdf5') store.append('c', pd.DataFrame([C()])) # TypeError: Cannot serialize the column [0] because # its data contents are [mixed] object dtype.

http://stackoverflow.com/q/50295729
has comment: http://stackoverflow.com/comment/87608341
has answer: http://stackoverflow.com/a/74960883
has answer: http://stackoverflow.com/a/53407670
tagged with: python
score: 6
upvote count: 6
accepted answer: http://stackoverflow.com/a/50295844
type: AnsweredQuestion
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50295844
tagged with: python-requests
has body: The simple import of requests import requests can be executes and used in windows shell but the same code says in pycharm: Traceback (most recent call last): File "C:/Users/XPS13/PycharmProjects/Testing/Webcrawler_Test.py", line 1, in &lt;module&gt; import requests ModuleNotFoundError: No module named 'requests' requests was correctly pip installed. Even uninstalling and reinstalling doesn't work. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/87608494
favorite count: 0
has title: Import requests working on Windows shell but not in PyCharm
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/53407670
has comment: http://stackoverflow.com/comment/87608320
type: Question

http://stackoverflow.com/a/50384765
has comment: http://stackoverflow.com/comment/87785456
type: Answer
has body: Your problem is here: if card_number.index(i) % 2 != 0: This looks for a specific digit in the number, but if the digit is repeated, you will get the position of the first occurrence. If both (or all, or no) occurrences are in odd positions, your code will work. But if one is in an even position and another not, then your odd/even test will produce the wrong answer. Do the odd/even position check this way: for n,i in enumerate(card_number): if n % 2 != 0: temp1.append(int(i) * 2) else: temp1.append(int(i))
score: 1
accepted answer of: http://stackoverflow.com/q/50384078
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50384078

http://stackoverflow.com/q/50384598
has title: python: How to determined if a value is contained in a certain column of 2D list?
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has body: Each index needs to appear only once. So I want to check whether a value of 2 exists already in the second column. my_list = [[0, 0], [1, 3], [2, 5], [3, 4]] It should return False in this case if I check for "2".
tagged with: list
accepted answer: http://stackoverflow.com/a/50384673
has answer: http://stackoverflow.com/a/50384685
has answer: http://stackoverflow.com/a/50384673
type: Question
has comment: http://stackoverflow.com/comment/87784924
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/87784990
possible better answer: http://stackoverflow.com/a/50384685
has comment: http://stackoverflow.com/comment/87784939
tagged with: multidimensional-array
tagged with: python

http://stackoverflow.com/a/50340545
upvote count: 8
has body: This is one way. Append or stack-based methods are inefficient, as memory is not pre-allocated. Manipulation of numpy arrays works best when memory allocation is determined ahead of time. arr1 = np.array([0.0, 1.0, 11.0, 111.0]) arr2 = np.array([0.5, 1.5, 11.5, 111.5]) arr3 = np.zeros(arr1.shape[0] + arr2.shape[0], dtype=arr1.dtype) arr3[::2] = arr1 arr3[1::2] = arr2 print(arr3) [ 0. 0.5 1. 1.5 11. 11.5 111. 111.5]
answers question: http://stackoverflow.com/q/50340520
type: Answer
has comment: http://stackoverflow.com/comment/114165213
score: 8
accepted answer of: http://stackoverflow.com/q/50340520
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87746622
score: 0
type: Comment
has text: They are illegal for a filename but not for a path. `c:\temp\tmp.txt` is a valid path but not a valid filename.
type: AnswerComment
comment on: http://stackoverflow.com/a/50365196

http://stackoverflow.com/comment/87522736
has text: Ok, thank you! yes I'm confused because I don't know how the function I'm using really works.
score: 0
comment on: http://stackoverflow.com/q/50251432
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50305911
score: 0
answers question: http://stackoverflow.com/q/50305572
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50305572
has body: I defined the following two methods: def check_repeat(l): for i in range(1,len(l)//2+1): pattern=l[:i] sub_lists=create_sublists(l, i, True) if all([x==pattern for x in sub_lists]): print("Found pattern {} with length {}".format(pattern, i)) return pattern def create_sublists(l, n, only_full=False): sub_lists=[] for j in range(n, len(l),n): if only_full and len(l[j:j+n])&lt;n: continue sub_lists.append(l[j:j+n]) return sub_lists It works as follows: with check_repeat(your_list) the input list is checked for patterns of arbitrary length. A pattern of length i is found, if the first i entries of your_list equal all following sub_lists of length i. The sublists are created by the method create_sublists, which returns a list of lists. If only_full is set to True, only sublists with length n are allowed. This handles the case where your list looks for example like this A=[1,2,3,1,2,3,1,2] and you want to accept [1,2,3] as a valid pattern and ignore the remaining sublist [1,2]. Each sublist is then compared to the current pattern, i.e. the first i entries of your input list. If all sublists, equal the current pattern, a true pattern is found. In contrast to the solution in Python finding repeating sequence in list of integers?, I do not only check the next i entries if they match the current pattern, but all of the following sublists with length i.

google-cloud-platform
tags question: http://stackoverflow.com/q/50311969
tags question: http://stackoverflow.com/q/50315126
tags question: http://stackoverflow.com/q/50364381
tags question: http://stackoverflow.com/q/50279905
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/50380237
tags question: http://stackoverflow.com/q/50282890
tags question: http://stackoverflow.com/q/50334017
tags question: http://stackoverflow.com/q/50309000
tags question: http://stackoverflow.com/q/50277963
type: Tag

http://stackoverflow.com/q/50361379
has comment: http://stackoverflow.com/comment/87739366
has comment: http://stackoverflow.com/comment/87822230
has body: How to check if every value in a pandas series is integer and count? I found a way to use to transform it to a list pd.xxx.tolist() and check every value with 1.1.is_integer() False to check for it . I'm just thinking if there is more tricky way to check it using pandas or numpy? Env:python3.6
tagged with: pandas
has title: how to check every pandas series value is integer and count?
answer count: 1
has comment: http://stackoverflow.com/comment/87739467
downvote count: 1
favorite count: 0
score: -1
type: Question
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50361420

http://stackoverflow.com/q/50346992
has body: Lets assume we have the following Dataframe: import pandas as pd df = pd.read_csv('subjects.csv') Col A, Interest, Col Start, Col Go, Col Learn, Learn English Lit Go Mathematics Start Science Learn Science Go English Start Math Learn Math Go Biology Start English I've written some code to pull out interests from a similar dataset as follows #Map Interests Mapper = ['English', 'Math', 'Maths', 'Mathematics', 'Biology', 'Science'] #Join Mapper to Interest Column pat = '|'.join(r"\b{}\b".format(x) for x in Mapper) df['interest'] = df['col A'].str.extract('('+ pat + ')', expand=False) #Align Interest Names by creating a dict and replacing values enter code here d = {'English Lit' : 'English', 'Biology' : 'Science', 'Mathematics' : 'Maths'} df['Interests'] = df['Interests'].replace(d, inplace=False) &gt;&gt;&gt; Output: Col A, Interest, Col Start, Col Go, Col Learn, Learn English Lit English Go Mathematics Maths Start Science Science Learn Science Science Go English English Start Math Maths Learn Math Maths Go Biology Science Start English English Now I need to measure engagement of Col A with a keyword and interest. I've done this as follows but I'm sure there are better ways to do this. df['Col Start'][df['col A'].str.contains("Learn", na=False) &amp; df['interest'].str.contains("Science")] = 'Learn' Additionally, what would be the best way to append multiple values into one column? for example if I had: Col A Learn Science, Math, Biology. I would like to have the keyword + interest mapped into a new column with the values separated by commas. This is where my current scripts falls apart, it writes over new values with previous ones, where I was trying to capture all engagement levels (if that makes sense..) Col A Col B Learn Science, Math, Biology. Learn S, Learn, M, Learn B Any help would be appreciative. (please be gentle I started coding in Feb!) Edit For Clarity: df.loc[df['col A'].str.contains("Learn", na=False) &amp; df['interest'].str.contains("Science"), 'Col …
favorite count: 0
type: Question
downvote count: 0
upvote count: 1
has title: Slicing Data from two columns and outputting a new values in Pandas Advice
has answer: http://stackoverflow.com/a/50347746
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
answer count: 1
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/50347746

http://stackoverflow.com/comment/87662194
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50323276
has text: Please provide the original `coordinates` list

http://stackoverflow.com/comment/87647915
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50315296
has text: I understand that what i'm trying to do is unclear and that this seems like an "XY problem". As the level of my question indicates, i'm quite new to python. In the above example, the 'index' dictionary is shown with only 4 pair of values but in fact it has hundreds. I need to split that back down into lists containing the keys of that dict and using the values to sort them. The answer from @Netwave seems to be doing just that.
type: Comment

http://stackoverflow.com/a/50247008
answers question: http://stackoverflow.com/q/50244737
has body: Figured out a solution. The problem is that I am treating row like a list but pymysql returns a dictionary. When I do a,b,c=row, the values of a,b,c are set to the keys (column headers) of row. The trick is to access the values of the dictionary and convert them to a list. a, b, c = list(row.values())
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/50244737
type: AcceptedAnswer

http://stackoverflow.com/comment/87613514
comment on: http://stackoverflow.com/a/50298237
score: 1
type: Comment
has text: It doesn't throw an error anymore, however, it still does not click on the button.
type: AnswerComment

http://stackoverflow.com/comment/87485187
type: QuestionComment
comment on: http://stackoverflow.com/q/50233302
has text: In that case I would maybe consider looping row by row, maybe using `iloc`, rather than selection. If I understand correctly you wish to compare rows with the indexes (r, r + 1)?
score: 0
type: Comment

http://stackoverflow.com/q/50258928
has answer: http://stackoverflow.com/a/50259346
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: numpy
has comment: http://stackoverflow.com/comment/87536224
has body: If I have a dictionary where all its elements are of the same shape, I can filter those elements by index as follows: import numpy as np import random # Some random data a1 = np.random.uniform(0., 1., 1000) a2 = np.random.uniform(0., 1., 1000) a3 = np.random.uniform(0., 1., 1000) # Some random indexes idx = random.sample(range(0, 1000), 25) # My dict aa = {'a1': a1, 'a2': a2, 'a3': a3} # New filtered dict bb = {k: v[idx] for k, v in aa.iteritems()} But if the elements within the dictionary have different shapes: a1 = np.random.uniform(0., 1., 1000) a2 = np.random.uniform(0., 1., (3, 1000)) a3 = np.random.uniform(0., 1., (5, 1000)) the above does not work anymore. Is there a way to generalize the filtering to work on arrays of different shapes (but equal lengths)?
type: Question
has comment: http://stackoverflow.com/comment/87536379
has title: Filter arrays of different shapes in dictionary by index
accepted answer: http://stackoverflow.com/a/50259346
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/87631830
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50307700
has text: Assuming that you create the `s` socket before you make the `connect` call, this would still raise an exception because the `s` in `(s, p)` would be a socket
score: 0

http://stackoverflow.com/a/53461250
type: Answer
score: 0
has body: Modifying your code: _, state = tf.nn.dynamic_rnn(lstm_cell, embed, dtype=tf.float32, sequence_length=some_placeholder) last_output = state.h Don't forget to add a sequence_length parameter in the call to dynamic_rnn if you want the sequence lengths to vary. Alternatively, you could use tf.gather_nd.
answers question: http://stackoverflow.com/q/50358767

firefox
type: Tag
tags question: http://stackoverflow.com/q/50250580
tag name: firefox
tags question: http://stackoverflow.com/q/50321278
tags question: http://stackoverflow.com/q/50301920
tags question: http://stackoverflow.com/q/50358454

http://stackoverflow.com/comment/87543479
has text: Thanks this is helpful, produces the correct answer and looks faster. It still takes awhile to run given the size of the data, is there anything else that would help? thank you
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50262648

http://stackoverflow.com/q/50266682
answer count: 0
type: UnansweredQuestion
has title: how to copy the contents between same string that are in two different files
score: 0
has comment: http://stackoverflow.com/comment/87552309
upvote count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87552114
has body: I have multiple log files in a folder and i need to copy the log contents of a particular test case which is spread between two files using python. Find the code here: inFile = open("log2file.txt") outFile = open("parse2", "w") copy = False for line in infile: if line.strip() == "Start": copy = True elif line.strip() == "End": copy = False elif copy: outfile.write(line)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87551238

http://stackoverflow.com/comment/87588154
has text: There's not actually a basemap loaded at all, I simply plot [`TIGER/LINE` shapefiles from the census bureau](https://www.census.gov/geo/maps-data/data/tiger-line.html) to give the viewer a minimal reference point without detracting from the data; that's the `points = gpd.read_file('points.shp')` and `roads.plot( . . . )` lines above.
type: QuestionComment
comment on: http://stackoverflow.com/q/50285019
type: Comment
score: 0

http://stackoverflow.com/q/50307483
linked to: http://stackoverflow.com/q/714475
accepted answer: http://stackoverflow.com/a/50309069
tagged with: python
upvote count: 18
tagged with: namespaces
has answer: http://stackoverflow.com/a/50309069
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50307485
linked to: http://stackoverflow.com/q/1463306
downvote count: 0
has comment: http://stackoverflow.com/comment/87631832
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50307485
tagged with: python-internals
has body: We already know that Function arguments used to have the limit of 255 explicitly passed arguments. However, this behaviour is changed now and since Python-3.7 there's no limit except sys.maxsize which is actually the limit of python's containers. But what about the local variables? We basically cannot add local variables to a function in a dynamic manner and/or changing the locals() dictionary is not permitted directly so that one can even test this in a brute force way. But the problem is that even if you change the locals() using compile module or exec function it doesn't affect the function.__code__.co_varnames, hence, you cannot access the variables explicitly inside the function. In [142]: def bar(): ...: exec('k=10') ...: print(f"locals: {locals()}") ...: print(k) ...: g = 100 ...: ...: In [143]: bar() locals: {'k': 10} --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-143-226d01f48125&gt; in &lt;module&gt;() ----&gt; 1 bar() &lt;ipython-input-142-69d0ec0a7b24&gt; in bar() 2 exec('k=10') 3 print(f"locals: {locals()}") ----&gt; 4 print(k) 5 g = 100 6 NameError: name 'k' is not defined In [144]: bar.__code__.co_varnames Out[144]: ('g',) This means that even if you use a for loop like: for i in range(2**17): exec(f'var_{i} = {i}') The locals() will be contain 2**17 variables but you cannot do something like print(var_100) inside the function. We know that basically there is no need to dynamically add a variable to the function while you can use a dictionary or in other words a custom namespace. But what's the proper way to test the limit of the maximum number of local variables in a function?
has title: How many local variables can a Python (CPython implementation) function possibly hold?
tagged with: function
has comment: http://stackoverflow.com/comment/87631045
score: 18

http://stackoverflow.com/comment/87525758
has text: Yeah sorry, misread your comment
score: 0
comment on: http://stackoverflow.com/q/50253997
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87501148
type: Comment
comment on: http://stackoverflow.com/a/50241715
has text: @RafaelC yep, I think so , also , if the last lane is not type , it should not count in my result
score: 0
type: AnswerComment

http://stackoverflow.com/a/50258854
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87537725
has body: You need to use yield instead of just printing locations for the output to be present in .jl file yield {'locations':locations}
answers question: http://stackoverflow.com/q/50258604
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/50258604

http://stackoverflow.com/comment/87618377
type: Comment
has text: But anyway, going by what's in your question: if you don't have `pip` on your PATH, but do have `python` (or `Python.exe`, or whatever), that's exactly why [the docs](https://docs.python.org/3/installing/#basic-usage) recommend `python -m pip install` in place of just `pip install`.
type: QuestionComment
comment on: http://stackoverflow.com/q/50300785
score: 1

http://stackoverflow.com/q/50344335
tagged with: python
has title: Grouping pandas dataframe based on common key
has body: I have a file which I have parsed as pandas DataFrame but want to collectively group by their individual element at column 3 w.r.t column 2. 0 1 2 3 4 0 00B2 0 -67 39 1.13 1 00B2 85 -72 39 1.13 2 00B2 1 -67 86 1.13 3 00B2 2 -67 87 1.13 4 00B2 3 -67 88 1.13 5 00B2 91 -67 39 1.13 6 00B2 4 -67 246 1.13 7 00B2 5 -67 78 1.13 8 00B2 6 -67 10 1.13 9 00B2 7 -67 153 1.13 10 00B2 1 -67 38 1.13 11 00B2 8 -67 225 1.13 12 00B2 9 -67 135 1.13 13 00B2 10 -67 23 1.13 14 00B2 4 -67 38 1.13 15 00B2 11 -67 132 1.13 16 00B2 12 -71 214 1.13 17 00B2 13 -71 71 1.13 18 00B2 14 -71 215 1.13 19 00B2 8 -71 38 1.13 20 00B2 15 -71 249 1.13 21 00B2 16 -71 174 1.13 22 00B2 17 -71 196 1.13 23 00B2 18 -71 38 1.13 24 00B2 19 -71 252 1.13 25 00B2 20 -71 196 1.13 26 00B2 21 -71 39 1.13 27 00B2 22 -71 39 1.13 28 00B2 23 -71 252 1.13 29 00B2 24 -71 39 1.13 .. ... .. ... ... ... I want the data that looks something like this DF1: -67 37 -72 37 -71 37 ... ... DF2: -68 38 -67 38 -70 38 ... ... DF3: -64 39 -63 39 -62 39 ... ... I have tried the following: e1 = pd.DataFrame(e1) print (e1) group = e1[3][2] == "group" print (e1[group]) This leads to nowhere close to what I want so how to groupby such data according to my requirement?
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50344411
has answer: http://stackoverflow.com/a/50344411

http://stackoverflow.com/comment/87555021
type: Comment
has text: Ahhhh, I finally get it. Thanks.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50268454

http://stackoverflow.com/comment/87598443
score: 0
has text: @Yann Vernier youre right. I was about to mention that with an edit. I tried to minimize the try block.
type: Comment
comment on: http://stackoverflow.com/a/50289964
type: AnswerComment

http://stackoverflow.com/q/50349451
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/87715466
downvote count: 2
tagged with: data-cleaning
possible better answer: http://stackoverflow.com/a/50349584
has comment: http://stackoverflow.com/comment/87715480
tagged with: python
has comment: http://stackoverflow.com/comment/87715154
tagged with: regex
has comment: http://stackoverflow.com/comment/87714966
has body: I'm working with a file using commas as a delimiter. However, it has a field, address in it where the address is of form x,y,z which causes a problem as each part of the address gets a new column entry. The address is immediately followed by member_no a 1 digit number like 2 etc. Col1 (Address), Col2(1 Digit number) text = '52A, XYZ Street, ABC District, 2' I basically want to remove all commas before that number from the address field. The output should be like 52A XYZ Street ABC District, 2' I tried re.sub(r',', ' ', text) but it's replacing all instances of commas.
has answer: http://stackoverflow.com/a/50349598
has comment: http://stackoverflow.com/comment/87715523
has answer: http://stackoverflow.com/a/68065022
has comment: http://stackoverflow.com/comment/87715292
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/50349579
has answer: http://stackoverflow.com/a/50349579
score: 1
has title: Regex to remove commas before a number in python
has answer: http://stackoverflow.com/a/50349584
favorite count: 0
has comment: http://stackoverflow.com/comment/87715579
has comment: http://stackoverflow.com/comment/87715325

http://stackoverflow.com/q/50265297
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87603928
has comment: http://stackoverflow.com/comment/87548911
score: 0
has comment: http://stackoverflow.com/comment/87569095
has title: UnicodeError: encoding with 'idna' codec failed when sending email in Python
has comment: http://stackoverflow.com/comment/87548648
tagged with: python
has comment: http://stackoverflow.com/comment/87585156
has comment: http://stackoverflow.com/comment/87632360
type: Question
tagged with: smtplib
answer count: 0
has body: I am following a tutorial in which I run the following code. import smtplib email_user = 'email@gmail.com' email_send = 'email@gmail.com' server = smtplib.SMTP('smtp.gmail.com',587) server.starttls() server.login(email_user,'pass') message = 'Hello' server.sendmail(email_user,email_send,message) server.quit() Unfortunately, the code is throwing an error: Traceback (most recent call last): File "C:\Users\lol\PycharmProjects\untitled\venv\lib\encodings\idna.py", line 165, in encode raise UnicodeError("label empty or too long") UnicodeError: label empty or too long The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/lol/PycharmProjects/untitled/hello.py", line 27, in &lt;module&gt; server = smtplib.SMTP('smtp.gmail.com', 587) File "C:\Users\lol\AppData\Local\Programs\Python\Python36-32\Lib\smtplib.py", line 261, in __init__ fqdn = socket.getfqdn() File "C:\Users\lol\AppData\Local\Programs\Python\Python36-32\Lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long) How can I fix this?

http://stackoverflow.com/comment/87593133
comment on: http://stackoverflow.com/q/50288459
type: QuestionComment
has text: @fferri There is a ternary operator like `1 if False else True` but the point is it makes no sense here since append is in-place and the else condition is basically not required if the logic is inverted
score: 0
type: Comment

http://stackoverflow.com/comment/87612600
has text: Thank you @ jezrael. Sorry, I still do not understand much of RE. This command does what, please? Do I need to replace some of it with words of interest?
comment on: http://stackoverflow.com/a/50292745
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/87653075
has text: @chrisz Yep, I made sure the inputs were cast to floats so this would work. Otherwise, you would need `x[m] = x[m] / y[m]` and you'd end up coercing `x`.
comment on: http://stackoverflow.com/a/50318378
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/50325198
answers question: http://stackoverflow.com/q/50325063
type: Answer
score: 0
has body: my_range=(1,1000), (1000,2000), (2000,3000), (3000,4000), (4000,5000) my_output='Very Low, Low, Medium, High, Very High'.split(', ') num=3565 for k,i in enumerate(my_range): if i[0]&lt;=num&lt;i[1]:print(my_output[k]);break else: print('Out of range')

http://stackoverflow.com/comment/87746715
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50361783
score: 0
has text: Yes, you can. According to the docs: https://radimrehurek.com/gensim/models/word2vec.html the `gensim.models.Word2vec` takes a param `sentences`as input which is a list of the tokens in the sentence. These are usually the words of the sentence. But you can have your own definition of tokens, as in your case. So, in your case, you need to implement your own small function that would produce the individual+compound tokens and then pass those to `gensim.models.Word2vec`

http://stackoverflow.com/comment/87723763
type: QuestionComment
has text: We've already had this conversation in the original question and I responded that you should await any operation that can block. I also referred you to [a tutorial](https://medium.freecodecamp.org/a-guide-to-asynchronous-programming-in-python-with-asyncio-232e2afa44f6) and [an answer](https://stackoverflow.com/questions/33357233/when-to-use-and-when-not-to-use-python-3-5-await/33399896#33399896) with more information.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50352077

http://stackoverflow.com/a/50235365
answers question: http://stackoverflow.com/q/50235218
has comment: http://stackoverflow.com/comment/87490445
has comment: http://stackoverflow.com/comment/87528398
type: Answer
has body: Put your contenthost = [] initial declaration outside of the for loop and try again.
has comment: http://stackoverflow.com/comment/87507658
score: 0
has comment: http://stackoverflow.com/comment/87488495
has comment: http://stackoverflow.com/comment/87512370
has comment: http://stackoverflow.com/comment/87497372

http://stackoverflow.com/comment/87745606
comment on: http://stackoverflow.com/a/50354506
type: AnswerComment
score: 0
has text: Thank you for your answer. It does not however solve my problem at the moment. The issue I'm having is that `line` here `xmlVal = ET.fromstring(line)` sometimes contains the `&` that it can't handle. Unless I can somehow read `line` in and escape it before I hand it to `ElementTree` my problem still stands, I think.
type: Comment

http://stackoverflow.com/a/50302407
has comment: http://stackoverflow.com/comment/87632016
answers question: http://stackoverflow.com/q/50302365
has comment: http://stackoverflow.com/comment/87621312
downvote count: 0
type: Answer
has body: The logger returned by logging.getLogger(__name__) is the same logger each time %run main.py is executed. But ch = logging.StreamHandler() instantiates a new StreamHandler each time, which is then added to the logger: logger.addHandler(ch) Thus, on subsequent runs of %run main.py, the logger has multiple handlers attached to it and a record gets emitted by each handler. In [5]: %run main.py 2018-05-11 2251:17 - WARNING - 3. This is a warning! 2018-05-11 2251:17 - ERROR - 4. This is an error 2018-05-11 2251:17 - CRITICAL - 5. This is fucking critical! In [6]: logger Out[6]: &lt;logging.Logger at 0x7f5d0152fe10&gt; The first time %run main.py is run, two handlers are attached to logger: In [7]: logger.handlers Out[12]: [&lt;logging.StreamHandler at 0x7f5d0152fdd8&gt;, &lt;logging.FileHandler at 0x7f5d014c40f0&gt;] In [13]: %run main.py 2018-05-11 2251:44 - WARNING - 3. This is a warning! 2018-05-11 2251:44 - WARNING - 3. This is a warning! 2018-05-11 2251:44 - ERROR - 4. This is an error 2018-05-11 2251:44 - ERROR - 4. This is an error 2018-05-11 2251:44 - CRITICAL - 5. This is fucking critical! 2018-05-11 2251:44 - CRITICAL - 5. This is fucking critical! The second time, there are now four handlers: In [14]: logger.handlers Out[14]: [&lt;logging.StreamHandler at 0x7f5d0152fdd8&gt;, &lt;logging.FileHandler at 0x7f5d014c40f0&gt;, &lt;logging.StreamHandler at 0x7f5d014c4668&gt;, &lt;logging.FileHandler at 0x7f5d014c4550&gt;] In [15]: logger Out[15]: &lt;logging.Logger at 0x7f5d0152fe10&gt; To prevent duplication, you could call logger.removeHandler between %run calls: In [29]: for handler in logger.handlers: logger.removeHandler(handler) In [30]: %run main.py 2018-05-11 2257:30 - WARNING - 3. This is a warning! 2018-05-11 2257:30 - ERROR - 4. This is an error 2018-05-11 2257:30 - CRITICAL - 5. This is fucking critical! or, modify main.py so that new handlers are not attached each time %run is called. For example, you could setup logger using logging.config.dictConfig: i…
accepted answer of: http://stackoverflow.com/q/50302365
score: 2
has comment: http://stackoverflow.com/comment/87656942
has comment: http://stackoverflow.com/comment/87621357
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87632153
has comment: http://stackoverflow.com/comment/87621426
upvote count: 2

http://stackoverflow.com/a/50321080
answers question: http://stackoverflow.com/q/50320955
downvote count: 0
has body: Most likely this is caused by a timezone issue. I suspect when you convert to timestamp and back to datetime the timezone information is lost.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/87716301
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50347080
has text: Thank you @Daniel Roseman! My form wasn't in the form-tag of my template (it should have been but I reverted my changes with git and didn't check again).

http://stackoverflow.com/comment/87645948
type: QuestionComment
score: 0
has text: Blogs = self.model.objects.get (slug=slug) worked but form is still not showing up
type: Comment
comment on: http://stackoverflow.com/q/50314846

http://stackoverflow.com/comment/87729602
has text: There is a bug in this solution: if you have a sequence of more than one element appearing in `l1` then only the first element appears in the result and the other elements are discarded. I'd expect instead to find all these elements as separate keys, but, possibly, with empty lists as values. To do that you could have a `nonlocal` counter, the `key` function then becomes something like `counter += x in keys; return counter`.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/50351198

http://stackoverflow.com/a/50340982
has body: Apparently textcat expects gold values which where made with GoldParse, not plaintext values. The working version looks like this: import spacy from spacy.pipeline import TextCategorizer from spacy.gold import GoldParse nlp = spacy.load('en') doc1 = nlp(u'This is my first document in the dataset.') doc2 = nlp(u'This is my second document in the dataset.') gold1 = GoldParse(doc=doc1, cats={'Category1': 1, 'Category2': 0}) gold2 = GoldParse(doc=doc2, cats={'Category1': 0, 'Category2': 1}) textcat = TextCategorizer(nlp.vocab) textcat.add_label('Category1') textcat.add_label('Category2') losses = {} optimizer = textcat.begin_training() textcat.update([doc1, doc2], [gold1, gold2], losses=losses, sgd=optimizer) Thanks to @abarnert in the comments for helping me debug this.
has comment: http://stackoverflow.com/comment/87725447
answers question: http://stackoverflow.com/q/50340611
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/70120487
upvote count: 3
downvote count: 0
has body: First we add the column and allow it to have null values op.add_column('abc', Column('id', BIGINT(unsigned=True), comment='This column stores the type of phrase') ) Then we create the primary key op.create_primary_key( 'abc_pk', table_name='abc', columns=['id'] ) Not sure how it allows me to add a primary key on an empty column but i guess it is because it is in a transaction block. Then we alter the column to have the autoincrement column op.alter_column( existing_type=BIGINT(unsigned=True), table_name='abc', column_name='id', autoincrement=True, existing_autoincrement=True, nullable=False)
score: 3
answers question: http://stackoverflow.com/q/50232239
type: Answer

http://stackoverflow.com/comment/87569384
score: 3
type: Comment
type: QuestionComment
has text: Suppose you configure a window size. If the window is not shown yet in the screen, or tkinter hasn't finished all its UI update tasks, and you ask for the window size, it may not reflect the size you configured, because the window or widget is not yet at its requested size. The req methods will give you the requested values for the widget size, no matter what the real size was at the moment.
comment on: http://stackoverflow.com/q/50236055

http://stackoverflow.com/q/50246282
possible better answer: http://stackoverflow.com/a/50250134
has title: Django Annotate Sum
has answer: http://stackoverflow.com/a/50250134
downvote count: 0
has body: I'm trying to get a simple sum for a column with several rows in a queryset. My direct question is (a) how do I set get_queryset() to include a sum of a column and (b) how do I access that element in a template? Following this question: #models.py class ItemPrice( models.Model ): price = models.DecimalField ( max_digits = 8, decimal_places=2 ) .... There are two answers provided - one using the .aggregate() method which I don't believe returns a queryset and .annotate() method which I believe appends an item to the queryset. So, I would have expected that the following would add another item to the object list in this view: #views.py def get_queryset(self): # generate table and filter down to a subquery. queryset = ItemPrice.objects.filter(&lt;some_filter&gt;) # sum the price for each row in the subquery. queryset = queryset.annotate(totals=Sum('price')) return queryset Then in the the Template, I would be able to iterate through the object list like this: #template.html {% for item in object_list %} {{ item }} {% endfor %} With the expectation that one of the items (the last item?) would be price_sum and that the balance could be accessed as price_sum.price. However, when i add the following to my template, I get the prices for each line item - no summation. {% for item in object_list %} {{ item.totals }} {% endfor %} But, I can't access the item. I don't know if the problem is the view modification of the get_queryset() or if it's in the template?
has comment: http://stackoverflow.com/comment/87510303
has comment: http://stackoverflow.com/comment/87530406
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/50265003
score: 6
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/8616343
upvote count: 6
accepted answer: http://stackoverflow.com/a/50265003
type: AnsweredQuestion

http://stackoverflow.com/comment/87535216
has text: Where and how are you running this? Did you open the produced images in a image viewer and checked how large (in pixels) they are? There might be a maximum optainable figure size but at 150 inch you should not have reached that point yet. The code above produces two different images for me as expected.
score: 0
comment on: http://stackoverflow.com/q/50257509
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57999278
score: 8
upvote count: 8
has body: First add this line to your ~/.zshrc file: export PATH="~/miniconda3/bin:$PATH" Then navigate to miniconda3 folder and update it: cd ~/miniconda3/bin && ./conda update conda Finally there is script to automatically init conda for your shell: ./conda init zsh
downvote count: 0
answers question: http://stackoverflow.com/q/50336405
type: Answer
has comment: http://stackoverflow.com/comment/102638115

pca
tag name: pca
tags question: http://stackoverflow.com/q/50247596
type: Tag

http://stackoverflow.com/comment/87484141
has text: `''.join(mylist)` creates a string from a list
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50233337

http://stackoverflow.com/q/50237688
score: 0
tagged with: pandas
has body: I'm getting row counts for a particular column like so: subreddit_count = df['body'].groupby(df['subreddit']).agg(['count']) Which returns the following df: subreddit count 0 0xProject 12 1 100sexiest 1 2 100yearsago 2 3 1022 3 4 1200isjerky 2 5 1200isplenty 37 6 1200isplentyketo 1 7 12ozmouse 1 8 12thMan 4 9 12winArenaLog 1 10 13ReasonsWhy 5 11 13or30 3 12 14ers 1 13 1500isplenty 1 14 15SecondStories 3 15 18650masterrace 1 16 18_19 10 17 1911 5 18 195 2 19 19KidsandCounting 4 20 1P_LSD 18 21 2007oneclan 2 22 2007scape 1044 23 2010sMusic 1 24 21savage 1 25 22lr 1 26 23andme 9 27 240sx 4 28 24CarrotCraft 1 29 24hoursupport 5 I would like to essentially undo the groupby so that these counts are added to every row in the original df. I've tried using reset_index to no avail. What's the right approach here?
has comment: http://stackoverflow.com/comment/87492741
linked to: http://stackoverflow.com/q/17995024
tagged with: python
answer count: 0
duplicate of: http://stackoverflow.com/q/17995024
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87493404
has title: Add row counts to entire dataframe
type: Question

http://stackoverflow.com/a/50381513
has body: try upgrading pip. Use pip install --upgrade pip
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87779217
answers question: http://stackoverflow.com/q/50381372
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87574283
type: QuestionComment
comment on: http://stackoverflow.com/q/50278343
score: 0
has text: @DanielleM. I made another error on how the output is formed. Its (x,y,x,y,x) where the y is all the same value from each tuple set and the x is the respective x values from each tuple set. Thank you for pointing that out
type: Comment

http://stackoverflow.com/a/50263935
answers question: http://stackoverflow.com/q/50263862
score: 0
has comment: http://stackoverflow.com/comment/87545899
has body: The input and print syntax is slightly different between python 2.7 and 3. In 2.7 input evaluates the data, whereas raw_input reads it in as a string. In 3.x input will read in the data an as a string. print doesn't need brackets in 2.7 but needs them in 3.x Python 2.7 foodname=raw_input('please enter food name.') # raw_input returns a string foodcost=int(raw_input('please enter food cost.')) # read as string cast to int print foodname, foodcost Python 3.x foodname=input('please enter food name.') # Input returns a string foodcost=int(input('please enter food cost.')) print(foodname, foodcost) # add brackets to print
type: Answer

http://stackoverflow.com/comment/87545785
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50263862
has text: run it again and show us the screenshot of it.

http://stackoverflow.com/a/50312501
has comment: http://stackoverflow.com/comment/87641276
has comment: http://stackoverflow.com/comment/87641355
has comment: http://stackoverflow.com/comment/87641377
has comment: http://stackoverflow.com/comment/87641305
score: 0
has body: You want to just increase the value of i by 10 every time. You can use a builtin function like range in python. Do check it out, range is used quite often in conjunction with the for loop in python for i in range(1 , 100, 10): url = "https://www.minsalud.gov.co/sites/rid/Paginas/freesearchresults.aspxk=&amp;k=Salud%20Mental%20Legislacion#k=%2CSalud%20Mental%20Legislacion=+ "+ str(i)+")" print(url) The above for loop will start with a value of i = 1, with an increment of 10 every time until i reaches a maximum value that is less than 100. The value of i in the above for loop will be 1 11 21 31 41 51 61 71 81 91 When i becomes 101, it ends the for loop. Edit : To write these url's to a file with open('urls.txt','w') as f: for i in range(1 , 100, 10): url = "https://www.minsalud.gov.co/sites/rid/Paginas/freesearchresults.aspxk=&amp;k=Salud%20Mental%20Legislacion#k=%2CSalud%20Mental%20Legislacion=+ "+ str(i)+")" f.write(url+'\n') For more information, checkout reading and writing files in python3
type: Answer
has comment: http://stackoverflow.com/comment/87641267
answers question: http://stackoverflow.com/q/50312432
has comment: http://stackoverflow.com/comment/87641432

http://stackoverflow.com/q/50381790
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50381826
type: Question
type: UnansweredQuestion
has body: I may be doing all of this completely wrong, but I'm a google taugh python programmer, so there's that. I have a created a class called "create" that builds an object. Properties of that object are instances of another class (settings) class setting: def __init__(self,name,value,IsRequired): self.name=name self.IsRequired=IsRequired self.value=value class create: filter=setting("filter","filter_name",True) consumer=setting("consumer","","True") def __init__(self, name): self.name=name &gt;&gt;&gt;a=create("test") &gt;&gt;&gt;a.name 'test' &gt;&gt;&gt; a.filter.IsRequired True &gt;&gt;&gt; a.filter.value 'filter_name' This lets me call the complex properties of each of my objects settings individually. For example, see if a setting (filter) is required for execution by checking a.filter.IsRequired To adjust the settings, specifically 'value' I am taking input from the user. I can reference the overall object with a string by using eval. &gt;&gt;&gt;one="a" &gt;&gt;&gt;eval(one).filter.IsRequired True &gt;&gt;&gt;eval(one).filter.value="NewValue" &gt;&gt;&gt;a.filter.value 'NewValue' Now the issue. I'm trying to change 'filter' based on user supplied input. var1="a" var2="filter" &gt;&gt;&gt; eval(var1).eval(var2).value Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: create instance has no attribute 'eval' How can I assign a user supplied variable to the 'value' of 'filter' in this example?
has answer: http://stackoverflow.com/a/50381844
tagged with: python
has title: How do I assign a user-supplied argument to a python attribute when that attribute is a class itself

http://stackoverflow.com/q/50358870
tagged with: python
has title: SPSS, transform data, one variable, into ten different variables
tagged with: statistics
has comment: http://stackoverflow.com/comment/88111124
tagged with: syntax
score: 0
has body: I have data, in one variable. It is about 800 numbers. I need actually to work with the median of every 10 value. I realize that it is much more practical to use ten different variables, as these 10 values are attributes to one case/measurement in my experiment. Easier to calculate median this way. Can this be done via syntax or in combination with python? SPSS does support python. Many many thanks for any input. I will eventually have to it number by number. Hope someone got any idea
answer count: 1
has answer: http://stackoverflow.com/a/50825211
type: Question
tagged with: spss
type: UnansweredQuestion

http://stackoverflow.com/q/50330762
tagged with: curve-fitting
tagged with: python
has title: Performing a Gaussian fit on many arrays in a matrix in a row and saving the results
accepted answer: http://stackoverflow.com/a/50331047
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50331047
has comment: http://stackoverflow.com/comment/87678076
has comment: http://stackoverflow.com/comment/87677559
score: 1
has comment: http://stackoverflow.com/comment/87677951
answer count: 1
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/87677909
has comment: http://stackoverflow.com/comment/87677829
upvote count: 1
has body: I have a matrix of data with 1024 columns of 100 values each where I'm trying to perform a Gaussian fit to each column and save the results in a new array. My code is the following: from astropy.io import fits from astropy.modeling import models, fitting import numpy as np Image1 = fits.open('Image.fits') Image_data = Image1.data[:,:] x = np.linspace(-50,50,50) Gauss_Model = models.Gaussian1D(amplitude=1000., mean=0, stddev=1.) Fitting_Model = fitting.LevMarLSQFitter() Fit_Data = Fitting_Model(Gauss_Model, x, Image_data[:,0]) This code works just fine and gives a fit to the first column in Image_data, but I want it to perform a fit to all 1024 columns of data in Image_data and save the results in a new array. I tried to use a for-loop but it didn't work. I would very much appreciate some help with how to do this, thanks!
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87677771
tagged with: gaussian

http://stackoverflow.com/comment/87686343
type: QuestionComment
comment on: http://stackoverflow.com/q/50335057
score: 2
has text: uppercase `Print` without parentheses? What python version is it?
type: Comment

http://stackoverflow.com/a/50385083
upvote count: 1
has comment: http://stackoverflow.com/comment/87825686
answers question: http://stackoverflow.com/q/50383845
has comment: http://stackoverflow.com/comment/87789916
has comment: http://stackoverflow.com/comment/87791110
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/87814275
has body: The index query is using a rather unnecessary field doc, while the update query is working as expected it updated the _source , not the doc inside it. For the error, the body used isn't valid. Use resp = es.update(index="radsearch", doc_type="default", id=18, body={"doc": edit_author1}) Refer: example-usage
downvote count: 0

http://stackoverflow.com/q/50326464
downvote count: 0
tagged with: pandas
score: 1
tagged with: python
has body: I have a csv-file with severel values for several stocks that looks like this: date stock_A date stock_B date stock_C 30.10.2017 09:00 3223 30.10.2017 09:00 53234 ... ..... 30.10.2017 09:02 2544 30.10.2017 09:01 24337 ... ..... 30.10.2017 09:04 925 30.10.2017 09:02 4529 ... ..... 30.10.2017 09:05 3210 30.10.2017 09:03 8534 ... ..... As you can see, every second column is a datetime index. However, it is not in the same order/frequency. Is there a way to import this data with pandas such that I get only one index and the data is mapped accordingly? I already tried this code: pd.read_csv(file, sep=";", header=0, index_col=['date'], parse_dates=True, dtype=object) But it only imports the first row as index and the other dates as columns with values. However, I would like to have my DataFrame as follows: date stock_A stock_B stock_C 30.10.2017 09:00 3223 53234 122 30.10.2017 09:01 0 24337 1215 30.10.2017 09:02 2544 4529 0 30.10.2017 09:03 0 8534 1354 ...
type: Question
upvote count: 1
type: UnansweredQuestion
answer count: 1
has title: pandas read_csv with index in every second column
has answer: http://stackoverflow.com/a/50326669
favorite count: 0

object-detection
tags question: http://stackoverflow.com/q/50293090
tags question: http://stackoverflow.com/q/50307347
type: Tag
tags question: http://stackoverflow.com/q/50364281
tag name: object-detection
tags question: http://stackoverflow.com/q/50354682
tags question: http://stackoverflow.com/q/50253535

amazon-athena
type: Tag
tag name: amazon-athena
tags question: http://stackoverflow.com/q/50291963

http://stackoverflow.com/comment/87658202
has text: If I manually copy/paste one of the list elements into a string x my expression works.
comment on: http://stackoverflow.com/q/50321100
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/87533473
has text: It's impossible to tell without knowing which API you are calling and how this API is designed to work. You should contact the API developer and work with them to figure out why the API response does not match the API docs.
score: 0
comment on: http://stackoverflow.com/q/50248921
type: Comment
type: QuestionComment

http://stackoverflow.com/q/50316330
score: 1
has title: Globbing in list search
accepted answer: http://stackoverflow.com/a/50316342
tagged with: python
has answer: http://stackoverflow.com/a/50316342
type: Question
has body: Given this list: aa = ['a.b.*', 'a.b.x', '*'] I'd like a.b.c to match aa[0] and aa[2] using globbing. glob and fnmatch seem to expect filename paths to do this work. Is there anything that implements globbing for arbitrary string searches?
upvote count: 2
answer count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: glob

http://stackoverflow.com/comment/87788166
has text: Thank you for both of your answers! Really helpful. For the user id variable, is it possible to pass a list instead of just one ID? Or to run it all with a list comprehension? Or should I look at other avenues? Not asking for the code, just a pointer in the right direction. Thanks again!
type: Comment
comment on: http://stackoverflow.com/a/50384124
score: 0
type: AnswerComment

http://stackoverflow.com/comment/87772278
type: Comment
type: QuestionComment
has text: It would be nice to have the full error output here.
score: 0
comment on: http://stackoverflow.com/q/50377897

http://stackoverflow.com/a/70537454
downvote count: 0
has body: Instead of patching the __set__ method you can patch the specific descriptor's max value. This approach is more surgical in that it only patches the font family descriptor that is causing the error. By comparison, if you patch descriptors\base.py as suggested in other answers, you'll be allowing potentially bad values for all descriptors, not just font family. # IMPORTANT, you must do this before importing openpyxl from unittest import mock # Set max font family value to 100 p = mock.patch('openpyxl.styles.fonts.Font.family.max', new=100) p.start() import openpyxl openpyxl.open('my-bugged-worksheet.xlsx') # this works now! This approach uses mock but in principle you can also patch the .py file where the openpyxl.styles.fonts.Font.family.max descriptor is contained.
answers question: http://stackoverflow.com/q/50236928
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/50320159
downvote count: 0
has title: Calculating degenerate states for N-dimensions
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: Trying to generalize a calculation of degenerate states,(from quantum mechanics n1^2 + n2^2 +n3^2 = Energy) but can't quite get the iteration down right. Creating a list of size N that starts with all zeroes. then want to slowly iterate each number of that list, sum together the squares of each number in that list, and check to see if they equal a given number. If not, increase number by one and check again. def sqsum(a): return sum(a[i]**2 for i in range(len(a))) def degeneracy(n,E): import numpy as np a=[0]*n #creates a list of zeroes of size n [0,0,0,....] z=0 #used to count number of degenerate states print(a, "original") EE=int(np.floor(np.sqrt(E))) for i in range(len(a)): #iterates through list a[] print(i) if a[i]&lt;=EE: for j in a: sum=0 print(a) sum+=a[j]*a[j] if sum == E: print("sum equals", sum) z+=1 a[i]+=1 print("Total number of degenerate states is", z) Problem is that I can get the first number in the list to iterate [0,0,0], [1,0,0], [2,0,0] and so on, but I also want to iterate the other numbers, then have it reset after a point. [1,0,0],[1,1,0],[1,1,1],[2,0,0],[2,1,0],[2,1,1],[0,1,0]. If someone could help me figure out the loop, that would be great. *Edit(woops, realized the sqsum() function up top is part of other attempt at this, you can ignore it)
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/comment/87547788
type: Comment
has text: @peteryoung yw : -) happy coding
comment on: http://stackoverflow.com/a/50254966
type: AnswerComment
score: 0

http://stackoverflow.com/q/50384348
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87784393
has comment: http://stackoverflow.com/comment/87785061
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87784467
tagged with: python
has comment: http://stackoverflow.com/comment/87784628
has comment: http://stackoverflow.com/comment/87785252
has comment: http://stackoverflow.com/comment/87784492
has comment: http://stackoverflow.com/comment/87785875
has comment: http://stackoverflow.com/comment/87784666
has comment: http://stackoverflow.com/comment/87784856
has title: When is cwd in PYTHONPATH needed?
score: 1
has comment: http://stackoverflow.com/comment/87784782
has comment: http://stackoverflow.com/comment/87784696
has comment: http://stackoverflow.com/comment/87784721
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/50202762
tagged with: python-import
answer count: 0
has body: I am working at the top of my project. In some environments, I can simply: from cslib.svc import SVC without problems. In others: from cslib.svc import SVC E ModuleNotFoundError: No module named 'cslib' In each case, PYTHONPATH is not set, and I am at the top of my project. Setting PYTHONPATH=. solves the problem, but I would like to understand why in some cases this is needed, and why in some cases it is not. Here it works: $ python --version Python 2.7.12 Here it works also: » python --version Python 3.5.2 Here it doesn't: » python --version Python 2.7.13 But I am not convinced this problem is version related. When / why do we need to add the cwd to PYTHONPATH?

http://stackoverflow.com/q/50281005
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/50281351
tagged with: trading
has comment: http://stackoverflow.com/comment/87578901
upvote count: 4
type: AnsweredQuestion
tagged with: pandas
answer count: 1
has body: This is a long read but I looked through as many examples on StackOverflow of creating functions to iterate through DataFrames, etc. and just couldn't find anything to fit my needs. I have also only been using python and coding in general for about 2 months, so I apologize if something is unclear. I have a dataframe with daily price history and am trying to create a back-test for buy signals based on this strategy: We first look for a day where the closing price is greater than the closing price of both the day before and the day after. Let's call this the "base day." To initiate our buy signal we wait for a day where the closing price is back above the "base day." We now have an open position. We hold this position until we get a sell signal which comes from the opposite of what our buy signal was looking for. (ie. closing price below a previous day where day prior and day after were higher) I only want one buy to be active at a time until we get a sell signal and then the process starts over. Below is an example dataframe with a small portion of the data I am looking at import pandas as pd data = { 'date': [1/3/2000,1/4/2000,1/5/2000,1/6/2000,1/7/2000,1/10/2000,1/11/2000,1/12/2000,1/13/2000,1/14/2000,1/18/2000,1/19/2000,1/20/2000,1/21/2000,1/24/2000,1/25/2000,1/26/2000,1/27/2000,1/28/2000,1/31/2000,2/1/2000,2/2/2000,2/3/2000,2/4/2000,2/7/2000,2/8/2000,2/9/2000,2/10/2000,2/11/2000,2/14/2000,2/15/2000,2/16/2000,2/17/2000,2/18/2000,2/22/2000,2/23/2000,2/24/2000,2/25/2000,2/28/2000,2/29/2000], 'close': [308.3,315.3,314.4,307.5,309.8,313.4,310.7,324.2,332.5,348.8,351.1,348.2,348.7,343.5,343,343.3,342.4,343,334.4,334.6,336,333.8,331.6,332.8,335.9,341.2,338.4,342.1,343.2,339.5,346.9,342,339.6,337.4,335,330.8,331.3,331.1,332.6,335.1]} df = pd.DataFrame(data) ## Create columns to compare price to day before and day after df['prev_close'] = df['close'].shift(1) df['next_close'] = df['close'].shift(-1) ## BOOLEAN TO RETURN IF PRICE IS LOWER THAN PREVIOUS AND NEXT DAY df['hig…
downvote count: 1
favorite count: 0
type: Question
has title: Backtesting Trading Strategy with python and pandas - Recognizing only one open position at a time
score: 3
has comment: http://stackoverflow.com/comment/87603915
accepted answer: http://stackoverflow.com/a/50281351

http://stackoverflow.com/q/50233521
answer count: 1
has answer: http://stackoverflow.com/a/50233813
accepted answer: http://stackoverflow.com/a/50233813
type: Question
tagged with: numpy
has title: Sorting Numpy Array of two different types
has comment: http://stackoverflow.com/comment/87485512
tagged with: python
has comment: http://stackoverflow.com/comment/87484909
tagged with: sorting
tagged with: data-structures
has body: I mainly code in C++ and I'm trying to figure out how to sort this data structure that I've managed to create. Please find the code following: dtype = [('dist',float) , ('type',int)] arr = np.zeros((200,2), dtype = dtype) i = 0 for current_image in all_images: arr[i][0] = distance(current_image, new_image) if current_image[576] == 1: arr[i][1] = 1 else: arr[i][1] = 0 i = i + 1 I wanted to create a 200 by 2 array of floats in the first column and ints in the second. I'm not particularly sure how to sort all 200 elements based on the dist value from smallest to largest. Also my data structure looks strange, something like this: [[( 9.47168802, 9) ( 0. , 0)] [( 6.95162905, 6) ( 1. , 1)] [( 8.72382552, 8) ( 0. , 0)] [( 8.9333134 , 8) ( 1. , 1)]]
has comment: http://stackoverflow.com/comment/87485933
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/50237263
has answer: http://stackoverflow.com/a/50239330
answer count: 5
tagged with: python
linked to: http://stackoverflow.com/q/1119722
has answer: http://stackoverflow.com/a/50242152
has body: I am trying to map a string of characters (A, T, C, G) into a 64 bit integer where each letter is represented as two bits using this mapping: mapping = {'A': 0b00, 'C': 0b01, 'G': 0b10, 'T': 0b11} The "sequence" string will not be longer than 28 characters, and I intend for the integer to be zero-padded at the beginning to make it 64 bits. Currently, I use the below function, but it is incredibly slow. I then convert the output using by calling: int(result, 2) This currently works, but I'd like to make this function incredibly fast. I don't know C++ well so it's hard for me to port to that. I am trying Cython now but I am unfamiliar with that as well. Any help making this more efficient in Python (or even C++ or Cython equivalent) would be greatly appreciated. Below is my code, again which I call int() on afterwards. def seq_to_binary(seq): values = [mapping[c] for c in seq] BITWIDTH = 2 return "".join(map(lambda x: bin(x)[2:].zfill(BITWIDTH), values)).encode(); At typical sequence input would be something like: 'TGTGAGAAGCACCATAAAAGGCGTTGTG'
type: UnansweredQuestion
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50237642
has answer: http://stackoverflow.com/a/50238252
tagged with: cython
has title: Convert String to 64bit integer mapping characters to custom two-bit values mapping
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: binary
score: 3
has answer: http://stackoverflow.com/a/50237701

http://stackoverflow.com/a/60022080
type: AcceptedAnswer
has body: You could put a format string inside a format string. l = [1000, 10, 100] for n in l: # 3.6 and newer: print(f"Money earned: {f'${n}':&gt;5}.") for n in l: # older than 3.6: print("Money earned: {0:&gt;5}.".format("${0}".format(n))) Outcome: Money earned: $1000. Money earned: $10. Money earned: $100. Money earned: $1000. Money earned: $10. Money earned: $100.
type: Answer
accepted answer of: http://stackoverflow.com/q/50240030
score: 0
answers question: http://stackoverflow.com/q/50240030

http://stackoverflow.com/comment/87556374
type: QuestionComment
comment on: http://stackoverflow.com/q/50269461
has text: can you share a sample of your directory structure?
score: 0
type: Comment

http://stackoverflow.com/comment/87585226
comment on: http://stackoverflow.com/q/50266855
type: Comment
score: 0
has text: There is a full stack trace, but here is the beginning of the error: ValueError Traceback (most recent call last) <ipython-input-3-71f6c878576e> in <module>() 13 data_request=requests.get("http://api.etherscan.io/api?module=account&action=txlist&address="+address+"=5585000&endblock=5590000&sort=asc&apikey=SZAEWWTN9YXQNR4X593AUDB7Y5323D6CAE") 14 json=data_request.json() ---> 15 df = pd.DataFrame(json,dtype=object,index=[0])
type: QuestionComment

http://stackoverflow.com/comment/87691384
score: 2
type: AnswerComment
has text: Thank you, that's a great answer! I think one problem I have is understanding the order that flask files are executed when you run them, in a more complex flask project like this. I'll ask a follow up question on this later.
comment on: http://stackoverflow.com/a/50336878
type: Comment

http://stackoverflow.com/comment/87515047
has text: How Do i print the sresult over here in json format
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50246757

http://stackoverflow.com/a/50245952
type: AcceptedAnswer
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/50244982
score: 4
has body: The SegmentationClass file has color map component in it and so when using tf.decode_png() you need to specify as : label = tf.image.decode_png(file, channels=3) Now you have got the RGB values you can use create_pascal_label_colormap() function to convert to class Id's.
answers question: http://stackoverflow.com/q/50244982
downvote count: 0

http://stackoverflow.com/a/50335476
answers question: http://stackoverflow.com/q/50335402
type: Answer
has body: Use axis parameter in .loc: vetor_valores.loc(axis=0)[1,:] Output: ano peds_val_fat mes clif_cod 1 1 2016 10.2
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/87597966
score: 0
has text: @PM2Ring: so we can't have two name name under same key. any way to achieve this other than list.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50290872

http://stackoverflow.com/comment/87674608
has text: It would seem to be related to mapping the columns to attributes with different name. If you skip that, it works.
score: 0
comment on: http://stackoverflow.com/q/50325599
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87719817
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50351922
has text: Is `ORDER BY order DESC` clause is really necessary ? I don't see the purpose of this clause here, `UPDATE user SET order = order+1` would be enough for what you are trying to do

http://stackoverflow.com/comment/87787934
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50379009
has text: It doesn't have this problem on linux.

http://stackoverflow.com/a/50284540
has comment: http://stackoverflow.com/comment/87651226
has comment: http://stackoverflow.com/comment/87685244
has comment: http://stackoverflow.com/comment/87598760
has comment: http://stackoverflow.com/comment/87651405
has comment: http://stackoverflow.com/comment/87607186
has comment: http://stackoverflow.com/comment/87651020
answers question: http://stackoverflow.com/q/50284112
has comment: http://stackoverflow.com/comment/87605044
accepted answer of: http://stackoverflow.com/q/50284112
score: 1
has comment: http://stackoverflow.com/comment/87640992
has comment: http://stackoverflow.com/comment/87641114
has comment: http://stackoverflow.com/comment/87598954
has body: The model restore seems to be problem. First you create the graph using import_meta_graph and then restore the parameters to the graph using saver.restore. There are other issues like when restoring the graph you need to load the tensors using get_tensor_by_name, so you name the tensors appropriately. Here are the changes you may need to make: # The test batch size is different from the hard-coded batch_size in the original graph, so replace `120` to `None` in the placeholders of X and y. new_samples = np.array([[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=np.float32) tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): with tf.Session() as sess: # Create the network, load the meta file appropriately. saver = tf.train.import_meta_graph('{your meta file for the hidden unit}.meta') # Load the parameters saver.restore(sess , tf.train.latest_checkpoint(model_path)) # Get the tensors from the graph. X = graph.get_tensor_by_name("X:0") # `y_est` is not named in your graph: change to y_est = tf.identity(tf.sigmoid(tf.matmul(A1, W2)), 'y_est') y_est = graph.get_tensor_by_name("y_est:0") y_est_val = sess.run(y_est, feed_dict={X: new_samples}) Note: You need the different checkpoints without overwriting them, so do: save_path = saver.save(sess, model_dir+str(hidden_nodes)+'/' , hidden_nodes ).
has comment: http://stackoverflow.com/comment/87651116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87609276
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/87605114
upvote count: 1

http://stackoverflow.com/q/50358345
tagged with: tensorflow
type: Question
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0
has body: I am getting a tensor as an argument, Now I want to create some variables, I am trying tf.get_variables (I don't want to use tf.Variable): input=tensor_argument sequence_length = tf.shape(inputs)[1] # the length hidden_size = tf.shape(inputs)[2] # hidden size W_omega = tf.get_variable(name='w_omega',shape=[sequence_length,sequence_length],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01)) When I run this code, I am getting this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Tensor' I tried with tf.shape and tf.size() but nothing is working. Example: import tensorflow as tf import numpy as np data=np.random.randint(0,10,[2,4,300]) tensor_va=tf.constant(data) d=tf.shape(tensor_va)[1] W_omega = tf.get_variable(name='a_omega', shape=[d,d], dtype=tf.float32, initializer=tf.random_uniform_initializer(-0.01, 0.01)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(W_omega)) How to use or convert tensor to int for get_variable?
score: 3
answer count: 1
has answer: http://stackoverflow.com/a/65050907
has title: Tensorflow : TypeError: int() argument must be a string, a bytes-like object or a number, not 'Tensor'

http://stackoverflow.com/comment/87750946
has text: @absss I added a more "self-contained" approach using the `type` constructor.
type: AnswerComment
comment on: http://stackoverflow.com/a/50366647
type: Comment
score: 0

http://stackoverflow.com/comment/87546277
type: Comment
score: 0
type: AnswerComment
has text: Very thorough explanation Gwang-Jin. Thanks!!
comment on: http://stackoverflow.com/a/50245498

http://stackoverflow.com/a/50304696
has comment: http://stackoverflow.com/comment/87685556
accepted answer of: http://stackoverflow.com/q/50301358
answers question: http://stackoverflow.com/q/50301358
type: Answer
has body: Your format string wants a positional list, so this should work: label_name = "${1}_${2}_${3}_${6}" metric = "connstats_by.vip.nested._Common_Domain.89.44.250.117.conncount:40|g" rx = re.compile('connstats_by\\.vip\\.nested\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^.]*)\\.([^\:]*)(?:\:)([^\|]*)(?:\|)([^\n]*)') print(label_name.format(*rx.match(metric).groups())) Which prints $89_$44_$250_$40
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/50256841
has comment: http://stackoverflow.com/comment/96009734
answer count: 1
tagged with: recurrent-neural-network
tagged with: tensorflow
has title: Tensorflow RNN for classification with single output
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50273052
tagged with: python
has comment: http://stackoverflow.com/comment/96014636
score: 0
has body: I want to create a RNN in Tensorflow that classifies short texts analyzing them on per-letter basis. For that I created a numpy 2D array, where each piece of text was either padded or truncated, where each element is a character code. An output is just vector of clasess represented as one-hot encoded numpy 2D-array. Here is an example: train_x.shape, train_y.shape ((91845, 50), (91845, 5)) Input consists of 90K rows 50 chars each, output is 90K rows with 5 classes. Next, I want to build a network shown in a figure below. The structure looks trivial, but I deffinetelly lack knowledge in Tensorflow and run in all kinds of problems trying to at least do training. Here is the part of code I use to build the network chars = sequence_categorical_column_with_identity('chars', params['domain_size']+1) chars_emb = tf.feature_column.embedding_column(chars, dimension=10) columns = [chars_emb] input_layer, sequence_length = sequence_input_layer(features, columns) hidden_units = 32 lstm = tf.nn.rnn_cell.LSTMCell(hidden_units, state_is_tuple=True) rnn_outputs, state = tf.nn.dynamic_rnn(lstm, inputs = input_layer, sequence_length=sequence_length, dtype=tf.float32) output = rnn_outputs[:,-1,:] logits = tf.layers.dense(output, params['n_classes'], activation=tf.nn.tanh) # apply projection to every timestep. # Compute predictions. predicted_classes = tf.nn.softmax(logits) # Compute loss. loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=logits) # Compute evaluation metrics. accuracy = tf.metrics.accuracy(labels=labels, predictions=predicted_classes, name='acc_op') But I get an error InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 8 values, but the requested shape has 1 [[Node: Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](softmax_cross_entropy_with_logits, sequence_input_layer/chars_embedding/assert_equal/Const)]] A fuller minimal example you can find here. Most likely you…

http://stackoverflow.com/q/50283992
has body: I am using Python to find the last digit of a Fibonacci number. This is my code: import numpy as np def calc_fib(n): if n &lt;= 1: return n else: a=np.arange(n+1,dtype='int64') for i in range(2,n+1): a[i]=a[i-1]+a[i-2] return a[n]%10 n = int(input()) print(calc_fib(n)) The code is working fine for small values of n like when n = 10, it yields output of 5, but when using bigger values of n, it yields the output: /Users/amrsulaiman/Desktop/Algorithms_Coursera/W2_2.py:10: RuntimeWarning: overflow encountered in long_scalars a[i]=a[i-1]+a[i-2] 5 The value 5 is wrong. It is supposed to be 9. How to solve this overflow issue and fix my code.
downvote count: 0
has comment: http://stackoverflow.com/comment/87584352
favorite count: 0
has answer: http://stackoverflow.com/a/50284107
type: Question
has title: I get the error "RuntimeWarning: overflow encountered in long_scalars" when trying to calculate the last digit of a Fibonacci number using python
score: 3
tagged with: algorithm
has answer: http://stackoverflow.com/a/50284388
tagged with: python
possible better answer: http://stackoverflow.com/a/50284107
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/50284388
has comment: http://stackoverflow.com/comment/87584466
upvote count: 3

http://stackoverflow.com/a/50319133
accepted answer of: http://stackoverflow.com/q/50307042
score: 1
type: Answer
answers question: http://stackoverflow.com/q/50307042
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: When running on apache the latency issue went away, so it seems to be a problem with the python development server. In addition, i setup connection pooling to stop the reconnect on every request. This had no effect on the dev server though. The pooling was done by sqlalchemy pool for PostgreSQL.

http://stackoverflow.com/a/50375367
downvote count: 1
has comment: http://stackoverflow.com/comment/107556743
has comment: http://stackoverflow.com/comment/87769959
type: Answer
has comment: http://stackoverflow.com/comment/87770202
has body: You can just iterate calling the grad function: import torch from torch.autograd import grad def nth_derivative(f, wrt, n): for i in range(n): grads = grad(f, wrt, create_graph=True)[0] f = grads.sum() return grads x = torch.arange(4, requires_grad=True).reshape(2, 2) loss = (x ** 4).sum() print(nth_derivative(f=loss, wrt=x, n=3)) outputs tensor([[ 0., 24.], [ 48., 72.]])
has comment: http://stackoverflow.com/comment/118231579
score: 25
has comment: http://stackoverflow.com/comment/132831442
upvote count: 26
answers question: http://stackoverflow.com/q/50322833
has comment: http://stackoverflow.com/comment/87770196

http://stackoverflow.com/comment/87586008
type: Comment
has text: I think you will find your answer here: https://github.com/keras-team/keras/issues/7551
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/50284939

http://stackoverflow.com/comment/87515602
score: 0
has text: @SheikhJames As everyone here pointed out, it's not possible. You need to change your way of thinking or the implementation.
type: Comment
comment on: http://stackoverflow.com/a/50248143
type: AnswerComment

http://stackoverflow.com/q/50258337
type: AnsweredQuestion
has body: I'm not sure if I'm using the correct wording in my question but the situation I have is that I'm calling a function and passing a value to one of its named keyword arguments only if I have a value for it. A simplified example of how I'm currently doing it: var_1 = data.get("var_1", None) if var_1: some_function(some_arg=var_1) else: some_function() The function some_function() does not accept setting some_arg to None so I can only call the function with the named argument if I have a valid value for it. The reason why the above is less desirable for me is that the actual function calls I'm making have a bunch (5+) of named arguments that I set. This results in repeating mostly similar function calls that differ by only one parameter. Is there a better way/more Pythonic way to do this? I wish I could call the function and set all possible named parameters that I might wish to pass but, at runtime, only pass in the values that I actually have something for. In case it matters, the function calls are to the AWS Python SDK (Boto3) so I can't alter the behavior of the function.
duplicate of: http://stackoverflow.com/q/8686225
has answer: http://stackoverflow.com/a/50258379
accepted answer: http://stackoverflow.com/a/50258379
tagged with: python
has comment: http://stackoverflow.com/comment/87534563
type: Question
upvote count: 9
score: 9
downvote count: 0
answer count: 1
favorite count: 0
has title: Conditionally passing a named keyword argument to a function

http://stackoverflow.com/comment/87806713
has text: Yeah, an oversight. Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50382390
type: Comment

http://stackoverflow.com/comment/87781045
score: 0
comment on: http://stackoverflow.com/a/50382558
type: Comment
has text: Do you have any suggestions for other ways to send data through the internet using python which would be more reliable?
type: AnswerComment

http://stackoverflow.com/comment/87533069
has text: Yes I was also trying to avoid all possible distance constraints as at a time only K points will be selected so only C(K,2) distances should be looked upon. I was not able to get proper formulation. Where is the constraints that only K points will be selected??
type: AnswerComment
comment on: http://stackoverflow.com/a/50257179
score: 0
type: Comment

http://stackoverflow.com/comment/87564995
has text: You can, this module was designed to handle this kind of problem efficiently.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50274072
score: 0

http://stackoverflow.com/comment/87642819
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50313325
type: Comment
has text: How are you running this, from IDLE or the command-line?

http://stackoverflow.com/q/50322377
has comment: http://stackoverflow.com/comment/87787276
has comment: http://stackoverflow.com/comment/87799009
tagged with: python
tagged with: flask
has body: In my Python (3.5) Flask project, I am using the CAS client for authentication and everything works fine. Once the authentication is done, I want to display the username in my output page. So I use the following code __init__.py: from flask import Flask from flask_cas import CAS from flask_cas import login_required # ... APP = Flask(__name__) cas = CAS(APP) # ... def list_page() return render_template("list.html", name=cas.username) @app.route('/admin/') @login_required def admin_page() return list_page(); list.html: ... &lt;H2&gt; Hi {{name}} &lt;/h2&gt; ... At the output page I am seeing Hi &lt;property object at 0x7fb37dfe6958&gt;
has comment: http://stackoverflow.com/comment/87799049
has comment: http://stackoverflow.com/comment/87807950
has comment: http://stackoverflow.com/comment/87799146
has answer: http://stackoverflow.com/a/50378157
type: AnsweredQuestion
score: 3
has title: Displaying property object instead of value in Flask template
answer count: 1
tagged with: cas
tagged with: templates
accepted answer: http://stackoverflow.com/a/50378157
downvote count: 1
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/87594141
score: 0
comment on: http://stackoverflow.com/q/50283741
type: QuestionComment
has text: @user2781994 I've installed CUDA 9.1. I did't understand what you are asking about PATH.
type: Comment

http://stackoverflow.com/comment/87516958
comment on: http://stackoverflow.com/a/50240551
has text: That was very useful, thanks! You are totally right, I tried fitting log(exp_rate) and now curve_fit works very smoothly. I also changed accordingly the error function so it returns Orbach_Raman(temperature, a, b, c, d) - np.log10(rate) but this is much more sensible to the initial guess as compared to curve_fit(), and the fitting is much worse.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/50309926
upvote count: 1
favorite count: 0
has body: I am trying to select an element in my web page with the xpath expression. This is the essential parts of the code from selenium import webdriver ... driver = webdriver.Chrome() ... xpath = "//select[@onchange='onCodeChanged('14', this);']/option[text()='CPT 99429']" e = driver.find_element_by_xpath(xpath) e.click() Part of page source i'm trying to select: CPT 99429 HCPCS G0402 .... Error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//select[@onchange='onCodeChanged('14', this);']/option[text()='CPT 99429']' is not a valid XPath expression. I have a feeling this has something to do with having the quotation marks or the ; symbol, as I've used this same method of selecting elements in the web page successfully, but now getting this error.
tagged with: syntax
score: 1
has comment: http://stackoverflow.com/comment/87635905
tagged with: python
has comment: http://stackoverflow.com/comment/87635784
has comment: http://stackoverflow.com/comment/87644278
type: Question
tagged with: xpath
has title: "not a valid xpath expression" selenium python
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: selenium

http://stackoverflow.com/q/50273897
has answer: http://stackoverflow.com/a/50274281
downvote count: 0
has answer: http://stackoverflow.com/a/50274069
tagged with: python
upvote count: 7
favorite count: 0
has body: I am trying to solve this problem from leetcode, going to copy here for convenience Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. After (unsuccessfully) trying it, I googled the solution and this works class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ ans = pa = pb = pc = None na = nb = 0x7FFFFFFF for n in nums: if n &gt; pa: pa, pb, pc = n, pa, pb elif n &gt; pb: pb, pc = n, pb elif n &gt; pc: pc = n if n &lt; na: na, nb = n, na elif n &lt; nb: nb = n return max(ans, pa * na * nb, pa * pb * pc) I understand the logic except why na and nb are assigned a value of 0x7FFFFFFF. It looks like it is int32's maximum value. Can someone help me explain the significance of this number and why it is used here? (I would have used 1001 instead)
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87564893
tagged with: algorithm
score: 7
has comment: http://stackoverflow.com/comment/87573112
has comment: http://stackoverflow.com/comment/87565103
has answer: http://stackoverflow.com/a/50274503
answer count: 4
type: Question
has title: Maximum Product of Three Numbers
possible better answer: http://stackoverflow.com/a/50274281
has comment: http://stackoverflow.com/comment/87564854
has answer: http://stackoverflow.com/a/50274956
accepted answer: http://stackoverflow.com/a/50274069

http://stackoverflow.com/q/50350379
tagged with: decorator
tagged with: python-decorators
favorite count: 0
has comment: http://stackoverflow.com/comment/87717585
type: Question
has body: I am trying to get correct function name while using 2 decorators. 1> profile - from memory_profiler import profile 2> custom timing decorator def timing(f): @wraps(f) def wrapper(*args, **kwargs): start = time() result = f(*args, **kwargs) end = time() print 'Elapsed time: {} - {}'.format(wrapper.__name__, end - start) return result return wrapper They are used in the following order as defined below @timing @profile def my_function(): something..... Problem is both functions work well individually but when used together I don't get correct name via the timing decorator. I always get wrapper instead of the actual function name. How do I get the actual function name instead of getting "wrapper" as the function name?
has title: Getting function name from nested decorator
has comment: http://stackoverflow.com/comment/87716625
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/87717873
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87716623
accepted answer: http://stackoverflow.com/a/73216159
score: 1
has answer: http://stackoverflow.com/a/73216159
downvote count: 0
answer count: 1

replit
type: Tag
tags question: http://stackoverflow.com/q/50373920
tag name: replit

http://stackoverflow.com/a/50381259
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87807286
has comment: http://stackoverflow.com/comment/87778813
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/50381203
type: Answer
has comment: http://stackoverflow.com/comment/87778820
has body: A possibility is to create a csv header that contains, along with the location value, a full listing of all subdictionary keys. That way, all subdictionary values can be written under their proper "key" columns: import csv dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}, "Location3":{'e':7,'f':8, 'g':9, 'h':10}, "Location4":{'e': 2, 'f': 3, 'g': 4, 'h': 5}} header = sorted(set(i for b in map(dict.keys, dic.values()) for i in b)) with open('filename.csv', 'w', newline="") as f: write = csv.writer(f) write.writerow(['location', *header]) for a, b in dic.items(): write.writerow([a]+[b.get(i, '') for i in header]) Output: location,a,b,c,e,f,g,h Location1,1,2,3,,,, Location2,4,5,6,,,, Location3,,,,7,8,9,10 Location4,,,,2,3,4,5
has comment: http://stackoverflow.com/comment/87778747
accepted answer of: http://stackoverflow.com/q/50381203
downvote count: 0
has comment: http://stackoverflow.com/comment/87778772

http://stackoverflow.com/comment/87579366
type: AnswerComment
score: 1
has text: Wow, this is incredible. Cannot believe how quickly this runs. Thank you
comment on: http://stackoverflow.com/a/50281242
type: Comment

http://stackoverflow.com/a/50318615
type: Answer
score: 0
answers question: http://stackoverflow.com/q/50318309
has body: Are you proabably running your code like python test_class/second_class.py. If you just do this then python will think the base directory to find modules is ./test_class. So when you import the test_class package python will start looking for a folder called ./test_class/test_class to find the sub-modules. This directory doesn't exist and so the import fails. There are several ways that you can tell python how to correctly find your modules. Using PYTHONPATH One way to get around this is to set PYTHONPATH before starting python. This is just an environment variable with which you can tell python where to look for your modules. eg. export PYTHONPATH=/path/to/your/root/folder python test_class/second_class.py Using the -m switch for python Be default python treats the directory of the main module as the place to look for other modules. However, if you use -m python will fall back to looking in the current directory. But you also need to specify the full name of the module you want to run (rather than as a file). eg. python -m test_class.second_class Writing a root entry point In this we just define your main module at the base level (the directory that contains test_class. Python will treat this folder as the place to look for user modules and will find everything appropriately. eg. main.py (in /path/to/your/root/folder) from test_class.second_class import SecondClass if __name__ == '__main__': print(SecondClass().minus_number()) at the command line python main.py

http://stackoverflow.com/comment/87571673
has text: The only situation that I can think of for using decimal is if the image dimensions are very small and you have a greyscale or palette-mapped image. Then you can print the decimalized image on the page so that the image structure is still kind-of visible.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50277215
type: QuestionComment

http://stackoverflow.com/comment/87657343
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50320657
has text: Of course if you actually want single-element lists, it doesn't do that, but you can adapt any of the variants. Although in that case it's even more obviously nicer with a list comprehension—`itemgetter(slice(1, None))` is pretty ugly compared to `i[1:]` (or `[i[1]]`).
type: Comment

http://stackoverflow.com/comment/87716988
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50350016
has text: Additional question: on a PC with 8 physical core and 16 logical cores, my guess is that with multiprocessing, logical cores are poorly used because of how the OS schedules the CPU usage. i.e. with this code, the `max_workers` should be 8 right?
type: Comment

http://stackoverflow.com/q/50367703
has title: Multilevel index won't go away
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50367983
tagged with: python
linked to: http://stackoverflow.com/q/18624039
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/50367983
tagged with: pandas
has body: I have a dataframe, which consists of summary statistics of another dataframe: df = sample'Place','Lifeexp' df = df.groupby('Place').agg(['count','mean', 'max','min']).reset_index() df = df.sort_values([('Lifeexp', 'count')], ascending=False) When looking at the structure, the dataframe has a multi index, which makes plot creations difficult: df.columns MultiIndex(levels=[['Lifeexp', 'Place'], ['count', 'mean', 'max', 'min', '']], labels=[[1, 0, 0, 0, 0], [4, 0, 1, 2, 3]]) I tried the solutions of different questions here (e.g. this), but somehow don't get the desired result. I want df to have Place, count, mean,max, min as column names and delete Lifeexp so that I can create easy plots e.g. df.plot.bar(x = "Place", y = 'count')
has comment: http://stackoverflow.com/comment/87755050
answer count: 1
upvote count: 1
tagged with: multi-index
downvote count: 1

http://stackoverflow.com/q/50275846
has answer: http://stackoverflow.com/a/50347135
has answer: http://stackoverflow.com/a/50314291
tagged with: matplotlib
has title: Matplotlib equivalent of pygame flip
has comment: http://stackoverflow.com/comment/87734811
upvote count: 10
has comment: http://stackoverflow.com/comment/87743778
answer count: 4
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/87646294
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50311026
possible better answer: http://stackoverflow.com/a/50311026
downvote count: 2
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/50390093
linked to: http://stackoverflow.com/q/40126176
accepted answer: http://stackoverflow.com/a/50390093
has body: I have a program with rapid animations which works perfectly under pygame, and for technical reasons, I need to do the same using only matplotlib or an other widespread module. The program structure is roughly: pygame.init() SURF = pygame.display.set_mode((500, 500)) arr = pygame.surfarray.pixels2d(SURF) # a view for numpy, as a 2D array while ok: # modify some pixels of arr pygame.display.flip() pygame.quit() I have no low level matplotlib experience, but I think it is possible to do equivalent things with matplotlib. In other words : How to share the bitmap of a figure, modify some pixels and refresh the screen ? Here is a minimal working exemple, which flips 250 frames per second (more than the screen ...) on my computer : import pygame,numpy,time pygame.init() size=(400,400) SURF = pygame.display.set_mode(size) arr = pygame.surfarray.pixels2d(SURF) # buffer pour numpy t0=time.clock() for counter in range(1000): arr[:]=numpy.random.randint(0,0xfffff,size) pygame.display.flip() pygame.quit() print(counter/(time.clock()-t0)) EDIT What I try with indications in answers : import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() def f(x, y): return np.sin(x) + np.cos(y) x = np.linspace(0, 2 * np.pi, 400) y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1) im = plt.imshow(f(x, y), animated=True) count=0 t0=time.clock()+1 def updatefig(*args): global x, y,count,t0 x += np.pi / 15. y += np.pi / 20. im.set_array(f(x, y)) if time.clock()&lt;t0: count+=1 else: print (count) count=0 t0=time.clock()+1 return im, ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) plt.show() But this only provides 20 fps....
has comment: http://stackoverflow.com/comment/87637957
type: AnsweredQuestion

http://stackoverflow.com/a/50259805
has comment: http://stackoverflow.com/comment/87537692
has comment: http://stackoverflow.com/comment/87537432
downvote count: 0
has body: You could try something like the following: mytable['label'] = (mytable.groupby('meet_id') .label.transform(lambda x: list(x.cumsum())) .apply(set)) &gt;&gt;&gt; mytable user_id meet_id text label 0 3c 1 abc {A} 1 3c 1 abc {A} 2 3c 1 abc {A} 3 3c 1 abc {A} 4 3c 1 abc {A} 5 3c 1 abc {A, B} 6 3c 1 abc {A, B} 7 3c 2 xyz {B} 8 3c 2 xyz {B} 9 3c 2 xyz {B} 10 3c 2 xyz {C, B} 11 3c 2 xyz {C, B} 12 3c 2 xyz {C, B, A} If you want to get rid of the set data type and just have it as a string (as in your desired output), you could apply ', '.join(sorted(set(x)))) instead of simply set (thanks @Wen and @ScottBoston): mytable['label'] = (mytable.groupby('meet_id') .label.transform(lambda x: list(x.cumsum())) .apply(lambda x: ', '.join(sorted(set(x))))) &gt;&gt;&gt; mytable user_id meet_id text label 0 3c 1 abc A 1 3c 1 abc A 2 3c 1 abc A 3 3c 1 abc A 4 3c 1 abc A 5 3c 1 abc A, B 6 3c 1 abc A, B 7 3c 2 xyz B 8 3c 2 xyz B 9 3c 2 xyz B 10 3c 2 xyz B, C 11 3c 2 xyz B, C 12 3c 2 xyz A, B, C
score: 6
type: Answer
answers question: http://stackoverflow.com/q/50259463
upvote count: 6
has comment: http://stackoverflow.com/comment/87537701
has comment: http://stackoverflow.com/comment/87865828

http://stackoverflow.com/a/50324275
has body: The problem with the standard fit is the estimate of the Jacobian. If a parameter is discrete the derivative is zero almost everywhere. A workaround might be that one uses leastsq with a self defined residual function and additionally providing the derivatives. One can set the parameter discrete in the residual function but let it be continuous in the derivative. I'm not saying that this is the general solution to this type of problem, but in case of the OP's function, it works quite OK. Edit - Code would be: # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from scipy.optimize import leastsq def f0( x, A, B, C ): return ( A * np.cos( x )**2 + B * np.sin( x )**2 + 2 * C * np.sin( x ) * np.cos( x ) ) def func(x, A, B, C): return f0( x, A, B, C )**2 a = 0.009 b = 0.3 c = 0.4 xList = np.linspace( -1, 6, 500 ) yList = np.fromiter( ( func( x, a, b, c ) for x in xList ), np.float ) def residuals( p, x, y ): return func(x, p[0], int(p[1]) * np.pi / 2. * p[0], p[2] ) - y def dfunc( p, x, y ): #Derivative return [ f0( x, p[0], int( p[1] ) * np.pi / 2. * p[0] , p[2] ) * ( np.cos( x )**2 + p[1] * np.pi / 2. * np.sin( x )**2 ), f0( x, p[0], int( p[1] ) * np.pi / 2. * p[0] , p[2] ) * ( p[0] * np.pi / 2.* np.sin( x )**2 ), f0( x, p[0], int( p[1] ) * np.pi / 2. * p[0] , p[2] ) * ( 2 * np.sin( x ) * np.cos( x ) ), ] plsq, cov, infodict, mesg, ier = leastsq( residuals, [ 0.009, .3/.01, .4 ], args=( xList, yList ), Dfun=dfunc, col_deriv=1, full_output=True ) fit = func(xList, plsq[0], int( plsq[1] ) * np.pi / 2. * plsq[0], plsq[2] ) print plsq print int( plsq[1] ) fig1 = plt.figure( 1, figsize=( 6, 4 ), dpi=80 ) ax = fig1.add_subplot( 1, 1, 1 ) ax.plot( xList, yList ) ax.plot( xList, fit, ls='--') plt.show() Providing: &gt;&gt;[8.68421935e-03 2.22248626e+01 4.00032135e-01] &gt;&gt;22
has comment: http://stackoverflow.com/comment/87674944
answers question: http://stackoverflow.com/q/50276206
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87716561
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/50276206
has comment: http://stackoverflow.com/comment/87703680
score: 2

http://stackoverflow.com/comment/87771488
has text: @Jessica I've added a more robust version of this. Try it. If the assertion fails, you know there's a problem with your data that you will badly need to revisit before testing either of our solutions again.
comment on: http://stackoverflow.com/a/50377446
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50306513
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87638140
type: Answer
answers question: http://stackoverflow.com/q/50305938
has body: You could use SymPy to represent the right-hand sides as expressions with respect to symbolic variables x, r, r0 and kB: x, r, r0, kB = sym.symbols('x,r,r0,kB') y = 1.0066*x**2-1.8908*x-0.888 U = 0.5*kB*(r-r0)**2 Now we can convert y and U into polynomials with respect to x and r: In [39]: sym.poly(y, x) Out[39]: Poly(1.0066*x**2 - 1.8908*x - 0.888, x, domain='RR') In [40]: sym.poly(U, r) Out[40]: Poly(0.5*kB*r**2 - 1.0*kB*r0*r + 0.5*kB*r0**2, r, domain='RR[r0,kB]') sym.Polys have a all_coeffs method which returns a list of the coefficients: In [41]: sym.poly(y, x).all_coeffs() Out[41]: [1.00660000000000, -1.89080000000000, -0.888000000000000] In [42]: sym.poly(U, r).all_coeffs() Out[42]: [0.5*kB, -1.0*kB*r0, 0.5*kB*r0**2] We can use zip to pair the coefficients from the two lists: In [43]: list(zip(sym.poly(y, x).all_coeffs(), sym.poly(U, r).all_coeffs())) Out[43]: [(1.00660000000000, 0.5*kB), (-1.89080000000000, -1.0*kB*r0), (-0.888000000000000, 0.5*kB*r0**2)] and then use sympy.Eq to equate the expressions, and use sympy.solve to solve them for kB. The Python construct I'm using here to generate the list is called a list comprehension: In [44]: [sym.solve(sym.Eq(a, b), [kB]) for a, b in zip(sym.poly(y, x).all_coeffs(), sym.poly(U, r).all_coeffs())] Out[44]: [[2.01320000000000], [1.8908/r0], [-1.776/r0**2]] Putting it all together: import sympy as sym x, r, r0, kB = sym.symbols('x,r,r0,kB') y = 1.0066*x**2-1.8908*x-0.888 U = 0.5*kB*(r-r0)**2 result = [sym.solve(sym.Eq(a, b), [kB]) for a, b in zip(sym.poly(U, r).all_coeffs(), sym.poly(y, x).all_coeffs())] print(result) prints [[2.01320000000000], [1.8908/r0], [-1.776/r0**2]]
accepted answer of: http://stackoverflow.com/q/50305938
score: 3
upvote count: 3

http://stackoverflow.com/a/50356498
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/87729415
answers question: http://stackoverflow.com/q/50356367
has body: You have to change the python interpreter that PyCharm is using. Go to options-&gt;project-&gt;project interpreter and select the correct one, most likely a virtualenv you created, where you installed tensorflow instead of the default.
downvote count: 1
type: Answer

http://stackoverflow.com/comment/93419140
type: AnswerComment
has text: You should use some kind of virtualenv mechanism and not just blatantly delete stock Python as it may be used by other stuff... Also remember to tick your answer as solved if you are happy with it so that the question is closed.
comment on: http://stackoverflow.com/a/50281610
type: Comment
score: 0

qwindow
type: Tag
tags question: http://stackoverflow.com/q/50248769
tag name: qwindow

http://stackoverflow.com/q/50329109
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/87674657
accepted answer: http://stackoverflow.com/a/50329690
has comment: http://stackoverflow.com/comment/87674162
favorite count: 0
has comment: http://stackoverflow.com/comment/87676599
type: Question
has answer: http://stackoverflow.com/a/50329690
has body: I want to process a pandas dataframe with rank-hot encoding instead of one-hot encoding. For example take this pandas dataframe: df = pd.DataFrame([[1,2],[3,2],[2,2]], columns=['colA', 'colB']) print(df) &gt;&gt; colA colB 0 1 2 1 3 0 2 2 3 How it should look in the end: print(df) &gt;&gt; colA_0 colA_1 colA_2 colA_3 colB_0 colB_1 colB_2 colB_3 0 1 1 0 0 1 1 1 0 1 1 1 1 1 1 0 0 0 2 1 1 1 0 1 1 1 1 This worked on small dataFrames: def rankHotEncode(row): newFeatures = {} for i, v in row.iteritems(): for k in range(MULTIPLYFEATURES): newFeatures[i + repr(k)] = 1 if v &gt;= k else 0 return pd.Series(newFeatures) df.apply(rankHotEncode, axis=1) The solution should not be hardcoded and efficient for order ~100.000 rows. How can I improve the provided solution to make it more efficient or what is the best way to do this?
has title: rank hot encoding python3
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/87482281
has text: Does your Post model have a user attribute?
score: 0
comment on: http://stackoverflow.com/q/50232369
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50310482
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/50310454
accepted answer of: http://stackoverflow.com/q/50310454
type: Answer
has body: Outer-merge merged = pd.merge(df1, df2, how='outer') then filter on rows &gt;&gt;&gt; merged[(merged.start &lt;= merged.no2) &amp; (merged.no2 &lt;= merged.stop)]'no1', 'start', 'stop', 'other2' no1 start stop other2 0 1 2 40 dog 8 3 5 15 dog

http://stackoverflow.com/q/50243899
favorite count: 0
accepted answer: http://stackoverflow.com/a/50243932
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/50243932
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: I have a data set with a datetimeindex and 2 columns, ['WorkoutID', 'power']. The datetimeindex is at the daily level, but I am trying to resample to the weekly level and get the max power from all workouts within each week: df['best_power'] = df['power'].resample('D').max() Right now the output of this gives me the datetimeindex at the weekly level and the max power ('best_power'), but it drops the workoutID column. I want to also be able to see what workoutId that max power is coming from - how can I retain the workoutID column?
answer count: 1
downvote count: 0
upvote count: 1
has title: Possilble to keep ID fields when resampling pandas datetimeindex?

http://stackoverflow.com/comment/87637510
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170923/discussion-between-shawn-and-t3am5hark).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50310478

http://stackoverflow.com/a/50330573
has body: You could just read all of the data into a pandas dataframe first to start with. Then you could process one column (whatever contains 'NC_010611.1') in a way that is conditional on another column. See examples here: Pandas conditional creation of a series/dataframe column. It's probably possible to get what you want in one pass through the data but it may be easier to write and read if you do 2 passes through the data.
answers question: http://stackoverflow.com/q/50330355
type: Answer
score: 0

http://stackoverflow.com/q/50255995
has body: Still pretty new to Python. My program needs to check if the current number is the same as the previous number inputted. It has to make no response at all to the very first number and there should be at least two numbers in the input. So far, I have come up with this - I can check against the first number but not the current number - I feel I'm missing something obvious here. Thanks for the help. f_n = 0 n_n = 0 print('Enter the first number: ' , end = ' ') fn = input() f_n = int(fn) finished = False while not finished: print('Enter the next number, 0 to finish: ' , end = ' ') nu = input() n_n = int(nu) if n_n != 0: if n_n == f_n: print('Same.') elif n_n &gt; f_n: print('Up.') elif n_n &lt; f_n: print('Down.') else: finished = True
has comment: http://stackoverflow.com/comment/87529679
has comment: http://stackoverflow.com/comment/87529796
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50256196
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/50256393
possible better answer: http://stackoverflow.com/a/50256393
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87530090
has answer: http://stackoverflow.com/a/71295973
has title: Python. How do I check if the current value is greater, the same, or smaller than the previous?
has comment: http://stackoverflow.com/comment/87530824
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87530060
tagged with: while-loop
answer count: 3
has answer: http://stackoverflow.com/a/50256196

http://stackoverflow.com/comment/87761135
comment on: http://stackoverflow.com/q/50370513
type: QuestionComment
type: Comment
has text: @danny actually, there is a little bit of confusion. Actually the interpreter's job is to convert the .py to binary.Once the program is already in binary, why interpreter is required.This is my thinking.I have read somewhere that cython converted binary works outside the interpreter, and that is why it gets the performance closer to C.Anyway I will have look at the Python standard library.
score: 0

http://stackoverflow.com/comment/87664122
type: QuestionComment
comment on: http://stackoverflow.com/q/50324135
score: 2
has text: Have you tried either of those? Your first rewrite will fail if `fkeywords` and `keywords` share the same parameter.
type: Comment

http://stackoverflow.com/q/50315010
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50315031
has title: Write multiple pandas dataframes to excel
score: 5
downvote count: 0
tagged with: pandas
has body: I am attempting to write multiple pandas dataframes which I extracted from a larger dataset into multiple worksheets of an excel workbook. The issue is that it only writes the first dataframe i.e. index[0], so the resulting workbook has only one worksheet, see sheet1 below. What am I missing? This is a recreation of my problem. Code: import pandas as pd from pandas import ExcelWriter df_list = [] a = pd.DataFrame({'A':[1,2,3,4,5,6,7,8,9], 'B':[10,11,12,13,14,15,16,17,18]}) b = pd.DataFrame({'C':[11,22,33,44,55,66,77,88,99], 'D':[105,117,128,139,140,153,166,176,188]}) df_list.append(a) df_list.append(b) writer = ExcelWriter('test_output.xlsx') for n, df in enumerate(df_list): df.to_excel(writer, 'sheet%s' % str(n + 1)) writer.save() Sheet1: A B 0 1 10 1 2 11 2 3 12 3 4 13 4 5 14 5 6 15 6 7 16 7 8 17 8 9 18
answer count: 1
linked to: http://stackoverflow.com/q/74948525
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50315031
upvote count: 5
tagged with: pandas.excelwriter
tagged with: python

http://stackoverflow.com/q/50302291
has answer: http://stackoverflow.com/a/50302320
score: 2
type: AnsweredQuestion
has body: Sorry about the title, I'm a little unsure how to exactly ask this. I have a dataset of game review information. The info is separated by commas, however some of the info, like titles or genres, have commas within them. These are all inside quotations. I want to convert this to a list but keep anything within quotes as a single index, rather than two. Here's an example. This is the raw data: 14,Amazing,Mark of the Ninja,PC,9.0,"Action, Adventure",Y,2012,9,7 I use .rstrip().split(',') to get: [14, Amazing, Mark of the Ninga, PC, 9.0, "Action, Adventure", Y, 2012, 9, 7] but "Action, Adventure" results in two indices. I want this as a single index, but I'm not sure how to go about it. I don't have too much experience with regular expressions but I'm guessing that's the solution I'm looking for. Any suggestions on the best way to go about this problem?
has comment: http://stackoverflow.com/comment/87621004
answer count: 1
downvote count: 0
has title: Data has same characters that I'm splitting it on
has comment: http://stackoverflow.com/comment/87621038
accepted answer: http://stackoverflow.com/a/50302320
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87621046
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/87621025

http://stackoverflow.com/a/50261461
has body: Got it. For anyone that might have this problem in the future: To fix this, change the line: self.cv=self.cv.decode("utf-8") to: get_text = self.cvfile.read().decode("utf-8", 'ignore')
accepted answer of: http://stackoverflow.com/q/50242948
upvote count: 1
answers question: http://stackoverflow.com/q/50242948
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/87580661
type: Comment
score: 0
type: AnswerComment
has text: I see, do you have any suggestions for the draw_circle issue?
comment on: http://stackoverflow.com/a/50281911

http://stackoverflow.com/comment/87735088
type: QuestionComment
has text: Also possible duplicate of [How do I convert this list of dictionaries to a csv file?](https://stackoverflow.com/questions/3086973/how-do-i-convert-this-list-of-dictionaries-to-a-csv-file)
type: Comment
score: 2
comment on: http://stackoverflow.com/q/50359002

http://stackoverflow.com/q/50351705
upvote count: 1
tagged with: nearest-neighbor
tagged with: tensorflow
favorite count: 0
type: Question
score: 1
tagged with: python
has title: Nearest Neighbors algorithm by attribute importance
tagged with: attributes
has body: I want to know what solutions are provided within Python libraries or Tensorflow libraries for finding nearest neighbor by attribute importance. In KDTree library attributes are treated equally with same importance. # KDTree import numpy as np from sklearn.neighbors import KDTree # Neighbors and Neighbor neighbors = np.array([[0, 1, 0, 1], [1, 2, 1, 2], [2, 1, 1, 1], [1, 0, 0, 0], [1, 2, 0, 2], [2, 2, 2, 2], [1, 0, 0, 1]]) neighbor = np.array([[1, 1, 0, 1]]) tree = KDTree(neighbors, leaf_size=2) distance, ind = tree.query(neighbor, k=7) In order to be explicit with what I am looking for I developed following halving interval algorithm to calculate nearest neighbor with decreasing importance of attribute from left to right. First attribute is the most important and last is the least important. https://github.com/itsergiu/Nearest-Neighbor-by-Attribute-Importance
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/87669792
comment on: http://stackoverflow.com/a/50277797
score: 0
type: AnswerComment
has text: @Wen How can I delete the index "product" from that output?. rest will be same.
type: Comment

http://stackoverflow.com/q/50296824
tagged with: python
has answer: http://stackoverflow.com/a/50297008
type: AnsweredQuestion
score: 0
has body: I'm trying to completely remove the y-axis from a plot in created with matplotlib. The code I'm using is: import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import skewnorm f = plt.figure(figsize=(8,4)) ax = f.add_subplot(111) colors = ["windows blue", "faded green", "dusty purple"] colors = sns.xkcd_palette(colors) b = 4 for j, a in enumerate([(0, 'No skew'), (b, 'Positive skew'), (-b, 'Negative skew')]): x = np.linspace(skewnorm.ppf(0.001, a[0]), skewnorm.ppf(0.999, a[0]), 100) y = skewnorm.pdf(x, a[0]) plt.plot(x, y, label=a[1], color=colors[j]) ax.yaxis.set_visible(False) plt.legend(loc=2) sns.despine() This produces a plot with the y-axis ticks removed, but the axis itself still visible (shown below). How can I turn this axis off entirely?
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/71411653
accepted answer: http://stackoverflow.com/a/50297008
has answer: http://stackoverflow.com/a/71411653
has title: matplotlib figure still shows y-axis after using set_visible(False)
type: Question
answer count: 2
tagged with: seaborn

http://stackoverflow.com/q/50305321
has body: I've tried to encode a set object and it failed to do it, claiming an AttributeError code. Is there a way for it to work? NOTE: I've been using the socket module. albums = set() for key, val in data.items(): albums.add(val['album']) msg = albums.encode()
downvote count: 3
has comment: http://stackoverflow.com/comment/87626926
favorite count: 0
has comment: http://stackoverflow.com/comment/87628718
tagged with: encode
tagged with: sockets
tagged with: python
score: -3
has comment: http://stackoverflow.com/comment/87626945
type: Question
has answer: http://stackoverflow.com/a/50306995
answer count: 2
has answer: http://stackoverflow.com/a/50305388
has title: A set object has no attribute 'encode' in socket module
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87627831

http://stackoverflow.com/q/50269153
has comment: http://stackoverflow.com/comment/87556317
score: 0
has comment: http://stackoverflow.com/comment/87556350
tagged with: database
has comment: http://stackoverflow.com/comment/87555975
tagged with: python
has comment: http://stackoverflow.com/comment/87556113
has comment: http://stackoverflow.com/comment/87556111
type: Question
has comment: http://stackoverflow.com/comment/87556432
answer count: 0
has body: I started a new Django project, the database I had before was still relevant so I want to merge it over to the new one using dumpdata &amp; loaddata. I am using the out of the box database django comes with: sqllite. The problem is when I use loaddata I get this error: bad_row[1], referenced_table_name, referenced_column_name, django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'django_admin_log' with primary key '1' has an invalid foreign key: django_admin_log.content_type_id contains a value '7' that does not have a corresponding value in django_content_type.id. The steps I followed to get here are: Copied and migrated the models page from my first project to my new one. python3 manage.py dumpdata admin &gt; db.json --indent 2 python3 manage.py loaddata db.json tldr; My goal is to take the data from the old database in another project and put it in the new project's database.
has title: Error when attempting loaddata on django database dump
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87556150
tagged with: django

http://stackoverflow.com/comment/87741053
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50361218
score: 0
has text: After `sphinx-apidoc -f -o ./source/ ..`, what is in your `utils.rst` and `main.rst`? I think part of the problem is that [sphinx-apidoc is designed for packages](http://www.sphinx-doc.org/en/stable/man/sphinx-apidoc.html#description), not modules: "sphinx-apidoc is a tool for automatic generation of Sphinx sources that, using the autodoc extension, **document a whole package** in the style of other automatic API documentation tools."

http://stackoverflow.com/q/50243762
has title: Pip Global Install Not Working
downvote count: 0
answer count: 1
tagged with: pip
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50790863
tagged with: package
score: 1
tagged with: python
tagged with: global
accepted answer: http://stackoverflow.com/a/50790863
has body: I followed this guide to setting up a Python environment and I'm having trouble with the part where you set up a function to bypass the virtual environment requirement. Basically, I want gpip install to work without a virtual environment. Also open to other methods of accomplishing this. This is my pip.conf file: [install] require-virtualenv = true [uninstall] require-virtualenv = true This is my .bash_profile file: 1 # Ensure user-installed binaries take precedence 2 export PATH=/usr/local/bin:$PATH 3 # Load .bashrc if it exists 4 test -f ~/.bashrc &amp;&amp; source ~/.bashrc This is my .bashrc file: 1 gpip(){ 2 PIP_REQUIRE_VIRTUALENV="" pip3 "$@" 3 } I've also tried 1 gpip(){ 2 PIP_REQUIRE_VIRTUALENV="" pip "$@" 3 } I still get Could not find an activated virtualenv (required). when I type in gpip install
type: AnsweredQuestion
tagged with: installation

http://stackoverflow.com/a/50239481
answers question: http://stackoverflow.com/q/50239310
type: AcceptedAnswer
downvote count: 0
has body: You can use datetime module like this example: import datetime date = "2018-05-08" final = datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S.%f') print(final) Output: 2018-05-08T00:00:00.000000 For more details visit datetime's documentation
accepted answer of: http://stackoverflow.com/q/50239310
score: 8
upvote count: 8
type: Answer

http://stackoverflow.com/comment/87703535
score: 1
type: Comment
comment on: http://stackoverflow.com/a/50340021
type: AnswerComment
has text: @upendra And [here is another good regex testing tool](https://regex101.com/r/LsOM2V/1), with pattern explanation, debugging and code snippet generation features.

http://stackoverflow.com/comment/87784134
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50384147
has text: Is there a specific situation that `find` works better than `index`?
score: 0

http://stackoverflow.com/q/50335886
has answer: http://stackoverflow.com/a/50335967
upvote count: 6
downvote count: 1
has title: Set intersection with custom comparator?
has comment: http://stackoverflow.com/comment/87688090
favorite count: 0
accepted answer: http://stackoverflow.com/a/50335967
type: Question
possible better answer: http://stackoverflow.com/a/50336024
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/50336024
has comment: http://stackoverflow.com/comment/87688029
tagged with: python
has body: I have sets of strings set_a = {'abcd', 'efgh', 'ghij'} set_b = {'abce', 'efgk', 'ghij'} I want to find the intersection between these two sets but element equality defined as the following def match(string_a, string_b, threshold=0.8): lcs_len = lcs(string_a, item_set_b) return (lcs_len / max(len(string_a), len(item_set_b))) &gt; 0.8 basically if the lcs is at least 80% of the length of the string we consider this matching "enough". I know passing custom comparators to sorting methods works something like this but I haven't found anything for custom comparators in set operations.
type: AnsweredQuestion

http://stackoverflow.com/a/50349306
answers question: http://stackoverflow.com/q/50349236
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87714874
has comment: http://stackoverflow.com/comment/87714820
accepted answer of: http://stackoverflow.com/q/50349236
has body: I think need compare sets with GroupBy.transform and filter by boolean indexing: neededVals = [1.0,2.0] df = df[df.groupby('A')['C'].transform(lambda x: set(x) &gt;= set(neededVals))] print (df) A B C 3 foo 4 1.0 4 foo 5 2.0 5 foo 6 9.0 Detail: print (df.groupby('A')['C'].transform(lambda x: set(x) &gt;= set(neededVals))) 0 False 1 False 2 False 3 True 4 True 5 True Name: C, dtype: bool And for second first filter out unnecessary rows by isin and then compare equality: df = df[df['C'].isin(neededVals)] df = df[df.groupby('A')['C'].transform(lambda x: set(x) == set(neededVals))] print (df) A B C 3 foo 4 1.0 4 foo 5 2.0
type: Answer

http://stackoverflow.com/comment/87634913
type: Comment
has text: @SalmanThank you for the links! The first one I saw myself, but the second one is very interesting! Thank you!
type: QuestionComment
comment on: http://stackoverflow.com/q/50296181
score: 0

http://stackoverflow.com/comment/87577830
score: 0
comment on: http://stackoverflow.com/q/50280590
type: Comment
type: QuestionComment
has text: Not familiar with `exifread`, what is the `type(tags)`?

http://stackoverflow.com/comment/87528313
type: Comment
type: QuestionComment
has text: This might be difficult if you're new to the subject -- what you want to do is called reverse engineering and is far from being a beginner topic :) [This question](https://reverseengineering.stackexchange.com/questions/160/how-do-you-reverse-engineer-an-exe-compiled-with-pyinstaller) is pretty much the same as yours but formulated differently, it should give you something to start with. Unfortunately a step-by-step approach is not going to be feasible here because of the complexity... you'll have to get at least a bit familiar with the subject.
score: 0
comment on: http://stackoverflow.com/q/50254926

http://stackoverflow.com/comment/87574625
score: 0
comment on: http://stackoverflow.com/q/50278875
has text: @user2357112 I should have elaborated. `sum(digits)` then recursively call.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50300672
answers question: http://stackoverflow.com/q/50283794
type: Answer
score: 0
has body: Here's a full example about running your blocking code in a separate thread and broadcasting messages to all connected clients. ... from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=1) # spawn only 1 thread class MyWebSocketServer(tornado.websocket.WebSocketHandler): connections = set() # create a set to hold connections def open(self): # put the new connection in connections set self.connections.add(self) def on_close(self): print('connection closed'+self.request.remote_ip) print('new connection'+self.request.remote_ip) # remove client from connections self.connections.remove(self) @classmethod def send_message(cls, msg): for client in cls.connections: client.write_message(msg) def read_from_serial(loop, msg_callback): """This function will read from serial and will run in aseparate thread `loop` is the IOLoop instance `msg_allback` is the function that will be called when new data is available from usb """ while True: # your code ... # ... # when you get new data # tell the IOLoop to schedule `msg_callback` # to send the data to all clients data = "new data" loop.add_callback(msg_callback, data) ... if __name__ == '__main__': loop = tornado.ioloop.IOLoop.current() msg_callback = MyWebSocketServer.send_message # run `read_from_serial` in another thread executor.submit(read_from_serial, loop, msg_callback) ... loop.start()
has comment: http://stackoverflow.com/comment/87624919
has comment: http://stackoverflow.com/comment/87709388
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87619851
has comment: http://stackoverflow.com/comment/87708780
accepted answer of: http://stackoverflow.com/q/50283794
has comment: http://stackoverflow.com/comment/87709115
has comment: http://stackoverflow.com/comment/87697696

http://stackoverflow.com/q/50365651
has comment: http://stackoverflow.com/comment/87758789
score: 6
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/75172068
upvote count: 6
answer count: 3
has title: Install using pip a development version of a python package but with stable dependencies
has answer: http://stackoverflow.com/a/75280538
downvote count: 0
has answer: http://stackoverflow.com/a/50366260
has body: Background The pip install command installs by default the newest stable version of a python package (stable versions as specified by PEP426) The flag --pre for the pip install command tells pip also consider release candidates and develompent versions of python packages. As far as I understand, though, pip install --pre packageA it will install a dev version of packageA, but also dev version of all its dependencies. The question is: Is it possible to use pip to install a development version of a package but stable versions of all its dependencies? Attempted solutions One thing I have tried is to install the stable version of the package (with stable dependencies), and then reinstall the dev version without dependencies: pip install packageA pip install --pre --no-deps --upgrade --force-reinstall packageA The problem, though, is that if the development version of packageA adds a new dependency, it will not be installed. I am missing anything? Thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/87747736
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/50255549
upvote count: 1
has comment: http://stackoverflow.com/comment/87530015
answers question: http://stackoverflow.com/q/50255044
has comment: http://stackoverflow.com/comment/87529662
type: Answer
has body: You should first analyse the distribution of your dataset because such normal-fraud datasets are usually highly imbalanced, meaning that they have disproportionately high number of normal cases compared to fraud cases. For example, if only 1% of the dataset represents fraud cases, then an accuracy of even 99% cannot be said to be good enough. In such cases, using precision and sensitivity is a better metric for accuracy. In your case, it is important that you recognize all fraud cases correctly, even if you classify a few normal cases as fraud. For such a requirement, sensitivity is a good metric (sensitivity basically represents how good the model is at detecting positives/frauds).
accepted answer of: http://stackoverflow.com/q/50255044
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/87857298
score: 0
type: AnswerComment
has text: To make a matrix of logits you can try `tf.one_hot`
comment on: http://stackoverflow.com/a/50402682
type: Comment

http://stackoverflow.com/a/50273973
has body: I see a couple problems. your if mouseClick2.y &gt;= y-50... conditional is spread out on two lines, but you don't have a line continuation character. You never call main(). You don't import random. You call draw_circle in the while loop with an argument of c, but there is no variable by that name in the global scope. You probably meant to pass in var. c in draw_circle ostensibly refers to the circle object you want to manipulate, but half the time you manipulate var instead of c. you assign a value to cvar in the loop, but never use it. Your else block in draw_circle calculates the movement delta by subtracting the cursor coordinates from c.p1. But c.p1 is the upper-left corner of the circle, not the center of the circle. So your hit detection is off by fifty pixels. &nbsp; import random from graphics import * def draw_circle(win, c=None): x = random.randint(0,500) y = random.randint(0,500) if c is None: centa = Point(x,y) c = Circle(centa,50) c.setFill(color_rgb(200,0,0)) c.draw(win) else: center_x = c.p1.x + 50 center_y = c.p1.y + 50 x_dif = (center_x - x) * -1 y_dif = (center_y - y) * -1 c.move(x_dif, y_dif) return (c, x, y) def main(): win= GraphWin("game",800,800) score = 0 var,x,y = draw_circle(win) while score &lt;= 7: mouseClick2=win.getMouse() if mouseClick2.y &gt;= y-50 and mouseClick2.y &lt;= y +50 and \ mouseClick2.x &gt;= x-50 and mouseClick2.x &lt;= x+50: score=score + random.randint(0,5) var,x,y = draw_circle(win, var) print ("Success!") print (("the score is, {0}").format(score)) main() Additional possible improvements: Your hit detection checks whether the cursor is in a 50x50 rectangle centered on the circle. You could instead check whether the cursor is inside the circle if you measured the distance between the cursor and the center, and checked whether it was less than the radius. var and c could stand to have more descriptive names. mouseClick2 doesn't make much sense as a name, considering there's no mouseClick1. The movement delta arithmetic …
has comment: http://stackoverflow.com/comment/87565535
answers question: http://stackoverflow.com/q/50273547
has comment: http://stackoverflow.com/comment/87565291
type: Answer
score: 0

http://stackoverflow.com/comment/87814084
has text: That's interesting that it works. As I said above (unless I am missing something) "\x00\x03\x01\xb8\x00\x01\x04\x02" is a broadcasted Read Holding Registers command that requests 1 register starting at address 440. There should never be a response to a broadcast packet.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50398950

http://stackoverflow.com/comment/87574365
has text: Can you access that address through some other means? Looks like there is a problem with it. Make sure it's reachable and your connection is OK.
score: 0
comment on: http://stackoverflow.com/q/50278762
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50294312
has body: This is one way to structure your logic. Similar to Ajax1234 but I add an extra optional parameter to strip_non_en. word_set = set(nltk.corpus.brown.words()) def strip_non_en(string, words=word_set, key=None): if key in (None, 'title'): string = ' '.join(w for w in nltk.wordpunct_tokenize(string) \ if w.lower() in words or not w.isalpha()) return string new_dict = {a: strip_non_en(b, key=a) for a, b in meta_data.items()}
score: 2
answers question: http://stackoverflow.com/q/50294019
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/50294019
type: Answer

unit-testing
tags question: http://stackoverflow.com/q/50380066
tags question: http://stackoverflow.com/q/50352493
tags question: http://stackoverflow.com/q/50330409
tags question: http://stackoverflow.com/q/50252114
tags question: http://stackoverflow.com/q/50232478
tags question: http://stackoverflow.com/q/50370495
type: Tag
tag name: unit-testing
tags question: http://stackoverflow.com/q/50238432
tags question: http://stackoverflow.com/q/50243583
tags question: http://stackoverflow.com/q/50301531
tags question: http://stackoverflow.com/q/50295078
tags question: http://stackoverflow.com/q/50255129
tags question: http://stackoverflow.com/q/50315300
tags question: http://stackoverflow.com/q/50292618
tags question: http://stackoverflow.com/q/50324563
tags question: http://stackoverflow.com/q/50336368
tags question: http://stackoverflow.com/q/50328918

http://stackoverflow.com/q/50246680
has comment: http://stackoverflow.com/comment/90059287
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/87511483
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87511089
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87511442
has comment: http://stackoverflow.com/comment/90059360
has title: How to handle a specific uncaught exception?
tagged with: exception
type: UnansweredQuestion
has body: I would like to handle one specific exception in my script in a single place without resorting to a try/exception everytime*. I was hoping that the code below would do this: import sys def handle(exc_type, exc_value, exc_traceback): if issubclass(exc_type, ValueError): print("ValueError handled here and the script continues") return # follow default behaviour for the exception sys.__excepthook__(exc_type, exc_value, exc_traceback) sys.excepthook = handle print("hello") raise ValueError("wazaa") print("world") a = 1/0 The idea was that ValueError would be handled "manually" and the script would continue running (return to the script). For any other error (ZeroDivisionError in the case above), the normal traceback and script crash would ensue. What happens is $ python scratch_13.py hello ValueError handled here and the script continues Process finished with exit code 1 The documentation mentions that (emphasis mine) When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. which would mean that when I am in handler() it is already too late as the script has decided to die anyway and my only possibility is to influence how the traceback will look like. Is there a way to ignore a specific exception globally in a script ? * this is for a debugging context where the exception would normally be raised and crash the script (in production) but in some specific cases (a dev platform for instance), this specific exception needs to just be discarded. Otherwise I would have put a try/exception clause everywhere where the issue could arise.
tagged with: python
has answer: http://stackoverflow.com/a/50246948
score: 2
linked to: http://stackoverflow.com/q/34425356

http://stackoverflow.com/a/50342686
answers question: http://stackoverflow.com/q/50342558
downvote count: 0
has comment: http://stackoverflow.com/comment/87701261
has comment: http://stackoverflow.com/comment/87701278
has comment: http://stackoverflow.com/comment/87701299
has body: You could use itertools.chain and collection.Counter: from itertools import chain from collections import Counter r = {k for k,v in Counter(chain.from_iterable(my_input_list)).items() if v==1}
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/50288997
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/50288685
has body: It seems that scipy.integrate.solve_ivp() was only introduced in scipy versions > 0.19.1: Documentation for version 0.19.1 and documentation for version 1.0.0. In order to use that function you will have to upgrade your version of scipy
answers question: http://stackoverflow.com/q/50288685
type: Answer
has comment: http://stackoverflow.com/comment/103643504
has comment: http://stackoverflow.com/comment/87593948

http://stackoverflow.com/a/50266037
downvote count: 0
type: AcceptedAnswer
has body: Lets assume you want to use PCA and TruncatedSVD as your dimesionality reduction step. pca = decomposition.PCA() svd = decomposition.TruncatedSVD() svm = SVC() n_components = [20, 40, 64] You can do this: pipe = Pipeline(steps=[('reduction', pca), ('svm', svm)]) # Change params_grid -> Instead of dict, make it a list of dict # In the first element, pass parameters related to pca, and in second related to svd params_grid = [{ 'svm__C': [1, 10, 100, 1000], 'svm__kernel': ['linear', 'rbf'], 'svm__gamma': [0.001, 0.0001], 'reduction':pca, 'reduction__n_components': n_components, }, { 'svm__C': [1, 10, 100, 1000], 'svm__kernel': ['linear', 'rbf'], 'svm__gamma': [0.001, 0.0001], 'reduction':svd, 'reduction__n_components': n_components, 'reduction__algorithm':['randomized'] }] and now just pass the pipeline object to gridsearchCV grd = GridSearchCV(pipe, param_grid = params_grid) Calling grd.fit() will search the parameters over both the elements of the params_grid list, using all values from one at a time. Please look at my other answer for more details: "Parallel" pipeline to get best model using gridsearch
has comment: http://stackoverflow.com/comment/87551081
accepted answer of: http://stackoverflow.com/q/50265993
has comment: http://stackoverflow.com/comment/87550692
type: Answer
has comment: http://stackoverflow.com/comment/111681292
answers question: http://stackoverflow.com/q/50265993
upvote count: 20
score: 20

http://stackoverflow.com/q/50366530
linked to: http://stackoverflow.com/q/11530196
downvote count: 0
score: 7
upvote count: 7
duplicate of: http://stackoverflow.com/q/11530196
answer count: 1
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: I'm trying to get all the rows in a table, but only one column. The model looks like this: class Person: id= db.Column(db.String(11), primary_key=True, nullable=False) name = db.Column(db.String(255), nullable=False) city = db.Column(db.String(255), nullable=False) I want to get the name column ONLY but I can't find anything on how to do this. I've tried stuff like: Person.query.get(person.name) The SQLAlchemy documentation doesn't help at all.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51173558
has title: SQLAlchemy: Get only one column
tagged with: python

http://stackoverflow.com/comment/87771538
comment on: http://stackoverflow.com/q/50377649
has text: It returns 2 on my machine. Your code has no problem at all.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/50365318
tagged with: flask
favorite count: 0
score: 1
tagged with: python
tagged with: wsgiserver
has comment: http://stackoverflow.com/comment/87753912
type: Question
has title: How enable/implement Multi Threading in the WSGIServer of Flask Python
has answer: http://stackoverflow.com/a/50398177
has body: I have a Flask API which servers to Web and Mobile Apps. But sometimes on heavy load, app or websites stop quick response and displays results taking time, I just want to enable multithreading in the flask running with WSGIServer. def main(): """Main entry point of the app.""" try: http_server = WSGIServer(('0.0.0.0', 8084), app, log=logging, error_log=logging) http_server.serve_forever() except Exception as exc: logger.error(exc.message) logger.exception(traceback.format_exc()) finally: # Do something here pass Thanks,
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/87596212
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50289220
has text: @Mr.T it should still find the best fit, whether it has one or not. It should be able to fit a triangle, simply by searching for the best combination of parameters, the fit won't be perfect, but it should do ok. The problem is that I don't know how to impose a tau2 > tau1

http://stackoverflow.com/comment/87687713
has text: I changed my exemple to explain better, I think I did not explain it well
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50335563
type: Comment

http://stackoverflow.com/comment/88166572
type: QuestionComment
comment on: http://stackoverflow.com/q/50364766
score: 0
has text: @PeterBrittain if you write your comment as answer, then I will upvote and accept it.
type: Comment

http://stackoverflow.com/comment/87760471
has text: I have added error checking to the script. Also if the URL is invalid, or if the link found does not work.
type: AnswerComment
comment on: http://stackoverflow.com/a/50369834
type: Comment
score: 0

http://stackoverflow.com/q/50275129
favorite count: 0
has comment: http://stackoverflow.com/comment/87571248
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50275259
upvote count: 1
accepted answer: http://stackoverflow.com/a/50275259
has comment: http://stackoverflow.com/comment/87567028
tagged with: python
has comment: http://stackoverflow.com/comment/87567380
type: AnsweredQuestion
score: 0
has title: TypeError: unsupported operand type(s) for /: 'str' and 'int' in python
has comment: http://stackoverflow.com/comment/87566927
tagged with: syntax
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87567199
has body: I am working on a project for finding students grade average for 3 exams. Everything seems fine with my work but one error I am receiving with the following line: student_avg = ((firstterm) +str (midterm) +str (final)) / 3 The program is an instructor's companion app. My professor told me to do 1st term mid term and final for 5 subjects. After one week of working I still faced some problems on that. Can anyone review my code and see what my mistake is? def determine_score(grade): if 95&lt;= grade &lt;=100: return 'A+' elif 91&lt;= grade &lt;=96: return 'A' elif 89&lt;= grade &lt;=92: return 'A-' elif 85&lt;= grade &lt;=90: return 'B+' elif 81&lt;= grade &lt;=86: return 'B' elif 79&lt;= grade &lt;=82: return 'B-' elif 75&lt;= grade &lt;=80: return 'C+' elif 72&lt;= grade &lt;=76: return 'C' elif 64&lt;= grade &lt;=73: return 'D' elif 0&lt;= grade &lt;=65: return 'F' else: return 'invalide score' def firstTerm(): fst_sub1=int(input("Enter first term marks of the first subject: ")) fst_sub2=int(input("Enter first term marks of the second subject: ")) fst_sub3=int(input("Enter first term marks of the third subject: ")) fst_sub4=int(input("Enter first term marks of the fourth subject: ")) fst_sub5=int(input("Enter first term marks of the fifth subject: ")) firsttermScore = (fst_sub1+fst_sub2+fst_sub3+fst_sub4+fst_sub5)/5 return 'firsttermScore' def midTerm(): mid_sub1=int(input("Enter mid term marks of the first subject: ")) mid_sub2=int(input("Enter mid term marks of the second subject: ")) mid_sub3=int(input("Enter mid term marks of the third subject: ")) mid_sub4=int(input("Enter mid term marks of the fourth subject: ")) mid_sub5=int(input("Enter mid term marks of the fifth subject: ")) midtermScore = (mid_sub1+mid_sub2+mid_sub3+mid_sub4+mid_sub5)/5 return 'midtermScore' def final(): fnl_sub1=int(input("Enter final marks of the first subject: ")) fnl_sub2=int(input("Enter final marks of the second subject: ")) fnl_sub3=int(input("Enter final marks of the third subject…

http://stackoverflow.com/a/50382813
has comment: http://stackoverflow.com/comment/87782782
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/50379670
has body: start = datetime(1998, 1, 1) end = datetime(2001, 12, 31) dates = pd.date_range(start, end, freq = 'D') Create the DataFrame with a MultiIndex - (year,quarter) index = pd.MultiIndex.from_tuples([(thing.year, thing.quarter) for thing in dates]) df = pd.DataFrame(np.random.randn(len(dates), 3), index = index, columns = ['returns', 'pnl', 'no_trades']) Then you can group by year, quarter or year and quarter: gb_yr = df.groupby(level=0) gb_qtr = df.groupby(level=1) gb_yr_qtr = df.groupby(level=(0,1)) &gt;&gt;&gt; &gt;&gt;&gt; # yearly means &gt;&gt;&gt; gb_yr.mean() returns pnl no_trades 1998 0.080989 -0.019115 0.142576 1999 -0.040881 -0.005331 0.029815 2000 -0.036227 -0.100028 -0.009175 2001 0.097230 -0.019342 -0.089498 &gt;&gt;&gt; &gt;&gt;&gt; # quarterly means across all years &gt;&gt;&gt; gb_qtr.mean() returns pnl no_trades 1 0.036992 0.023923 0.048497 2 0.053445 -0.039583 0.076721 3 0.003891 -0.016180 0.004619 4 0.007145 -0.111050 -0.054988 &gt;&gt;&gt; &gt;&gt;&gt; # means by year and quarter &gt;&gt;&gt; gb_yr_qtr.mean() returns pnl no_trades 1998 1 -0.062570 0.139856 0.105288 2 0.044946 -0.008685 0.200393 3 0.152209 0.007341 0.119093 4 0.185858 -0.211401 0.145347 1999 1 0.085799 0.072655 0.054060 2 0.111595 0.002972 0.068792 3 -0.194506 -0.093435 0.107210 4 -0.161999 -0.001732 -0.109851 2000 1 0.001543 -0.083488 0.174226 2 -0.064343 -0.158431 -0.071415 3 -0.036334 -0.037008 -0.068717 4 -0.045669 -0.121640 -0.069474 2001 1 0.123592 -0.032138 -0.140982 2 0.121582 0.005810 0.109115 3 0.094194 0.058382 -0.139110 4 0.050388 -0.109429 -0.185975 &gt;&gt;&gt; &gt;&gt;&gt; # operate on single columns &gt;&gt;&gt; gb_yr['pnl'].sum() 1998 -6.976917 1999 -1.945935 2000 -36.610206 2001 -7.060010 Name: pnl, dtype: float64 &gt;&gt;&gt; # plotting &gt;&gt;&gt; from matplotlib import pyplot as plt &gt;&gt;&gt; gb_yr.mean().plot() &lt;matplotlib.axes._subplots.AxesSubplot object at 0x000000000C04BF28&gt; &gt;&gt;&gt; plt.show() &gt;&gt;&gt; plt.close()
has comment: http://stackoverflow.com/comment/87813264

http://stackoverflow.com/comment/87622366
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50302951
has text: it's nothing to do with sublime text, that result is expected for python code. however, align `print(storage_list)` with the `for` line, and you'll get the expected behavior of one line output
score: 0

http://stackoverflow.com/a/50346745
answers question: http://stackoverflow.com/q/50346664
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Use a dictionary for a variable number of variables: tickers = ['IBM US Equity', 'AAPL US Equity'] df_dict = {} for num, ticker in enumerate(tickers, start=1): df_dict[num] = df.loc[ticker] Then access elements via df_dict[1], etc. An alternative way to formulate your logic is to use a dictionary comprehension: df_dict = {num: df.loc[ticker] for num, ticker in enumerate(tickers, 1)} The reason your code errors is pandas is trying to add a dataframe to a series: the left hand side of df[num] = df.loc[ticker] is a series, while the right hand side is a dataframe. This is not possible and, fairly descriptively, pandas complains about an incorrect number of items.
type: Answer
accepted answer of: http://stackoverflow.com/q/50346664

http://stackoverflow.com/a/50241373
accepted answer of: http://stackoverflow.com/q/50241216
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/50241216
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94255560
has comment: http://stackoverflow.com/comment/94255909
score: 1
has comment: http://stackoverflow.com/comment/94251426
has body: I think that you state the following situation: For a test vector X_test you find a predicted probability distribution y=[p1, p2, p3] from the predict_proba() method with p1>p2 and p1>p3 but the predict() method does not output class 0 for this vector. If you inspect the source code of the predict function of sklearn's RandomForestClassifier, you will see that the predict_proba() method of the RandomForest is called there: proba = self.predict_proba(X) From these probabilities, the argmax is used to output the class. Hence, the prediction step uses the predict_proba method for its output. For me it seems impossible that anything goes wrong there. I would assume that you mixed up some class names in your routine and got confused there. But it is not possible to give a more detailed answer based on the information you provided.

http://stackoverflow.com/a/50244965
has comment: http://stackoverflow.com/comment/120547117
has comment: http://stackoverflow.com/comment/87548281
has body: You can create a simple app in flask that receives user input and scans the items returned from a SELECT query in sqlite3: First, create the user form. You can use ajax with jquery for a dynamic response: In search.html: Search In app.py import flask import sqlite3 app = flask.Flask(__name__) @app.route('/') def home(): return "Search" @app.route('/search') def search(): term = flask.request.args.get('query') possibilities = [i for [i] in sqlite3.connect('filename.db').cursor().execute("SELECT * FROM stores") if term.lower() in i.lower()] return flask.jsonify({'html':' No results found ' if not possibilities else ' \n{} '.format('\n'.join(' {} '.format(i) for i in possibilities))})
answers question: http://stackoverflow.com/q/50244721
has comment: http://stackoverflow.com/comment/87526244
has comment: http://stackoverflow.com/comment/87507626
score: 0
has comment: http://stackoverflow.com/comment/87565902
accepted answer of: http://stackoverflow.com/q/50244721
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/comment/87562155
type: Comment
has text: Hi, can you give an example of what you are trying to achieve, e.g., what the end code should look like? Specifically, what do you mean by "but what if I want to create custom constructors"?
comment on: http://stackoverflow.com/q/50252481
score: 0
type: QuestionComment

http://stackoverflow.com/q/50360320
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87737871
has comment: http://stackoverflow.com/comment/87740032
tagged with: python-module
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87737581
tagged with: python
has comment: http://stackoverflow.com/comment/87795766
has comment: http://stackoverflow.com/comment/87737818
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/87737705
has title: ImportError: No module named _collections
tagged with: environment-variables
has body: Right after a fresh install, when python get-pip.py --user I get this error about _collections. From the python prompt I can import basic stuff such as os and sys but not time. my environment (done by hand sourcing a script) is such that ~&gt;echo $PYTHONPATH ~/python2715/lib/python2.7/:~/python2715/lib/python2.7/site-packages/ and ~&gt;echo $PYTHONHOME ~/python2715/lib/python2.7/:~/python2715/lib/python2.7/site-packages/ ~&gt;which python ~/python2715/bin/python ~&gt;python --version Python 2.7.15 Any suggestions as of why I cannot import modules? any other env variable to check?
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/87737652
has comment: http://stackoverflow.com/comment/87737927

http://stackoverflow.com/a/50296625
has body: You are very close. List comprehensions cannot store and reuse variables in the way you wish; they may only contain expressions. One solution is to use sum with a generator expression. The benefit of this solution is you avoid the expense of building a list, which is not necessary to count the number of elements satisfying a condition. A = [1,2,4,5,7,8,10] A_set = set(A) d = 3 count = 0 res = sum(1 for x in range(len(A)) if \ (A[x]+d in A_set) and (A[x]+2*d in A_set)) # 3 Note you should never name variables after classes. In addition, you can use set for O(1) lookup. Also note that we construct the A_set outside the list comprehension, otherwise it will be computed for each iteration of range(len(A)).
score: 2
answers question: http://stackoverflow.com/q/50296546
has comment: http://stackoverflow.com/comment/87610350
downvote count: 0
has comment: http://stackoverflow.com/comment/87610222
upvote count: 2
has comment: http://stackoverflow.com/comment/87610618
type: Answer
has comment: http://stackoverflow.com/comment/87610284

http://stackoverflow.com/comment/87588934
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50285525
has text: i installed it like this - `conda install --name pytorch pytorch-cpu -c pytorch`
score: 0

http://stackoverflow.com/comment/87814360
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/50377737
has text: @chepner g.sort() run currently when number isnt tensor .that is not my broblem ,my problem is: a list which has two number should be find in there, the error will be apear : cant use tensor as bool_var , when i want to use "if" statment either the largest less number or smalest greater number of tensor otherwise may used 'tf.cond' statment then at last the "value error" apear when i used 'tf.no_op' on 'tf.cond' in the false statment.how can i solve this error ?

http://stackoverflow.com/a/50379521
accepted answer of: http://stackoverflow.com/q/50379463
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/50379463
has body: Run your script through the nohup command. The interface is pretty simple. The call would look something like this: nohup script arg1 arg2 Here script arg1 arg2 are just the usual way you run the script. When you are able to log back in, stdout and stderr will be in a file called nohup.out. If you want something different, use redirection as described in man nohup.
score: 1
type: Answer

http://stackoverflow.com/q/50294951
has answer: http://stackoverflow.com/a/50295217
accepted answer: http://stackoverflow.com/a/50295217
tagged with: matplotlib
tagged with: boxplot
possible better answer: http://stackoverflow.com/a/50295118
tagged with: python
tagged with: statistics
upvote count: 2
type: AnsweredQuestion
answer count: 2
has body: I'm trying to print all the boxplots for each variable in a dataset with this python loop. colNameList = list(df.columns) for i in range (0, len(df.columns)): df.boxplot(column=colNameList[i]) Where df is my dataset. Why this simple code shows to me only the last one boxplot?
tagged with: pandas
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/50295118
favorite count: 0
type: Question
has title: Python boxplot on single variables

http://stackoverflow.com/comment/87717921
score: 2
type: Comment
type: QuestionComment
has text: Why use the same variable name for both function and the list ?
comment on: http://stackoverflow.com/q/50350975

http://stackoverflow.com/a/50242637
type: Answer
has body: I got the run time down by about 30% using: def avail_array(lengths): out = np.zeros((365, len(lengths))) for i in range(int(len(lengths))): out[int(lengths[i]):, i] = 1 return out Your version: 41 µs ± 734 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) This version: 28.2 µs ± 353 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) This may just be a quirk of what random lengths were selected, but at the very least not using 0*len(lengths[i]) and either using np.ones(...) or np.zeros(...) and not 1 + np.zeros(...) is a good start.
score: 0
answers question: http://stackoverflow.com/q/50242502

http://stackoverflow.com/a/50289869
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50289743
has body: You can simply get the values of each as shown below: data = split.groups() if len(data) == 2: name, id = data print(name, id) Or you can use group([group1, ...]).
type: Answer

http://stackoverflow.com/q/50299868
has answer: http://stackoverflow.com/a/50313431
score: -2
tagged with: web-crawler
tagged with: webdriver
type: Question
has comment: http://stackoverflow.com/comment/87616490
has comment: http://stackoverflow.com/comment/87616963
answer count: 2
has title: how to duplicate a webdriver in selenium
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/87620255
tagged with: selenium
has answer: http://stackoverflow.com/a/50302576
tagged with: web-scraping
tagged with: python
favorite count: 0
has body: I am doing some Web Scraping using selenium webdriver. The issue is that i need to go to lots of subpages(from main page) to scrape data. Instead of going back to main page, I want to make a duplicate of the driver when it is on main page. Something like driver_sub = driver.copy(). Then I can go to subpage using driver_sub and run driver_sub.quit() to end. Is it possible?

http://stackoverflow.com/comment/87535362
type: AnswerComment
has text: I have updated the answer . It was Not the problem with root .
type: Comment
comment on: http://stackoverflow.com/a/50258457
score: 0

http://stackoverflow.com/q/50377934
has answer: http://stackoverflow.com/a/50377986
favorite count: 0
type: Question
has body: The use case here is I have a main program continuously looping to grab sensor data and perform some computations and logic. At the same time I have a second program running flask with twilio listening for inbound sms messages. I am trying to set a variable in the second program based on the content of the sms message, and run logic in the first program depending on the value of this variable. I have defined a module imported into both, and depending on how it is called is supposed to either set the desired value or return it. To test this I have created a stripped down 'toy' version which just has two independent looping programs and a global module. It is not working the way I expect. globaltest.py (the global module). def varex(arg): statevar = 0 if arg != 1: statevar = arg elif arg == 1: return statevar else: return 'error' main_test.py (representing the first program) It is calling to get statevar in globaltest.varex set by stest. from globaltest import varex from time import sleep while True: loc_var = varex(1) print('local ',loc_var) sleep(3) stest.py (representing the flask server) This is setting statevar in globaltest.varex, in this case just simply indexing upward from globaltest import varex from time import sleep i = 2 while True: state = i i = i+1 varex(state) print(state) sleep(1) main_test always prints "local 0", so statevar in globaltest.py is not being updated by stest.py . I can't seem to figure out why this is, and also not sure this is the best way to solve the problem. I've looked at other similar questions but this seems to be a bit of a different use case.
has title: Python - Pass variable between programs using global module
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/87772038
type: AnsweredQuestion
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/50377986
upvote count: 1

instantiation
type: Tag
tags question: http://stackoverflow.com/q/50273608
tag name: instantiation

http://stackoverflow.com/comment/87575497
has text: Everything here looks fine. Sounds like you have a website dependent problem.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/50279436

http://stackoverflow.com/q/50297604
has title: Getting rid of the extra header row for HTML styling of Pandas multi-index DataFrames
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/50297729
tagged with: jupyter-notebook
type: Question
linked to: http://stackoverflow.com/q/40726362
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87612487
answer count: 1
duplicate of: http://stackoverflow.com/q/40726362
has body: This pandas code: import pandas as pd df=pd.DataFrame([[0,0,1,2,3],[0,1,3,4,5],[1,0,4,5,6],[1,1,5,6,7]], columns=['A','B','X','Y','Z']) df.set_index(['A','B'], inplace=True) df displays as follows in IPython Notebook: Note that there are two header rows, to distinguish the index columns from the data columns. Is there any way to get these to show in only one header row?
score: 0

http://stackoverflow.com/q/50383582
has answer: http://stackoverflow.com/a/50385317
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87783419
tagged with: python
has title: How to save the data entered from entry widget in tkinter python
score: -1
type: Question
tagged with: tkinter
upvote count: 0
accepted answer: http://stackoverflow.com/a/50385317
answer count: 1
has body: i have written a code and want to save the data entered but it shows an error from tkinter import* from tkinter import messagebox import webbrowser win= Tk() win.title("Facebook login") lbl=Label(win, text="Please enter your login and password") lbl.grid(column=5,row=3) uid=Entry(win,width=30) pas=Entry(win,width=30) uid.grid(column=3,row=6) pas.grid(column=3,row=9) def click(): messagebox.showinfo('Error ','The following data could not be transferred \nPlease login again from the page opening now') def kill(): win.destroy() button1=Button(win,text="Login",command=click) button1.grid(column=7,row=11) win.mainloop() webbrowser.open('https://www.facebook.com/') id=uid.get() ps=pas.get() file=open('D:\\cover.txt','w+') file.write("username:\t"+win) file.write("password:\t"+id) How to convert tk() to string or any other datatype so that i can store it Thank you

http://stackoverflow.com/comment/87691806
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50337464
has text: Yes. Also notice that I placed them in a tuple.

http://stackoverflow.com/comment/87579145
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50281268
has text: The data still aren't sorted: 30 Jun 2017 is out of order.
type: Comment

http://stackoverflow.com/a/50287235
upvote count: 2
has body: As per the HTML you have shared the element with text as Upload Resume is within the &lt;a&gt; tag and to click on the element you can use either of the following Locator Strategies : link_text : driver.find_elements_by_link_text("Upload Resume").click() css_selector : driver.find_element_by_css_selector("div#uploadCredential &gt; a").click() xpath : driver.find_element_by_xpath("//div[@id='uploadCredential']/a").click()
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/87590599
answers question: http://stackoverflow.com/q/50287049

http://stackoverflow.com/a/50377767
answers question: http://stackoverflow.com/q/50368390
type: Answer
has body: You can use Dependency Walker to find out which dependency of that DLL might be missing. Use it to open the Python extension file that's failing to load. The file name should be something like: C:\Users\Saeed\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\_C.pyd Another common cause is a DLL for Python 64-bit while using Python 32-bit or vice-versa. But you installed with pip so it should be OK. Nevertheless, it's a good idea to verify this is not the case.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50368390

http://stackoverflow.com/comment/87496654
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/50239594
type: Comment
has text: I have reproduced it at Ubuntu. Typed "test" in the CLI manually - so nothing has been sent to stdin.

http://stackoverflow.com/comment/87700927
has text: Looks like an [itinerary reconstruction](https://leetcode.com/problems/reconstruct-itinerary/description/) problem.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50342113

http://stackoverflow.com/a/50256635
type: AcceptedAnswer
type: Answer
has body: I have figured it out (and cleaned my code a bit): horse = IPython.display.Audio(url="http://www.w3schools.com/html/horse.ogg", autoplay=True) IPython.display.display(horse) time.sleep(10) IPython.display.display(horse)
upvote count: 1
answers question: http://stackoverflow.com/q/50256440
score: 1
accepted answer of: http://stackoverflow.com/q/50256440
downvote count: 0

http://stackoverflow.com/comment/87633863
type: QuestionComment
type: Comment
has text: No, I mean the Django view where the user creates the new record.
comment on: http://stackoverflow.com/q/50302418
score: 0

http://stackoverflow.com/comment/87486098
has text: Pass them using ```args```.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/50234234
type: QuestionComment

http://stackoverflow.com/comment/116973574
has text: Does not work well for large data sets. Failed with a warning `numpy.core._exceptions.MemoryError: Unable to allocate 4.18 TiB for an array with shape (4130207, 5) and data type <U55682`
score: 3
type: Comment
comment on: http://stackoverflow.com/a/50339260
type: AnswerComment

http://stackoverflow.com/q/50264334
favorite count: 0
type: Question
has body: If I have two columns as below: Origin Destination China USA China Turkey USA China USA Turkey USA Russia Russia China How would I perform label encoding while ensuring the label for the Origin column matches the one in the destination column i.e Origin Destination 0 1 0 3 1 0 1 0 1 0 2 1 If I do the encoding for each column separately then the algorithm will see the China in column1 as different from column2 which is not the case
possible better answer: http://stackoverflow.com/a/50264390
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50264590
tagged with: pandas
answer count: 5
has answer: http://stackoverflow.com/a/50264468
has title: Label encoding across multiple columns with same attributes in sckit-learn
downvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/50264403
upvote count: 12
has answer: http://stackoverflow.com/a/50264390
has answer: http://stackoverflow.com/a/50264543
tagged with: scikit-learn
score: 11
has answer: http://stackoverflow.com/a/50264403

http://stackoverflow.com/q/50309622
tagged with: python
type: AnsweredQuestion
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/50309639
answer count: 1
type: Question
tagged with: python-3.x
tagged with: tuples
accepted answer: http://stackoverflow.com/a/50309639
has body: I got two Python lists with some data: list_first = [(1, 2, 'Adam', 'Men', '3.5', '1'), (1, 2, 'Ewa', 'Women', '2', '1'), (1, 2, 'Adam', 'Men', '4', '2')] second_list = [(2, 5, 'Jack', 'Men', '3.5', '1'), (1, 3, 'Chris', 'Women', '5', '2'), (10, 22, 'Adam', 'Men', '42', '11')] Now I want to find duplicates in the second_list, but only with Name and Sex field, so in the above example: The duplicate in the second_list is Adam. (Adam, Men). Now I want tmove this tuple ((1, 2, 'Adam', 'Man', '4', '2')) to list_first. I tried to make it in the following way: (without success): name_fy = [(item[2] for item in list_first) and (item[3] for item in list_first)] name_sy = [(item[2] for item in list_second) and (item[3] for item in list_second)] for i in name_fy : for j in name_sy : if i == j: # move to list_first
has title: Given a list of tuples: Find duplicates and move them with the most effective way

http://stackoverflow.com/comment/87724455
has text: Can you give an example of your `dict` ? This should be possible with `csv` native library: https://docs.python.org/3/library/csv.html
comment on: http://stackoverflow.com/q/50354041
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50367642
type: Answer
score: 9
has body: Set button border = 0. bd=0 (extra caharacters to satisfy SO)
downvote count: 0
answers question: http://stackoverflow.com/q/50367083
upvote count: 9

http://stackoverflow.com/comment/87839064
type: AnswerComment
score: 0
has text: You're right. I looked at some other code written that communicates with the same slave device and it's broadcasting too. I'm wondering if the mod bus implementation on the slave machine isn't configured properly. Thanks for pointing this out.
type: Comment
comment on: http://stackoverflow.com/a/50398950

http://stackoverflow.com/comment/87504359
score: 0
type: AnswerComment
has text: Missing `from io import StringIO`
comment on: http://stackoverflow.com/a/50243332
type: Comment

http://stackoverflow.com/q/50257312
score: 1
tagged with: dynamic-programming
downvote count: 0
upvote count: 1
tagged with: weighted-average
has comment: http://stackoverflow.com/comment/87532741
has body: Problem statement : Dynamically allocate Pre-defined Weights on Categories in case of missing Category(ies). Details : there are 3 categories of data C1, C2 &amp; C3 each having a predefined weight (lets say its 0.5 ,0.3 &amp; 0.2 respectively). If data exists for all 3 categories, we are taking a "weighted-average" : C1*d1 + C2*d2 + C3*d3. C1,C2 &amp; C3 are predefined and will always sum to 1. Problem arises in case of missing data for d1/d2/d3. In such scenarios, we must distribute the weights of the respective categories evenly into other present categories. for example, if d1 &amp; d2 are present and d3 isnt, so C3's value should be evenly divided to C1 &amp; C2. So the new calculation would be newC1*d1 + newC2*d2 where newC1 and newC2 are revised weight values taken from C3. Similarly for all possible cases (of presence of d1,d2,d3). There will be 3 categories (C1,C2,C3) ONLY - to make this problem as simple as possible for now. Input dataframe containing d1,d2,d3 values is as below (called as SCORE) : Col1 Col2 **SCORE** Col4 Col5 Col6 123 987 **53.357809** 2017-05-03 16:39:20 456 'ABC' Is there a generic way to achieve this problem ? Any help will be appreciated.
has title: Dynamic allocation of weights to categories using Python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87532567
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/q/50267191
type: AnsweredQuestion
answer count: 2
has title: Testing Python method against 2
accepted answer: http://stackoverflow.com/a/50267283
upvote count: 0
has answer: http://stackoverflow.com/a/50267283
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87552486
has body: 1st please pardon the title I didn't know what else to title this. I am trying to test 2 cases. But when I fix it for one it breaks the other. The following method: singleline_diff_format(line1, line2, idx) Should return: ^ a But instead returns the empty string. For the case: singleline_diff_format('','a,0) It correctly returns the empty string for the following case: singleline_diff_format('abcdefg', 'abc', 5) because the index 5 is larger than the smaller string. How can I make it so it prints the correct output for both cases? Thank you. Here is the complete method: def singleline_diff_format(line1, line2, idx): """ Inputs: line1 - first single line string line2 - second single line string idx - index at which to indicate difference Output: Returns a three line formatted string showing the location of the first difference between line1 and line2. If either input line contains a newline or carriage return, then returns an empty string. If idx is not a valid index, then returns an empty string. """ if "\n" in line1 or "\n" in line2: return "" if idx &lt; 0: return "" if len(line1) &lt; len(line2): if idx &gt;= len(line1): return "" if len(line2) &lt; len(line1): if idx &gt;= len(line2): return "" return line1 + "\n" + "="*idx + "^" + "\n" + line2 + "\n"
tagged with: python
possible better answer: http://stackoverflow.com/a/50267475
has answer: http://stackoverflow.com/a/50267475
score: -1

http://stackoverflow.com/q/50321987
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50356547
tagged with: http://stackoverflow.com/tag/zip
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/87713591
has body: I am trying to download a ZIP file using from this website. I have looked at other questions like this, tried using the requests and urllib but I get the same error: urllib.error.HTTPError: HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Found Any ideas on how to open the file straight from the web? Here is some sample code from urllib.request import urlopen response = urlopen('http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip')
has answer: http://stackoverflow.com/a/50321997
has title: Download ZIP file from the web (Python)
linked to: http://stackoverflow.com/q/16760992
type: Question
has comment: http://stackoverflow.com/comment/87659752

http://stackoverflow.com/comment/87699950
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50341067
has text: @cricket_007 any thoughts?
type: Comment

http://stackoverflow.com/comment/87713887
comment on: http://stackoverflow.com/q/50255126
has text: Don't use prange on all loops (you would't do that with OpenMP either). Normally it is the goal to SIMD-vectorize the inner loops and parallelize over the outer loops for best performance. The fastmath keyword is also relevant for this type of operation. This will offer more algebraically correct optimizations that may have an impact on the numerical presicion (Summing by use of partial sums)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87631045
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50307483
has text: Note that this question refers to CPython (the reference implementation), not Python (the specification).
type: Comment

http://stackoverflow.com/q/50345601
has comment: http://stackoverflow.com/comment/87707307
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/87708625
answer count: 0
has comment: http://stackoverflow.com/comment/87739980
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87708447
score: 0
has comment: http://stackoverflow.com/comment/87708712
has title: Tensorflow (CPU-only) doesn't work in Windows Server 2016 (VM)?
has body: I installed python 3.6.5 (64-bit) and tensorflow (CPU-only) in Windows Server 2016 (VM). The installation seems fine but I had following errors (stack details removed) when try to run tensorflow python shell: ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. ImportError: No module named '_pywrap_tensorflow_internal' I did search and found a few answers about missing dll, nvidia libs but none works for me. Here's the recap: I'm using tensorflow CPU-only so nvidia libs should not be required. MSVCP140.DLL is already installed and is set in PATH I did this in two different VMs but neither works. However I did same steps in Windows Server 2012 (VM) and it worked after I installed c++ Redistributable 2015! So I'm wondering if there's any compatibility issue in Windows Server 2016 (and/or VM only)? Thanks!
tagged with: windows
tagged with: python

http://stackoverflow.com/comment/87699355
has text: Right... in this case the matches have the same match index (position of first match character).
type: Comment
score: 0
comment on: http://stackoverflow.com/q/50341554
type: QuestionComment

http://stackoverflow.com/comment/87739555
score: 0
has text: To elaborate on @chrisz's comment: the reason you do not want to name your dictionaries `dict` is because of name clashing. You instantiate dicts using the name `dict()`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/50361456

http://stackoverflow.com/a/50303319
accepted answer of: http://stackoverflow.com/q/50303300
answers question: http://stackoverflow.com/q/50303300
type: AcceptedAnswer
downvote count: 0
has body: If want see only values is possible convert to 2d numpy array: print (New_dataframe.values) [[1 2 3] [4 5 6] [7 8 9]] If need see DataFrame it is possible by: print (New_dataframe.to_csv(index=False, header=None, sep=' ')) 1 2 3 4 5 6 7 8 9 print (New_dataframe.to_string(index=False, header=None)) 1 2 3 4 5 6 7 8 9 EDIT: For convert to excel without index and headers use parameter index=False and header=None: New_dataframe.to_excel('test.xlsx', index=False, header=None)
has comment: http://stackoverflow.com/comment/87623093
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/a/50264071
downvote count: 0
type: Answer
upvote count: 1
has body: def f(a_list): return "\n".join(["\t".join([str(s) for s in line]) for line in a_list])
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/50264029
answers question: http://stackoverflow.com/q/50264029

http://stackoverflow.com/comment/87797328
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50339687
has text: You can remove any widget with `widget.grid_remove()`, but you will have to remember which buttons are in which column. The button will still exist, and you can show it again with `widget.grid()`. It will remember where it was placed.
type: Comment

http://stackoverflow.com/q/50342869
has comment: http://stackoverflow.com/comment/87702118
tagged with: laravel
has comment: http://stackoverflow.com/comment/87701739
has comment: http://stackoverflow.com/comment/87841097
has comment: http://stackoverflow.com/comment/87701761
has answer: http://stackoverflow.com/a/50355093
has comment: http://stackoverflow.com/comment/87701682
upvote count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/87701800
has comment: http://stackoverflow.com/comment/87701637
has comment: http://stackoverflow.com/comment/87702002
has comment: http://stackoverflow.com/comment/87701701
has body: I have a python script that returns JSON like that: { "2013": "34 124 682,7", "2014": "39 656 349,2", "2015": "34 452 255,0", "2016": "55 921 181,4", "2017": "27 026 543,1", "2018": "7 009 560,3" } In my Controller: $json = shell_exec("C:/Users/1/AppData/Local/Programs/Python/Python36-32/python -W ignore ../../../interprises_parsers/parsers/tax/parser.py ".$bin); $output = json_decode($json); return $output; Returns me null! Paths are correct! Bin is number also correct! P.S. Executing script in system console, gives me correct JSON output UPDATE: I got JSON from my script, but when i return it as json_decode variable it gives me next error: The Response content must be a string or object implementing __toString(), "object" given. Here is my var_dump: object(stdClass)#462 (6) { ["2013"]=&gt; string(4) "11,9" ["2014"]=&gt; string(4) "11,9" ["2015"]=&gt; string(4) "12,9" ["2016"]=&gt; string(4) "11,9" ["2017"]=&gt; string(3) "3,5" ["2018"]=&gt; string(4) "30,0" } {"2013": "11,9", "2014": "11,9", "2015": "12,9", "2016": "11,9", "2017": "3,5", "2018": "30,0"}
favorite count: 0
type: Question
has title: json_decode from python script returning null
tagged with: null
score: -2
has comment: http://stackoverflow.com/comment/87701652
tagged with: python
tagged with: php

http://stackoverflow.com/a/50314291
has comment: http://stackoverflow.com/comment/87698900
downvote count: 0
has comment: http://stackoverflow.com/comment/87699093
score: 6
answers question: http://stackoverflow.com/q/50275846
type: Answer
has body: If you just need to animate a matplotlib canvas the animation framework is the answer. There's a simple example here that does basically what you ask. If this is going to be part of a more complex application you probably want finer control over a specific backend. Here's a quick attempt using Qt loosely based on this matplotlib example. It's using a QTimer for the updates, probably there's also some idle callback in Qt you could attach to. import sys import numpy as np import matplotlib as mpl mpl.use('qt5agg') from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from PyQt5 import QtWidgets, QtCore size = (400, 400) class GameCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.gca() self.init_figure() FigureCanvas.__init__(self, fig) self.setParent(parent) timer = QtCore.QTimer(self) timer.timeout.connect(self.update_figure) timer.start(10) def gen_frame(self): return np.random.randint(0,0xfffff,size) def init_figure(self): self.img = self.axes.imshow(self.gen_frame()) def update_figure(self): self.img.set_data(self.gen_frame()) self.draw() class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.main_widget = QtWidgets.QWidget(self) dc = GameCanvas(self.main_widget, width=5, height=4, dpi=100) self.setCentralWidget(dc) def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit() app = QtWidgets.QApplication(sys.argv) appw = ApplicationWindow() appw.show() sys.exit(app.exec_()) One thing you should be careful with is that imshow computes the image normalization on the first frame. In the subsequent frames it's calling set_data so the normalization stays the same. If you want to update it you can call imshow instead (probably slower). Or you could just fix it manually with vmin and vmax in the first imshow call and provide properly normalized f…
upvote count: 6
has comment: http://stackoverflow.com/comment/87694232

http://stackoverflow.com/a/50293552
answers question: http://stackoverflow.com/q/50292718
has comment: http://stackoverflow.com/comment/87604290
has comment: http://stackoverflow.com/comment/87604437
has body: You need to save the company names, categories, and addresses in lists and then you can write the rows into the csv file. I.e. you can save the company names in a list like this: company_names = [] for company_name in soup.findAll('td', {'class': 'wpgmza_table_title all'}): company_names.append(company_name.string) And then the categories and addresses: company_categories = [] for company_category in soup.findAll('td', {'class': 'wpgmza_table_category'}): company_categories.append(company_category.string) company_addresses = [] for company_address in soup.findAll('td', {'class': 'wpgmza_table_address'}): company_addresses.append(company_address.string) And then you can use those lists to write the rows to your csv file using a for-loop: for i in range(len(company_names)): f.writerow([company_names[i], company_categories[i], company_adresses[i]])
type: Answer
has comment: http://stackoverflow.com/comment/87604800
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87604743

overflowexception
type: Tag
tags question: http://stackoverflow.com/q/50367014
tag name: overflowexception

http://stackoverflow.com/comment/87772946
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50377917
has text: I see two problems, one with using website adress extracted via xpath (variable xpath), the other one is how to properly merge it together? I mean visit those links for each user and then follow from page 1 till the end?

http://stackoverflow.com/q/50370810
has title: Deploy a java web app that uses a python script to Azure
downvote count: 0
tagged with: azure
tagged with: java
answer count: 1
has answer: http://stackoverflow.com/a/50406761
accepted answer: http://stackoverflow.com/a/50406761
linked to: http://stackoverflow.com/q/47155223
favorite count: 0
type: Question
has body: I am working on java web application and I'm trying to use a simple AI algorithm - NLP to parse texts. I want to run a python script from my app NLP.py which uses a data from another file (3 Gb size) that resides on my local pc, I downloaded the python plugin and I run the script like this: String pythonScriptPath = "MY-PATH\\NLP\\NLP.py"; String[] cmd = new String[3]; cmd[0] = "python"; // check version of installed python: python -V cmd[1] = pythonScriptPath; cmd[2]="playing sport"; // create runtime to execute external command Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); Files hierarchy: Now I want to run all these things on Azure, I didn't find any relevant tutorial, I deployed the app as a regular web app but I still don't know: Where to upload the file that the script uses ? What path to write instead of MY-PATH ? How will the python script run on Azure, what resource should I use and how? Will it work like this (as web app that uses a python plugin) or should I do something entirely different?
tagged with: spring-boot
tagged with: azure-web-app-service
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49087407

http://stackoverflow.com/comment/87751367
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50367370
has text: @Cid But this is not what is expected.. What do you mean by that?
type: AnswerComment

sorting
tags question: http://stackoverflow.com/q/50318613
tags question: http://stackoverflow.com/q/50322830
tags question: http://stackoverflow.com/q/50297639
tags question: http://stackoverflow.com/q/50285416
tags question: http://stackoverflow.com/q/50233521
tags question: http://stackoverflow.com/q/50287479
tags question: http://stackoverflow.com/q/50263809
tags question: http://stackoverflow.com/q/50272166
tags question: http://stackoverflow.com/q/50343137
tags question: http://stackoverflow.com/q/50378153
tags question: http://stackoverflow.com/q/50366484
tags question: http://stackoverflow.com/q/50304103
tags question: http://stackoverflow.com/q/50323160
tags question: http://stackoverflow.com/q/50251654
tag name: sorting
tags question: http://stackoverflow.com/q/50243740
tags question: http://stackoverflow.com/q/50280423
tags question: http://stackoverflow.com/q/50245294
tags question: http://stackoverflow.com/q/50315058
tags question: http://stackoverflow.com/q/50365579
tags question: http://stackoverflow.com/q/50296897
tags question: http://stackoverflow.com/q/50337132
tags question: http://stackoverflow.com/q/50301594
type: Tag

http://stackoverflow.com/comment/87539222
type: Comment
type: AnswerComment
has text: No and it's important. The embedding is *learnable* (unless it's pre-trained and fixed), so it's already part of the network. Pre-processing is done to the data *before* you feed it in, in this case character indices.
comment on: http://stackoverflow.com/a/50259941
score: 0

http://stackoverflow.com/q/50350632
score: 0
has comment: http://stackoverflow.com/comment/87812489
has title: dedupe OverflowError on record linkage
has comment: http://stackoverflow.com/comment/87734165
tagged with: duplicates
has body: I want to use Dedupe library for record linkage. I wrote this code from Dedupe examples on Github. But when i run my code i get this error : OverflowError: Python int too large to convert to C ssize_t ## its because my data are very big.how i cant filter my data_d columns?? it should help. I searched all stackoverflow questions but i couldn't find right answer. def readData(filename): """ Read in our data from a CSV file and create a dictionary of records, where the key is a unique record ID. """ data_d = {} with codecs.open(filename,encoding='utf-8') as f: reader = csv.DictReader(f) for i, row in enumerate(reader): clean_row = dict([(k, preProcess(v)) for (k, v) in row.items()]) data_d[filename + str(i)] = dict(clean_row) return data_d
has comment: http://stackoverflow.com/comment/87812753
has comment: http://stackoverflow.com/comment/87719819
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87721042
tagged with: record-linkage
upvote count: 1
tagged with: python
tagged with: python-dedupe
downvote count: 1

http://stackoverflow.com/comment/87483709
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/50232473
has text: can you post some sample data on `X` and `y` ?

http://stackoverflow.com/a/50260916
has body: On fist glance, I would think the issue would be the GPIO.setup is not propagated to the defined functions. Rather than define them globally at the top, make a sub method def gpio_setup(): pin = 15 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.OUT) GPIO.setup(pin, GPIO.HIGH) And then call that method in each of the other methods: def on_message(client, userdata, msg): gpio_setup() You could even start just by setting the GPIO.setup manually in each method to find where it breaks.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/50260767

http://stackoverflow.com/comment/87660569
type: Comment
has text: @TheInvertibleHogDog Yes, you can bind the address to the client if you wanted but it really doesn't matter, because the server will know the client's address when the client sends it a message anyway.
type: AnswerComment
comment on: http://stackoverflow.com/a/50321643
score: 0

http://stackoverflow.com/q/50282197
type: AnsweredQuestion
tagged with: pandas
upvote count: 5
has body: Problem: I have a large CSV file which looks something like this: A B C D ... 1 dog black NULL ... 1 dog white NULL ... 1 dog black NULL ... 2 cat red NULL ... ... Now I want to "group by" column A and aggregate each remaining column to a comma separated list without duplicates. The solutions should look something like this: A B C D ... 1 dog black, white NULL ... 2 cat red NULL ... ... Since the names and numbers of columns in the CSV may change, I prefer a solution without hard coded names. Used Approach: I tried the package pandas with the following code: import pandas as pd data = pd.read_csv("C://input.csv", sep=';') data = data.where((pd.notnull(data)), None) data_group = data.groupby(['A']).agg(lambda x: set(x)) data_group.to_csv("C://result.csv", sep=';') The set operator does exactly what I want. However, the resulting CSV looks like this: A B C D ... 1 {'dog'} {'black', 'white'} {None} ... 2 {'cat'} {'red'} {None} ... ... I don't want the {} and '' in my export and also column Dshould be empty and not containing the word None. Question: Am I on the right track, or is there a much more elegant way to achieve my goal?
has title: Pandas: Aggregate each column into a comma separated list without duplicates
answer count: 1
accepted answer: http://stackoverflow.com/a/50282270
tagged with: python
has answer: http://stackoverflow.com/a/50282270
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
downvote count: 0

http://stackoverflow.com/q/50361325
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/87739193
has title: My code doesn't work
has comment: http://stackoverflow.com/comment/87741157
downvote count: 4
type: UnansweredQuestion
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/50361368
has body: I have a problem with my code. When I enter numbers it still shows "only numbers are allowed". How can I fix it? This is the code: age = input("What's your age? ") while age != age.isdigit(): print("only numbers are allowed") age = input("What's your age? ") age = int(age)
favorite count: 0
type: Question
tagged with: while-loop
score: -3

http://stackoverflow.com/comment/87629560
type: QuestionComment
has text: @hansTheFranz i just checked using `end = event['end'].get('dateTime', event['end'].get('date')) if isinstance(end, datetime.datetime): print('YES') else: print('NO') ` it displayed NO so i recieve a string from the calendar api
score: 0
comment on: http://stackoverflow.com/q/50306386
type: Comment

http://stackoverflow.com/a/50278322
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/50277935
has body: Assuming that the next five days starts from tomorrow you could randomly select a number from 1 to 5 and add it to the current date. Then combine it with a time object to create a datetime to which you can add a randomly selected number from 1 to 25200 (the number of seconds between 8AM and 3PM). from datetime import date, time, datetime, timedelta from random import randint d = date.today() + timedelta(days=randint(1, 5)) t = time(8, 0, 0) dt = datetime.combine(d, t) + timedelta(seconds=randint(1, 25200)) print(dt) If the next five days start today adjust the first randint to randint(0, 4), and if your timestamp needs to include microseconds increase the second randint.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/87542357
type: Comment
comment on: http://stackoverflow.com/a/50259941
score: 0
type: AnswerComment
has text: I follow the second option, but still get the same error saying 'ref' not mutable. tslice = tf.Variable(tf.fill([64,sequence_length,embedding_size],0)). tslice = tf.slice(self.embedded_chars,[64,0,0],[1,sequence_length,embedding_size]). indices = 0,i update = tf.scatter_nd_update(tslice,indices,updates). The error is: TypeError: 'ScatterNdUpdate' Op requires that input 'ref' be a mutable tensor (e.g.: a tf.Variable)

http://stackoverflow.com/a/50338238
has body: The code seems to be fine, however these is a conceptual problem called Gradient Vanishing. When you use deep network you can see as u go near to input layers, in the calculation of gradient, number of derivative of sigmoid increases. The maximum value of derivative of sigmoid is 0.25, and that is not always the case, value of derivative of sigmoid can be near to like 0.001 or something, in that case when these small terms increases, Gradient is decreased drastically. So, ReLU is one thing that can solve this problem to some extent, its derivative is either 0 or 1, so if gradient vanish it would be due to only weights and not Activation. So, USE ReLU in hidden Layer instead of Sigmoid This article in the book by Michael Nielsen explains this in depth with calculus http://neuralnetworksanddeeplearning.com/chap5.html#the_vanishing_gradient_problem
answers question: http://stackoverflow.com/q/50337332
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/50337332

http://stackoverflow.com/q/50369872
tagged with: python
score: 0
has body: I have a database with population data. I want to create a page that shows a figure of this data (with for example matplotlib). How and where would I store the figures which I create with matplotlib? Example data: year | people 2010 | 100 2011 | 110 2012 | 110 2013 | 114 2014 | 124 2015 | 154 2016 | 143 2017 | 112 In my view I already have collected the variable, year and people. I would normally do something like this: plt.plot(year, people) plt.savefig('figure.svg') The question is where/how would I store this and present it to the user? Should I store this in a media directory? I do not want to store the file forever cause then diskspace would quickly fill up with graphs which are only used once.
answer count: 2
tagged with: django
linked to: http://stackoverflow.com/q/2451739
has answer: http://stackoverflow.com/a/50370866
type: Question
has comment: http://stackoverflow.com/comment/87755561
tagged with: static-files
has answer: http://stackoverflow.com/a/50370188
linked to: http://stackoverflow.com/q/30531990
type: UnansweredQuestion
has title: django - temporarily storing figures

http://stackoverflow.com/q/50381504
tagged with: keras
tagged with: tensorflow
type: Question
has body: I am trying to train an autoencoder whose input is some dense features concatenated with the output of an embedding layer. I therefore want to use the output of the concatenation layer for both the input and the labels to train the autoencoder: # Inputs dense = Input(shape=(train_dense_scaled.shape[1],)) sequences = Input(shape=(train_embed.shape[1],)) # Embedding layer embed = Embedding(vocab_size, 20, input_length=num_embed_cols)(sequences) flatten = Flatten()(embed) ae_input = concatenate([dense, flatten]) # Autoencoder e_128 = Dense(units=128, activation='relu', kernel_initializer=initializer)(ae_input) e_64 = Dense(units=64, activation='relu', kernel_initializer=initializer)(e_128) decoded = Dense(units=128, activation='relu', kernel_initializer=initializer)(e_64) model = Model(inputs=[sequences,dense], outputs=decoded) model.compile(loss='mse', optimizer='adam') model.fit(x=[train_dense_scaled,train_embed], y=ae_input, epochs=200, batch_size=128) I get the following error AttributeError Traceback (most recent call last) &lt;ipython-input-25-f29037b9f7ab&gt; in &lt;module&gt;() ---&gt; 50 model.fit(x=[train_dense_scaled,train_embed], y=ae_inputs, epochs=200, batch_size=128) ... AttributeError: 'Tensor' object has no attribute 'ndim' The output of the concatenation layer ae_input is the input into the autoencoder, and thus what I want to use as labels to train the model. I'm assuming this is where I'm going wrong and not properly feeding the output of this intermediate layer to the model.fit() method.
has comment: http://stackoverflow.com/comment/87813897
tagged with: python
type: UnansweredQuestion
has title: Use intermediate layer values to fit model
has comment: http://stackoverflow.com/comment/87882771
has comment: http://stackoverflow.com/comment/87832096
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/87832015

http://stackoverflow.com/a/50235241
score: 0
has body: Have you tried this.. import sys sys.path.insert(0, '/path/to/application/app/folder') import file
type: Answer
answers question: http://stackoverflow.com/q/50235121

http://stackoverflow.com/comment/87535043
comment on: http://stackoverflow.com/a/50258386
has text: This certainly works for this example. But see OP says - " I need to remove the last character if it is a punctuation mark until the last character is letter or number." So any punctuations at the end should ideally be removed.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/50305091
accepted answer of: http://stackoverflow.com/q/50304937
answers question: http://stackoverflow.com/q/50304937
upvote count: 1
score: 1
type: Answer
has body: You can add string by condition: df.loc[df['gene'] == 'gene1', 'gene'] += '_number1' print (df) gene scaf GC other 0 gene1_number1 3456 78 other1 1 gene2 7898 56 other 2 2 gene3 5667 23 other 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87626850
type: AcceptedAnswer

http://stackoverflow.com/comment/87737840
type: Comment
type: QuestionComment
has text: Added my attempt at porting to python. Happy to rewrite it, but I'm just not sure the best way to go about it. Thanks
comment on: http://stackoverflow.com/q/50360129
score: 0

http://stackoverflow.com/comment/87584218
type: AnswerComment
comment on: http://stackoverflow.com/a/50283871
score: 1
type: Comment
has text: Using a command line argument would be a much cleaner and easier-to-debug way to do thing (IMHO). It would frustrate me to be debugging the behaviour of a python script and figure out that its behaviour changes when run from a script vs by a user directly. Having programs behave the same way regardless of the invocation method is extremely valuable.

http://stackoverflow.com/q/50300976
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87618842
has title: My function keeps producing the word "none" in the output
has comment: http://stackoverflow.com/comment/87618820
upvote count: 0
accepted answer: http://stackoverflow.com/a/50301101
answer count: 1
downvote count: 3
has body: I am in a beginners computer science class, and for my final I have to create a menu that includes all of my previous coding assignments using only the basic techniques that we have been taught. I have created a code that works, but the problem is my code also produces the word "none" in the output. def options(): print ("Pick from the list") print ("1. Grade Conversion") print ("2. Temperature Conversion") print ("3. Currency Conversion") print ("4. Sum and Average") print ("5. Heads or Tails Guessing Game") print ("6. Fibonacci Sequence") print ("7. Factorials") print ("8. Multiplication Table") print ("9. Guess the Number Game") print ("10. Calculator") print ("11. Exit") def Student_A_Gets_A(): print ("Student A gets Grade A") print (Score) def Student_B_Gets_B(): print ("Student B gets Grade B") print (Score) def Student_C_Gets_C(): print ("Student C gets Grade C") print (Score) def Student_D_Gets_D(): print ("Student D gets Grade D") print (Score) def Student_F_Gets_F(): print ("Student F gets Grade F") print (Score) def Celsius(): Temperature = int(input ("Please enter Temp. in Celsius: ")) print ("Fahrenheit = ", (Temperature*(9/5))+32) def Fahrenheit(): Temperature = int(input ("Please enter Temp. in Fahrenheit: ")) print ("Celsius = ", (Temperature-32)*(5/9)) def Currency_Conversion(): print ("Pick from the list") print ("1. Dollar to Euro") print ("2. Dollar to Peso") print ("3. Euro to Dollar") print ("4. Peso to Dollar") print ("5. Euro to Peso") print ("6. Peso to Euro") def Dollar_to_Euro(): print ("You have selected 1 to convert Dollar to Euro") Amount = int(input("Please enter the amount in dollar(s): ")) print ("$", Amount, " = ", "€",(Amount)*(0.813654)) def Dollar_to_Peso(): print ("You have selected 2 to convert Dollar to Peso") Amount = int(input("Please enter the amount in dollar(s): ")) print ("$", Amount, " = ", "Mex$",(Amount)*(18.695653)) def Euro_to_Dollar(): print ("You have selected 3 to convert Euro to Dollar") Amount = int(input("Plea…
has comment: http://stackoverflow.com/comment/87618665
has answer: http://stackoverflow.com/a/50301101
has comment: http://stackoverflow.com/comment/87618743
has comment: http://stackoverflow.com/comment/87618751
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/87618852
score: -3
has comment: http://stackoverflow.com/comment/87618834
linked to: http://stackoverflow.com/q/7053652
tagged with: python